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 |
|---|---|---|---|---|---|---|---|---|---|---|
FalkorDB/JFalkorDB | src/main/java/com/falkordb/impl/api/GraphContextImpl.java | [
{
"identifier": "GraphContext",
"path": "src/main/java/com/falkordb/GraphContext.java",
"snippet": "public interface GraphContext extends Graph {\n\n /**\n * Returns a Redis transactional object, over the connection context, with graph API capabilities\n * @return Redis transactional object, ... | import java.util.List;
import com.falkordb.GraphContext;
import com.falkordb.GraphPipeline;
import com.falkordb.GraphTransaction;
import com.falkordb.ResultSet;
import com.falkordb.exceptions.GraphException;
import com.falkordb.impl.Utils;
import com.falkordb.impl.graph_cache.GraphCache;
import com.falkordb.impl.resultset.ResultSetImpl;
import redis.clients.jedis.Client;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.exceptions.JedisDataException;
import redis.clients.jedis.util.SafeEncoder; | 7,675 | package com.falkordb.impl.api;
/**
* An implementation of GraphContext. Allows sending Graph and some Redis commands,
* within a specific connection context
*/
public class GraphContextImpl extends AbstractGraph implements GraphContext {
private final Jedis connection;
private final String graphId;
private GraphCache cache;
/**
* Generates a new instance with a specific Jedis connection
* @param connection Jedis connection
* @param cache GraphCache
* @param graphId graph id
*/
public GraphContextImpl(Jedis connection, GraphCache cache, String graphId) {
this.connection = connection;
this.graphId = graphId;
this.cache = cache;
}
/**
* Sends the query over the instance only connection
* @param preparedQuery prepared query
* @return Result set with the query answer
*/
@Override
protected ResultSet sendQuery(String preparedQuery) {
try {
@SuppressWarnings("unchecked")
List<Object> rawResponse = (List<Object>) connection.sendCommand(GraphCommand.QUERY, graphId, preparedQuery, Utils.COMPACT_STRING);
return new ResultSetImpl(rawResponse, this, this.cache);
} catch (GraphException rt) {
throw rt;
} catch (JedisDataException j) {
throw new GraphException(j);
}
}
/**
* Sends the read-only query over the instance only connection
* @param preparedQuery prepared query
* @return Result set with the query answer
*/
@Override
protected ResultSet sendReadOnlyQuery(String preparedQuery) {
try {
@SuppressWarnings("unchecked")
List<Object> rawResponse = (List<Object>) connection.sendCommand(GraphCommand.RO_QUERY, graphId, preparedQuery, Utils.COMPACT_STRING);
return new ResultSetImpl(rawResponse, this, this.cache);
} catch (GraphException ge) {
throw ge;
} catch (JedisDataException de) {
throw new GraphException(de);
}
}
/**
* Sends the query over the instance only connection
* @param preparedQuery prepared query
* @param timeout timeout in milliseconds
* @return Result set with the query answer
*/
@Override
protected ResultSet sendQuery(String preparedQuery, long timeout) {
try {
@SuppressWarnings("unchecked")
List<Object> rawResponse = (List<Object>) connection.sendBlockingCommand(GraphCommand.QUERY,
graphId, preparedQuery, Utils.COMPACT_STRING, Utils.TIMEOUT_STRING, Long.toString(timeout));
return new ResultSetImpl(rawResponse, this, this.cache);
} catch (GraphException rt) {
throw rt;
} catch (JedisDataException j) {
throw new GraphException(j);
}
}
/**
* Sends the read-only query over the instance only connection
* @param preparedQuery prepared query
* @param timeout timeout in milliseconds
* @return Result set with the query answer
*/
@Override
protected ResultSet sendReadOnlyQuery(String preparedQuery, long timeout) {
try {
@SuppressWarnings("unchecked")
List<Object> rawResponse = (List<Object>) connection.sendBlockingCommand(GraphCommand.RO_QUERY,
graphId, preparedQuery, Utils.COMPACT_STRING, Utils.TIMEOUT_STRING, Long.toString(timeout));
return new ResultSetImpl(rawResponse, this, this.cache);
} catch (GraphException ge) {
throw ge;
} catch (JedisDataException de) {
throw new GraphException(de);
}
}
/**
* Creates a new GraphTransaction transactional object
* @return new GraphTransaction
*/
@Override
public GraphTransaction multi() {
Client client = connection.getClient();
client.multi();
client.getOne();
return new GraphTransactionImpl(client, this, this.cache, this.graphId);
}
/**
* Creates a new GraphPipeline pipeline object
* @return new GraphPipeline
*/
@Override | package com.falkordb.impl.api;
/**
* An implementation of GraphContext. Allows sending Graph and some Redis commands,
* within a specific connection context
*/
public class GraphContextImpl extends AbstractGraph implements GraphContext {
private final Jedis connection;
private final String graphId;
private GraphCache cache;
/**
* Generates a new instance with a specific Jedis connection
* @param connection Jedis connection
* @param cache GraphCache
* @param graphId graph id
*/
public GraphContextImpl(Jedis connection, GraphCache cache, String graphId) {
this.connection = connection;
this.graphId = graphId;
this.cache = cache;
}
/**
* Sends the query over the instance only connection
* @param preparedQuery prepared query
* @return Result set with the query answer
*/
@Override
protected ResultSet sendQuery(String preparedQuery) {
try {
@SuppressWarnings("unchecked")
List<Object> rawResponse = (List<Object>) connection.sendCommand(GraphCommand.QUERY, graphId, preparedQuery, Utils.COMPACT_STRING);
return new ResultSetImpl(rawResponse, this, this.cache);
} catch (GraphException rt) {
throw rt;
} catch (JedisDataException j) {
throw new GraphException(j);
}
}
/**
* Sends the read-only query over the instance only connection
* @param preparedQuery prepared query
* @return Result set with the query answer
*/
@Override
protected ResultSet sendReadOnlyQuery(String preparedQuery) {
try {
@SuppressWarnings("unchecked")
List<Object> rawResponse = (List<Object>) connection.sendCommand(GraphCommand.RO_QUERY, graphId, preparedQuery, Utils.COMPACT_STRING);
return new ResultSetImpl(rawResponse, this, this.cache);
} catch (GraphException ge) {
throw ge;
} catch (JedisDataException de) {
throw new GraphException(de);
}
}
/**
* Sends the query over the instance only connection
* @param preparedQuery prepared query
* @param timeout timeout in milliseconds
* @return Result set with the query answer
*/
@Override
protected ResultSet sendQuery(String preparedQuery, long timeout) {
try {
@SuppressWarnings("unchecked")
List<Object> rawResponse = (List<Object>) connection.sendBlockingCommand(GraphCommand.QUERY,
graphId, preparedQuery, Utils.COMPACT_STRING, Utils.TIMEOUT_STRING, Long.toString(timeout));
return new ResultSetImpl(rawResponse, this, this.cache);
} catch (GraphException rt) {
throw rt;
} catch (JedisDataException j) {
throw new GraphException(j);
}
}
/**
* Sends the read-only query over the instance only connection
* @param preparedQuery prepared query
* @param timeout timeout in milliseconds
* @return Result set with the query answer
*/
@Override
protected ResultSet sendReadOnlyQuery(String preparedQuery, long timeout) {
try {
@SuppressWarnings("unchecked")
List<Object> rawResponse = (List<Object>) connection.sendBlockingCommand(GraphCommand.RO_QUERY,
graphId, preparedQuery, Utils.COMPACT_STRING, Utils.TIMEOUT_STRING, Long.toString(timeout));
return new ResultSetImpl(rawResponse, this, this.cache);
} catch (GraphException ge) {
throw ge;
} catch (JedisDataException de) {
throw new GraphException(de);
}
}
/**
* Creates a new GraphTransaction transactional object
* @return new GraphTransaction
*/
@Override
public GraphTransaction multi() {
Client client = connection.getClient();
client.multi();
client.getOne();
return new GraphTransactionImpl(client, this, this.cache, this.graphId);
}
/**
* Creates a new GraphPipeline pipeline object
* @return new GraphPipeline
*/
@Override | public GraphPipeline pipelined() { | 1 | 2023-11-26 13:38:14+00:00 | 12k |
DueWesternersProgramming/FRC-2023-Swerve-Offseason | src/main/java/frc/robot/subsystems/DriveSubsystem.java | [
{
"identifier": "EntechSubsystem",
"path": "src/main/java/entech/subsystems/EntechSubsystem.java",
"snippet": "public abstract class EntechSubsystem extends SubsystemBase {\n\n public EntechSubsystem() { \n }\n\tpublic abstract void initialize();\n\tpublic abstract boolean isEnabled();\n}"
... | import java.util.Optional;
import com.kauailabs.navx.frc.AHRS;
import edu.wpi.first.math.filter.SlewRateLimiter;
import edu.wpi.first.math.geometry.Pose2d;
import edu.wpi.first.math.geometry.Rotation2d;
import edu.wpi.first.math.geometry.Translation2d;
import edu.wpi.first.math.kinematics.ChassisSpeeds;
import edu.wpi.first.math.kinematics.SwerveDriveKinematics;
import edu.wpi.first.math.kinematics.SwerveDriveOdometry;
import edu.wpi.first.math.kinematics.SwerveModulePosition;
import edu.wpi.first.math.kinematics.SwerveModuleState;
import edu.wpi.first.math.util.Units;
import edu.wpi.first.util.WPIUtilJNI;
import edu.wpi.first.wpilibj.I2C.Port;
import edu.wpi.first.wpilibj.smartdashboard.Field2d;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import entech.subsystems.EntechSubsystem;
import frc.robot.RobotConstants;
import frc.robot.RobotConstants.DrivetrainConstants;
import frc.robot.swerve.SwerveModule;
import frc.robot.swerve.SwerveUtils; | 8,574 | m_rearRight.setDesiredState(swerveModuleStates[3]);
}
}
/**
* Sets the wheels into an X formation to prevent movement.
*/
public void setX() {
if (ENABLED) {
m_frontLeft.setDesiredState(new SwerveModuleState(0,
Rotation2d.fromDegrees(45)));
m_frontRight.setDesiredState(new SwerveModuleState(0,
Rotation2d.fromDegrees(-45)));
m_rearLeft.setDesiredState(new SwerveModuleState(0,
Rotation2d.fromDegrees(-45)));
m_rearRight.setDesiredState(new SwerveModuleState(0,
Rotation2d.fromDegrees(45)));
}
}
/**
* Sets the swerve ModuleStates.
*
* @param desiredStates The desired SwerveModule states.
*/
public void setModuleStates(SwerveModuleState[] desiredStates) {
if (ENABLED) {
SwerveDriveKinematics.desaturateWheelSpeeds(
desiredStates, DrivetrainConstants.MAX_SPEED_METERS_PER_SECOND);
m_frontLeft.setDesiredState(desiredStates[0]);
m_frontRight.setDesiredState(desiredStates[1]);
m_rearLeft.setDesiredState(desiredStates[2]);
m_rearRight.setDesiredState(desiredStates[3]);
}
}
/**
* Resets the drive encoders to currently read a position of 0 and seeds the
* turn encoders using the absolute encoders.
*/
public void resetEncoders() {
if (ENABLED) {
m_frontLeft.resetEncoders();
m_rearLeft.resetEncoders();
m_frontRight.resetEncoders();
m_rearRight.resetEncoders();
}
}
/** Zeroes the heading of the robot. */
public void zeroHeading() {
if (ENABLED) {
m_gyro.reset();
m_gyro.setAngleAdjustment(180);
Pose2d pose = getPose().get();
Pose2d pose2 = new Pose2d(pose.getTranslation(), Rotation2d.fromDegrees(0));
resetOdometry(pose2);
}
}
/** Calibrates the gyro. */
public void calculateHeading() {
if (ENABLED) {
m_gyro.calibrate();
while (!m_gyro.isCalibrating()) {
;
}
}
}
/**
* Returns the heading of the robot.
*
* @return the robot's heading in degrees, from -180 to 180
*/
public Optional<Double> getHeading() {
return ENABLED ? Optional.of(Rotation2d.fromDegrees(GYRO_ORIENTATION * getGyroAngle()).getDegrees())
: Optional.empty();
}
/**
* Returns the turn rate of the robot.
*
* @return The turn rate of the robot, in degrees per second
*/
public Optional<Double> getTurnRate() {
return ENABLED ? Optional.of(m_gyro.getRate() * (DrivetrainConstants.kGyroReversed ? -1.0 : 1.0))
: Optional.empty();
}
public Optional<SwerveModule> getFrontLeftModule() {
return ENABLED ? Optional.of(m_frontLeft) : Optional.empty();
}
public Optional<SwerveModule> getFrontRightModule() {
return ENABLED ? Optional.of(m_frontRight) : Optional.empty();
}
public Optional<SwerveModule> getRearLeftModule() {
return ENABLED ? Optional.of(m_rearLeft) : Optional.empty();
}
public Optional<SwerveModule> getRearRightModule() {
return ENABLED ? Optional.of(m_rearRight) : Optional.empty();
}
public Optional<AHRS> getImu() {
return ENABLED ? Optional.of(m_gyro) : Optional.empty();
}
@Override
public boolean isEnabled() {
return ENABLED;
}
@Override
public void initialize() {
if (ENABLED) {
m_frontLeft = new SwerveModule( | // Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
package frc.robot.subsystems;
/**
* The {@code Drivetrain} class contains fields and methods pertaining to the
* function of the drivetrain.
*/
public class DriveSubsystem extends EntechSubsystem {
private static final boolean ENABLED = true;
public static final double FRONT_LEFT_VIRTUAL_OFFSET_RADIANS = 5.30603;
public static final double FRONT_RIGHT_VIRTUAL_OFFSET_RADIANS = 3.31033;
public static final double REAR_LEFT_VIRTUAL_OFFSET_RADIANS = 0.59211;
public static final double REAR_RIGHT_VIRTUAL_OFFSET_RADIANS = 5.67266;
public static final int GYRO_ORIENTATION = 1; // might be able to merge with kGyroReversed
public static final double FIELD_LENGTH_INCHES = 54 * 12 + 1; // 54ft 1in
public static final double FIELD_WIDTH_INCHES = 26 * 12 + 7; // 26ft 7in
private SwerveModule m_frontLeft;
private SwerveModule m_frontRight;
private SwerveModule m_rearLeft;
private SwerveModule m_rearRight;
private AHRS m_gyro;
private double m_currentRotation = 0.0;
private double m_currentTranslationDir = 0.0;
private double m_currentTranslationMag = 0.0;
private SlewRateLimiter m_magLimiter = new SlewRateLimiter(DrivetrainConstants.MAGNITUDE_SLEW_RATE);
private SlewRateLimiter m_rotLimiter = new SlewRateLimiter(DrivetrainConstants.ROTATIONAL_SLEW_RATE);
private double m_prevTime = WPIUtilJNI.now() * 1e-6;
private SwerveDriveOdometry m_odometry;
Field2d field = new Field2d();
/** Creates a new Drivetrain. */
public DriveSubsystem() {
}
// Bad look on scope needs to be fixed
// public Pose3d createPose3d() {
// Pose2d initial = m_odometry.getPoseMeters();
// return new Pose3d(new Translation3d(initial.getX(), initial.getY(), 0.0),
// new Rotation3d(Units.degreesToRadians(m_gyro.getRoll()),
// Units.degreesToRadians(m_gyro.getPitch()),
// Units.degreesToRadians(m_gyro.getYaw() * -1)));
// }
private double getGyroAngle() {
return m_gyro.getAngle() + 0;
}
@Override
public void periodic() {
if (ENABLED) {
field.setRobotPose(m_odometry.getPoseMeters());
SmartDashboard.putData("Odometry Pose Field", field);
SmartDashboard.putNumberArray("modules pose angles", new double[] {
m_frontLeft.getPosition().angle.getDegrees(),
m_frontRight.getPosition().angle.getDegrees(),
m_rearLeft.getPosition().angle.getDegrees(),
m_rearRight.getPosition().angle.getDegrees()
});
SmartDashboard.putNumberArray("modules pose meters", new double[] {
m_frontLeft.getPosition().distanceMeters,
m_frontRight.getPosition().distanceMeters,
m_rearLeft.getPosition().distanceMeters,
m_rearRight.getPosition().distanceMeters
});
SmartDashboard.putNumberArray("Virtual abs encoders", new double[] {
m_frontLeft.getTurningAbsoluteEncoder().getVirtualPosition(),
m_frontRight.getTurningAbsoluteEncoder().getVirtualPosition(),
m_rearLeft.getTurningAbsoluteEncoder().getVirtualPosition(),
m_rearRight.getTurningAbsoluteEncoder().getVirtualPosition()
});
SmartDashboard.putNumberArray("Raw abs encoders", new double[] {
m_frontLeft.getTurningAbsoluteEncoder().getPosition(),
m_frontRight.getTurningAbsoluteEncoder().getPosition(),
m_rearLeft.getTurningAbsoluteEncoder().getPosition(),
m_rearRight.getTurningAbsoluteEncoder().getPosition()
});
SmartDashboard.putNumber("LEFT", m_rearRight.getTurningAbsoluteEncoder().getPosition());
SmartDashboard.putData("NAVX", m_gyro);
// Update the odometry in the periodic block
m_odometry.update(
Rotation2d.fromDegrees(GYRO_ORIENTATION * m_gyro.getAngle()),
new SwerveModulePosition[] {
m_frontLeft.getPosition(),
m_frontRight.getPosition(),
m_rearLeft.getPosition(),
m_rearRight.getPosition()
});
}
}
/**
* Returns the currently-estimated pose of the robot.
*
* @return The pose.
*/
public Optional<Pose2d> getPose() {
return ENABLED ? Optional.of(m_odometry.getPoseMeters()) : Optional.empty();
}
/**
* Resets the odometry to the specified pose.
*
* @param pose The pose to which to set the odometry.
*/
public void resetOdometry(Pose2d pose) {
if (ENABLED) {
m_odometry.resetPosition(
Rotation2d.fromDegrees(GYRO_ORIENTATION * m_gyro.getAngle()),
new SwerveModulePosition[] {
m_frontLeft.getPosition(),
m_frontRight.getPosition(),
m_rearLeft.getPosition(),
m_rearRight.getPosition()
},
pose);
}
}
/**
* Method to drive the robot using joystick info.
*
* @param xSpeed Speed of the robot in the x direction (forward).
* @param ySpeed Speed of the robot in the y direction (sideways).
* @param rot Angular rate of the robot.
* @param fieldRelative Whether the provided x and y speeds are relative to the
* field.
* @param rateLimit Whether to enable rate limiting for smoother control.
*/
public void drive(double xSpeed, double ySpeed, double rot, boolean fieldRelative, boolean rateLimit) {
if (ENABLED) {
double xSpeedCommanded;
double ySpeedCommanded;
if (rateLimit) {
// Convert XY to polar for rate limiting
double inputTranslationDir = Math.atan2(ySpeed, xSpeed);
double inputTranslationMag = Math.sqrt(Math.pow(xSpeed, 2) + Math.pow(ySpeed, 2));
// Calculate the direction slew rate based on an estimate of the lateral
// acceleration
double directionSlewRate;
if (m_currentTranslationMag != 0.0) {
directionSlewRate = Math.abs(DrivetrainConstants.DIRECTION_SLEW_RATE / m_currentTranslationMag);
} else {
directionSlewRate = 500.0; // some high number that means the slew rate is effectively instantaneous
}
double currentTime = WPIUtilJNI.now() * 1e-6;
double elapsedTime = currentTime - m_prevTime;
double angleDif = SwerveUtils.AngleDifference(inputTranslationDir, m_currentTranslationDir);
if (angleDif < 0.45 * Math.PI) {
m_currentTranslationDir = SwerveUtils.StepTowardsCircular(m_currentTranslationDir,
inputTranslationDir,
directionSlewRate * elapsedTime);
m_currentTranslationMag = m_magLimiter.calculate(inputTranslationMag);
} else if (angleDif > 0.85 * Math.PI) {
if (m_currentTranslationMag > 1e-4) {
m_currentTranslationMag = m_magLimiter.calculate(0.0);
} else {
m_currentTranslationDir = SwerveUtils.WrapAngle(m_currentTranslationDir + Math.PI);
m_currentTranslationMag = m_magLimiter.calculate(inputTranslationMag);
}
} else {
m_currentTranslationDir = SwerveUtils.StepTowardsCircular(m_currentTranslationDir,
inputTranslationDir,
directionSlewRate * elapsedTime);
m_currentTranslationMag = m_magLimiter.calculate(0.0);
}
m_prevTime = currentTime;
xSpeedCommanded = m_currentTranslationMag * Math.cos(m_currentTranslationDir);
ySpeedCommanded = m_currentTranslationMag * Math.sin(m_currentTranslationDir);
m_currentRotation = m_rotLimiter.calculate(rot);
} else {
xSpeedCommanded = xSpeed;
ySpeedCommanded = ySpeed;
m_currentRotation = rot;
}
// Convert the commanded speeds into the correct units for the drivetrain
double xSpeedDelivered = xSpeedCommanded * DrivetrainConstants.MAX_SPEED_METERS_PER_SECOND;
double ySpeedDelivered = ySpeedCommanded * DrivetrainConstants.MAX_SPEED_METERS_PER_SECOND;
double rotDelivered = m_currentRotation * DrivetrainConstants.MAX_ANGULAR_SPEED_RADIANS_PER_SECOND;
var swerveModuleStates = DrivetrainConstants.DRIVE_KINEMATICS.toSwerveModuleStates(
fieldRelative
? ChassisSpeeds.fromFieldRelativeSpeeds(xSpeedDelivered, ySpeedDelivered, rotDelivered,
Rotation2d.fromDegrees(GYRO_ORIENTATION * getGyroAngle()))
: new ChassisSpeeds(xSpeedDelivered, ySpeedDelivered, rotDelivered));
SwerveDriveKinematics.desaturateWheelSpeeds(
swerveModuleStates, DrivetrainConstants.MAX_SPEED_METERS_PER_SECOND);
m_frontLeft.setDesiredState(swerveModuleStates[0]);
m_frontRight.setDesiredState(swerveModuleStates[1]);
m_rearLeft.setDesiredState(swerveModuleStates[2]);
m_rearRight.setDesiredState(swerveModuleStates[3]);
}
}
/**
* Sets the wheels into an X formation to prevent movement.
*/
public void setX() {
if (ENABLED) {
m_frontLeft.setDesiredState(new SwerveModuleState(0,
Rotation2d.fromDegrees(45)));
m_frontRight.setDesiredState(new SwerveModuleState(0,
Rotation2d.fromDegrees(-45)));
m_rearLeft.setDesiredState(new SwerveModuleState(0,
Rotation2d.fromDegrees(-45)));
m_rearRight.setDesiredState(new SwerveModuleState(0,
Rotation2d.fromDegrees(45)));
}
}
/**
* Sets the swerve ModuleStates.
*
* @param desiredStates The desired SwerveModule states.
*/
public void setModuleStates(SwerveModuleState[] desiredStates) {
if (ENABLED) {
SwerveDriveKinematics.desaturateWheelSpeeds(
desiredStates, DrivetrainConstants.MAX_SPEED_METERS_PER_SECOND);
m_frontLeft.setDesiredState(desiredStates[0]);
m_frontRight.setDesiredState(desiredStates[1]);
m_rearLeft.setDesiredState(desiredStates[2]);
m_rearRight.setDesiredState(desiredStates[3]);
}
}
/**
* Resets the drive encoders to currently read a position of 0 and seeds the
* turn encoders using the absolute encoders.
*/
public void resetEncoders() {
if (ENABLED) {
m_frontLeft.resetEncoders();
m_rearLeft.resetEncoders();
m_frontRight.resetEncoders();
m_rearRight.resetEncoders();
}
}
/** Zeroes the heading of the robot. */
public void zeroHeading() {
if (ENABLED) {
m_gyro.reset();
m_gyro.setAngleAdjustment(180);
Pose2d pose = getPose().get();
Pose2d pose2 = new Pose2d(pose.getTranslation(), Rotation2d.fromDegrees(0));
resetOdometry(pose2);
}
}
/** Calibrates the gyro. */
public void calculateHeading() {
if (ENABLED) {
m_gyro.calibrate();
while (!m_gyro.isCalibrating()) {
;
}
}
}
/**
* Returns the heading of the robot.
*
* @return the robot's heading in degrees, from -180 to 180
*/
public Optional<Double> getHeading() {
return ENABLED ? Optional.of(Rotation2d.fromDegrees(GYRO_ORIENTATION * getGyroAngle()).getDegrees())
: Optional.empty();
}
/**
* Returns the turn rate of the robot.
*
* @return The turn rate of the robot, in degrees per second
*/
public Optional<Double> getTurnRate() {
return ENABLED ? Optional.of(m_gyro.getRate() * (DrivetrainConstants.kGyroReversed ? -1.0 : 1.0))
: Optional.empty();
}
public Optional<SwerveModule> getFrontLeftModule() {
return ENABLED ? Optional.of(m_frontLeft) : Optional.empty();
}
public Optional<SwerveModule> getFrontRightModule() {
return ENABLED ? Optional.of(m_frontRight) : Optional.empty();
}
public Optional<SwerveModule> getRearLeftModule() {
return ENABLED ? Optional.of(m_rearLeft) : Optional.empty();
}
public Optional<SwerveModule> getRearRightModule() {
return ENABLED ? Optional.of(m_rearRight) : Optional.empty();
}
public Optional<AHRS> getImu() {
return ENABLED ? Optional.of(m_gyro) : Optional.empty();
}
@Override
public boolean isEnabled() {
return ENABLED;
}
@Override
public void initialize() {
if (ENABLED) {
m_frontLeft = new SwerveModule( | RobotConstants.Ports.CAN.FRONT_LEFT_DRIVING, | 1 | 2023-11-21 01:49:41+00:00 | 12k |
Staffilon/KestraDataOrchestrator | IoT Simulator/src/main/java/net/acesinc/data/json/generator/JsonDataGenerator.java | [
{
"identifier": "JSONConfigReader",
"path": "IoT Simulator/src/main/java/net/acesinc/data/json/generator/config/JSONConfigReader.java",
"snippet": "public class JSONConfigReader {\n private static final Logger log = LogManager.getLogger(JSONConfigReader.class);\n \n public static String getJsonC... | import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.LinkedBlockingQueue;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.pulsar.client.api.PulsarClientException;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.json.simple.parser.ParseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
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.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import net.acesinc.data.json.generator.config.JSONConfigReader;
import net.acesinc.data.json.generator.config.SimulationConfig;
import net.acesinc.data.json.generator.log.AzureIoTHubLogger;
import net.acesinc.data.json.generator.log.EventLogger;
import net.acesinc.data.json.generator.log.FileLogger;
import net.acesinc.data.json.generator.log.HttpPostLogger;
import net.acesinc.data.json.generator.log.KafkaLogger;
import net.acesinc.data.json.generator.log.KinesisLogger;
import net.acesinc.data.json.generator.log.Log4JLogger;
import net.acesinc.data.json.generator.log.MqttLogger;
import net.acesinc.data.json.generator.log.NatsLogger;
import net.acesinc.data.json.generator.log.PulsarLogger;
import net.acesinc.data.json.generator.log.TranquilityLogger;
import net.acesinc.data.json.generator.log.WampLogger; | 10,688 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package net.acesinc.data.json.generator;
/**
*
* @author andrewserff
*/
@RestController
public class JsonDataGenerator {
@Autowired
Environment environment;
private static final Logger log = LogManager.getLogger(JsonDataGenerator.class);
private SimulationRunner simRunner;
private String simConfigFile;
public JsonDataGenerator() {
}
public String getFilePath(String file) {
String filePath = getSimulationContentPath() + "/" + file;
return filePath;
}
public String getSimulationContentPath() {
String folder = null;
if (environment != null)
environment.getProperty("myApp.folder", "conf");
else
folder = System.getProperty("myApp.folder", "conf");
return folder;
}
public JsonDataGenerator setUpSimulation(String simConfigString) {
simConfigFile = simConfigString;
LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<>();
try {
log.debug("Creating Simulation Runner using Simulation Config [ " + simConfigString + " ]");
SimulationConfig simConfig = getSimConfig();
List<EventLogger> loggers = new ArrayList<>();
for (Map<String, Object> elProps : simConfig.getProducers()) {
String elType = (String) elProps.get("type");
switch (elType) {
case "logger": {
log.info("Adding Log4JLogger Producer");
loggers.add(new Log4JLogger());
break;
}
case "file": {
log.info("Adding File Logger with properties: " + elProps);
loggers.add(new FileLogger(queue, elProps));
break;
}
case "kafka": {
log.info("Adding Kafka Producer with properties: " + elProps);
loggers.add(new KafkaLogger(queue, elProps));
break;
}
case "tranquility": {
log.info("Adding Tranqulity Logger with properties: " + elProps);
loggers.add(new TranquilityLogger(queue, elProps));
break;
}
case "nats": {
log.info("Adding NATS Logger with properties: " + elProps);
loggers.add(new NatsLogger(queue, elProps));
break;
}
case "http-post": {
log.info("Adding HTTP Post Logger with properties: " + elProps);
try {
loggers.add(new HttpPostLogger(queue, elProps));
} catch (NoSuchAlgorithmException ex) {
log.error("http-post Logger unable to initialize", ex);
}
break;
}
case "mqtt": {
log.info("Adding MQTT Logger with properties: " + elProps);
try {
loggers.add(new MqttLogger(queue, elProps));
} catch (MqttException ex) {
log.error("mqtt Logger unable to initialize", ex);
}
break;
}
case "iothub": {
log.info("Adding Azure IoT Hub Logger with properties: " + elProps);
try { | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package net.acesinc.data.json.generator;
/**
*
* @author andrewserff
*/
@RestController
public class JsonDataGenerator {
@Autowired
Environment environment;
private static final Logger log = LogManager.getLogger(JsonDataGenerator.class);
private SimulationRunner simRunner;
private String simConfigFile;
public JsonDataGenerator() {
}
public String getFilePath(String file) {
String filePath = getSimulationContentPath() + "/" + file;
return filePath;
}
public String getSimulationContentPath() {
String folder = null;
if (environment != null)
environment.getProperty("myApp.folder", "conf");
else
folder = System.getProperty("myApp.folder", "conf");
return folder;
}
public JsonDataGenerator setUpSimulation(String simConfigString) {
simConfigFile = simConfigString;
LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<>();
try {
log.debug("Creating Simulation Runner using Simulation Config [ " + simConfigString + " ]");
SimulationConfig simConfig = getSimConfig();
List<EventLogger> loggers = new ArrayList<>();
for (Map<String, Object> elProps : simConfig.getProducers()) {
String elType = (String) elProps.get("type");
switch (elType) {
case "logger": {
log.info("Adding Log4JLogger Producer");
loggers.add(new Log4JLogger());
break;
}
case "file": {
log.info("Adding File Logger with properties: " + elProps);
loggers.add(new FileLogger(queue, elProps));
break;
}
case "kafka": {
log.info("Adding Kafka Producer with properties: " + elProps);
loggers.add(new KafkaLogger(queue, elProps));
break;
}
case "tranquility": {
log.info("Adding Tranqulity Logger with properties: " + elProps);
loggers.add(new TranquilityLogger(queue, elProps));
break;
}
case "nats": {
log.info("Adding NATS Logger with properties: " + elProps);
loggers.add(new NatsLogger(queue, elProps));
break;
}
case "http-post": {
log.info("Adding HTTP Post Logger with properties: " + elProps);
try {
loggers.add(new HttpPostLogger(queue, elProps));
} catch (NoSuchAlgorithmException ex) {
log.error("http-post Logger unable to initialize", ex);
}
break;
}
case "mqtt": {
log.info("Adding MQTT Logger with properties: " + elProps);
try {
loggers.add(new MqttLogger(queue, elProps));
} catch (MqttException ex) {
log.error("mqtt Logger unable to initialize", ex);
}
break;
}
case "iothub": {
log.info("Adding Azure IoT Hub Logger with properties: " + elProps);
try { | loggers.add(new AzureIoTHubLogger(queue, elProps)); | 2 | 2023-11-26 10:57:17+00:00 | 12k |
Invadermonky/JustEnoughMagiculture | src/main/java/com/invadermonky/justenoughmagiculture/integrations/jei/mods/JEIErebusPlugin.java | [
{
"identifier": "JustEnoughMagiculture",
"path": "src/main/java/com/invadermonky/justenoughmagiculture/JustEnoughMagiculture.java",
"snippet": "@Mod(\n modid = JustEnoughMagiculture.MOD_ID,\n name = JustEnoughMagiculture.MOD_NAME,\n version = JustEnoughMagiculture.MOD_VERSION,\n ... | import com.invadermonky.justenoughmagiculture.JustEnoughMagiculture;
import com.invadermonky.justenoughmagiculture.configs.JEMConfig;
import com.invadermonky.justenoughmagiculture.integrations.jei.categories.erebus.composter.ComposterCategory;
import com.invadermonky.justenoughmagiculture.integrations.jei.categories.erebus.composter.ComposterWrapper;
import com.invadermonky.justenoughmagiculture.integrations.jei.categories.erebus.offeringtable.OfferingAltarCategory;
import com.invadermonky.justenoughmagiculture.integrations.jei.categories.erebus.offeringtable.OfferingAltarWrapper;
import com.invadermonky.justenoughmagiculture.integrations.jei.categories.erebus.smoothiemaker.SmoothieMakerCategory;
import com.invadermonky.justenoughmagiculture.integrations.jei.categories.erebus.smoothiemaker.SmoothieMakerWrapper;
import com.invadermonky.justenoughmagiculture.util.ModIds;
import erebus.ModBlocks;
import erebus.recipes.ComposterRegistry;
import erebus.recipes.OfferingAltarRecipe;
import erebus.recipes.SmoothieMakerRecipe;
import mezz.jei.api.IModRegistry;
import mezz.jei.api.recipe.IRecipeCategoryRegistration;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.NonNullList;
import net.minecraftforge.fml.common.registry.GameRegistry;
import net.minecraftforge.registries.IForgeRegistry; | 8,798 | package com.invadermonky.justenoughmagiculture.integrations.jei.mods;
public class JEIErebusPlugin {
private static JEIErebusPlugin instance; | package com.invadermonky.justenoughmagiculture.integrations.jei.mods;
public class JEIErebusPlugin {
private static JEIErebusPlugin instance; | private final boolean canLoad = (!ModIds.MORETWEAKER.isLoaded || JEMConfig.EREBUS.JUST_ENOUGH_ITEMS.forceLoadCategories); | 8 | 2023-11-19 23:09:14+00:00 | 12k |
Provismet/ProviHealth | src/main/java/com/provismet/provihealth/hud/TargetHealthBar.java | [
{
"identifier": "ProviHealthClient",
"path": "src/main/java/com/provismet/provihealth/ProviHealthClient.java",
"snippet": "public class ProviHealthClient implements ClientModInitializer {\n public static final String MODID = \"provihealth\";\n public static final Logger LOGGER = LoggerFactory.getL... | import org.jetbrains.annotations.Nullable;
import org.joml.Matrix4f;
import org.joml.Quaternionf;
import org.joml.Vector3f;
import com.mojang.blaze3d.systems.RenderSystem;
import com.provismet.provihealth.ProviHealthClient;
import com.provismet.provihealth.config.Options;
import com.provismet.provihealth.config.Options.HUDPosition;
import com.provismet.provihealth.config.Options.HUDType;
import com.provismet.provihealth.util.Visibility;
import com.provismet.provihealth.world.EntityHealthBar;
import net.fabricmc.fabric.api.client.rendering.v1.HudRenderCallback;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.DrawContext;
import net.minecraft.client.render.DiffuseLighting;
import net.minecraft.client.render.entity.EntityRenderDispatcher;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityPose;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.text.Text;
import net.minecraft.util.Identifier;
import net.minecraft.util.math.MathHelper; | 7,622 | package com.provismet.provihealth.hud;
public class TargetHealthBar implements HudRenderCallback {
public static boolean disabledLabels = false;
| package com.provismet.provihealth.hud;
public class TargetHealthBar implements HudRenderCallback {
public static boolean disabledLabels = false;
| private static final Identifier BARS = ProviHealthClient.identifier("textures/gui/healthbars/bars.png"); | 0 | 2023-11-26 02:46:37+00:00 | 12k |
codingmiao/hppt | sc/src/main/java/org/wowtools/hppt/sc/StartSc.java | [
{
"identifier": "AesCipherUtil",
"path": "common/src/main/java/org/wowtools/hppt/common/util/AesCipherUtil.java",
"snippet": "@Slf4j\npublic class AesCipherUtil {\n\n public final Encryptor encryptor;\n\n public final Descriptor descriptor;\n\n\n public AesCipherUtil(String strKey, long ts) {\n... | import lombok.extern.slf4j.Slf4j;
import okhttp3.Response;
import org.apache.logging.log4j.core.config.Configurator;
import org.wowtools.common.utils.ResourcesReader;
import org.wowtools.hppt.common.util.AesCipherUtil;
import org.wowtools.hppt.common.util.BytesUtil;
import org.wowtools.hppt.common.util.Constant;
import org.wowtools.hppt.common.util.HttpUtil;
import org.wowtools.hppt.sc.pojo.ScConfig;
import org.wowtools.hppt.sc.service.ClientPort;
import org.wowtools.hppt.sc.service.ClientSession;
import org.wowtools.hppt.sc.service.ClientSessionManager;
import org.wowtools.hppt.sc.service.ClientSessionService;
import java.io.File;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets; | 9,112 | package org.wowtools.hppt.sc;
/**
* @author liuyu
* @date 2023/11/25
*/
@Slf4j
public class StartSc {
public static final ScConfig config;
public static final AesCipherUtil aesCipherUtil;
public static final String loginCode;
static {
Configurator.reconfigure(new File(ResourcesReader.getRootPath(StartSc.class) + "/log4j2.xml").toURI());
try {
config = Constant.ymlMapper.readValue(ResourcesReader.readStr(StartSc.class, "sc.yml"), ScConfig.class);
} catch (Exception e) {
throw new RuntimeException("读取配置文件异常", e);
}
AesCipherUtil _aesCipherUtil = login();
if (null == _aesCipherUtil) {
//排除整点附近登录失败的情况
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
_aesCipherUtil = login();
}
if (null == _aesCipherUtil) {
throw new RuntimeException("登录失败");
}
aesCipherUtil = _aesCipherUtil;
loginCode = BytesUtil.bytes2base64(aesCipherUtil.encryptor.encrypt(StartSc.config.clientId.getBytes(StandardCharsets.UTF_8)));
log.info("登录成功");
}
//获取服务端时间-本地时间的差值
private static long getDt() {
long localTs = System.currentTimeMillis();
String res;
try (Response response = HttpUtil.doPost(StartSc.config.serverUrl + "/time")) {
assert response.body() != null;
res = response.body().string();
} catch (Exception e) {
throw new RuntimeException("获取服务器时间异常", e);
}
long serverTs = Long.parseLong(res);
return serverTs - localTs;
}
private static AesCipherUtil login() {
long dt = getDt();
AesCipherUtil aesCipherUtil = new AesCipherUtil(StartSc.config.clientId, System.currentTimeMillis() + dt);
String loginCode = BytesUtil.bytes2base64(aesCipherUtil.encryptor.encrypt(StartSc.config.clientId.getBytes(StandardCharsets.UTF_8)));
String res;
try (Response response = HttpUtil.doPost(StartSc.config.serverUrl + "/login?c="
+ URLEncoder.encode(loginCode, StandardCharsets.UTF_8))) {
assert response.body() != null;
res = response.body().string();
} catch (Exception e) {
throw new RuntimeException("获取服务器时间异常", e);
}
if ("1".equals(res)) {
return aesCipherUtil;
} else {
log.warn("登录失败 " + res);
return null;
}
}
public static void main(String[] args) throws Exception {
for (ScConfig.Forward forward : config.forwards) {
new ClientPort(forward.localPort, (_clientPort, channelHandlerContext) -> {
/* 1、用户发起连接,ClientPort收到连接信息后向ServerPort发起连接请求,ServerPort返回一个唯一的sessionId; */
//去服务端拿sessionId
int sessionId;
try {
sessionId = ClientSessionService.initServerSession(forward.remoteHost, forward.remotePort);
log.info("新会话建立 {} {} --> {} --> {}:{}",
sessionId, channelHandlerContext.channel().remoteAddress(),
forward.localPort,
forward.remoteHost, forward.remotePort);
} catch (Exception e) {
log.info("建立会话异常,主动关闭 {} --> {} --> {}:{}",
channelHandlerContext.channel().remoteAddress(),
forward.localPort,
forward.remoteHost, forward.remotePort);
channelHandlerContext.close();
return;
}
/* 2、ClientPort根据sessionId新建一个ClientSession,ServerPort根据sessionId新建一个ServerSession;*/ | package org.wowtools.hppt.sc;
/**
* @author liuyu
* @date 2023/11/25
*/
@Slf4j
public class StartSc {
public static final ScConfig config;
public static final AesCipherUtil aesCipherUtil;
public static final String loginCode;
static {
Configurator.reconfigure(new File(ResourcesReader.getRootPath(StartSc.class) + "/log4j2.xml").toURI());
try {
config = Constant.ymlMapper.readValue(ResourcesReader.readStr(StartSc.class, "sc.yml"), ScConfig.class);
} catch (Exception e) {
throw new RuntimeException("读取配置文件异常", e);
}
AesCipherUtil _aesCipherUtil = login();
if (null == _aesCipherUtil) {
//排除整点附近登录失败的情况
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
_aesCipherUtil = login();
}
if (null == _aesCipherUtil) {
throw new RuntimeException("登录失败");
}
aesCipherUtil = _aesCipherUtil;
loginCode = BytesUtil.bytes2base64(aesCipherUtil.encryptor.encrypt(StartSc.config.clientId.getBytes(StandardCharsets.UTF_8)));
log.info("登录成功");
}
//获取服务端时间-本地时间的差值
private static long getDt() {
long localTs = System.currentTimeMillis();
String res;
try (Response response = HttpUtil.doPost(StartSc.config.serverUrl + "/time")) {
assert response.body() != null;
res = response.body().string();
} catch (Exception e) {
throw new RuntimeException("获取服务器时间异常", e);
}
long serverTs = Long.parseLong(res);
return serverTs - localTs;
}
private static AesCipherUtil login() {
long dt = getDt();
AesCipherUtil aesCipherUtil = new AesCipherUtil(StartSc.config.clientId, System.currentTimeMillis() + dt);
String loginCode = BytesUtil.bytes2base64(aesCipherUtil.encryptor.encrypt(StartSc.config.clientId.getBytes(StandardCharsets.UTF_8)));
String res;
try (Response response = HttpUtil.doPost(StartSc.config.serverUrl + "/login?c="
+ URLEncoder.encode(loginCode, StandardCharsets.UTF_8))) {
assert response.body() != null;
res = response.body().string();
} catch (Exception e) {
throw new RuntimeException("获取服务器时间异常", e);
}
if ("1".equals(res)) {
return aesCipherUtil;
} else {
log.warn("登录失败 " + res);
return null;
}
}
public static void main(String[] args) throws Exception {
for (ScConfig.Forward forward : config.forwards) {
new ClientPort(forward.localPort, (_clientPort, channelHandlerContext) -> {
/* 1、用户发起连接,ClientPort收到连接信息后向ServerPort发起连接请求,ServerPort返回一个唯一的sessionId; */
//去服务端拿sessionId
int sessionId;
try {
sessionId = ClientSessionService.initServerSession(forward.remoteHost, forward.remotePort);
log.info("新会话建立 {} {} --> {} --> {}:{}",
sessionId, channelHandlerContext.channel().remoteAddress(),
forward.localPort,
forward.remoteHost, forward.remotePort);
} catch (Exception e) {
log.info("建立会话异常,主动关闭 {} --> {} --> {}:{}",
channelHandlerContext.channel().remoteAddress(),
forward.localPort,
forward.remoteHost, forward.remotePort);
channelHandlerContext.close();
return;
}
/* 2、ClientPort根据sessionId新建一个ClientSession,ServerPort根据sessionId新建一个ServerSession;*/ | ClientSession clientSession = ClientSessionManager.createClientSession(sessionId, _clientPort, channelHandlerContext); | 7 | 2023-12-22 14:14:27+00:00 | 12k |
3arthqu4ke/phobot | src/main/java/me/earth/phobot/pathfinder/algorithm/AlgorithmRenderer.java | [
{
"identifier": "RenderEvent",
"path": "src/main/java/me/earth/phobot/event/RenderEvent.java",
"snippet": "@Getter\n@Setter\n@NoArgsConstructor(access = AccessLevel.PRIVATE)\npublic class RenderEvent {\n @Getter\n private static final RenderEvent instance = new RenderEvent();\n\n // TODO: priva... | import me.earth.phobot.event.RenderEvent;
import me.earth.phobot.pathfinder.mesh.MeshNode;
import me.earth.phobot.pathfinder.movement.MovementNode;
import me.earth.phobot.pathfinder.movement.MovementPathfindingAlgorithm;
import me.earth.phobot.util.render.Renderer;
import me.earth.pingbypass.api.event.SubscriberImpl;
import me.earth.pingbypass.api.event.api.EventBus;
import me.earth.pingbypass.api.event.listeners.generic.Listener;
import java.awt.*;
import java.util.concurrent.CompletableFuture; | 8,488 | package me.earth.phobot.pathfinder.algorithm;
public class AlgorithmRenderer<T extends PathfindingNode<T>> extends SubscriberImpl {
private final RenderableAlgorithm<T> algorithm;
public AlgorithmRenderer(RenderableAlgorithm<T> algorithm) {
this.algorithm = algorithm;
listen(new Listener<RenderEvent>() {
@Override
public void onEvent(RenderEvent event) {
render(event);
}
});
}
public void render(RenderEvent event) {
T current = algorithm.getCurrent();
if (current != null) { | package me.earth.phobot.pathfinder.algorithm;
public class AlgorithmRenderer<T extends PathfindingNode<T>> extends SubscriberImpl {
private final RenderableAlgorithm<T> algorithm;
public AlgorithmRenderer(RenderableAlgorithm<T> algorithm) {
this.algorithm = algorithm;
listen(new Listener<RenderEvent>() {
@Override
public void onEvent(RenderEvent event) {
render(event);
}
});
}
public void render(RenderEvent event) {
T current = algorithm.getCurrent();
if (current != null) { | Renderer.startLines(1.5f, true); | 4 | 2023-12-22 14:32:16+00:00 | 12k |
ArmanKhanDev/FakepixelDungeonHelper | src/main/java/io/github/quantizr/handlers/ConfigHandler.java | [
{
"identifier": "DungeonRooms",
"path": "build/sources/main/java/io/github/quantizr/DungeonRooms.java",
"snippet": "@Mod(modid = DungeonRooms.MODID, version = DungeonRooms.VERSION)\npublic class DungeonRooms\n{\n public static final String MODID = \"FDH\";\n public static final String VERSION = \"... | import io.github.quantizr.DungeonRooms;
import io.github.quantizr.core.AutoRoom;
import io.github.quantizr.core.Waypoints;
import net.minecraftforge.common.config.ConfigCategory;
import net.minecraftforge.common.config.Configuration;
import java.io.File; | 9,643 | }
return "";
}
public static boolean getBoolean(String category, String key) {
config = new Configuration(new File(file));
try {
config.load();
if (config.getCategory(category).containsKey(key)) {
return config.get(category, key, false).getBoolean();
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
config.save();
}
return true;
}
public static void writeIntConfig(String category, String key, int value) {
config = new Configuration(new File(file));
try {
config.load();
int set = config.get(category, key, value).getInt();
config.getCategory(category).get(key).set(value);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
config.save();
}
}
public static void writeDoubleConfig(String category, String key, double value) {
config = new Configuration(new File(file));
try {
config.load();
double set = config.get(category, key, value).getDouble();
config.getCategory(category).get(key).set(value);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
config.save();
}
}
public static void writeStringConfig(String category, String key, String value) {
config = new Configuration(new File(file));
try {
config.load();
String set = config.get(category, key, value).getString();
config.getCategory(category).get(key).set(value);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
config.save();
}
}
public static void writeBooleanConfig(String category, String key, boolean value) {
config = new Configuration(new File(file));
try {
config.load();
boolean set = config.get(category, key, value).getBoolean();
config.getCategory(category).get(key).set(value);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
config.save();
}
}
public static boolean hasKey(String category, String key) {
config = new Configuration(new File(file));
try {
config.load();
if (!config.hasCategory(category)) return false;
return config.getCategory(category).containsKey(key);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
config.save();
}
return false;
}
public static void deleteCategory(String category) {
config = new Configuration(new File(file));
try {
config.load();
if (config.hasCategory(category)) {
config.removeCategory(new ConfigCategory(category));
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
config.save();
}
}
public static void reloadConfig() {
if (!hasKey("toggles", "chatToggled")) writeBooleanConfig("toggles", "chatToggled", false);
if (!hasKey("toggles", "guiToggled")) writeBooleanConfig("toggles", "guiToggled", true);
if (!hasKey("toggles", "coordToggled")) writeBooleanConfig("toggles", "coordToggled", false);
if (!hasKey("toggles", "waypointsToggled")) writeBooleanConfig("toggles", "waypointsToggled", true);
if (!hasKey("waypoint", "showEntrance")) writeBooleanConfig("waypoint", "showEntrance", true);
if (!hasKey("waypoint", "showSuperboom")) writeBooleanConfig("waypoint", "showSuperboom", true);
if (!hasKey("waypoint", "showSecrets")) writeBooleanConfig("waypoint", "showSecrets", true);
if (!hasKey("waypoint", "showFairySouls")) writeBooleanConfig("waypoint", "showFairySouls", true);
if (!hasKey("waypoint", "sneakToDisable")) writeBooleanConfig("waypoint", "sneakToDisable", true);
if (!hasKey("waypoint", "disableWhenAllFound")) writeBooleanConfig("waypoint", "disableWhenAllFound", true);
if (!hasKey("waypoint", "showWaypointText")) writeBooleanConfig("waypoint", "showWaypointText", true);
if (!hasKey("waypoint", "showBoundingBox")) writeBooleanConfig("waypoint", "showBoundingBox", true);
if (!hasKey("waypoint", "showBeacon")) writeBooleanConfig("waypoint", "showBeacon", true);
if (!hasKey("gui", "scaleX")) writeIntConfig("gui", "scaleX", 50);
if (!hasKey("gui", "scaleY")) writeIntConfig("gui", "scaleY", 5);
if (!hasKey("gui", "hotkeyOpen")) writeStringConfig("gui", "hotkeyOpen", "gui");
| /*
Taken from Danker's Skyblock Mod (https://github.com/bowser0000/SkyblockMod/).
This file was released under GNU General Public License v3.0 and remains under said license.
Modified by Quantizr (_risk) in Feb. 2021.
*/
package io.github.quantizr.handlers;
public class ConfigHandler {
public static Configuration config;
private final static String file = "config/DungeonRooms.cfg";
public static void init() {
config = new Configuration(new File(file));
try {
config.load();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
config.save();
}
}
public static int getInt(String category, String key) {
config = new Configuration(new File(file));
try {
config.load();
if (config.getCategory(category).containsKey(key)) {
return config.get(category, key, 0).getInt();
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
config.save();
}
return 0;
}
public static double getDouble(String category, String key) {
config = new Configuration(new File(file));
try {
config.load();
if (config.getCategory(category).containsKey(key)) {
return config.get(category, key, 0D).getDouble();
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
config.save();
}
return 0D;
}
public static String getString(String category, String key) {
config = new Configuration(new File(file));
try {
config.load();
if (config.getCategory(category).containsKey(key)) {
return config.get(category, key, "").getString();
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
config.save();
}
return "";
}
public static boolean getBoolean(String category, String key) {
config = new Configuration(new File(file));
try {
config.load();
if (config.getCategory(category).containsKey(key)) {
return config.get(category, key, false).getBoolean();
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
config.save();
}
return true;
}
public static void writeIntConfig(String category, String key, int value) {
config = new Configuration(new File(file));
try {
config.load();
int set = config.get(category, key, value).getInt();
config.getCategory(category).get(key).set(value);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
config.save();
}
}
public static void writeDoubleConfig(String category, String key, double value) {
config = new Configuration(new File(file));
try {
config.load();
double set = config.get(category, key, value).getDouble();
config.getCategory(category).get(key).set(value);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
config.save();
}
}
public static void writeStringConfig(String category, String key, String value) {
config = new Configuration(new File(file));
try {
config.load();
String set = config.get(category, key, value).getString();
config.getCategory(category).get(key).set(value);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
config.save();
}
}
public static void writeBooleanConfig(String category, String key, boolean value) {
config = new Configuration(new File(file));
try {
config.load();
boolean set = config.get(category, key, value).getBoolean();
config.getCategory(category).get(key).set(value);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
config.save();
}
}
public static boolean hasKey(String category, String key) {
config = new Configuration(new File(file));
try {
config.load();
if (!config.hasCategory(category)) return false;
return config.getCategory(category).containsKey(key);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
config.save();
}
return false;
}
public static void deleteCategory(String category) {
config = new Configuration(new File(file));
try {
config.load();
if (config.hasCategory(category)) {
config.removeCategory(new ConfigCategory(category));
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
config.save();
}
}
public static void reloadConfig() {
if (!hasKey("toggles", "chatToggled")) writeBooleanConfig("toggles", "chatToggled", false);
if (!hasKey("toggles", "guiToggled")) writeBooleanConfig("toggles", "guiToggled", true);
if (!hasKey("toggles", "coordToggled")) writeBooleanConfig("toggles", "coordToggled", false);
if (!hasKey("toggles", "waypointsToggled")) writeBooleanConfig("toggles", "waypointsToggled", true);
if (!hasKey("waypoint", "showEntrance")) writeBooleanConfig("waypoint", "showEntrance", true);
if (!hasKey("waypoint", "showSuperboom")) writeBooleanConfig("waypoint", "showSuperboom", true);
if (!hasKey("waypoint", "showSecrets")) writeBooleanConfig("waypoint", "showSecrets", true);
if (!hasKey("waypoint", "showFairySouls")) writeBooleanConfig("waypoint", "showFairySouls", true);
if (!hasKey("waypoint", "sneakToDisable")) writeBooleanConfig("waypoint", "sneakToDisable", true);
if (!hasKey("waypoint", "disableWhenAllFound")) writeBooleanConfig("waypoint", "disableWhenAllFound", true);
if (!hasKey("waypoint", "showWaypointText")) writeBooleanConfig("waypoint", "showWaypointText", true);
if (!hasKey("waypoint", "showBoundingBox")) writeBooleanConfig("waypoint", "showBoundingBox", true);
if (!hasKey("waypoint", "showBeacon")) writeBooleanConfig("waypoint", "showBeacon", true);
if (!hasKey("gui", "scaleX")) writeIntConfig("gui", "scaleX", 50);
if (!hasKey("gui", "scaleY")) writeIntConfig("gui", "scaleY", 5);
if (!hasKey("gui", "hotkeyOpen")) writeStringConfig("gui", "hotkeyOpen", "gui");
| AutoRoom.chatToggled = getBoolean("toggles", "chatToggled"); | 1 | 2023-12-22 04:44:39+00:00 | 12k |
HChenX/ClipboardList | app/src/main/java/com/hchen/clipboardlist/HookMain.java | [
{
"identifier": "ClipboardList",
"path": "app/src/main/java/com/hchen/clipboardlist/clipboard/ClipboardList.java",
"snippet": "public class ClipboardList extends Hook {\n public static ArrayList<?> lastArray = new ArrayList<>();\n\n public static String lastFilePath;\n public ArrayList<?> mClip... | import android.content.Context;
import android.view.inputmethod.InputMethodInfo;
import android.view.inputmethod.InputMethodManager;
import com.hchen.clipboardlist.clipboard.ClipboardList;
import com.hchen.clipboardlist.hook.Hook;
import com.hchen.clipboardlist.hook.Log;
import com.hchen.clipboardlist.unlockIme.UnlockIme;
import java.util.ArrayList;
import java.util.List;
import de.robv.android.xposed.IXposedHookLoadPackage;
import de.robv.android.xposed.callbacks.XC_LoadPackage.LoadPackageParam; | 10,188 | package com.hchen.clipboardlist;
public class HookMain implements IXposedHookLoadPackage {
public static List<String> mAppsUsingInputMethod = new ArrayList<>();
@Override
public void handleLoadPackage(LoadPackageParam lpparam) {
if (mAppsUsingInputMethod.isEmpty()) {
mAppsUsingInputMethod = getAppsUsingInputMethod(Hook.findContext());
}
String pkg = lpparam.packageName;
initHook(new ClipboardList(), lpparam, isInputMethod(pkg));
initHook(new UnlockIme(), lpparam, isInputMethod(pkg));
}
public static void initHook(Hook hook, LoadPackageParam param, boolean needHook) {
if (needHook)
hook.runHook(param);
}
private List<String> getAppsUsingInputMethod(Context context) {
try {
if (context == null) { | package com.hchen.clipboardlist;
public class HookMain implements IXposedHookLoadPackage {
public static List<String> mAppsUsingInputMethod = new ArrayList<>();
@Override
public void handleLoadPackage(LoadPackageParam lpparam) {
if (mAppsUsingInputMethod.isEmpty()) {
mAppsUsingInputMethod = getAppsUsingInputMethod(Hook.findContext());
}
String pkg = lpparam.packageName;
initHook(new ClipboardList(), lpparam, isInputMethod(pkg));
initHook(new UnlockIme(), lpparam, isInputMethod(pkg));
}
public static void initHook(Hook hook, LoadPackageParam param, boolean needHook) {
if (needHook)
hook.runHook(param);
}
private List<String> getAppsUsingInputMethod(Context context) {
try {
if (context == null) { | Log.logE("getAppsUsingInputMethod", "context is null"); | 2 | 2023-12-22 15:07:33+00:00 | 12k |
danielfeitopin/MUNICS-SAPP-P1 | src/main/java/es/storeapp/web/controller/OrderController.java | [
{
"identifier": "CreditCard",
"path": "src/main/java/es/storeapp/business/entities/CreditCard.java",
"snippet": "@Embeddable\npublic class CreditCard implements Serializable {\n\n private String card;\n \n private Integer cvv;\n \n private Integer expirationMonth;\n \n private Integ... | import es.storeapp.business.entities.CreditCard;
import es.storeapp.business.entities.Order;
import es.storeapp.business.entities.Product;
import es.storeapp.business.entities.User;
import es.storeapp.business.exceptions.InstanceNotFoundException;
import es.storeapp.business.exceptions.InvalidStateException;
import es.storeapp.business.services.OrderService;
import es.storeapp.common.Constants;
import es.storeapp.web.exceptions.ErrorHandlingUtils;
import es.storeapp.web.forms.OrderForm;
import es.storeapp.web.forms.PaymentForm;
import es.storeapp.web.session.ShoppingCart;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import jakarta.servlet.http.HttpSession;
import jakarta.validation.Valid;
import es.storeapp.common.EscapingLoggerWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttribute;
import org.springframework.web.servlet.mvc.support.RedirectAttributes; | 7,678 | package es.storeapp.web.controller;
@Controller
public class OrderController {
private static final EscapingLoggerWrapper logger = new EscapingLoggerWrapper(OrderController.class);
@Autowired
private OrderService orderService;
@Autowired
private MessageSource messageSource;
@Autowired
ErrorHandlingUtils errorHandlingUtils;
@GetMapping(Constants.ORDERS_ENDPOINT) | package es.storeapp.web.controller;
@Controller
public class OrderController {
private static final EscapingLoggerWrapper logger = new EscapingLoggerWrapper(OrderController.class);
@Autowired
private OrderService orderService;
@Autowired
private MessageSource messageSource;
@Autowired
ErrorHandlingUtils errorHandlingUtils;
@GetMapping(Constants.ORDERS_ENDPOINT) | public String doGetOrdersPage(@SessionAttribute(Constants.USER_SESSION) User user, | 3 | 2023-12-24 19:24:49+00:00 | 12k |
RoderickQiu/SUSTech_CSE_Projects | CS109_2022_Fall/Chess/view/Chessboard.java | [
{
"identifier": "Main",
"path": "CS109_2022_Fall/Chess/Main.java",
"snippet": "public class Main {\r\n private static ChessGameFrame gameFrame = null;\r\n private static StartFrame startFrame = null;\r\n public static Font titleFont, sansFont, serifFont;\r\n public static String theme = \"像素... | import Chess.Main;
import Chess.chessComponent.*;
import Chess.model.*;
import Chess.controller.ClickController;
import Chess.utils.FileUtils;
import Chess.utils.GeneralUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import javax.swing.*;
import java.awt.*;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import static Chess.Main.*;
import static Chess.Main.data;
import static Chess.utils.GeneralUtils.addPrefixZero;
import static Chess.utils.ImageUtils.changeToOriginalSize;
| 7,331 | CHESS_SIZE = (height - 6) / 8;
SquareComponent.setSpacingLength(CHESS_SIZE / 7);
System.out.printf("chessboard [%d * %d], chess size = %d\n", width, height, CHESS_SIZE);
addReverseButton();
addCheatingButton();
initAllChessOnBoard();
}
private void initAllChessOnBoard() {
int a = 0;
for (int i = 0; i < squareComponents.length; i++) {
for (int j = 0; j < squareComponents[i].length; j++) {
int type = chooseChessType();
ChessColor color = type >= 7 ? ChessColor.RED : ChessColor.BLACK;
SquareComponent squareComponent = switch (type) {
case 0, 7 ->
new ShuaiComponent(new ChessboardPoint(i, j), calculatePoint(i, j), color, clickController, CHESS_SIZE);
case 1, 8 ->
new ShiComponent(new ChessboardPoint(i, j), calculatePoint(i, j), color, clickController, CHESS_SIZE);
case 2, 9 ->
new XiangComponent(new ChessboardPoint(i, j), calculatePoint(i, j), color, clickController, CHESS_SIZE);
case 3, 10 ->
new JuComponent(new ChessboardPoint(i, j), calculatePoint(i, j), color, clickController, CHESS_SIZE);
case 4, 11 ->
new MaComponent(new ChessboardPoint(i, j), calculatePoint(i, j), color, clickController, CHESS_SIZE);
case 5, 12 ->
new ZuComponent(new ChessboardPoint(i, j), calculatePoint(i, j), color, clickController, CHESS_SIZE);
case 6, 13 ->
new PaoComponent(new ChessboardPoint(i, j), calculatePoint(i, j), color, clickController, CHESS_SIZE);
default -> throw new IllegalStateException("Unexpected value: " + j);
};
//id 用颜色换掉
//camp category=100
//get isreversal (是否翻开
squareComponent.setVisible(true);
putChessOnBoard(squareComponent);
}
}
}
/**
* ***把被吃掉的棋子放进栈里存储,用来悔棋,存储状态;
*/
public SquareComponent[][] getChessComponents() {
return squareComponents;
}
public ChessColor getCurrentColor() {
return currentColor;
}
public void setCurrentColor(ChessColor currentColor) {
this.currentColor = currentColor;
if (ModeChoice == 0) {
this.playerColor = this.playerColor.equals(ChessColor.BLACK) ? ChessColor.RED : ChessColor.BLACK;
this.enemyColor = this.enemyColor.equals(ChessColor.BLACK) ? ChessColor.RED : ChessColor.BLACK;
}
}
public ChessColor getEnemyColor() {
return enemyColor;
}
public void setEnemyColor(ChessColor enemyColor) {
this.enemyColor = enemyColor;
}
public ChessColor getPlayerColor() {
return playerColor;
}
public void setPlayerColor(ChessColor playerColor) {
this.playerColor = playerColor;
}
/**
* 将SquareComponent 放置在 ChessBoard上。里面包含移除原有的component及放置新的component
*
* @param squareComponent
*/
public void putChessOnBoard(SquareComponent squareComponent) {
int row = squareComponent.getChessboardPoint().getX(), col = squareComponent.getChessboardPoint().getY();
if (squareComponents[row][col] != null) {
remove(squareComponents[row][col]);
}
add(squareComponents[row][col] = squareComponent);
}
/**
* 交换chess1 chess2的位置
*
* @param chess1
* @param chess2
*/
private int player_Score = 0;//玩家血量
private int com_Score = 0;//电脑血量
public void swapChessComponents(SquareComponent chess1, SquareComponent chess2) {
// Note that chess1 has higher priority, 'destroys' chess2 if exists.
if (chess1.canMoveTo(squareComponents, chess2.getChessboardPoint(), chess1.getChessboardPoint(), playerColor)) {
isEat[++q] = true;
System.out.print(chess2.getBlood());
if (chess2.getChessColor() == enemyColor) {
if (enemyColor.equals(ChessColor.BLACK)) {
player_Score += chess2.getBlood();
ChessGameFrame.appendBlackEatenLabel(chess2.getName());
} else {
com_Score += chess2.getBlood();
ChessGameFrame.appendRedEatenLabel(chess2.getName());
}
}
if (chess2.getChessColor() == playerColor) {
if (playerColor.equals(ChessColor.BLACK)) {
player_Score += chess2.getBlood();
ChessGameFrame.appendBlackEatenLabel(chess2.getName());
} else {
com_Score += chess2.getBlood();
ChessGameFrame.appendRedEatenLabel(chess2.getName());
}
}
| package Chess.view;
/**
* 这个类表示棋盘组建,其包含:
* SquareComponent[][]: 4*8个方块格子组件
*/
public class Chessboard extends JComponent {
public int ModeChoice;//0代表人人对战,1代表人机难度1,2代表人机难度2;
private final SquareComponent[][] squareComponents = new SquareComponent[ROW_SIZE][COL_SIZE];
//todo: you can change the initial player
private ChessColor currentColor = ChessColor.RED;
private ChessColor playerColor = ChessColor.RED;
private ChessColor enemyColor = ChessColor.BLACK;
//all chessComponents in this chessboard are shared only one Chess.model Chess.controller
public final ClickController clickController = new ClickController(this);
private final int CHESS_SIZE;
private int[] blackList = {0, 0, 0, 0, 0, 0, 0}, redList = {0, 0, 0, 0, 0, 0, 0};
private final int[] maxList = {1, 2, 2, 2, 2, 5, 2};
private boolean hasLost = false, isCheating = false;
private int num = 32;
public static final int ROW_SIZE = 8;
public static final int COL_SIZE = 4;
private static Stack<ChessboardPoint> stackX1 = new Stack<>();
private static Stack<ChessboardPoint> stackX2 = new Stack<>();
private static Stack<SquareComponent> stack1 = new Stack<>();
private static Stack<SquareComponent> stack2 = new Stack<>();
public static Stack<SquareComponent> Now = new Stack<>();
public static boolean isComReverse = false;
public boolean isPlayerDo = false;
private Gson gson = new Gson();
public boolean[] isEat = new boolean[320];
private int q = 0;
private Random random = new Random();
//所有棋子的定义都在这了
private ChessComponent[][] pieces = new ChessComponent[8][4];
public Chessboard(int width, int height, int mode) {
ModeChoice = mode;//0代表人人对战,1代表人机难度1,2代表人机难度2;
setLayout(null); // Use absolute layout.
setSize(width + 10, height);
CHESS_SIZE = (height - 6) / 8;
SquareComponent.setSpacingLength(CHESS_SIZE / 7);
System.out.printf("chessboard [%d * %d], chess size = %d\n", width, height, CHESS_SIZE);
addReverseButton();
addCheatingButton();
initAllChessOnBoard();
}
private void initAllChessOnBoard() {
int a = 0;
for (int i = 0; i < squareComponents.length; i++) {
for (int j = 0; j < squareComponents[i].length; j++) {
int type = chooseChessType();
ChessColor color = type >= 7 ? ChessColor.RED : ChessColor.BLACK;
SquareComponent squareComponent = switch (type) {
case 0, 7 ->
new ShuaiComponent(new ChessboardPoint(i, j), calculatePoint(i, j), color, clickController, CHESS_SIZE);
case 1, 8 ->
new ShiComponent(new ChessboardPoint(i, j), calculatePoint(i, j), color, clickController, CHESS_SIZE);
case 2, 9 ->
new XiangComponent(new ChessboardPoint(i, j), calculatePoint(i, j), color, clickController, CHESS_SIZE);
case 3, 10 ->
new JuComponent(new ChessboardPoint(i, j), calculatePoint(i, j), color, clickController, CHESS_SIZE);
case 4, 11 ->
new MaComponent(new ChessboardPoint(i, j), calculatePoint(i, j), color, clickController, CHESS_SIZE);
case 5, 12 ->
new ZuComponent(new ChessboardPoint(i, j), calculatePoint(i, j), color, clickController, CHESS_SIZE);
case 6, 13 ->
new PaoComponent(new ChessboardPoint(i, j), calculatePoint(i, j), color, clickController, CHESS_SIZE);
default -> throw new IllegalStateException("Unexpected value: " + j);
};
//id 用颜色换掉
//camp category=100
//get isreversal (是否翻开
squareComponent.setVisible(true);
putChessOnBoard(squareComponent);
}
}
}
/**
* ***把被吃掉的棋子放进栈里存储,用来悔棋,存储状态;
*/
public SquareComponent[][] getChessComponents() {
return squareComponents;
}
public ChessColor getCurrentColor() {
return currentColor;
}
public void setCurrentColor(ChessColor currentColor) {
this.currentColor = currentColor;
if (ModeChoice == 0) {
this.playerColor = this.playerColor.equals(ChessColor.BLACK) ? ChessColor.RED : ChessColor.BLACK;
this.enemyColor = this.enemyColor.equals(ChessColor.BLACK) ? ChessColor.RED : ChessColor.BLACK;
}
}
public ChessColor getEnemyColor() {
return enemyColor;
}
public void setEnemyColor(ChessColor enemyColor) {
this.enemyColor = enemyColor;
}
public ChessColor getPlayerColor() {
return playerColor;
}
public void setPlayerColor(ChessColor playerColor) {
this.playerColor = playerColor;
}
/**
* 将SquareComponent 放置在 ChessBoard上。里面包含移除原有的component及放置新的component
*
* @param squareComponent
*/
public void putChessOnBoard(SquareComponent squareComponent) {
int row = squareComponent.getChessboardPoint().getX(), col = squareComponent.getChessboardPoint().getY();
if (squareComponents[row][col] != null) {
remove(squareComponents[row][col]);
}
add(squareComponents[row][col] = squareComponent);
}
/**
* 交换chess1 chess2的位置
*
* @param chess1
* @param chess2
*/
private int player_Score = 0;//玩家血量
private int com_Score = 0;//电脑血量
public void swapChessComponents(SquareComponent chess1, SquareComponent chess2) {
// Note that chess1 has higher priority, 'destroys' chess2 if exists.
if (chess1.canMoveTo(squareComponents, chess2.getChessboardPoint(), chess1.getChessboardPoint(), playerColor)) {
isEat[++q] = true;
System.out.print(chess2.getBlood());
if (chess2.getChessColor() == enemyColor) {
if (enemyColor.equals(ChessColor.BLACK)) {
player_Score += chess2.getBlood();
ChessGameFrame.appendBlackEatenLabel(chess2.getName());
} else {
com_Score += chess2.getBlood();
ChessGameFrame.appendRedEatenLabel(chess2.getName());
}
}
if (chess2.getChessColor() == playerColor) {
if (playerColor.equals(ChessColor.BLACK)) {
player_Score += chess2.getBlood();
ChessGameFrame.appendBlackEatenLabel(chess2.getName());
} else {
com_Score += chess2.getBlood();
ChessGameFrame.appendRedEatenLabel(chess2.getName());
}
}
| ChessGameFrame.getScoreLabel().setText(addPrefixZero(player_Score) + " - " + addPrefixZero(com_Score));
| 6 | 2023-12-31 05:50:13+00:00 | 12k |
psobiech/opengr8on | lib/src/main/java/pl/psobiech/opengr8on/client/Client.java | [
{
"identifier": "DiscoverCLUsCommand",
"path": "lib/src/main/java/pl/psobiech/opengr8on/client/commands/DiscoverCLUsCommand.java",
"snippet": "public class DiscoverCLUsCommand {\n private static final int HASH_MOD_A = 0x0D;\n\n private static final int HASH_MOD_B = 0x13;\n\n private DiscoverCLU... | import java.io.Closeable;
import java.net.DatagramPacket;
import java.net.Inet4Address;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Queue;
import java.util.Spliterators.AbstractSpliterator;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.Future.State;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pl.psobiech.opengr8on.client.commands.DiscoverCLUsCommand;
import pl.psobiech.opengr8on.client.device.CLUDevice;
import pl.psobiech.opengr8on.util.IPv4AddressUtil;
import pl.psobiech.opengr8on.util.RandomUtil;
import pl.psobiech.opengr8on.util.SocketUtil;
import pl.psobiech.opengr8on.util.SocketUtil.Payload;
import pl.psobiech.opengr8on.util.SocketUtil.UDPSocket;
import pl.psobiech.opengr8on.util.ThreadUtil; | 9,737 | /*
* OpenGr8on, open source extensions to systems based on Grenton devices
* Copyright (C) 2023 Piotr Sobiech
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package pl.psobiech.opengr8on.client;
public class Client implements Closeable {
private static final Logger LOGGER = LoggerFactory.getLogger(Client.class);
public static final int COMMAND_PORT = 1234;
private static final int BUFFER_SIZE = 2048;
private static final int ESTIMATED_CLUS = 8;
private final DatagramPacket responsePacket = new DatagramPacket(new byte[BUFFER_SIZE], BUFFER_SIZE);
protected final ReentrantLock socketLock = new ReentrantLock();
protected final UDPSocket socket;
private final ExecutorService executor = ThreadUtil.executor("cluClient");
protected final Inet4Address localAddress;
private final Inet4Address broadcastAddress;
private final int port;
public Client(Inet4Address localAddress) {
this(localAddress, IPv4AddressUtil.BROADCAST_ADDRESS, COMMAND_PORT);
}
public Client(Inet4Address localAddress, Inet4Address broadcastAddress, int port) {
this.localAddress = localAddress;
this.broadcastAddress = broadcastAddress;
this.port = port;
this.socket = SocketUtil.udpRandomPort(localAddress);
this.socket.open();
}
public Stream<CLUDevice> discover(CipherKey projectCipherKey, Map<Long, byte[]> privateKeys, Duration timeout, int limit) { | /*
* OpenGr8on, open source extensions to systems based on Grenton devices
* Copyright (C) 2023 Piotr Sobiech
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package pl.psobiech.opengr8on.client;
public class Client implements Closeable {
private static final Logger LOGGER = LoggerFactory.getLogger(Client.class);
public static final int COMMAND_PORT = 1234;
private static final int BUFFER_SIZE = 2048;
private static final int ESTIMATED_CLUS = 8;
private final DatagramPacket responsePacket = new DatagramPacket(new byte[BUFFER_SIZE], BUFFER_SIZE);
protected final ReentrantLock socketLock = new ReentrantLock();
protected final UDPSocket socket;
private final ExecutorService executor = ThreadUtil.executor("cluClient");
protected final Inet4Address localAddress;
private final Inet4Address broadcastAddress;
private final int port;
public Client(Inet4Address localAddress) {
this(localAddress, IPv4AddressUtil.BROADCAST_ADDRESS, COMMAND_PORT);
}
public Client(Inet4Address localAddress, Inet4Address broadcastAddress, int port) {
this.localAddress = localAddress;
this.broadcastAddress = broadcastAddress;
this.port = port;
this.socket = SocketUtil.udpRandomPort(localAddress);
this.socket.open();
}
public Stream<CLUDevice> discover(CipherKey projectCipherKey, Map<Long, byte[]> privateKeys, Duration timeout, int limit) { | final byte[] randomBytes = RandomUtil.bytes(Command.RANDOM_SIZE); | 3 | 2023-12-23 09:56:14+00:00 | 12k |
Pigmice2733/frc-2024 | src/main/java/frc/robot/subsystems/Vision.java | [
{
"identifier": "Constants",
"path": "src/main/java/frc/robot/Constants.java",
"snippet": "public final class Constants {\n public static final ShuffleboardTab DRIVER_TAB = Shuffleboard.getTab(\"Driver\");\n public static final ShuffleboardTab SWERVE_TAB = Shuffleboard.getTab(\"Drivetrain\");\n ... | import com.pigmice.frc.lib.shuffleboard_helper.ShuffleboardHelper;
import edu.wpi.first.math.geometry.Pose2d;
import edu.wpi.first.wpilibj2.command.SubsystemBase;
import frc.robot.Constants;
import frc.robot.LimelightHelpers;
import frc.robot.Constants.VisionConfig;
import frc.robot.LimelightHelpers.LimelightResults;
import frc.robot.LimelightHelpers.LimelightTarget_Fiducial;
import frc.robot.LimelightHelpers.Results; | 10,303 | package frc.robot.subsystems;
public class Vision extends SubsystemBase {
private static String camName = VisionConfig.CAM_NAME;
private Results targetingResults;
private LimelightTarget_Fiducial bestTarget;
private boolean hasTarget;
public Vision() {
ShuffleboardHelper.addOutput("Target X", Constants.VISION_TAB,
() -> bestTarget == null ? 0 : bestTarget.tx);
ShuffleboardHelper.addOutput("Target Y", Constants.VISION_TAB,
() -> bestTarget == null ? 0 : bestTarget.ty);
ShuffleboardHelper.addOutput("Bot Pose X", Constants.VISION_TAB,
() -> targetingResults == null ? 0 : getEstimatedRobotPose().getX());
ShuffleboardHelper.addOutput("Bot Pose Y", Constants.VISION_TAB,
() -> targetingResults == null ? 0 : getEstimatedRobotPose().getY());
ShuffleboardHelper.addOutput("Pose to tag X", Constants.VISION_TAB,
() -> targetingResults == null ? 0 : getTranslationToBestTarget().getX());
ShuffleboardHelper.addOutput("Pose to tag Y", Constants.VISION_TAB,
() -> targetingResults == null ? 0 : getTranslationToBestTarget().getY());
}
@Override
public void periodic() { | package frc.robot.subsystems;
public class Vision extends SubsystemBase {
private static String camName = VisionConfig.CAM_NAME;
private Results targetingResults;
private LimelightTarget_Fiducial bestTarget;
private boolean hasTarget;
public Vision() {
ShuffleboardHelper.addOutput("Target X", Constants.VISION_TAB,
() -> bestTarget == null ? 0 : bestTarget.tx);
ShuffleboardHelper.addOutput("Target Y", Constants.VISION_TAB,
() -> bestTarget == null ? 0 : bestTarget.ty);
ShuffleboardHelper.addOutput("Bot Pose X", Constants.VISION_TAB,
() -> targetingResults == null ? 0 : getEstimatedRobotPose().getX());
ShuffleboardHelper.addOutput("Bot Pose Y", Constants.VISION_TAB,
() -> targetingResults == null ? 0 : getEstimatedRobotPose().getY());
ShuffleboardHelper.addOutput("Pose to tag X", Constants.VISION_TAB,
() -> targetingResults == null ? 0 : getTranslationToBestTarget().getX());
ShuffleboardHelper.addOutput("Pose to tag Y", Constants.VISION_TAB,
() -> targetingResults == null ? 0 : getTranslationToBestTarget().getY());
}
@Override
public void periodic() { | LimelightResults results = LimelightHelpers.getLatestResults(camName); | 1 | 2023-12-30 06:06:45+00:00 | 12k |
Deenu143/GradleParser | app/src/main/java/org/deenu/gradle/script/GradleScript.java | [
{
"identifier": "Dependency",
"path": "app/src/main/java/org/deenu/gradle/models/Dependency.java",
"snippet": "public class Dependency {\n\n private String configuration;\n private String group;\n private String name;\n private String version;\n\n public Dependency(String group, String name, String... | import java.io.File;
import java.io.FileNotFoundException;
import java.nio.file.Files;
import java.util.List;
import org.codehaus.groovy.ast.ASTNode;
import org.codehaus.groovy.ast.GroovyCodeVisitor;
import org.codehaus.groovy.ast.builder.AstBuilder;
import org.deenu.gradle.models.Dependency;
import org.deenu.gradle.models.FlatDir;
import org.deenu.gradle.models.Include;
import org.deenu.gradle.models.Plugin;
import org.deenu.gradle.models.Repository;
import org.deenu.gradle.parser.exception.UnsupportedFileException;
import org.deenu.gradle.script.visitors.GradleScriptVisitor; | 8,217 | package org.deenu.gradle.script;
public class GradleScript {
private File gradleFile;
private AstBuilder astBuilder;
private List<ASTNode> aSTNodes;
private String scriptContents;
private GradleScriptVisitor gradleScriptVisitor;
public GradleScript(File gradleFile) throws Exception, FileNotFoundException {
this.gradleFile = gradleFile;
if (gradleFile == null || !gradleFile.exists()) {
throw new FileNotFoundException("Failed to get '.gradle' or '.gradle.kts' file.");
} else if (gradleFile != null) {
String fileName = gradleFile.getName();
String[] fileExtensions = new String[] {".gradle", ".gradle.kts"};
if (fileName != null) {
if (!fileName.endsWith(fileExtensions[0]) && !fileName.endsWith(fileExtensions[1])) {
throw new UnsupportedFileException("Unsupported file: " + gradleFile.getAbsolutePath());
}
}
}
this.scriptContents = new String(Files.readAllBytes(this.gradleFile.toPath()));
init(scriptContents, gradleFile);
}
private void init(String script, File gradleFile) throws Exception {
if (script == null || script.isEmpty()) {
throw new Exception("Failed to get gradle script from file: " + gradleFile.getAbsolutePath());
}
this.astBuilder = new AstBuilder();
this.aSTNodes = getASTNodes();
}
public File getGradleFile() {
return this.gradleFile;
}
public String getGradleFileName() {
return this.gradleFile.getName();
}
public boolean isGradleBuildFile() {
return getGradleFileName().startsWith("build.gradle");
}
public boolean isGradleSettingsFile() {
return getGradleFileName().startsWith("settings.gradle");
}
private List<ASTNode> getASTNodes() throws Exception {
return this.astBuilder.buildFromString(scriptContents);
}
public List<Plugin> getPlugins() {
this.gradleScriptVisitor = new GradleScriptVisitor();
walkScript(gradleScriptVisitor);
return this.gradleScriptVisitor.getPlugins();
}
| package org.deenu.gradle.script;
public class GradleScript {
private File gradleFile;
private AstBuilder astBuilder;
private List<ASTNode> aSTNodes;
private String scriptContents;
private GradleScriptVisitor gradleScriptVisitor;
public GradleScript(File gradleFile) throws Exception, FileNotFoundException {
this.gradleFile = gradleFile;
if (gradleFile == null || !gradleFile.exists()) {
throw new FileNotFoundException("Failed to get '.gradle' or '.gradle.kts' file.");
} else if (gradleFile != null) {
String fileName = gradleFile.getName();
String[] fileExtensions = new String[] {".gradle", ".gradle.kts"};
if (fileName != null) {
if (!fileName.endsWith(fileExtensions[0]) && !fileName.endsWith(fileExtensions[1])) {
throw new UnsupportedFileException("Unsupported file: " + gradleFile.getAbsolutePath());
}
}
}
this.scriptContents = new String(Files.readAllBytes(this.gradleFile.toPath()));
init(scriptContents, gradleFile);
}
private void init(String script, File gradleFile) throws Exception {
if (script == null || script.isEmpty()) {
throw new Exception("Failed to get gradle script from file: " + gradleFile.getAbsolutePath());
}
this.astBuilder = new AstBuilder();
this.aSTNodes = getASTNodes();
}
public File getGradleFile() {
return this.gradleFile;
}
public String getGradleFileName() {
return this.gradleFile.getName();
}
public boolean isGradleBuildFile() {
return getGradleFileName().startsWith("build.gradle");
}
public boolean isGradleSettingsFile() {
return getGradleFileName().startsWith("settings.gradle");
}
private List<ASTNode> getASTNodes() throws Exception {
return this.astBuilder.buildFromString(scriptContents);
}
public List<Plugin> getPlugins() {
this.gradleScriptVisitor = new GradleScriptVisitor();
walkScript(gradleScriptVisitor);
return this.gradleScriptVisitor.getPlugins();
}
| public List<Repository> getRepositories() { | 4 | 2023-12-27 10:10:31+00:00 | 12k |
Prototik/TheConfigLib | common/src/main/java/dev/tcl/gui/controllers/ColorController.java | [
{
"identifier": "Option",
"path": "common/src/main/java/dev/tcl/api/Option.java",
"snippet": "public interface Option<T> {\n /**\n * Name of the option\n */\n @NotNull Component name();\n\n @NotNull OptionDescription description();\n\n /**\n * Widget provider for a type of option... | import com.google.common.collect.ImmutableList;
import dev.tcl.api.Option;
import dev.tcl.api.utils.Dimension;
import dev.tcl.api.utils.MutableDimension;
import dev.tcl.gui.controllers.string.IStringController;
import dev.tcl.gui.controllers.string.StringControllerElement;
import dev.tcl.gui.AbstractWidget;
import dev.tcl.gui.TCLScreen;
import net.minecraft.ChatFormatting;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.MutableComponent;
import java.awt.*;
import java.util.List; | 9,961 | package dev.tcl.gui.controllers;
/**
* A color controller that uses a hex color field as input.
*/
public class ColorController implements IStringController<Color> {
private final Option<Color> option;
private final boolean allowAlpha;
/**
* Constructs a color controller with {@link ColorController#allowAlpha()} defaulting to false
*
* @param option bound option
*/
public ColorController(Option<Color> option) {
this(option, false);
}
/**
* Constructs a color controller
*
* @param option bound option
* @param allowAlpha allows the color input to accept alpha values
*/
public ColorController(Option<Color> option, boolean allowAlpha) {
this.option = option;
this.allowAlpha = allowAlpha;
}
/**
* {@inheritDoc}
*/
@Override
public Option<Color> option() {
return option;
}
public boolean allowAlpha() {
return allowAlpha;
}
@Override
public String getString() {
return formatValue().getString();
}
@Override
public Component formatValue() {
MutableComponent text = Component.literal("#");
text.append(Component.literal(toHex(option().pendingValue().getRed())).withStyle(ChatFormatting.RED));
text.append(Component.literal(toHex(option().pendingValue().getGreen())).withStyle(ChatFormatting.GREEN));
text.append(Component.literal(toHex(option().pendingValue().getBlue())).withStyle(ChatFormatting.BLUE));
if (allowAlpha()) text.append(toHex(option().pendingValue().getAlpha()));
return text;
}
private String toHex(int value) {
String hex = Integer.toString(value, 16).toUpperCase();
if (hex.length() == 1)
hex = "0" + hex;
return hex;
}
@Override
public void setFromString(String value) {
if (value.startsWith("#"))
value = value.substring(1);
int red = Integer.parseInt(value.substring(0, 2), 16);
int green = Integer.parseInt(value.substring(2, 4), 16);
int blue = Integer.parseInt(value.substring(4, 6), 16);
if (allowAlpha()) {
int alpha = Integer.parseInt(value.substring(6, 8), 16);
option().requestSet(new Color(red, green, blue, alpha));
} else {
option().requestSet(new Color(red, green, blue));
}
}
@Override
public AbstractWidget provideWidget(TCLScreen screen, dev.tcl.api.utils.Dimension<Integer> widgetDimension) {
return new ColorControllerElement(this, screen, widgetDimension);
}
| package dev.tcl.gui.controllers;
/**
* A color controller that uses a hex color field as input.
*/
public class ColorController implements IStringController<Color> {
private final Option<Color> option;
private final boolean allowAlpha;
/**
* Constructs a color controller with {@link ColorController#allowAlpha()} defaulting to false
*
* @param option bound option
*/
public ColorController(Option<Color> option) {
this(option, false);
}
/**
* Constructs a color controller
*
* @param option bound option
* @param allowAlpha allows the color input to accept alpha values
*/
public ColorController(Option<Color> option, boolean allowAlpha) {
this.option = option;
this.allowAlpha = allowAlpha;
}
/**
* {@inheritDoc}
*/
@Override
public Option<Color> option() {
return option;
}
public boolean allowAlpha() {
return allowAlpha;
}
@Override
public String getString() {
return formatValue().getString();
}
@Override
public Component formatValue() {
MutableComponent text = Component.literal("#");
text.append(Component.literal(toHex(option().pendingValue().getRed())).withStyle(ChatFormatting.RED));
text.append(Component.literal(toHex(option().pendingValue().getGreen())).withStyle(ChatFormatting.GREEN));
text.append(Component.literal(toHex(option().pendingValue().getBlue())).withStyle(ChatFormatting.BLUE));
if (allowAlpha()) text.append(toHex(option().pendingValue().getAlpha()));
return text;
}
private String toHex(int value) {
String hex = Integer.toString(value, 16).toUpperCase();
if (hex.length() == 1)
hex = "0" + hex;
return hex;
}
@Override
public void setFromString(String value) {
if (value.startsWith("#"))
value = value.substring(1);
int red = Integer.parseInt(value.substring(0, 2), 16);
int green = Integer.parseInt(value.substring(2, 4), 16);
int blue = Integer.parseInt(value.substring(4, 6), 16);
if (allowAlpha()) {
int alpha = Integer.parseInt(value.substring(6, 8), 16);
option().requestSet(new Color(red, green, blue, alpha));
} else {
option().requestSet(new Color(red, green, blue));
}
}
@Override
public AbstractWidget provideWidget(TCLScreen screen, dev.tcl.api.utils.Dimension<Integer> widgetDimension) {
return new ColorControllerElement(this, screen, widgetDimension);
}
| public static class ColorControllerElement extends StringControllerElement { | 4 | 2023-12-25 14:48:27+00:00 | 12k |
Man2Dev/N-Queen | lib/jfreechart-1.0.19/tests/org/jfree/chart/renderer/xy/CandlestickRendererTest.java | [
{
"identifier": "TestUtilities",
"path": "lib/jfreechart-1.0.19/tests/org/jfree/chart/TestUtilities.java",
"snippet": "public class TestUtilities {\n\n /**\n * Returns <code>true</code> if the collections contains any object that\n * is an instance of the specified class, and <code>false</cod... | import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import java.awt.Color;
import java.awt.GradientPaint;
import java.util.Date;
import org.jfree.chart.TestUtilities;
import org.jfree.data.Range;
import org.jfree.data.xy.DefaultOHLCDataset;
import org.jfree.data.xy.OHLCDataItem;
import org.jfree.data.xy.OHLCDataset;
import org.jfree.util.PublicCloneable; | 9,403 | /* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2013, by Object Refinery Limited and Contributors.
*
* Project Info: http://www.jfree.org/jfreechart/index.html
*
* 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, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* [Oracle and Java are registered trademarks of Oracle and/or its affiliates.
* Other names may be trademarks of their respective owners.]
*
* ----------------------------
* CandlestickRendererTest.java
* ----------------------------
* (C) Copyright 2003-2013, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 25-Mar-2003 : Version 1 (DG);
* 22-Oct-2003 : Added hashCode test (DG);
* 17-Aug-2006 : Strengthened testEquals() and added testFindRangeBounds()
* method (DG);
* 05-Mar-2007 : Added new field to testEquals() (DG);
* 08-Oct-2007 : Added tests for new volumePaint field (DG);
* 22-Apr-2008 : Added testPublicCloneable() (DG);
*
*/
package org.jfree.chart.renderer.xy;
/**
* Tests for the {@link CandlestickRenderer} class.
*/
public class CandlestickRendererTest {
private static final double EPSILON = 0.0000000001;
/**
* Some checks for the constructor.
*/
@Test
public void testConstructor() {
CandlestickRenderer r1 = new CandlestickRenderer();
// check defaults
assertEquals(Color.green, r1.getUpPaint());
assertEquals(Color.red, r1.getDownPaint());
assertFalse(r1.getUseOutlinePaint());
assertTrue(r1.getDrawVolume());
assertEquals(Color.gray, r1.getVolumePaint());
assertEquals(-1.0, r1.getCandleWidth(), EPSILON);
}
/**
* Check that the equals() method distinguishes all fields.
*/
@Test
public void testEquals() {
CandlestickRenderer r1 = new CandlestickRenderer();
CandlestickRenderer r2 = new CandlestickRenderer();
assertEquals(r1, r2);
// upPaint
r1.setUpPaint(new GradientPaint(1.0f, 2.0f, Color.red, 3.0f, 4.0f,
Color.white));
assertFalse(r1.equals(r2));
r2.setUpPaint(new GradientPaint(1.0f, 2.0f, Color.red, 3.0f, 4.0f,
Color.white));
assertTrue(r1.equals(r2));
// downPaint
r1.setDownPaint(new GradientPaint(5.0f, 6.0f, Color.green, 7.0f, 8.0f,
Color.yellow));
assertFalse(r1.equals(r2));
r2.setDownPaint(new GradientPaint(5.0f, 6.0f, Color.green, 7.0f, 8.0f,
Color.yellow));
assertTrue(r1.equals(r2));
// drawVolume
r1.setDrawVolume(false);
assertFalse(r1.equals(r2));
r2.setDrawVolume(false);
assertTrue(r1.equals(r2));
// candleWidth
r1.setCandleWidth(3.3);
assertFalse(r1.equals(r2));
r2.setCandleWidth(3.3);
assertTrue(r1.equals(r2));
// maxCandleWidthInMilliseconds
r1.setMaxCandleWidthInMilliseconds(123);
assertFalse(r1.equals(r2));
r2.setMaxCandleWidthInMilliseconds(123);
assertTrue(r1.equals(r2));
// autoWidthMethod
r1.setAutoWidthMethod(CandlestickRenderer.WIDTHMETHOD_SMALLEST);
assertFalse(r1.equals(r2));
r2.setAutoWidthMethod(CandlestickRenderer.WIDTHMETHOD_SMALLEST);
assertTrue(r1.equals(r2));
// autoWidthFactor
r1.setAutoWidthFactor(0.22);
assertFalse(r1.equals(r2));
r2.setAutoWidthFactor(0.22);
assertTrue(r1.equals(r2));
// autoWidthGap
r1.setAutoWidthGap(1.1);
assertFalse(r1.equals(r2));
r2.setAutoWidthGap(1.1);
assertTrue(r1.equals(r2));
r1.setUseOutlinePaint(true);
assertFalse(r1.equals(r2));
r2.setUseOutlinePaint(true);
assertTrue(r1.equals(r2));
r1.setVolumePaint(Color.blue);
assertFalse(r1.equals(r2));
r2.setVolumePaint(Color.blue);
assertTrue(r1.equals(r2));
}
/**
* Two objects that are equal are required to return the same hashCode.
*/
@Test
public void testHashcode() {
CandlestickRenderer r1 = new CandlestickRenderer();
CandlestickRenderer r2 = new CandlestickRenderer();
assertTrue(r1.equals(r2));
int h1 = r1.hashCode();
int h2 = r2.hashCode();
assertEquals(h1, h2);
}
/**
* Confirm that cloning works.
*/
@Test
public void testCloning() throws CloneNotSupportedException {
CandlestickRenderer r1 = new CandlestickRenderer();
CandlestickRenderer r2 = (CandlestickRenderer) r1.clone();
assertTrue(r1 != r2);
assertTrue(r1.getClass() == r2.getClass());
assertTrue(r1.equals(r2));
}
/**
* Verify that this class implements {@link PublicCloneable}.
*/
@Test
public void testPublicCloneable() {
CandlestickRenderer r1 = new CandlestickRenderer();
assertTrue(r1 instanceof PublicCloneable);
}
/**
* Serialize an instance, restore it, and check for equality.
*/
@Test
public void testSerialization() {
CandlestickRenderer r1 = new CandlestickRenderer();
CandlestickRenderer r2 = (CandlestickRenderer)
TestUtilities.serialised(r1);
assertEquals(r1, r2);
}
/**
* Some checks for the findRangeBounds() method.
*/
@Test
public void testFindRangeBounds() {
CandlestickRenderer renderer = new CandlestickRenderer();
OHLCDataItem item1 = new OHLCDataItem(new Date(1L), 2.0, 4.0, 1.0, 3.0,
100); | /* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2013, by Object Refinery Limited and Contributors.
*
* Project Info: http://www.jfree.org/jfreechart/index.html
*
* 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, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* [Oracle and Java are registered trademarks of Oracle and/or its affiliates.
* Other names may be trademarks of their respective owners.]
*
* ----------------------------
* CandlestickRendererTest.java
* ----------------------------
* (C) Copyright 2003-2013, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 25-Mar-2003 : Version 1 (DG);
* 22-Oct-2003 : Added hashCode test (DG);
* 17-Aug-2006 : Strengthened testEquals() and added testFindRangeBounds()
* method (DG);
* 05-Mar-2007 : Added new field to testEquals() (DG);
* 08-Oct-2007 : Added tests for new volumePaint field (DG);
* 22-Apr-2008 : Added testPublicCloneable() (DG);
*
*/
package org.jfree.chart.renderer.xy;
/**
* Tests for the {@link CandlestickRenderer} class.
*/
public class CandlestickRendererTest {
private static final double EPSILON = 0.0000000001;
/**
* Some checks for the constructor.
*/
@Test
public void testConstructor() {
CandlestickRenderer r1 = new CandlestickRenderer();
// check defaults
assertEquals(Color.green, r1.getUpPaint());
assertEquals(Color.red, r1.getDownPaint());
assertFalse(r1.getUseOutlinePaint());
assertTrue(r1.getDrawVolume());
assertEquals(Color.gray, r1.getVolumePaint());
assertEquals(-1.0, r1.getCandleWidth(), EPSILON);
}
/**
* Check that the equals() method distinguishes all fields.
*/
@Test
public void testEquals() {
CandlestickRenderer r1 = new CandlestickRenderer();
CandlestickRenderer r2 = new CandlestickRenderer();
assertEquals(r1, r2);
// upPaint
r1.setUpPaint(new GradientPaint(1.0f, 2.0f, Color.red, 3.0f, 4.0f,
Color.white));
assertFalse(r1.equals(r2));
r2.setUpPaint(new GradientPaint(1.0f, 2.0f, Color.red, 3.0f, 4.0f,
Color.white));
assertTrue(r1.equals(r2));
// downPaint
r1.setDownPaint(new GradientPaint(5.0f, 6.0f, Color.green, 7.0f, 8.0f,
Color.yellow));
assertFalse(r1.equals(r2));
r2.setDownPaint(new GradientPaint(5.0f, 6.0f, Color.green, 7.0f, 8.0f,
Color.yellow));
assertTrue(r1.equals(r2));
// drawVolume
r1.setDrawVolume(false);
assertFalse(r1.equals(r2));
r2.setDrawVolume(false);
assertTrue(r1.equals(r2));
// candleWidth
r1.setCandleWidth(3.3);
assertFalse(r1.equals(r2));
r2.setCandleWidth(3.3);
assertTrue(r1.equals(r2));
// maxCandleWidthInMilliseconds
r1.setMaxCandleWidthInMilliseconds(123);
assertFalse(r1.equals(r2));
r2.setMaxCandleWidthInMilliseconds(123);
assertTrue(r1.equals(r2));
// autoWidthMethod
r1.setAutoWidthMethod(CandlestickRenderer.WIDTHMETHOD_SMALLEST);
assertFalse(r1.equals(r2));
r2.setAutoWidthMethod(CandlestickRenderer.WIDTHMETHOD_SMALLEST);
assertTrue(r1.equals(r2));
// autoWidthFactor
r1.setAutoWidthFactor(0.22);
assertFalse(r1.equals(r2));
r2.setAutoWidthFactor(0.22);
assertTrue(r1.equals(r2));
// autoWidthGap
r1.setAutoWidthGap(1.1);
assertFalse(r1.equals(r2));
r2.setAutoWidthGap(1.1);
assertTrue(r1.equals(r2));
r1.setUseOutlinePaint(true);
assertFalse(r1.equals(r2));
r2.setUseOutlinePaint(true);
assertTrue(r1.equals(r2));
r1.setVolumePaint(Color.blue);
assertFalse(r1.equals(r2));
r2.setVolumePaint(Color.blue);
assertTrue(r1.equals(r2));
}
/**
* Two objects that are equal are required to return the same hashCode.
*/
@Test
public void testHashcode() {
CandlestickRenderer r1 = new CandlestickRenderer();
CandlestickRenderer r2 = new CandlestickRenderer();
assertTrue(r1.equals(r2));
int h1 = r1.hashCode();
int h2 = r2.hashCode();
assertEquals(h1, h2);
}
/**
* Confirm that cloning works.
*/
@Test
public void testCloning() throws CloneNotSupportedException {
CandlestickRenderer r1 = new CandlestickRenderer();
CandlestickRenderer r2 = (CandlestickRenderer) r1.clone();
assertTrue(r1 != r2);
assertTrue(r1.getClass() == r2.getClass());
assertTrue(r1.equals(r2));
}
/**
* Verify that this class implements {@link PublicCloneable}.
*/
@Test
public void testPublicCloneable() {
CandlestickRenderer r1 = new CandlestickRenderer();
assertTrue(r1 instanceof PublicCloneable);
}
/**
* Serialize an instance, restore it, and check for equality.
*/
@Test
public void testSerialization() {
CandlestickRenderer r1 = new CandlestickRenderer();
CandlestickRenderer r2 = (CandlestickRenderer)
TestUtilities.serialised(r1);
assertEquals(r1, r2);
}
/**
* Some checks for the findRangeBounds() method.
*/
@Test
public void testFindRangeBounds() {
CandlestickRenderer renderer = new CandlestickRenderer();
OHLCDataItem item1 = new OHLCDataItem(new Date(1L), 2.0, 4.0, 1.0, 3.0,
100); | OHLCDataset dataset = new DefaultOHLCDataset("S1", | 4 | 2023-12-24 12:36:47+00:00 | 12k |
CodecNomad/MayOBees | src/main/java/com/github/may2beez/mayobees/module/impl/other/Dev.java | [
{
"identifier": "MayOBeesConfig",
"path": "src/main/java/com/github/may2beez/mayobees/config/MayOBeesConfig.java",
"snippet": "public class MayOBeesConfig extends Config {\n\n //<editor-fold desc=\"COMBAT\">\n @KeyBind(\n name = \"Shortbow Aura\",\n description = \"Automatica... | import com.github.may2beez.mayobees.config.MayOBeesConfig;
import com.github.may2beez.mayobees.module.IModule;
import com.github.may2beez.mayobees.util.LogUtils;
import com.github.may2beez.mayobees.util.TablistUtils;
import net.minecraft.client.Minecraft;
import java.io.FileWriter;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List; | 9,036 | package com.github.may2beez.mayobees.module.impl.other;
public class Dev implements IModule {
private static Dev instance;
public static Dev getInstance() {
if (instance == null) {
instance = new Dev();
}
return instance;
}
@Override
public String getName() {
return "Dev";
}
private final Minecraft mc = Minecraft.getMinecraft();
@Override
public boolean isRunning() {
return false;
}
//<editor-fold desc="Tablist">
public static List<String> transposeList(List<String> originalTable, int numRows, int numCols) {
List<String> transposedTable = new ArrayList<>();
for (int col = 0; col < numCols; col++) {
StringBuilder sb = new StringBuilder();
for (int row = 0; row < numRows; row++) {
int index = row * numCols + col;
String originalRow = originalTable.get(index);
sb.append(originalRow).append("\n");
}
transposedTable.add(sb.toString());
}
return transposedTable;
}
public void getTablist() {
if (mc.thePlayer == null || mc.theWorld == null)
return;
if (TablistUtils.getTabListPlayersUnprocessed().isEmpty()) { | package com.github.may2beez.mayobees.module.impl.other;
public class Dev implements IModule {
private static Dev instance;
public static Dev getInstance() {
if (instance == null) {
instance = new Dev();
}
return instance;
}
@Override
public String getName() {
return "Dev";
}
private final Minecraft mc = Minecraft.getMinecraft();
@Override
public boolean isRunning() {
return false;
}
//<editor-fold desc="Tablist">
public static List<String> transposeList(List<String> originalTable, int numRows, int numCols) {
List<String> transposedTable = new ArrayList<>();
for (int col = 0; col < numCols; col++) {
StringBuilder sb = new StringBuilder();
for (int row = 0; row < numRows; row++) {
int index = row * numCols + col;
String originalRow = originalTable.get(index);
sb.append(originalRow).append("\n");
}
transposedTable.add(sb.toString());
}
return transposedTable;
}
public void getTablist() {
if (mc.thePlayer == null || mc.theWorld == null)
return;
if (TablistUtils.getTabListPlayersUnprocessed().isEmpty()) { | LogUtils.debug("Tablist is empty!"); | 2 | 2023-12-24 15:39:11+00:00 | 12k |
viceice/verbrauchsapp | app/src/main/java/de/anipe/verbrauchsapp/fragments/CarListFragment.java | [
{
"identifier": "CarInputActivity",
"path": "app/src/main/java/de/anipe/verbrauchsapp/CarInputActivity.java",
"snippet": "public class CarInputActivity extends AppCompatActivity {\n\n private ConsumptionDataSource dataSource;\n private FileSystemAccessor accessor;\n private long carId;\n pri... | import android.app.Activity;
import android.app.ActivityOptions;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import de.anipe.verbrauchsapp.CarInputActivity;
import de.anipe.verbrauchsapp.MainActivity;
import de.anipe.verbrauchsapp.R;
import de.anipe.verbrauchsapp.adapters.CarListAdapter;
import de.anipe.verbrauchsapp.adapters.IOnCarSelected;
import de.anipe.verbrauchsapp.db.ConsumptionDataSource;
import de.anipe.verbrauchsapp.objects.Car;
import de.anipe.verbrauchsapp.support.DividerItemDecoration; | 8,260 | package de.anipe.verbrauchsapp.fragments;
public class CarListFragment extends Fragment implements IOnCarSelected {
private ConsumptionDataSource dataSource; | package de.anipe.verbrauchsapp.fragments;
public class CarListFragment extends Fragment implements IOnCarSelected {
private ConsumptionDataSource dataSource; | private CarListAdapter adapter; | 2 | 2023-12-28 12:33:52+00:00 | 12k |
strokegmd/StrokeClient | stroke/client/modules/render/StorageESP.java | [
{
"identifier": "StrokeClient",
"path": "stroke/client/StrokeClient.java",
"snippet": "public class StrokeClient {\r\n\tpublic static Minecraft mc;\r\n\t\r\n\tpublic static String dev_username = \"megao4ko\";\r\n\tpublic static String title = \"[stroke] client ・ v1.0.00 | Minecraft 1.12.2\";\r\n\tpubli... | import java.awt.Color;
import net.minecraft.block.BlockChest;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.tileentity.TileEntityChest;
import net.minecraft.tileentity.TileEntityDispenser;
import net.minecraft.tileentity.TileEntityDropper;
import net.minecraft.tileentity.TileEntityEnderChest;
import net.minecraft.tileentity.TileEntityFurnace;
import net.minecraft.tileentity.TileEntityHopper;
import net.minecraft.tileentity.TileEntityShulkerBox;
import net.stroke.client.StrokeClient;
import net.stroke.client.clickgui.Setting;
import net.stroke.client.modules.BaseModule;
import net.stroke.client.modules.ModuleCategory;
import net.stroke.client.util.RenderUtils;
| 7,716 | package net.stroke.client.modules.render;
public class StorageESP extends BaseModule {
public StorageESP() {
super("StorageESP", "Highlights storages", 0x00, ModuleCategory.Render, false);
| package net.stroke.client.modules.render;
public class StorageESP extends BaseModule {
public StorageESP() {
super("StorageESP", "Highlights storages", 0x00, ModuleCategory.Render, false);
| StrokeClient.instance.settingsManager.rSetting(new Setting("Chests", this, true));
| 0 | 2023-12-31 10:56:59+00:00 | 12k |
piovas-lu/condominio | src/main/java/app/condominio/service/RelatorioService.java | [
{
"identifier": "Categoria",
"path": "src/main/java/app/condominio/domain/Categoria.java",
"snippet": "@SuppressWarnings(\"serial\")\r\n@Entity\r\n@Table(name = \"categorias\")\r\npublic class Categoria implements Serializable, Comparable<Categoria> {\r\n\r\n\tpublic static final int NIVEL_MAX = 4;\r\n\... | import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import app.condominio.domain.Categoria;
import app.condominio.domain.Cobranca;
import app.condominio.domain.Moradia;
import app.condominio.domain.Movimento;
import app.condominio.domain.Periodo;
import app.condominio.domain.Subcategoria;
import app.condominio.domain.enums.TipoCategoria;
| 9,873 | package app.condominio.service;
public interface RelatorioService {
/**
* @return Retorna um BigDecimal com a soma do saldo de todas as Contas do
* Condomínio. Nunca retorna nulo, se não houver contas, retorna
* BigDecimal.ZERO.
*/
public BigDecimal saldoAtualTodasContas();
/**
* @param data
* Um dia para pesquisa.
* @return Retorna um BigDecimal com o saldo de todas as Contas do Condomínio no
* início do dia passado no parâmetro. Nunca retorna nulo, se não houver
* contas, retorna BigDecimal.ZERO.
*/
public BigDecimal saldoInicialTodasContasEm(LocalDate data);
/**
* @param data
* Um dia para pesquisa.
* @return Retorna um BigDecimal com o saldo de todas as Contas do Condomínio no
* fim do dia passado no parâmetro. Nunca retorna nulo, se não houver
* contas, retorna BigDecimal.ZERO.
*/
public BigDecimal saldoFinalTodasContasEm(LocalDate data);
/**
* @return Retorna um BigDecimal com o valor total da inadimplência do
* Condomínio na data atual (considera o valor total da Cobrança, com
* acréscimos e deduções). Nunca retorna nulo, se não houver
* inadimplência, retorna BigDecimal.ZERO.
*/
public BigDecimal inadimplenciaAtual();
/**
* @return Retorna um vetor de BigDecimal[] com duas posições. A posição [0] é a
* soma dos lançamentos de receitas do mês atual, e a posição [1] é a
* soma dos lançamentos de despesas do mês atual. Nunca retorna nulo, se
* não houver lançamentos, retorna BigDecimal.ZERO na respectiva posição
* do vetor.
*/
public BigDecimal[] receitaDespesaMesAtual();
/**
* @param inicio
* Data inicial para pesquisa
* @param fim
* Data final para pesquisa
* @return Retorna um vetor de BigDecimal[] com duas posições. A posição [0] é a
* soma dos lançamentos de receitas dentro das datas informadas no
* parâmetro, e a posição [1] é a soma dos lançamentos de despesas
* dentro das datas informadas no parâmetro. Nunca retorna nulo, se não
* houver lançamentos, retorna BigDecimal.ZERO na respectiva posição do
* vetor.
*/
public BigDecimal[] receitaDespesaEntre(LocalDate inicio, LocalDate fim);
/**
* @return Retorna um vetor de BigDecimal[] com duas posições. A posição [0] é a
* soma dos lançamentos de receitas realizadas do Período atual, e a
* posição [1] é a soma dos lançamentos de despesas realizadas do
* Período atual. Nunca retorna nulo, se não houver lançamentos, retorna
* BigDecimal.ZERO na respectiva posição do vetor.
*/
public BigDecimal[] receitaDespesaRealizadaPeriodoAtual();
/**
* @return Retorna um vetor de BigDecimal[] com duas posições. A posição [0] é a
* soma dos lançamentos de receitas orçadas do Período atual, e a
* posição [1] é a soma dos lançamentos de despesas orçadas do Período
* atual. Nunca retorna nulo, se não houver lançamentos, retorna
* BigDecimal.ZERO na respectiva posição do vetor.
*/
public BigDecimal[] receitaDespesaOrcadaPeriodoAtual();
/**
* @param inicio
* Data inicial para pesquisa
* @param fim
* Data final para pesquisa
* @return Retorna uma lista do tipo List{@literal <}Movimento{@literal >} com
* Lançamentos existentes em todas as Contas dentro das datas informadas
* no parâmetro. Nunca retorna nulo, se não houverem Contas ou
* Lançamentos, retorna uma lista vazia.
*/
public List<Movimento> lancamentosEntre(LocalDate inicio, LocalDate fim);
/**
* @param movimentos
* Uma lista do tipo List{@literal <}Movimento{@literal >}
* @param saldoInicial
* Um BigDecimal para ser considerado como saldo inicial
* @return Retorna um vetor de BigDecimal[] com tamanho igual ao número de
* elementos na lista passada no parâmetro, contendo em cada enésima
* posição o saldo após processado o enésimo Movimento, partindo do
* saldo inicial informado no parâmetro. Nunca retorna nulo, se a lista
* passada no parâmetro estiver vazia, retorna um vetor com uma posição
* com valor BigDecimal.ZERO.
*/
public BigDecimal[] saldosAposMovimentos(List<Movimento> movimentos, BigDecimal saldoInicial);
/**
* @param inicio
* Data inicial para pesquisa
* @param fim
* Data final para pesquisa
* @param tipoCategoria
* O tipo da Categoria pai da Subcategoria a ser buscada
* @return Retorna um mapa do tipo Map{@literal <}Subcategoria,
* BigDecimal{@literal >}. Cada entrada do mapa é composta por uma
* Subcategoria como chave e um BigDecimal como valor. O valor
* representa a soma de todos os Lançamentos existentes para a
* respectiva Subcategoria dentro das datas informadas no parâmetro.
* Retorna somente Subcategorias com soma diferente de zero. Nunca
* retorna nulo, se não houverem entradas, retorna um mapa vazio.
*/
public SortedMap<Subcategoria, BigDecimal> somasPorTipoEntre(LocalDate inicio, LocalDate fim,
TipoCategoria tipoCategoria);
/**
* @return Retorna um mapa do tipo Map{@literal <}Moradia,List{@literal
* <}Cobranca{@literal >>}. Cada entrada do mapa é composta por uma
* Moradia como chave e uma lista de Cobranca como valor. Esta lista
* contém todas as Cobranças vencidas até a data atual da respectiva
* Moradia. Retorna somente Moradias com uma lista não vazia. Nunca
* retorna nulo, se não houverem entradas, retorna um mapa vazio.
*/
public SortedMap<Moradia, List<Cobranca>> inadimplenciaAtualDetalhada();
/**
* @param map
* Um mapa do tipo Map{@literal <}Moradia,List{@literal
* <}Cobranca{@literal >>} para ser somado
* @return Retorna um mapa do tipo Map{@literal <}Moradia,BigDecimal{@literal >}
* com as mesmas chaves do mapa fornecido no parâmetro. Cada valor
* corresponde à soma das Cobranças da respectiva Moradia. Nunca retorna
* nulo, se não houverem entradas, retorna um mapa vazio.
*/
public Map<Moradia, BigDecimal> somaCobrancas(Map<Moradia, List<Cobranca>> map);
/**
* @param periodo
* Um Periodo para pesquisa
* @return Retorna um mapa do tipo
* Map{@literal <}Subcategoria,BigDecimal[]{@literal >} tendo como chave
* uma Subcategoria. Retorna somente Subcategorias que tiveram, no
* Período fornecido por parâmetro, valores Orçados ou Realizados. O
* valor é um vetor de BigDecimal[] com duas posições. A posição [0] é o
* valor orçado da respectiva Subcategoria naquele Período, e a posição
* [1] é a soma dos Lançamentos realizados da respectiva Subcategoria
* naquele Período, em todas as Contas. Nunca retorna nulo, se não
* houverem entradas, retorna um mapa vazio.
*/
public Map<Subcategoria, BigDecimal[]> somaOrcadoRealizadoSubcategorias(Periodo periodo);
/**
* @param periodo
* Um Periodo para pesquisa
* @return Retorna um mapa do tipo
* Map{@literal <}Categoria,BigDecimal[]{@literal >} tendo como chave
* uma Categoria. Retorna somente Categorias que tiveram, no Período
* fornecido por parâmetro, valores Orçados ou Realizados em alguma de
* suas Subcategorias. O valor é um vetor de BigDecimal[] com duas
* posições. A posição [0] é a soma do valor orçado das Subcategorias da
* respectiva Categoria naquele Período, e a posição [1] é a soma dos
* Lançamentos realizados das Subcategorias da respectiva Categoria
* naquele Período, em todas as Contas. Nunca retorna nulo, se não
* houverem entradas, retorna um mapa vazio.
*/
| package app.condominio.service;
public interface RelatorioService {
/**
* @return Retorna um BigDecimal com a soma do saldo de todas as Contas do
* Condomínio. Nunca retorna nulo, se não houver contas, retorna
* BigDecimal.ZERO.
*/
public BigDecimal saldoAtualTodasContas();
/**
* @param data
* Um dia para pesquisa.
* @return Retorna um BigDecimal com o saldo de todas as Contas do Condomínio no
* início do dia passado no parâmetro. Nunca retorna nulo, se não houver
* contas, retorna BigDecimal.ZERO.
*/
public BigDecimal saldoInicialTodasContasEm(LocalDate data);
/**
* @param data
* Um dia para pesquisa.
* @return Retorna um BigDecimal com o saldo de todas as Contas do Condomínio no
* fim do dia passado no parâmetro. Nunca retorna nulo, se não houver
* contas, retorna BigDecimal.ZERO.
*/
public BigDecimal saldoFinalTodasContasEm(LocalDate data);
/**
* @return Retorna um BigDecimal com o valor total da inadimplência do
* Condomínio na data atual (considera o valor total da Cobrança, com
* acréscimos e deduções). Nunca retorna nulo, se não houver
* inadimplência, retorna BigDecimal.ZERO.
*/
public BigDecimal inadimplenciaAtual();
/**
* @return Retorna um vetor de BigDecimal[] com duas posições. A posição [0] é a
* soma dos lançamentos de receitas do mês atual, e a posição [1] é a
* soma dos lançamentos de despesas do mês atual. Nunca retorna nulo, se
* não houver lançamentos, retorna BigDecimal.ZERO na respectiva posição
* do vetor.
*/
public BigDecimal[] receitaDespesaMesAtual();
/**
* @param inicio
* Data inicial para pesquisa
* @param fim
* Data final para pesquisa
* @return Retorna um vetor de BigDecimal[] com duas posições. A posição [0] é a
* soma dos lançamentos de receitas dentro das datas informadas no
* parâmetro, e a posição [1] é a soma dos lançamentos de despesas
* dentro das datas informadas no parâmetro. Nunca retorna nulo, se não
* houver lançamentos, retorna BigDecimal.ZERO na respectiva posição do
* vetor.
*/
public BigDecimal[] receitaDespesaEntre(LocalDate inicio, LocalDate fim);
/**
* @return Retorna um vetor de BigDecimal[] com duas posições. A posição [0] é a
* soma dos lançamentos de receitas realizadas do Período atual, e a
* posição [1] é a soma dos lançamentos de despesas realizadas do
* Período atual. Nunca retorna nulo, se não houver lançamentos, retorna
* BigDecimal.ZERO na respectiva posição do vetor.
*/
public BigDecimal[] receitaDespesaRealizadaPeriodoAtual();
/**
* @return Retorna um vetor de BigDecimal[] com duas posições. A posição [0] é a
* soma dos lançamentos de receitas orçadas do Período atual, e a
* posição [1] é a soma dos lançamentos de despesas orçadas do Período
* atual. Nunca retorna nulo, se não houver lançamentos, retorna
* BigDecimal.ZERO na respectiva posição do vetor.
*/
public BigDecimal[] receitaDespesaOrcadaPeriodoAtual();
/**
* @param inicio
* Data inicial para pesquisa
* @param fim
* Data final para pesquisa
* @return Retorna uma lista do tipo List{@literal <}Movimento{@literal >} com
* Lançamentos existentes em todas as Contas dentro das datas informadas
* no parâmetro. Nunca retorna nulo, se não houverem Contas ou
* Lançamentos, retorna uma lista vazia.
*/
public List<Movimento> lancamentosEntre(LocalDate inicio, LocalDate fim);
/**
* @param movimentos
* Uma lista do tipo List{@literal <}Movimento{@literal >}
* @param saldoInicial
* Um BigDecimal para ser considerado como saldo inicial
* @return Retorna um vetor de BigDecimal[] com tamanho igual ao número de
* elementos na lista passada no parâmetro, contendo em cada enésima
* posição o saldo após processado o enésimo Movimento, partindo do
* saldo inicial informado no parâmetro. Nunca retorna nulo, se a lista
* passada no parâmetro estiver vazia, retorna um vetor com uma posição
* com valor BigDecimal.ZERO.
*/
public BigDecimal[] saldosAposMovimentos(List<Movimento> movimentos, BigDecimal saldoInicial);
/**
* @param inicio
* Data inicial para pesquisa
* @param fim
* Data final para pesquisa
* @param tipoCategoria
* O tipo da Categoria pai da Subcategoria a ser buscada
* @return Retorna um mapa do tipo Map{@literal <}Subcategoria,
* BigDecimal{@literal >}. Cada entrada do mapa é composta por uma
* Subcategoria como chave e um BigDecimal como valor. O valor
* representa a soma de todos os Lançamentos existentes para a
* respectiva Subcategoria dentro das datas informadas no parâmetro.
* Retorna somente Subcategorias com soma diferente de zero. Nunca
* retorna nulo, se não houverem entradas, retorna um mapa vazio.
*/
public SortedMap<Subcategoria, BigDecimal> somasPorTipoEntre(LocalDate inicio, LocalDate fim,
TipoCategoria tipoCategoria);
/**
* @return Retorna um mapa do tipo Map{@literal <}Moradia,List{@literal
* <}Cobranca{@literal >>}. Cada entrada do mapa é composta por uma
* Moradia como chave e uma lista de Cobranca como valor. Esta lista
* contém todas as Cobranças vencidas até a data atual da respectiva
* Moradia. Retorna somente Moradias com uma lista não vazia. Nunca
* retorna nulo, se não houverem entradas, retorna um mapa vazio.
*/
public SortedMap<Moradia, List<Cobranca>> inadimplenciaAtualDetalhada();
/**
* @param map
* Um mapa do tipo Map{@literal <}Moradia,List{@literal
* <}Cobranca{@literal >>} para ser somado
* @return Retorna um mapa do tipo Map{@literal <}Moradia,BigDecimal{@literal >}
* com as mesmas chaves do mapa fornecido no parâmetro. Cada valor
* corresponde à soma das Cobranças da respectiva Moradia. Nunca retorna
* nulo, se não houverem entradas, retorna um mapa vazio.
*/
public Map<Moradia, BigDecimal> somaCobrancas(Map<Moradia, List<Cobranca>> map);
/**
* @param periodo
* Um Periodo para pesquisa
* @return Retorna um mapa do tipo
* Map{@literal <}Subcategoria,BigDecimal[]{@literal >} tendo como chave
* uma Subcategoria. Retorna somente Subcategorias que tiveram, no
* Período fornecido por parâmetro, valores Orçados ou Realizados. O
* valor é um vetor de BigDecimal[] com duas posições. A posição [0] é o
* valor orçado da respectiva Subcategoria naquele Período, e a posição
* [1] é a soma dos Lançamentos realizados da respectiva Subcategoria
* naquele Período, em todas as Contas. Nunca retorna nulo, se não
* houverem entradas, retorna um mapa vazio.
*/
public Map<Subcategoria, BigDecimal[]> somaOrcadoRealizadoSubcategorias(Periodo periodo);
/**
* @param periodo
* Um Periodo para pesquisa
* @return Retorna um mapa do tipo
* Map{@literal <}Categoria,BigDecimal[]{@literal >} tendo como chave
* uma Categoria. Retorna somente Categorias que tiveram, no Período
* fornecido por parâmetro, valores Orçados ou Realizados em alguma de
* suas Subcategorias. O valor é um vetor de BigDecimal[] com duas
* posições. A posição [0] é a soma do valor orçado das Subcategorias da
* respectiva Categoria naquele Período, e a posição [1] é a soma dos
* Lançamentos realizados das Subcategorias da respectiva Categoria
* naquele Período, em todas as Contas. Nunca retorna nulo, se não
* houverem entradas, retorna um mapa vazio.
*/
| public Map<Categoria, BigDecimal[]> somaOrcadoRealizadoCategorias(Periodo periodo);
| 0 | 2023-12-29 22:19:42+00:00 | 12k |
HuXin0817/shop_api | framework/src/main/java/cn/lili/modules/member/serviceimpl/StoreMenuRoleServiceImpl.java | [
{
"identifier": "Cache",
"path": "framework/src/main/java/cn/lili/cache/Cache.java",
"snippet": "public interface Cache<T> {\n\n /**\n * Get an item from the cache, nontransactionally\n *\n * @param key 缓存key\n * @return the cached object or <tt>null</tt>\n */\n T get(Object ke... | import cn.lili.cache.Cache;
import cn.lili.cache.CachePrefix;
import cn.lili.common.security.context.UserContext;
import cn.lili.common.security.enums.UserEnums;
import cn.lili.modules.member.entity.dos.StoreMenuRole;
import cn.lili.modules.member.entity.vo.StoreUserMenuVO;
import cn.lili.modules.member.mapper.StoreMenuRoleMapper;
import cn.lili.modules.member.service.StoreMenuRoleService;
import cn.lili.modules.member.service.StoreMenuService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import groovy.util.logging.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List; | 7,807 | package cn.lili.modules.member.serviceimpl;
/**
* 角色菜单业务层实现
*
* @author Chopper
* @since 2020/11/22 11:43
*/
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class StoreMenuRoleServiceImpl extends ServiceImpl<StoreMenuRoleMapper, StoreMenuRole> implements StoreMenuRoleService {
/**
* 菜单
*/
@Autowired
private StoreMenuService storeMenuService;
@Autowired | package cn.lili.modules.member.serviceimpl;
/**
* 角色菜单业务层实现
*
* @author Chopper
* @since 2020/11/22 11:43
*/
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class StoreMenuRoleServiceImpl extends ServiceImpl<StoreMenuRoleMapper, StoreMenuRole> implements StoreMenuRoleService {
/**
* 菜单
*/
@Autowired
private StoreMenuService storeMenuService;
@Autowired | private Cache<Object> cache; | 0 | 2023-12-24 19:45:18+00:00 | 12k |
bta-team-port/moon-mod | src/main/java/teamport/moonmod/MoonMod.java | [
{
"identifier": "BiomeProviderMoon",
"path": "src/main/java/teamport/moonmod/world/BiomeProviderMoon.java",
"snippet": "public class BiomeProviderMoon extends BiomeProvider {\n\tprivate static final BiomeRangeMap brm = new BiomeRangeMap();\n\tprivate final PerlinSimplexNoise temperatureNoise;\n\tprivate... | import net.fabricmc.api.ModInitializer;
import net.fabricmc.loader.api.entrypoint.PreLaunchEntrypoint;
import net.minecraft.core.world.type.WorldType;
import net.minecraft.core.world.type.WorldTypes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import teamport.moonmod.world.BiomeProviderMoon;
import teamport.moonmod.world.ModDimensions;
import teamport.moonmod.world.WorldTypeMoon;
import teamport.moonmod.world.biome.MoonBiomes;
import teamport.moonmod.entity.EntityUFO;
import teamport.moonmod.entity.render.UFOModel;
import teamport.moonmod.entity.render.UFORenderer;
import teamport.moonmod.block.MoonModBlocks;
import teamport.moonmod.item.MoonModItems;
import net.minecraft.client.sound.block.BlockSound;
import net.minecraft.core.block.Block;
import net.minecraft.core.block.material.Material;
import net.minecraft.core.block.tag.BlockTags;
import teamport.moonmod.block.MoonModBlocks;
import teamport.moonmod.item.MoonModItems;
import turniplabs.halplibe.helper.BlockBuilder;
import turniplabs.halplibe.helper.EntityHelper;
import turniplabs.halplibe.util.GameStartEntrypoint;
import turniplabs.halplibe.util.RecipeEntrypoint;
import useless.dragonfly.helper.ModelHelper; | 8,716 | package teamport.moonmod;
public class MoonMod implements ModInitializer, GameStartEntrypoint, RecipeEntrypoint, PreLaunchEntrypoint {
public static final String MOD_ID = "moonmod";
public static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID);
public static WorldType MOON_WORLD;
@Override
public void onInitialize() {
new MoonModBlocks().initializeBlocks();
new MoonModItems().initializeItems();
| package teamport.moonmod;
public class MoonMod implements ModInitializer, GameStartEntrypoint, RecipeEntrypoint, PreLaunchEntrypoint {
public static final String MOD_ID = "moonmod";
public static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID);
public static WorldType MOON_WORLD;
@Override
public void onInitialize() {
new MoonModBlocks().initializeBlocks();
new MoonModItems().initializeItems();
| EntityHelper.createEntity(EntityUFO.class, | 4 | 2023-12-24 14:52:01+00:00 | 12k |
LeeKyeongYong/SBookStudy | src/main/java/com/multibook/bookorder/global/initData/NotProd.java | [
{
"identifier": "Book",
"path": "src/main/java/com/multibook/bookorder/domain/book/book/entity/Book.java",
"snippet": "@Entity\n@Builder\n@AllArgsConstructor(access = PROTECTED)\n@NoArgsConstructor(access = PROTECTED)\n@Setter\n@Getter\n@ToString(callSuper = true)\npublic class Book extends BaseTime {\n... | import com.multibook.bookorder.domain.book.book.entity.Book;
import com.multibook.bookorder.domain.book.book.service.BookService;
import com.multibook.bookorder.domain.cash.cash.entity.CashLog;
import com.multibook.bookorder.domain.cash.withdraw.service.WithdrawService;
import com.multibook.bookorder.domain.member.member.entity.Member;
import com.multibook.bookorder.domain.member.member.service.MemberService;
import com.multibook.bookorder.domain.product.cart.service.CartService;
import com.multibook.bookorder.domain.product.order.entity.Order;
import com.multibook.bookorder.domain.product.order.service.OrderService;
import com.multibook.bookorder.domain.product.product.entity.Product;
import com.multibook.bookorder.domain.product.product.service.ProductService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import com.multibook.bookorder.domain.product.order.entity.Order;
import org.springframework.transaction.annotation.Transactional; | 7,552 | package com.multibook.bookorder.global.initData;
@Configuration
@RequiredArgsConstructor
public class NotProd {
@Autowired
@Lazy
private NotProd self;
private final MemberService memberService;
private final BookService bookService;
private final ProductService productService;
private final CartService cartService;
private final OrderService orderService;
private final WithdrawService withdrawService;
@Bean
@org.springframework.core.annotation.Order(3)
ApplicationRunner initNotProd() {
return args -> {
self.work1();
self.work2();
};
}
@Transactional
public void work1() {
if (memberService.findByUsername("admin").isPresent()) return;
Member memberAdmin = memberService.join("admin", "1234", "관리자").getData();
Member memberUser1 = memberService.join("user1", "1234", "유저1").getData();
Member memberUser2 = memberService.join("user2", "1234", "유저2").getData();
Member memberUser3 = memberService.join("user3", "1234", "유저3").getData();
Member memberUser4 = memberService.join("user4", "1234", "유저4").getData();
Member memberUser5 = memberService.join("user5", "1234", "유저5").getData();
Book book1 = bookService.createBook(memberUser1, "책 제목 1", "책 내용 1", 10_000, true);
Book book2 = bookService.createBook(memberUser2, "책 제목 2", "책 내용 2", 20_000, true);
Book book3 = bookService.createBook(memberUser2, "책 제목 3", "책 내용 3", 30_000, true);
Book book4 = bookService.createBook(memberUser3, "책 제목 4", "책 내용 4", 40_000, true);
Book book5 = bookService.createBook(memberUser3, "책 제목 5", "책 내용 5", 15_000, true);
Book book6 = bookService.createBook(memberUser3, "책 제목 6", "책 내용 6", 20_000, true);
| package com.multibook.bookorder.global.initData;
@Configuration
@RequiredArgsConstructor
public class NotProd {
@Autowired
@Lazy
private NotProd self;
private final MemberService memberService;
private final BookService bookService;
private final ProductService productService;
private final CartService cartService;
private final OrderService orderService;
private final WithdrawService withdrawService;
@Bean
@org.springframework.core.annotation.Order(3)
ApplicationRunner initNotProd() {
return args -> {
self.work1();
self.work2();
};
}
@Transactional
public void work1() {
if (memberService.findByUsername("admin").isPresent()) return;
Member memberAdmin = memberService.join("admin", "1234", "관리자").getData();
Member memberUser1 = memberService.join("user1", "1234", "유저1").getData();
Member memberUser2 = memberService.join("user2", "1234", "유저2").getData();
Member memberUser3 = memberService.join("user3", "1234", "유저3").getData();
Member memberUser4 = memberService.join("user4", "1234", "유저4").getData();
Member memberUser5 = memberService.join("user5", "1234", "유저5").getData();
Book book1 = bookService.createBook(memberUser1, "책 제목 1", "책 내용 1", 10_000, true);
Book book2 = bookService.createBook(memberUser2, "책 제목 2", "책 내용 2", 20_000, true);
Book book3 = bookService.createBook(memberUser2, "책 제목 3", "책 내용 3", 30_000, true);
Book book4 = bookService.createBook(memberUser3, "책 제목 4", "책 내용 4", 40_000, true);
Book book5 = bookService.createBook(memberUser3, "책 제목 5", "책 내용 5", 15_000, true);
Book book6 = bookService.createBook(memberUser3, "책 제목 6", "책 내용 6", 20_000, true);
| Product product1 = productService.createProduct(book3, true); | 9 | 2023-12-26 14:58:59+00:00 | 12k |
SDeVuyst/pingys-waddles-1.20.1 | src/main/java/com/sdevuyst/pingyswaddles/entity/ModEntities.java | [
{
"identifier": "PingysWaddles",
"path": "src/main/java/com/sdevuyst/pingyswaddles/PingysWaddles.java",
"snippet": "@Mod(PingysWaddles.MOD_ID)\npublic class PingysWaddles\n{\n // Define mod id in a common place for everything to reference\n public static final String MOD_ID = \"pingyswaddles\";\n ... | import com.sdevuyst.pingyswaddles.PingysWaddles;
import com.sdevuyst.pingyswaddles.entity.custom.AbstractSurfboard;
import com.sdevuyst.pingyswaddles.entity.custom.EmperorPenguinEntity;
import com.sdevuyst.pingyswaddles.entity.custom.SurfboardEntity;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.MobCategory;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.registries.DeferredRegister;
import net.minecraftforge.registries.ForgeRegistries;
import net.minecraftforge.registries.RegistryObject; | 9,359 | package com.sdevuyst.pingyswaddles.entity;
public class ModEntities
{
public static final DeferredRegister<EntityType<?>> ENTITY_TYPES =
DeferredRegister.create(ForgeRegistries.ENTITY_TYPES, PingysWaddles.MOD_ID);
public static final RegistryObject<EntityType<EmperorPenguinEntity>> EMPEROR_PENGUIN =
ENTITY_TYPES.register("emperor_penguin", () -> EntityType.Builder.of(EmperorPenguinEntity::new, MobCategory.CREATURE)
.sized(2, 2).build("emperor_penguin"));
public static final RegistryObject<EntityType<Entity>> SURFBOARD = | package com.sdevuyst.pingyswaddles.entity;
public class ModEntities
{
public static final DeferredRegister<EntityType<?>> ENTITY_TYPES =
DeferredRegister.create(ForgeRegistries.ENTITY_TYPES, PingysWaddles.MOD_ID);
public static final RegistryObject<EntityType<EmperorPenguinEntity>> EMPEROR_PENGUIN =
ENTITY_TYPES.register("emperor_penguin", () -> EntityType.Builder.of(EmperorPenguinEntity::new, MobCategory.CREATURE)
.sized(2, 2).build("emperor_penguin"));
public static final RegistryObject<EntityType<Entity>> SURFBOARD = | ENTITY_TYPES.register("surfboard", () -> EntityType.Builder.of(SurfboardEntity::new, MobCategory.MISC) | 3 | 2023-12-31 09:54:03+00:00 | 12k |
quarkiverse/quarkus-langchain4j | openai/openai-vanilla/runtime/src/main/java/io/quarkiverse/langchain4j/openai/runtime/OpenAiRecorder.java | [
{
"identifier": "firstOrDefault",
"path": "core/runtime/src/main/java/io/quarkiverse/langchain4j/runtime/OptionalUtil.java",
"snippet": "@SafeVarargs\npublic static <T> T firstOrDefault(T defaultValue, Optional<T>... values) {\n for (Optional<T> o : values) {\n if (o != null && o.isPresent()) ... | import static io.quarkiverse.langchain4j.runtime.OptionalUtil.firstOrDefault;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Optional;
import java.util.function.Supplier;
import dev.langchain4j.model.openai.OpenAiChatModel;
import dev.langchain4j.model.openai.OpenAiEmbeddingModel;
import dev.langchain4j.model.openai.OpenAiModerationModel;
import dev.langchain4j.model.openai.OpenAiStreamingChatModel;
import io.quarkiverse.langchain4j.openai.QuarkusOpenAiClient;
import io.quarkiverse.langchain4j.openai.QuarkusOpenAiImageModel;
import io.quarkiverse.langchain4j.openai.runtime.config.ChatModelConfig;
import io.quarkiverse.langchain4j.openai.runtime.config.EmbeddingModelConfig;
import io.quarkiverse.langchain4j.openai.runtime.config.ImageModelConfig;
import io.quarkiverse.langchain4j.openai.runtime.config.Langchain4jOpenAiConfig;
import io.quarkiverse.langchain4j.openai.runtime.config.ModerationModelConfig;
import io.quarkus.runtime.ShutdownContext;
import io.quarkus.runtime.annotations.Recorder;
import io.smallrye.config.ConfigValidationException; | 10,006 | package io.quarkiverse.langchain4j.openai.runtime;
@Recorder
public class OpenAiRecorder {
public Supplier<?> chatModel(Langchain4jOpenAiConfig runtimeConfig) {
Optional<String> apiKeyOpt = runtimeConfig.apiKey();
if (apiKeyOpt.isEmpty()) {
throw new ConfigValidationException(createApiKeyConfigProblems());
}
ChatModelConfig chatModelConfig = runtimeConfig.chatModel();
var builder = OpenAiChatModel.builder()
.baseUrl(runtimeConfig.baseUrl())
.apiKey(apiKeyOpt.get())
.timeout(runtimeConfig.timeout())
.maxRetries(runtimeConfig.maxRetries())
.logRequests(firstOrDefault(false, chatModelConfig.logRequests(), runtimeConfig.logRequests()))
.logResponses(firstOrDefault(false, chatModelConfig.logResponses(), runtimeConfig.logResponses()))
.modelName(chatModelConfig.modelName())
.temperature(chatModelConfig.temperature())
.topP(chatModelConfig.topP())
.presencePenalty(chatModelConfig.presencePenalty())
.frequencyPenalty(chatModelConfig.frequencyPenalty());
runtimeConfig.organizationId().ifPresent(builder::organizationId);
if (chatModelConfig.maxTokens().isPresent()) {
builder.maxTokens(chatModelConfig.maxTokens().get());
}
return new Supplier<>() {
@Override
public Object get() {
return builder.build();
}
};
}
public Supplier<?> streamingChatModel(Langchain4jOpenAiConfig runtimeConfig) {
Optional<String> apiKeyOpt = runtimeConfig.apiKey();
if (apiKeyOpt.isEmpty()) {
throw new ConfigValidationException(createApiKeyConfigProblems());
}
ChatModelConfig chatModelConfig = runtimeConfig.chatModel();
var builder = OpenAiStreamingChatModel.builder()
.baseUrl(runtimeConfig.baseUrl())
.apiKey(apiKeyOpt.get())
.timeout(runtimeConfig.timeout())
.logRequests(firstOrDefault(false, chatModelConfig.logRequests(), runtimeConfig.logRequests()))
.logResponses(firstOrDefault(false, chatModelConfig.logResponses(), runtimeConfig.logResponses()))
.modelName(chatModelConfig.modelName())
.temperature(chatModelConfig.temperature())
.topP(chatModelConfig.topP())
.presencePenalty(chatModelConfig.presencePenalty())
.frequencyPenalty(chatModelConfig.frequencyPenalty());
runtimeConfig.organizationId().ifPresent(builder::organizationId);
if (chatModelConfig.maxTokens().isPresent()) {
builder.maxTokens(chatModelConfig.maxTokens().get());
}
return new Supplier<>() {
@Override
public Object get() {
return builder.build();
}
};
}
public Supplier<?> embeddingModel(Langchain4jOpenAiConfig runtimeConfig) {
Optional<String> apiKeyOpt = runtimeConfig.apiKey();
if (apiKeyOpt.isEmpty()) {
throw new ConfigValidationException(createApiKeyConfigProblems());
}
EmbeddingModelConfig embeddingModelConfig = runtimeConfig.embeddingModel();
var builder = OpenAiEmbeddingModel.builder()
.baseUrl(runtimeConfig.baseUrl())
.apiKey(apiKeyOpt.get())
.timeout(runtimeConfig.timeout())
.maxRetries(runtimeConfig.maxRetries())
.logRequests(firstOrDefault(false, embeddingModelConfig.logRequests(), runtimeConfig.logRequests()))
.logResponses(firstOrDefault(false, embeddingModelConfig.logResponses(), runtimeConfig.logResponses()))
.modelName(embeddingModelConfig.modelName());
if (embeddingModelConfig.user().isPresent()) {
builder.user(embeddingModelConfig.user().get());
}
runtimeConfig.organizationId().ifPresent(builder::organizationId);
return new Supplier<>() {
@Override
public Object get() {
return builder.build();
}
};
}
public Supplier<?> moderationModel(Langchain4jOpenAiConfig runtimeConfig) {
Optional<String> apiKeyOpt = runtimeConfig.apiKey();
if (apiKeyOpt.isEmpty()) {
throw new ConfigValidationException(createApiKeyConfigProblems());
}
ModerationModelConfig moderationModelConfig = runtimeConfig.moderationModel();
var builder = OpenAiModerationModel.builder()
.baseUrl(runtimeConfig.baseUrl())
.apiKey(apiKeyOpt.get())
.timeout(runtimeConfig.timeout())
.maxRetries(runtimeConfig.maxRetries())
.logRequests(firstOrDefault(false, moderationModelConfig.logRequests(), runtimeConfig.logRequests()))
.logResponses(firstOrDefault(false, moderationModelConfig.logResponses(), runtimeConfig.logResponses()))
.modelName(moderationModelConfig.modelName());
runtimeConfig.organizationId().ifPresent(builder::organizationId);
return new Supplier<>() {
@Override
public Object get() {
return builder.build();
}
};
}
public Supplier<?> imageModel(Langchain4jOpenAiConfig runtimeConfig) {
Optional<String> apiKeyOpt = runtimeConfig.apiKey();
if (apiKeyOpt.isEmpty()) {
throw new ConfigValidationException(createApiKeyConfigProblems());
} | package io.quarkiverse.langchain4j.openai.runtime;
@Recorder
public class OpenAiRecorder {
public Supplier<?> chatModel(Langchain4jOpenAiConfig runtimeConfig) {
Optional<String> apiKeyOpt = runtimeConfig.apiKey();
if (apiKeyOpt.isEmpty()) {
throw new ConfigValidationException(createApiKeyConfigProblems());
}
ChatModelConfig chatModelConfig = runtimeConfig.chatModel();
var builder = OpenAiChatModel.builder()
.baseUrl(runtimeConfig.baseUrl())
.apiKey(apiKeyOpt.get())
.timeout(runtimeConfig.timeout())
.maxRetries(runtimeConfig.maxRetries())
.logRequests(firstOrDefault(false, chatModelConfig.logRequests(), runtimeConfig.logRequests()))
.logResponses(firstOrDefault(false, chatModelConfig.logResponses(), runtimeConfig.logResponses()))
.modelName(chatModelConfig.modelName())
.temperature(chatModelConfig.temperature())
.topP(chatModelConfig.topP())
.presencePenalty(chatModelConfig.presencePenalty())
.frequencyPenalty(chatModelConfig.frequencyPenalty());
runtimeConfig.organizationId().ifPresent(builder::organizationId);
if (chatModelConfig.maxTokens().isPresent()) {
builder.maxTokens(chatModelConfig.maxTokens().get());
}
return new Supplier<>() {
@Override
public Object get() {
return builder.build();
}
};
}
public Supplier<?> streamingChatModel(Langchain4jOpenAiConfig runtimeConfig) {
Optional<String> apiKeyOpt = runtimeConfig.apiKey();
if (apiKeyOpt.isEmpty()) {
throw new ConfigValidationException(createApiKeyConfigProblems());
}
ChatModelConfig chatModelConfig = runtimeConfig.chatModel();
var builder = OpenAiStreamingChatModel.builder()
.baseUrl(runtimeConfig.baseUrl())
.apiKey(apiKeyOpt.get())
.timeout(runtimeConfig.timeout())
.logRequests(firstOrDefault(false, chatModelConfig.logRequests(), runtimeConfig.logRequests()))
.logResponses(firstOrDefault(false, chatModelConfig.logResponses(), runtimeConfig.logResponses()))
.modelName(chatModelConfig.modelName())
.temperature(chatModelConfig.temperature())
.topP(chatModelConfig.topP())
.presencePenalty(chatModelConfig.presencePenalty())
.frequencyPenalty(chatModelConfig.frequencyPenalty());
runtimeConfig.organizationId().ifPresent(builder::organizationId);
if (chatModelConfig.maxTokens().isPresent()) {
builder.maxTokens(chatModelConfig.maxTokens().get());
}
return new Supplier<>() {
@Override
public Object get() {
return builder.build();
}
};
}
public Supplier<?> embeddingModel(Langchain4jOpenAiConfig runtimeConfig) {
Optional<String> apiKeyOpt = runtimeConfig.apiKey();
if (apiKeyOpt.isEmpty()) {
throw new ConfigValidationException(createApiKeyConfigProblems());
}
EmbeddingModelConfig embeddingModelConfig = runtimeConfig.embeddingModel();
var builder = OpenAiEmbeddingModel.builder()
.baseUrl(runtimeConfig.baseUrl())
.apiKey(apiKeyOpt.get())
.timeout(runtimeConfig.timeout())
.maxRetries(runtimeConfig.maxRetries())
.logRequests(firstOrDefault(false, embeddingModelConfig.logRequests(), runtimeConfig.logRequests()))
.logResponses(firstOrDefault(false, embeddingModelConfig.logResponses(), runtimeConfig.logResponses()))
.modelName(embeddingModelConfig.modelName());
if (embeddingModelConfig.user().isPresent()) {
builder.user(embeddingModelConfig.user().get());
}
runtimeConfig.organizationId().ifPresent(builder::organizationId);
return new Supplier<>() {
@Override
public Object get() {
return builder.build();
}
};
}
public Supplier<?> moderationModel(Langchain4jOpenAiConfig runtimeConfig) {
Optional<String> apiKeyOpt = runtimeConfig.apiKey();
if (apiKeyOpt.isEmpty()) {
throw new ConfigValidationException(createApiKeyConfigProblems());
}
ModerationModelConfig moderationModelConfig = runtimeConfig.moderationModel();
var builder = OpenAiModerationModel.builder()
.baseUrl(runtimeConfig.baseUrl())
.apiKey(apiKeyOpt.get())
.timeout(runtimeConfig.timeout())
.maxRetries(runtimeConfig.maxRetries())
.logRequests(firstOrDefault(false, moderationModelConfig.logRequests(), runtimeConfig.logRequests()))
.logResponses(firstOrDefault(false, moderationModelConfig.logResponses(), runtimeConfig.logResponses()))
.modelName(moderationModelConfig.modelName());
runtimeConfig.organizationId().ifPresent(builder::organizationId);
return new Supplier<>() {
@Override
public Object get() {
return builder.build();
}
};
}
public Supplier<?> imageModel(Langchain4jOpenAiConfig runtimeConfig) {
Optional<String> apiKeyOpt = runtimeConfig.apiKey();
if (apiKeyOpt.isEmpty()) {
throw new ConfigValidationException(createApiKeyConfigProblems());
} | ImageModelConfig imageModelConfig = runtimeConfig.imageModel(); | 5 | 2023-11-13 09:10:27+00:00 | 12k |
qiusunshine/xiu | clinglibrary/src/main/java/org/fourthline/cling/UpnpServiceConfiguration.java | [
{
"identifier": "DeviceDescriptorBinder",
"path": "clinglibrary/src/main/java/org/fourthline/cling/binding/xml/DeviceDescriptorBinder.java",
"snippet": "public interface DeviceDescriptorBinder {\n\n public <T extends Device> T describe(T undescribedDevice, String descriptorXml)\n throws De... | import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import org.fourthline.cling.binding.xml.DeviceDescriptorBinder;
import org.fourthline.cling.binding.xml.ServiceDescriptorBinder;
import org.fourthline.cling.model.Namespace;
import org.fourthline.cling.model.message.UpnpHeaders;
import org.fourthline.cling.model.meta.RemoteDeviceIdentity;
import org.fourthline.cling.model.meta.RemoteService;
import org.fourthline.cling.model.types.ServiceType;
import org.fourthline.cling.transport.spi.DatagramIO;
import org.fourthline.cling.transport.spi.DatagramProcessor;
import org.fourthline.cling.transport.spi.GENAEventProcessor;
import org.fourthline.cling.transport.spi.MulticastReceiver;
import org.fourthline.cling.transport.spi.NetworkAddressFactory;
import org.fourthline.cling.transport.spi.SOAPActionProcessor;
import org.fourthline.cling.transport.spi.StreamClient;
import org.fourthline.cling.transport.spi.StreamServer; | 10,058 | /*
* Copyright (C) 2013 4th Line GmbH, Switzerland
*
* The contents of this file are subject to the terms of either the GNU
* Lesser General Public License Version 2 or later ("LGPL") or the
* Common Development and Distribution License Version 1 or later
* ("CDDL") (collectively, the "License"). You may not use this file
* except in compliance with the License. See LICENSE.txt for more
* information.
*
* 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.
*/
package org.fourthline.cling;
/**
* Shared configuration data of the UPnP stack.
* <p>
* This interface offers methods for retrieval of configuration data by the
* {@link org.fourthline.cling.transport.Router} and the {@link org.fourthline.cling.registry.Registry},
* as well as other parts of the UPnP stack.
* </p>
* <p>
* You can re-use this interface if you implement a subclass of {@link UpnpServiceImpl} or
* if you create a new implementation of {@link UpnpService}.
* </p>
*
* @author Christian Bauer
*/
public interface UpnpServiceConfiguration {
/**
* @return A new instance of the {@link org.fourthline.cling.transport.spi.NetworkAddressFactory} interface.
*/
public NetworkAddressFactory createNetworkAddressFactory();
/**
* @return The shared implementation of {@link org.fourthline.cling.transport.spi.DatagramProcessor}.
*/
public DatagramProcessor getDatagramProcessor();
/**
* @return The shared implementation of {@link org.fourthline.cling.transport.spi.SOAPActionProcessor}.
*/
public SOAPActionProcessor getSoapActionProcessor();
/**
* @return The shared implementation of {@link org.fourthline.cling.transport.spi.GENAEventProcessor}.
*/
public GENAEventProcessor getGenaEventProcessor();
/**
* @return A new instance of the {@link org.fourthline.cling.transport.spi.StreamClient} interface.
*/
public StreamClient createStreamClient();
/**
* @param networkAddressFactory The configured {@link org.fourthline.cling.transport.spi.NetworkAddressFactory}.
* @return A new instance of the {@link org.fourthline.cling.transport.spi.MulticastReceiver} interface.
*/
public MulticastReceiver createMulticastReceiver(NetworkAddressFactory networkAddressFactory);
/**
* @param networkAddressFactory The configured {@link org.fourthline.cling.transport.spi.NetworkAddressFactory}.
* @return A new instance of the {@link org.fourthline.cling.transport.spi.DatagramIO} interface.
*/
public DatagramIO createDatagramIO(NetworkAddressFactory networkAddressFactory);
/**
* @param networkAddressFactory The configured {@link org.fourthline.cling.transport.spi.NetworkAddressFactory}.
* @return A new instance of the {@link org.fourthline.cling.transport.spi.StreamServer} interface.
*/
public StreamServer createStreamServer(NetworkAddressFactory networkAddressFactory);
/**
* @return The executor which runs the listening background threads for multicast datagrams.
*/
public Executor getMulticastReceiverExecutor();
/**
* @return The executor which runs the listening background threads for unicast datagrams.
*/
public Executor getDatagramIOExecutor();
/**
* @return The executor which runs the listening background threads for HTTP requests.
*/
public ExecutorService getStreamServerExecutorService();
/**
* @return The shared implementation of {@link org.fourthline.cling.binding.xml.DeviceDescriptorBinder} for the UPnP 1.0 Device Architecture..
*/ | /*
* Copyright (C) 2013 4th Line GmbH, Switzerland
*
* The contents of this file are subject to the terms of either the GNU
* Lesser General Public License Version 2 or later ("LGPL") or the
* Common Development and Distribution License Version 1 or later
* ("CDDL") (collectively, the "License"). You may not use this file
* except in compliance with the License. See LICENSE.txt for more
* information.
*
* 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.
*/
package org.fourthline.cling;
/**
* Shared configuration data of the UPnP stack.
* <p>
* This interface offers methods for retrieval of configuration data by the
* {@link org.fourthline.cling.transport.Router} and the {@link org.fourthline.cling.registry.Registry},
* as well as other parts of the UPnP stack.
* </p>
* <p>
* You can re-use this interface if you implement a subclass of {@link UpnpServiceImpl} or
* if you create a new implementation of {@link UpnpService}.
* </p>
*
* @author Christian Bauer
*/
public interface UpnpServiceConfiguration {
/**
* @return A new instance of the {@link org.fourthline.cling.transport.spi.NetworkAddressFactory} interface.
*/
public NetworkAddressFactory createNetworkAddressFactory();
/**
* @return The shared implementation of {@link org.fourthline.cling.transport.spi.DatagramProcessor}.
*/
public DatagramProcessor getDatagramProcessor();
/**
* @return The shared implementation of {@link org.fourthline.cling.transport.spi.SOAPActionProcessor}.
*/
public SOAPActionProcessor getSoapActionProcessor();
/**
* @return The shared implementation of {@link org.fourthline.cling.transport.spi.GENAEventProcessor}.
*/
public GENAEventProcessor getGenaEventProcessor();
/**
* @return A new instance of the {@link org.fourthline.cling.transport.spi.StreamClient} interface.
*/
public StreamClient createStreamClient();
/**
* @param networkAddressFactory The configured {@link org.fourthline.cling.transport.spi.NetworkAddressFactory}.
* @return A new instance of the {@link org.fourthline.cling.transport.spi.MulticastReceiver} interface.
*/
public MulticastReceiver createMulticastReceiver(NetworkAddressFactory networkAddressFactory);
/**
* @param networkAddressFactory The configured {@link org.fourthline.cling.transport.spi.NetworkAddressFactory}.
* @return A new instance of the {@link org.fourthline.cling.transport.spi.DatagramIO} interface.
*/
public DatagramIO createDatagramIO(NetworkAddressFactory networkAddressFactory);
/**
* @param networkAddressFactory The configured {@link org.fourthline.cling.transport.spi.NetworkAddressFactory}.
* @return A new instance of the {@link org.fourthline.cling.transport.spi.StreamServer} interface.
*/
public StreamServer createStreamServer(NetworkAddressFactory networkAddressFactory);
/**
* @return The executor which runs the listening background threads for multicast datagrams.
*/
public Executor getMulticastReceiverExecutor();
/**
* @return The executor which runs the listening background threads for unicast datagrams.
*/
public Executor getDatagramIOExecutor();
/**
* @return The executor which runs the listening background threads for HTTP requests.
*/
public ExecutorService getStreamServerExecutorService();
/**
* @return The shared implementation of {@link org.fourthline.cling.binding.xml.DeviceDescriptorBinder} for the UPnP 1.0 Device Architecture..
*/ | public DeviceDescriptorBinder getDeviceDescriptorBinderUDA10(); | 0 | 2023-11-10 14:28:40+00:00 | 12k |
noear/folkmq | folkmq-server/src/main/java/org/noear/folkmq/server/pro/mq/FolkmqLifecycleBean.java | [
{
"identifier": "FolkMQ",
"path": "folkmq/src/main/java/org/noear/folkmq/FolkMQ.java",
"snippet": "public class FolkMQ {\n /**\n * 获取版本\n */\n public static String version() {\n return \"1.0.27\";\n }\n\n /**\n * 创建服务端\n */\n public static MqServer createServer() {\... | import org.noear.folkmq.FolkMQ;
import org.noear.folkmq.common.MqConstants;
import org.noear.folkmq.server.MqServer;
import org.noear.folkmq.server.MqServiceInternal;
import org.noear.folkmq.server.MqServiceListener;
import org.noear.folkmq.server.pro.MqWatcherSnapshotPlus;
import org.noear.folkmq.server.pro.admin.dso.ViewUtils;
import org.noear.folkmq.server.pro.common.ConfigNames;
import org.noear.snack.ONode;
import org.noear.socketd.SocketD;
import org.noear.socketd.transport.client.ClientSession;
import org.noear.socketd.transport.core.entity.StringEntity;
import org.noear.socketd.utils.StrUtils;
import org.noear.solon.Solon;
import org.noear.solon.Utils;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;
import org.noear.solon.core.AppContext;
import org.noear.solon.core.bean.LifecycleBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Map; | 8,172 | package org.noear.folkmq.server.pro.mq;
/**
* @author noear
* @since 1.0
*/
@Component
public class FolkmqLifecycleBean implements LifecycleBean {
private static final Logger log = LoggerFactory.getLogger(FolkmqLifecycleBean.class);
@Inject
private AppContext appContext;
private MqServer localServer;
| package org.noear.folkmq.server.pro.mq;
/**
* @author noear
* @since 1.0
*/
@Component
public class FolkmqLifecycleBean implements LifecycleBean {
private static final Logger log = LoggerFactory.getLogger(FolkmqLifecycleBean.class);
@Inject
private AppContext appContext;
private MqServer localServer;
| private MqServiceListener brokerServiceListener; | 4 | 2023-11-18 19:09:28+00:00 | 12k |
BlyznytsiaOrg/bring | web/src/test/java/io/github/blyznytsiaorg/bring/web/RestControllerTest.java | [
{
"identifier": "BringApplicationContext",
"path": "core/src/main/java/io/github/blyznytsiaorg/bring/core/context/impl/BringApplicationContext.java",
"snippet": "@Slf4j\npublic class BringApplicationContext extends AnnotationBringBeanRegistry implements BringBeanFactory {\n\n private final BeanPostPr... | import static org.assertj.core.api.Assertions.assertThat;
import static testdata.generalintegrationtest.ExampleRestController.User;
import io.github.blyznytsiaorg.bring.core.context.impl.BringApplicationContext;
import io.github.blyznytsiaorg.bring.web.server.properties.ServerProperties;
import io.github.blyznytsiaorg.bring.web.servlet.error.ErrorResponse;
import io.github.blyznytsiaorg.bring.web.servlet.http.HttpStatus;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.blyznytsiaorg.bring.web.utils.TestUtils;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse; | 7,742 | package io.github.blyznytsiaorg.bring.web;
class RestControllerTest {
public static final String HELLO_PATH = "/example/hello";
public static final String NUMBER_PATH = "/example/number";
public static final String REQUEST_PATH = "/example/request";
public static final String RESPONSE_PATH = "/example/response";
public static final String NOT_EXIST_PATH = "/not-exist";
public static final String STATUS = "/example/status";
public static final String URL = "http://localhost:%s%s";
public static final String APPLICATION_JSON = "application/json";
public static final String PACKAGE = "testdata.generalintegrationtest";
private static ObjectMapper objectMapper;
private static ServerProperties serverProperties;
private HttpClient httpClient;
@BeforeAll
static void beforeAll() {
BringApplicationContext bringApplicationContext = BringWebApplication.run(PACKAGE);
objectMapper = bringApplicationContext.getBean(ObjectMapper.class);
serverProperties = bringApplicationContext.getBean(ServerProperties.class);
}
@BeforeEach
void setUp() {
httpClient = HttpClient.newHttpClient();
}
@Test
@DisplayName("should return 'Hello'")
void shouldReturnHello() throws URISyntaxException, IOException, InterruptedException {
//given
String expectedValue = "Hello";
String url = getHost() + HELLO_PATH;
HttpRequest request = TestUtils.getHttpGetRequest(url);
//when
String actualResponse = httpClient.send(request, HttpResponse.BodyHandlers.ofString()).body();
//then
assertThat(actualResponse).isEqualTo(expectedValue);
}
@Test
@DisplayName("should return '200'")
void number_ok() throws IOException, InterruptedException, URISyntaxException {
//given
String expectedValue = "200";
String url = getHost() + NUMBER_PATH;
HttpRequest request = TestUtils.getHttpGetRequest(url);
//when
String actualResponse = httpClient.send(request, HttpResponse.BodyHandlers.ofString()).body();
//then
assertThat(actualResponse).isEqualTo(expectedValue);
}
@Test
@DisplayName("should return 'This application has no explicit mapping for 'path'")
void shouldThrowExceptionOnInvalidMapping() throws URISyntaxException, IOException, InterruptedException {
//given
String url = getHost() + NOT_EXIST_PATH;
HttpRequest request = TestUtils.getHttpGetRequest(url);
String expectedValue = String.format("This application has no explicit mapping for '%s'",
NOT_EXIST_PATH);
//when
String actualResponse = httpClient.send(request, HttpResponse.BodyHandlers.ofString()).body();
ErrorResponse errorResponse = objectMapper.readValue(actualResponse, ErrorResponse.class);
//then
assertThat(errorResponse.getMessage()).isEqualTo(expectedValue);
}
@Test
@DisplayName("should return Content-Length from HttpServletRequest")
void shouldUseHttpServletRequest() throws URISyntaxException, IOException, InterruptedException {
//given
String body = "I am sending PUT request";
int expectedValue = body.length();
String url = getHost() + REQUEST_PATH;
HttpRequest request = TestUtils.getHttpPutRequest(url, body);
//when
String actualResponse = httpClient.send(request, HttpResponse.BodyHandlers.ofString()).body();
//then
assertThat(Integer.parseInt(actualResponse)).isEqualTo(expectedValue);
}
@Test
@DisplayName("should return Content-Type from HttpServletResponse")
void shouldUseHttpServletResponse() throws URISyntaxException, IOException, InterruptedException {
//given
String url = getHost() + RESPONSE_PATH;
HttpRequest request = TestUtils.getHttpGetRequest(url);
//when
String actualResponse = httpClient.send(request, HttpResponse.BodyHandlers.ofString()).body();
//then
assertThat(actualResponse).isEqualTo(APPLICATION_JSON);
}
@Test
@DisplayName("should set a response status")
void shouldReturnResponseStatus() throws URISyntaxException, IOException, InterruptedException {
//given
String url = getHost() + STATUS;
HttpRequest request = TestUtils.getHttpGetRequest(url);
//when
HttpResponse<Void> response = httpClient.send(request, HttpResponse.BodyHandlers.discarding());
int actualStatusCode = response.statusCode();
//then | package io.github.blyznytsiaorg.bring.web;
class RestControllerTest {
public static final String HELLO_PATH = "/example/hello";
public static final String NUMBER_PATH = "/example/number";
public static final String REQUEST_PATH = "/example/request";
public static final String RESPONSE_PATH = "/example/response";
public static final String NOT_EXIST_PATH = "/not-exist";
public static final String STATUS = "/example/status";
public static final String URL = "http://localhost:%s%s";
public static final String APPLICATION_JSON = "application/json";
public static final String PACKAGE = "testdata.generalintegrationtest";
private static ObjectMapper objectMapper;
private static ServerProperties serverProperties;
private HttpClient httpClient;
@BeforeAll
static void beforeAll() {
BringApplicationContext bringApplicationContext = BringWebApplication.run(PACKAGE);
objectMapper = bringApplicationContext.getBean(ObjectMapper.class);
serverProperties = bringApplicationContext.getBean(ServerProperties.class);
}
@BeforeEach
void setUp() {
httpClient = HttpClient.newHttpClient();
}
@Test
@DisplayName("should return 'Hello'")
void shouldReturnHello() throws URISyntaxException, IOException, InterruptedException {
//given
String expectedValue = "Hello";
String url = getHost() + HELLO_PATH;
HttpRequest request = TestUtils.getHttpGetRequest(url);
//when
String actualResponse = httpClient.send(request, HttpResponse.BodyHandlers.ofString()).body();
//then
assertThat(actualResponse).isEqualTo(expectedValue);
}
@Test
@DisplayName("should return '200'")
void number_ok() throws IOException, InterruptedException, URISyntaxException {
//given
String expectedValue = "200";
String url = getHost() + NUMBER_PATH;
HttpRequest request = TestUtils.getHttpGetRequest(url);
//when
String actualResponse = httpClient.send(request, HttpResponse.BodyHandlers.ofString()).body();
//then
assertThat(actualResponse).isEqualTo(expectedValue);
}
@Test
@DisplayName("should return 'This application has no explicit mapping for 'path'")
void shouldThrowExceptionOnInvalidMapping() throws URISyntaxException, IOException, InterruptedException {
//given
String url = getHost() + NOT_EXIST_PATH;
HttpRequest request = TestUtils.getHttpGetRequest(url);
String expectedValue = String.format("This application has no explicit mapping for '%s'",
NOT_EXIST_PATH);
//when
String actualResponse = httpClient.send(request, HttpResponse.BodyHandlers.ofString()).body();
ErrorResponse errorResponse = objectMapper.readValue(actualResponse, ErrorResponse.class);
//then
assertThat(errorResponse.getMessage()).isEqualTo(expectedValue);
}
@Test
@DisplayName("should return Content-Length from HttpServletRequest")
void shouldUseHttpServletRequest() throws URISyntaxException, IOException, InterruptedException {
//given
String body = "I am sending PUT request";
int expectedValue = body.length();
String url = getHost() + REQUEST_PATH;
HttpRequest request = TestUtils.getHttpPutRequest(url, body);
//when
String actualResponse = httpClient.send(request, HttpResponse.BodyHandlers.ofString()).body();
//then
assertThat(Integer.parseInt(actualResponse)).isEqualTo(expectedValue);
}
@Test
@DisplayName("should return Content-Type from HttpServletResponse")
void shouldUseHttpServletResponse() throws URISyntaxException, IOException, InterruptedException {
//given
String url = getHost() + RESPONSE_PATH;
HttpRequest request = TestUtils.getHttpGetRequest(url);
//when
String actualResponse = httpClient.send(request, HttpResponse.BodyHandlers.ofString()).body();
//then
assertThat(actualResponse).isEqualTo(APPLICATION_JSON);
}
@Test
@DisplayName("should set a response status")
void shouldReturnResponseStatus() throws URISyntaxException, IOException, InterruptedException {
//given
String url = getHost() + STATUS;
HttpRequest request = TestUtils.getHttpGetRequest(url);
//when
HttpResponse<Void> response = httpClient.send(request, HttpResponse.BodyHandlers.discarding());
int actualStatusCode = response.statusCode();
//then | assertThat(actualStatusCode).isEqualTo(HttpStatus.ACCEPTED.getValue()); | 3 | 2023-11-10 13:42:05+00:00 | 12k |
johndeweyzxc/AWPS-Command | app/src/main/java/com/johndeweydev/awps/view/manualarmafragment/ManualArmaFragment.java | [
{
"identifier": "BAUD_RATE",
"path": "app/src/main/java/com/johndeweydev/awps/AppConstants.java",
"snippet": "public static final int BAUD_RATE = 19200;"
},
{
"identifier": "DATA_BITS",
"path": "app/src/main/java/com/johndeweydev/awps/AppConstants.java",
"snippet": "public static final i... | import static com.johndeweydev.awps.AppConstants.BAUD_RATE;
import static com.johndeweydev.awps.AppConstants.DATA_BITS;
import static com.johndeweydev.awps.AppConstants.PARITY_NONE;
import static com.johndeweydev.awps.AppConstants.STOP_BITS;
import android.content.Context;
import android.content.IntentSender;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.LinearLayoutManager;
import com.google.android.gms.common.api.ResolvableApiException;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResponse;
import com.google.android.gms.location.LocationSettingsStatusCodes;
import com.google.android.gms.location.Priority;
import com.google.android.gms.location.SettingsClient;
import com.google.android.gms.tasks.Task;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.textfield.TextInputEditText;
import com.johndeweydev.awps.R;
import com.johndeweydev.awps.databinding.FragmentManualArmaBinding;
import com.johndeweydev.awps.model.data.AccessPointData;
import com.johndeweydev.awps.model.data.DeviceConnectionParamData;
import com.johndeweydev.awps.model.data.HashInfoEntity;
import com.johndeweydev.awps.model.repo.serial.sessionreposerial.SessionRepoSerial;
import com.johndeweydev.awps.viewmodel.hashinfoviewmodel.HashInfoViewModel;
import com.johndeweydev.awps.viewmodel.serial.sessionviewmodel.SessionViewModel;
import com.johndeweydev.awps.viewmodel.serial.sessionviewmodel.SessionViewModelFactory;
import java.util.ArrayList;
import java.util.Objects; | 7,598 | package com.johndeweydev.awps.view.manualarmafragment;
public class ManualArmaFragment extends Fragment {
private FragmentManualArmaBinding binding;
private ManualArmaArgs manualArmaArgs = null;
private SessionViewModel sessionViewModel;
private HashInfoViewModel hashInfoViewModel;
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) { | package com.johndeweydev.awps.view.manualarmafragment;
public class ManualArmaFragment extends Fragment {
private FragmentManualArmaBinding binding;
private ManualArmaArgs manualArmaArgs = null;
private SessionViewModel sessionViewModel;
private HashInfoViewModel hashInfoViewModel;
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) { | SessionRepoSerial sessionRepoSerial = new SessionRepoSerial(); | 5 | 2023-11-15 15:54:39+00:00 | 12k |
Charles7c/continew-starter | continew-starter-extension/continew-starter-extension-crud/src/main/java/top/charles7c/continew/starter/extension/crud/base/BaseServiceImpl.java | [
{
"identifier": "ExceptionUtils",
"path": "continew-starter-core/src/main/java/top/charles7c/continew/starter/core/util/ExceptionUtils.java",
"snippet": "@Slf4j\n@NoArgsConstructor(access = AccessLevel.PRIVATE)\npublic class ExceptionUtils {\n\n /**\n * 打印线程异常信息\n *\n * @param runnable 线... | import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.Opt;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.util.ClassUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.transaction.annotation.Transactional;
import top.charles7c.continew.starter.core.util.ExceptionUtils;
import top.charles7c.continew.starter.core.util.ReflectUtils;
import top.charles7c.continew.starter.core.util.validate.CheckUtils;
import top.charles7c.continew.starter.data.mybatis.plus.base.BaseMapper;
import top.charles7c.continew.starter.data.mybatis.plus.query.QueryHelper;
import top.charles7c.continew.starter.extension.crud.annotation.TreeField;
import top.charles7c.continew.starter.extension.crud.model.query.PageQuery;
import top.charles7c.continew.starter.extension.crud.model.query.SortQuery;
import top.charles7c.continew.starter.extension.crud.model.resp.PageDataResp;
import top.charles7c.continew.starter.extension.crud.util.TreeUtils;
import top.charles7c.continew.starter.file.excel.util.ExcelUtils;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List; | 9,781 | /*
* Copyright (c) 2022-present Charles7c Authors. All Rights Reserved.
* <p>
* Licensed under the GNU LESSER GENERAL PUBLIC LICENSE 3.0;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.gnu.org/licenses/lgpl.html
* <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 top.charles7c.continew.starter.extension.crud.base;
/**
* 业务实现基类
*
* @param <M> Mapper 接口
* @param <T> 实体类
* @param <L> 列表信息
* @param <D> 详情信息
* @param <Q> 查询条件
* @param <C> 创建或修改信息
* @author Charles7c
* @since 1.0.0
*/
public abstract class BaseServiceImpl<M extends BaseMapper<T>, T extends BaseDO, L, D, Q, C extends BaseReq>
implements BaseService<L, D, Q, C> {
@Autowired
protected M baseMapper;
private final Class<T> entityClass;
private final Class<L> listClass;
private final Class<D> detailClass;
protected BaseServiceImpl() {
this.entityClass = (Class<T>) ClassUtil.getTypeArgument(this.getClass(), 1);
this.listClass = (Class<L>) ClassUtil.getTypeArgument(this.getClass(), 2);
this.detailClass = (Class<D>) ClassUtil.getTypeArgument(this.getClass(), 3);
}
@Override
public PageDataResp<L> page(Q query, PageQuery pageQuery) {
QueryWrapper<T> queryWrapper = QueryHelper.build(query);
IPage<T> page = baseMapper.selectPage(pageQuery.toPage(), queryWrapper);
PageDataResp<L> pageDataResp = PageDataResp.build(page, listClass);
pageDataResp.getList().forEach(this::fill);
return pageDataResp;
}
@Override
public List<Tree<Long>> tree(Q query, SortQuery sortQuery, boolean isSimple) {
List<L> list = this.list(query, sortQuery);
if (CollUtil.isEmpty(list)) {
return new ArrayList<>(0);
}
// 如果构建简单树结构,则不包含基本树结构之外的扩展字段
TreeNodeConfig treeNodeConfig = TreeUtils.DEFAULT_CONFIG;
TreeField treeField = listClass.getDeclaredAnnotation(TreeField.class);
if (!isSimple) {
// 根据 @TreeField 配置生成树结构配置
treeNodeConfig = TreeUtils.genTreeNodeConfig(treeField);
}
// 构建树
return TreeUtils.build(list, treeNodeConfig, (node, tree) -> {
// 转换器
tree.setId(ReflectUtil.invoke(node, StrUtil.genGetter(treeField.value())));
tree.setParentId(ReflectUtil.invoke(node, StrUtil.genGetter(treeField.parentIdKey())));
tree.setName(ReflectUtil.invoke(node, StrUtil.genGetter(treeField.nameKey())));
tree.setWeight(ReflectUtil.invoke(node, StrUtil.genGetter(treeField.weightKey())));
if (!isSimple) {
List<Field> fieldList = ReflectUtils.getNonStaticFields(listClass);
fieldList.removeIf(f -> StrUtil.containsAnyIgnoreCase(f.getName(), treeField.value(),
treeField.parentIdKey(), treeField.nameKey(), treeField.weightKey(), treeField.childrenKey()));
fieldList
.forEach(f -> tree.putExtra(f.getName(), ReflectUtil.invoke(node, StrUtil.genGetter(f.getName()))));
}
});
}
@Override
public List<L> list(Q query, SortQuery sortQuery) {
List<L> list = this.list(query, sortQuery, listClass);
list.forEach(this::fill);
return list;
}
/**
* 查询列表
*
* @param query 查询条件
* @param sortQuery 排序查询条件
* @param targetClass 指定类型
* @return 列表信息
*/
protected <E> List<E> list(Q query, SortQuery sortQuery, Class<E> targetClass) {
QueryWrapper<T> queryWrapper = QueryHelper.build(query);
// 设置排序
this.sort(queryWrapper, sortQuery);
List<T> entityList = baseMapper.selectList(queryWrapper);
return BeanUtil.copyToList(entityList, targetClass);
}
/**
* 设置排序
*
* @param queryWrapper 查询 Wrapper
* @param sortQuery 排序查询条件
*/
protected void sort(QueryWrapper<T> queryWrapper, SortQuery sortQuery) {
Sort sort = Opt.ofNullable(sortQuery).orElseGet(SortQuery::new).getSort();
for (Sort.Order order : sort) {
if (null != order) {
queryWrapper.orderBy(true, order.isAscending(), StrUtil.toUnderlineCase(order.getProperty()));
}
}
}
@Override
public D get(Long id) {
T entity = this.getById(id);
D detail = BeanUtil.copyProperties(entity, detailClass);
this.fillDetail(detail);
return detail;
}
@Override
public Long add(C req) {
if (null == req) {
return 0L;
}
T entity = BeanUtil.copyProperties(req, entityClass);
baseMapper.insert(entity);
return entity.getId();
}
@Override
public void update(C req, Long id) {
T entity = this.getById(id);
BeanUtil.copyProperties(req, entity, CopyOptions.create().ignoreNullValue());
baseMapper.updateById(entity);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void delete(List<Long> ids) {
baseMapper.deleteBatchIds(ids);
}
@Override
public void export(Q query, SortQuery sortQuery, HttpServletResponse response) {
List<D> list = this.list(query, sortQuery, detailClass);
list.forEach(this::fillDetail); | /*
* Copyright (c) 2022-present Charles7c Authors. All Rights Reserved.
* <p>
* Licensed under the GNU LESSER GENERAL PUBLIC LICENSE 3.0;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.gnu.org/licenses/lgpl.html
* <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 top.charles7c.continew.starter.extension.crud.base;
/**
* 业务实现基类
*
* @param <M> Mapper 接口
* @param <T> 实体类
* @param <L> 列表信息
* @param <D> 详情信息
* @param <Q> 查询条件
* @param <C> 创建或修改信息
* @author Charles7c
* @since 1.0.0
*/
public abstract class BaseServiceImpl<M extends BaseMapper<T>, T extends BaseDO, L, D, Q, C extends BaseReq>
implements BaseService<L, D, Q, C> {
@Autowired
protected M baseMapper;
private final Class<T> entityClass;
private final Class<L> listClass;
private final Class<D> detailClass;
protected BaseServiceImpl() {
this.entityClass = (Class<T>) ClassUtil.getTypeArgument(this.getClass(), 1);
this.listClass = (Class<L>) ClassUtil.getTypeArgument(this.getClass(), 2);
this.detailClass = (Class<D>) ClassUtil.getTypeArgument(this.getClass(), 3);
}
@Override
public PageDataResp<L> page(Q query, PageQuery pageQuery) {
QueryWrapper<T> queryWrapper = QueryHelper.build(query);
IPage<T> page = baseMapper.selectPage(pageQuery.toPage(), queryWrapper);
PageDataResp<L> pageDataResp = PageDataResp.build(page, listClass);
pageDataResp.getList().forEach(this::fill);
return pageDataResp;
}
@Override
public List<Tree<Long>> tree(Q query, SortQuery sortQuery, boolean isSimple) {
List<L> list = this.list(query, sortQuery);
if (CollUtil.isEmpty(list)) {
return new ArrayList<>(0);
}
// 如果构建简单树结构,则不包含基本树结构之外的扩展字段
TreeNodeConfig treeNodeConfig = TreeUtils.DEFAULT_CONFIG;
TreeField treeField = listClass.getDeclaredAnnotation(TreeField.class);
if (!isSimple) {
// 根据 @TreeField 配置生成树结构配置
treeNodeConfig = TreeUtils.genTreeNodeConfig(treeField);
}
// 构建树
return TreeUtils.build(list, treeNodeConfig, (node, tree) -> {
// 转换器
tree.setId(ReflectUtil.invoke(node, StrUtil.genGetter(treeField.value())));
tree.setParentId(ReflectUtil.invoke(node, StrUtil.genGetter(treeField.parentIdKey())));
tree.setName(ReflectUtil.invoke(node, StrUtil.genGetter(treeField.nameKey())));
tree.setWeight(ReflectUtil.invoke(node, StrUtil.genGetter(treeField.weightKey())));
if (!isSimple) {
List<Field> fieldList = ReflectUtils.getNonStaticFields(listClass);
fieldList.removeIf(f -> StrUtil.containsAnyIgnoreCase(f.getName(), treeField.value(),
treeField.parentIdKey(), treeField.nameKey(), treeField.weightKey(), treeField.childrenKey()));
fieldList
.forEach(f -> tree.putExtra(f.getName(), ReflectUtil.invoke(node, StrUtil.genGetter(f.getName()))));
}
});
}
@Override
public List<L> list(Q query, SortQuery sortQuery) {
List<L> list = this.list(query, sortQuery, listClass);
list.forEach(this::fill);
return list;
}
/**
* 查询列表
*
* @param query 查询条件
* @param sortQuery 排序查询条件
* @param targetClass 指定类型
* @return 列表信息
*/
protected <E> List<E> list(Q query, SortQuery sortQuery, Class<E> targetClass) {
QueryWrapper<T> queryWrapper = QueryHelper.build(query);
// 设置排序
this.sort(queryWrapper, sortQuery);
List<T> entityList = baseMapper.selectList(queryWrapper);
return BeanUtil.copyToList(entityList, targetClass);
}
/**
* 设置排序
*
* @param queryWrapper 查询 Wrapper
* @param sortQuery 排序查询条件
*/
protected void sort(QueryWrapper<T> queryWrapper, SortQuery sortQuery) {
Sort sort = Opt.ofNullable(sortQuery).orElseGet(SortQuery::new).getSort();
for (Sort.Order order : sort) {
if (null != order) {
queryWrapper.orderBy(true, order.isAscending(), StrUtil.toUnderlineCase(order.getProperty()));
}
}
}
@Override
public D get(Long id) {
T entity = this.getById(id);
D detail = BeanUtil.copyProperties(entity, detailClass);
this.fillDetail(detail);
return detail;
}
@Override
public Long add(C req) {
if (null == req) {
return 0L;
}
T entity = BeanUtil.copyProperties(req, entityClass);
baseMapper.insert(entity);
return entity.getId();
}
@Override
public void update(C req, Long id) {
T entity = this.getById(id);
BeanUtil.copyProperties(req, entity, CopyOptions.create().ignoreNullValue());
baseMapper.updateById(entity);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void delete(List<Long> ids) {
baseMapper.deleteBatchIds(ids);
}
@Override
public void export(Q query, SortQuery sortQuery, HttpServletResponse response) {
List<D> list = this.list(query, sortQuery, detailClass);
list.forEach(this::fillDetail); | ExcelUtils.export(list, "导出数据", detailClass, response); | 9 | 2023-11-16 15:48:18+00:00 | 12k |
xIdentified/Devotions | src/main/java/me/xidentified/devotions/Deity.java | [
{
"identifier": "Blessing",
"path": "src/main/java/me/xidentified/devotions/effects/Blessing.java",
"snippet": "public class Blessing extends Effect {\n\n private final PotionEffectType potionEffectType;\n\n public Blessing(String type, int duration, int potency, PotionEffectType potionEffectType)... | import lombok.Getter;
import me.xidentified.devotions.effects.Blessing;
import me.xidentified.devotions.effects.Curse;
import me.xidentified.devotions.managers.CooldownManager;
import me.xidentified.devotions.managers.RitualManager;
import me.xidentified.devotions.rituals.Ritual;
import me.xidentified.devotions.util.Messages;
import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors; | 8,299 | package me.xidentified.devotions;
public class Deity {
private final Devotions plugin;
// Getter methods below
@Getter public final String name;
@Getter private final String lore;
@Getter private final String alignment;
private final String domain;
private final List<Offering> offerings;
private final List<String> rituals;
private final List<Blessing> blessings; | package me.xidentified.devotions;
public class Deity {
private final Devotions plugin;
// Getter methods below
@Getter public final String name;
@Getter private final String lore;
@Getter private final String alignment;
private final String domain;
private final List<Offering> offerings;
private final List<String> rituals;
private final List<Blessing> blessings; | private final List<Curse> curses; | 1 | 2023-11-10 07:03:24+00:00 | 12k |
SplitfireUptown/datalinkx | datalinkx-job/src/main/java/com/datalinkx/datajob/action/FlinkAction.java | [
{
"identifier": "MessageHubConstants",
"path": "datalinkx-common/src/main/java/com/datalinkx/common/constants/MessageHubConstants.java",
"snippet": "public class MessageHubConstants {\n\n public static final String WHITE_TOPIC = \"DATALINKX:MESSAGEHUB:TOPIC\";\n\n public static final String REDIS_... | import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import com.datalinkx.common.constants.MessageHubConstants;
import com.datalinkx.common.constants.MetaConstants;
import com.datalinkx.datajob.bean.JobSyncModeForm;
import com.datalinkx.driver.dsdriver.DsDriverFactory;
import com.datalinkx.driver.dsdriver.IDsReader;
import com.datalinkx.driver.dsdriver.IDsWriter;
import com.datalinkx.driver.dsdriver.base.model.FlinkActionParam;
import com.datalinkx.common.exception.DatalinkXJobException;
import com.datalinkx.driver.model.DataTransJobDetail;
import com.datalinkx.driver.utils.JobUtils;
import com.datalinkx.common.utils.JsonUtils;
import com.datalinkx.datajob.bean.JobExecCountDto;
import com.datalinkx.datajob.bean.JobStateForm;
import com.datalinkx.datajob.client.datalinkxserver.DatalinkXServerClient;
import com.datalinkx.datajob.client.flink.FlinkClient;
import com.datalinkx.datajob.client.flink.response.FlinkJobAccumulators;
import com.datalinkx.datajob.client.flink.response.FlinkJobStatus;
import com.datalinkx.datajob.config.DsProperties;
import com.datalinkx.datajob.job.ExecutorJobHandler;
import com.datalinkx.messagehub.bean.form.ProducerAdapterForm;
import com.datalinkx.messagehub.service.MessageHubService;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils; | 8,797 | jobExecCountDto.setFilterCount(jobExecCountDto.getFilterCount() + value.getFilterCount());
});
}
datalinkXServerClient.updateJobStatus(JobStateForm.builder().jobId(info.getJobId())
.jobStatus(status).startTime(startTime.get()).endTime(new Date().getTime())
.tbTotal(JobUtils.cntx().getTotal()).tbSuccess(JobUtils.cntx().getSuccess())
.allCount(jobExecCountDto.getAllCount())
.appendCount(jobExecCountDto.getAppendCount())
.filterCount(jobExecCountDto.getFilterCount())
.errmsg(errmsg)
.build());
}
@Override
protected void beforeExec(FlinkActionParam unit) throws Exception {
// init reader and writer
initUnit(unit);
if (!ObjectUtils.isEmpty(unit.getErrorMsg())) {
throw new Exception(unit.getErrorMsg());
}
String fromDbType = unit.getReader().getType();
String toDbType = unit.getWriter().getType();
if (!this.isSupportedDb(fromDbType, toDbType)) {
log.error(String.format("flink not support from %s to %s", fromDbType, toDbType));
return;
}
log.info(String.format("jobid: %s, begin from %s to %s",
unit.getJobId(), unit.getReader().getTableName(), unit.getWriter().getTableName()));
// 同步表状态
IDsReader readDsDriver;
IDsWriter writeDsDriver;
try {
readDsDriver = DsDriverFactory.getDsReader(unit.getReader().getConnectId());
writeDsDriver = DsDriverFactory.getDsWriter(unit.getWriter().getConnectId());
unit.setDsReader(readDsDriver);
unit.setDsWriter(writeDsDriver);
} catch (Exception e) {
throw new Exception("ds not exist", e);
}
}
@Override
protected void execute(FlinkActionParam unit) throws Exception {
log.info(String.format("jobid: %s, exec from %s to %s",
unit.getJobId(), unit.getReader().getTableName(), unit.getWriter().getTableName()));
String taskId = unit.getTaskId();
try {
if (!ObjectUtils.isEmpty(taskId)) {
return;
}
Object reader = unit.getDsReader().getReaderInfo(unit);
Object writer = unit.getDsWriter().getWriterInfo(unit);
String readerStr = JsonUtils.toJson(reader);
String writerStr = JsonUtils.toJson(writer);
log.info(String.format("jobid : %s; reader: %s, writer: %s", unit.getJobId(), readerStr, writerStr));
taskId = executorJobHandler.execute(unit.getJobId(), readerStr, writerStr);
unit.setTaskId(taskId) ;
// 更新task
datalinkXServerClient.updateJobTaskRel(unit.getJobId(), taskId);
} catch (DatalinkXJobException e) {
log.error("flink sync failed", e);
throw e;
}
}
@Override
protected boolean checkResult(FlinkActionParam unitParam) throws DatalinkXJobException {
String taskId = unitParam.getTaskId();
if (StringUtils.isEmpty(taskId)) {
throw new DatalinkXJobException("flink task id is empty.");
}
FlinkJobStatus flinkJobStatus = JsonUtils.toObject(JsonUtils.toJson(flinkClient.jobStatus(taskId)), FlinkJobStatus.class);
String state = flinkJobStatus.getState();
if ("finished".equalsIgnoreCase(state)) {
computeRecords(unitParam, flinkJobStatus);
return true;
}
if ("failed".equalsIgnoreCase(state)) {
String errorMsg = "flink task failed.";
if (flinkClient != null) {
JsonNode jsonNode = flinkClient.jobExceptions(taskId);
if (jsonNode.has("all-exceptions")) {
Iterator<JsonNode> exceptions = jsonNode.get("all-exceptions").elements();
if (exceptions.hasNext()) {
errorMsg = exceptions.next().get("exception").asText();
}
}
}
log.error(errorMsg);
throw new DatalinkXJobException(errorMsg);
}
if ("canceled".equalsIgnoreCase(state)) {
log.error("flink task canceled.");
throw new DatalinkXJobException("flink task canceled.");
}
computeRecords(unitParam, flinkJobStatus);
return false;
}
private void computeRecords(FlinkActionParam unitParam, FlinkJobStatus flinkJobStatus) {
AtomicInteger readRecords = new AtomicInteger(0);
AtomicInteger writeRecords = new AtomicInteger(0);
AtomicInteger errorRecords = new AtomicInteger(0);
AtomicLong bytes = new AtomicLong(0);
| // CHECKSTYLE:OFF
package com.datalinkx.datajob.action;
@Slf4j
@Component
public class FlinkAction extends AbstractFlinkAction<DataTransJobDetail, DataTransJobDetail, FlinkActionParam> {
public static ThreadLocal<Long> startTime = new ThreadLocal<>();
public static ThreadLocal<Map<String, JobExecCountDto>> countRes = new ThreadLocal<>();
public static ThreadLocal<Thread> checkThread = new ThreadLocal<>();
public static final long SLEEP_TIME = 1000L;
@Autowired
private ExecutorJobHandler executorJobHandler;
@Autowired
private FlinkClient flinkClient;
@Autowired
private DatalinkXServerClient datalinkXServerClient;
@Autowired
private DsProperties dsProperties;
@Resource(name = "messageHubServiceImpl")
MessageHubService messageHubService;
public boolean isSupportedDb(String fromDbType, String toDbTYpe) {
return dsProperties.getDatasource().contains(fromDbType) && dsProperties.getDatasource().contains(toDbTYpe);
}
@Override
protected void begin(DataTransJobDetail info) {
// 更新同步任务的状态
startTime.set(new Date().getTime());
countRes.set(new HashMap<>());
JobExecCountDto jobExecCountDto = new JobExecCountDto();
log.info(String.format("jobid: %s, begin to sync", info.getJobId()));
datalinkXServerClient.updateJobStatus(JobStateForm.builder().jobId(info.getJobId())
.jobStatus(MetaConstants.JobStatus.JOB_STATUS_CREATE).startTime(startTime.get()).endTime(null)
.allCount(jobExecCountDto.getAllCount())
.appendCount(jobExecCountDto.getAppendCount())
.filterCount(jobExecCountDto.getFilterCount())
.build());
}
@Override
protected void end(DataTransJobDetail info, int status, String errmsg) {
JobExecCountDto jobExecCountDto = new JobExecCountDto();
log.info(String.format("jobid: %s, end to sync", info.getJobId()));
Thread thread = FlinkAction.checkThread.get();
if (null != thread && thread.isAlive()) {
thread.interrupt();
}
if (countRes.get() != null) {
countRes.get().forEach((key, value) -> {
jobExecCountDto.setAllCount(jobExecCountDto.getAllCount() + value.getAllCount());
jobExecCountDto.setAppendCount(jobExecCountDto.getAppendCount() + value.getAppendCount());
jobExecCountDto.setFilterCount(jobExecCountDto.getFilterCount() + value.getFilterCount());
});
}
datalinkXServerClient.updateJobStatus(JobStateForm.builder().jobId(info.getJobId())
.jobStatus(status).startTime(startTime.get()).endTime(new Date().getTime())
.tbTotal(JobUtils.cntx().getTotal()).tbSuccess(JobUtils.cntx().getSuccess())
.allCount(jobExecCountDto.getAllCount())
.appendCount(jobExecCountDto.getAppendCount())
.filterCount(jobExecCountDto.getFilterCount())
.errmsg(errmsg)
.build());
}
@Override
protected void beforeExec(FlinkActionParam unit) throws Exception {
// init reader and writer
initUnit(unit);
if (!ObjectUtils.isEmpty(unit.getErrorMsg())) {
throw new Exception(unit.getErrorMsg());
}
String fromDbType = unit.getReader().getType();
String toDbType = unit.getWriter().getType();
if (!this.isSupportedDb(fromDbType, toDbType)) {
log.error(String.format("flink not support from %s to %s", fromDbType, toDbType));
return;
}
log.info(String.format("jobid: %s, begin from %s to %s",
unit.getJobId(), unit.getReader().getTableName(), unit.getWriter().getTableName()));
// 同步表状态
IDsReader readDsDriver;
IDsWriter writeDsDriver;
try {
readDsDriver = DsDriverFactory.getDsReader(unit.getReader().getConnectId());
writeDsDriver = DsDriverFactory.getDsWriter(unit.getWriter().getConnectId());
unit.setDsReader(readDsDriver);
unit.setDsWriter(writeDsDriver);
} catch (Exception e) {
throw new Exception("ds not exist", e);
}
}
@Override
protected void execute(FlinkActionParam unit) throws Exception {
log.info(String.format("jobid: %s, exec from %s to %s",
unit.getJobId(), unit.getReader().getTableName(), unit.getWriter().getTableName()));
String taskId = unit.getTaskId();
try {
if (!ObjectUtils.isEmpty(taskId)) {
return;
}
Object reader = unit.getDsReader().getReaderInfo(unit);
Object writer = unit.getDsWriter().getWriterInfo(unit);
String readerStr = JsonUtils.toJson(reader);
String writerStr = JsonUtils.toJson(writer);
log.info(String.format("jobid : %s; reader: %s, writer: %s", unit.getJobId(), readerStr, writerStr));
taskId = executorJobHandler.execute(unit.getJobId(), readerStr, writerStr);
unit.setTaskId(taskId) ;
// 更新task
datalinkXServerClient.updateJobTaskRel(unit.getJobId(), taskId);
} catch (DatalinkXJobException e) {
log.error("flink sync failed", e);
throw e;
}
}
@Override
protected boolean checkResult(FlinkActionParam unitParam) throws DatalinkXJobException {
String taskId = unitParam.getTaskId();
if (StringUtils.isEmpty(taskId)) {
throw new DatalinkXJobException("flink task id is empty.");
}
FlinkJobStatus flinkJobStatus = JsonUtils.toObject(JsonUtils.toJson(flinkClient.jobStatus(taskId)), FlinkJobStatus.class);
String state = flinkJobStatus.getState();
if ("finished".equalsIgnoreCase(state)) {
computeRecords(unitParam, flinkJobStatus);
return true;
}
if ("failed".equalsIgnoreCase(state)) {
String errorMsg = "flink task failed.";
if (flinkClient != null) {
JsonNode jsonNode = flinkClient.jobExceptions(taskId);
if (jsonNode.has("all-exceptions")) {
Iterator<JsonNode> exceptions = jsonNode.get("all-exceptions").elements();
if (exceptions.hasNext()) {
errorMsg = exceptions.next().get("exception").asText();
}
}
}
log.error(errorMsg);
throw new DatalinkXJobException(errorMsg);
}
if ("canceled".equalsIgnoreCase(state)) {
log.error("flink task canceled.");
throw new DatalinkXJobException("flink task canceled.");
}
computeRecords(unitParam, flinkJobStatus);
return false;
}
private void computeRecords(FlinkActionParam unitParam, FlinkJobStatus flinkJobStatus) {
AtomicInteger readRecords = new AtomicInteger(0);
AtomicInteger writeRecords = new AtomicInteger(0);
AtomicInteger errorRecords = new AtomicInteger(0);
AtomicLong bytes = new AtomicLong(0);
| FlinkJobAccumulators flinkJobAccumulators = JsonUtils.toObject( | 15 | 2023-11-16 02:22:52+00:00 | 12k |
12manel123/tsys-my-food-api-1011 | src/main/java/com/myfood/controllers/OrderController.java | [
{
"identifier": "Dish",
"path": "src/main/java/com/myfood/dto/Dish.java",
"snippet": "@Entity\n@Table(name = \"dishes\")\npublic class Dish {\n\n @Id\n @Column(name = \"id\")\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n \n\t@Column(name = \"name\", nullable =... | import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.data.domain.Pageable;
import com.myfood.dto.Dish;
import com.myfood.dto.ListOrder;
import com.myfood.dto.Order;
import com.myfood.dto.OrderCookDTO;
import com.myfood.dto.OrderUserDTO;
import com.myfood.dto.Slot;
import com.myfood.dto.User;
import com.myfood.services.OrderServiceImpl;
import com.myfood.services.SlotServiceImpl;
import com.myfood.services.UserServiceImpl;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import jakarta.transaction.Transactional; | 7,867 | package com.myfood.controllers;
@RestController
@RequestMapping("api/v1")
public class OrderController {
@Autowired
private OrderServiceImpl orderService;
@Autowired
private SlotServiceImpl slotService;
@Autowired
private UserServiceImpl userService;
/**
* Retrieves a paginated list of user orders with Dishes. It's for the ADMIN
*
* @param page The page number (default is 0).
* @param size The number of orders per page (default is 10).
* @return ResponseEntity containing a paginated list of {@link OrderUserDTO}.
* @see OrderService#getAllOrdersWithPagination(Pageable)
*/
@Transactional
@Operation(summary = "Endpoint for ADMIN", security = @SecurityRequirement(name = "bearerAuth"))
@GetMapping("/orders")
public ResponseEntity<Page<OrderCookDTO>> getAllOrdersWithDish(
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "8") int size) {
List<Order> ordersForCook = orderService.getAllOrders();
List<Order> filteredOrders = ordersForCook.stream()
.filter(order -> order.getActualDate() != null)
.collect(Collectors.toList());
Pageable pageable = PageRequest.of(page, size);
Page<Order> paginatedOrders = paginate(filteredOrders, pageable);
List<OrderCookDTO> orderCookDTOList = paginatedOrders.getContent().stream()
.map(this::mapToOrderCookDTOWithDishes)
.collect(Collectors.toList());
return ResponseEntity.ok(new PageImpl<>(orderCookDTOList, pageable, filteredOrders.size()));
}
/**
* Retrieves details of a specific order identified by its ID. It's for the ADMIN
*
* @param id The unique identifier of the order.
* @return ResponseEntity containing the details of the order as an {@link OrderUserDTO}.
* @throws DataNotFoundException If the specified order does not exist.
* @see OrderService#getOneOrder(Long)
*/
@Operation(summary = "Endpoint for ADMIN", security = @SecurityRequirement(name = "bearerAuth"))
@PreAuthorize("hasRole('ADMIN')")
@GetMapping("/order/{id}")
public ResponseEntity<?> getOneOrder(@PathVariable(name = "id") Long id) {
Optional<Order> entity = orderService.getOneOrder(id);
if (entity.isPresent()) {
Order order = entity.get();
OrderUserDTO orderUserDTO = new OrderUserDTO(order.getId(), order.isMaked(), order.getSlot(),order.getTotalPrice(),order.getActualDate());
return ResponseEntity.ok(orderUserDTO);
} else {
return createErrorResponse("The order not exists", HttpStatus.NOT_FOUND);
}
}
/**
* Creates a new order based on the provided order details. It's for the ADMIN
*
* @param entity The order details provided in the request body.
* @return ResponseEntity containing the details of the created order as an {@link OrderUserDTO}.
* {@link OrderUserDTO} and returned in the ResponseEntity with status 200 (OK).
* @see OrderService#createOrder(Order)
*/
@Operation(summary = "Endpoint for ADMIN", security = @SecurityRequirement(name = "bearerAuth"))
@PreAuthorize("hasRole('ADMIN')")
@PostMapping("/order")
public ResponseEntity<OrderUserDTO> saveOrder(@RequestBody Order entity) {
Order savedOrder = orderService.createOrder(entity);
OrderUserDTO orderUserDTO = new OrderUserDTO(savedOrder.getId(), savedOrder.isMaked(), savedOrder.getSlot(),savedOrder.getTotalPrice(),savedOrder.getActualDate());
return ResponseEntity.ok(orderUserDTO);
}
/**
* Updates an existing order with the provided order details. It's for ADMIN
*
* @param id The identifier of the order to be updated.
* @param entity The updated order details provided in the request body.
* @return ResponseEntity containing a message and the details of the updated
* order as an {@link OrderUserDTO}.
* @see OrderService#getOneOrder(Long)
* @see OrderService#updateOrder(Long, Order)
*/
@Operation(summary = "Endpoint for ADMIN", security = @SecurityRequirement(name = "bearerAuth"))
@PreAuthorize("hasRole('ADMIN')")
@PutMapping("/order/{id}")
public ResponseEntity<?> updateOrder(@PathVariable(name = "id") Long id, @RequestBody Order entity) {
Optional<Order> entityOld = orderService.getOneOrder(id);
if (entityOld.isPresent()) {
return ResponseEntity.ok(Map.of("Message", "Updated order", "order",
new OrderUserDTO(id, entity.isMaked(), entity.getSlot(),entity.getTotalPrice(),entity.getActualDate())));
} else {
return createErrorResponse("The order not exists", HttpStatus.NOT_FOUND);
}
}
/**
* Deletes an existing order based on the provided order ID. It's for ADMIN
*
* @param id The identifier of the order to be deleted.
* @return ResponseEntity indicating the success or failure of the delete operation.
* @see OrderService#getOneOrder(Long)
* @see OrderService#deleteOrder(Long)
*/
@Transactional
@Operation(summary = "Endpoint for ADMIN", security = @SecurityRequirement(name = "bearerAuth"))
@PreAuthorize("hasRole('ADMIN')")
@DeleteMapping("/order/{id}")
public ResponseEntity<?> deleteOrder(@PathVariable(name = "id") Long id) {
Optional<Order> entity = orderService.getOneOrder(id);
if (entity.isPresent()) {
Order order = entity.get();
order.setActualDate(null);
order.setSlot(null);
orderService.deleteOrder(id);
return ResponseEntity.status(204).body(Map.of("Message", "Order deleted"));
} else {
return createErrorResponse("The order not exists", HttpStatus.BAD_REQUEST);
}
}
/**
* Retrieves a paginated list of orders suitable for a cook, including
* associated dishes. It's for CHEF
*
* @param page The page number for pagination (default is 0).
* @param size The number of orders per page (default is 8).
* @return ResponseEntity containing a paginated list of OrderCookDTO objects.
* @see OrderService#getAllOrdersForCook()
* @see OrderController#mapToOrderCookDTO(Order)
* @see OrderController#paginate(List, Pageable)
* @see OrderCookDTO
*/
@Transactional
@Operation(summary = "Endpoint for CHEF and ADMIN", security = @SecurityRequirement(name = "bearerAuth"))
@GetMapping("/orders/chef")
public ResponseEntity<Page<OrderCookDTO>> getAllOrdersForChef(
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "8") int size) {
List<Order> ordersForCook = orderService.getAllOrdersForCook();
List<Order> filteredOrders = ordersForCook.stream()
.filter(order -> order.getActualDate() != null)
.collect(Collectors.toList());
Pageable pageable = PageRequest.of(page, size);
Page<Order> paginatedOrders = paginate(filteredOrders, pageable);
List<OrderCookDTO> orderCookDTOList = paginatedOrders.getContent().stream()
.map(this::mapToOrderCookDTOWithDishes)
.collect(Collectors.toList());
return ResponseEntity.ok(new PageImpl<>(orderCookDTOList, pageable, filteredOrders.size()));
}
private OrderCookDTO mapToOrderCookDTOWithDishes(Order order) {
OrderCookDTO orderCookDTO = new OrderCookDTO();
orderCookDTO.setOrderId(order.getId());
orderCookDTO.setMaked(order.isMaked());
orderCookDTO.setSlot(order.getSlot());
orderCookDTO.setActualDate(order.getActualDate());
orderCookDTO.setTotalPrice(order.getTotalPrice());
List<ListOrder> listOrders = order.getListOrder(); | package com.myfood.controllers;
@RestController
@RequestMapping("api/v1")
public class OrderController {
@Autowired
private OrderServiceImpl orderService;
@Autowired
private SlotServiceImpl slotService;
@Autowired
private UserServiceImpl userService;
/**
* Retrieves a paginated list of user orders with Dishes. It's for the ADMIN
*
* @param page The page number (default is 0).
* @param size The number of orders per page (default is 10).
* @return ResponseEntity containing a paginated list of {@link OrderUserDTO}.
* @see OrderService#getAllOrdersWithPagination(Pageable)
*/
@Transactional
@Operation(summary = "Endpoint for ADMIN", security = @SecurityRequirement(name = "bearerAuth"))
@GetMapping("/orders")
public ResponseEntity<Page<OrderCookDTO>> getAllOrdersWithDish(
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "8") int size) {
List<Order> ordersForCook = orderService.getAllOrders();
List<Order> filteredOrders = ordersForCook.stream()
.filter(order -> order.getActualDate() != null)
.collect(Collectors.toList());
Pageable pageable = PageRequest.of(page, size);
Page<Order> paginatedOrders = paginate(filteredOrders, pageable);
List<OrderCookDTO> orderCookDTOList = paginatedOrders.getContent().stream()
.map(this::mapToOrderCookDTOWithDishes)
.collect(Collectors.toList());
return ResponseEntity.ok(new PageImpl<>(orderCookDTOList, pageable, filteredOrders.size()));
}
/**
* Retrieves details of a specific order identified by its ID. It's for the ADMIN
*
* @param id The unique identifier of the order.
* @return ResponseEntity containing the details of the order as an {@link OrderUserDTO}.
* @throws DataNotFoundException If the specified order does not exist.
* @see OrderService#getOneOrder(Long)
*/
@Operation(summary = "Endpoint for ADMIN", security = @SecurityRequirement(name = "bearerAuth"))
@PreAuthorize("hasRole('ADMIN')")
@GetMapping("/order/{id}")
public ResponseEntity<?> getOneOrder(@PathVariable(name = "id") Long id) {
Optional<Order> entity = orderService.getOneOrder(id);
if (entity.isPresent()) {
Order order = entity.get();
OrderUserDTO orderUserDTO = new OrderUserDTO(order.getId(), order.isMaked(), order.getSlot(),order.getTotalPrice(),order.getActualDate());
return ResponseEntity.ok(orderUserDTO);
} else {
return createErrorResponse("The order not exists", HttpStatus.NOT_FOUND);
}
}
/**
* Creates a new order based on the provided order details. It's for the ADMIN
*
* @param entity The order details provided in the request body.
* @return ResponseEntity containing the details of the created order as an {@link OrderUserDTO}.
* {@link OrderUserDTO} and returned in the ResponseEntity with status 200 (OK).
* @see OrderService#createOrder(Order)
*/
@Operation(summary = "Endpoint for ADMIN", security = @SecurityRequirement(name = "bearerAuth"))
@PreAuthorize("hasRole('ADMIN')")
@PostMapping("/order")
public ResponseEntity<OrderUserDTO> saveOrder(@RequestBody Order entity) {
Order savedOrder = orderService.createOrder(entity);
OrderUserDTO orderUserDTO = new OrderUserDTO(savedOrder.getId(), savedOrder.isMaked(), savedOrder.getSlot(),savedOrder.getTotalPrice(),savedOrder.getActualDate());
return ResponseEntity.ok(orderUserDTO);
}
/**
* Updates an existing order with the provided order details. It's for ADMIN
*
* @param id The identifier of the order to be updated.
* @param entity The updated order details provided in the request body.
* @return ResponseEntity containing a message and the details of the updated
* order as an {@link OrderUserDTO}.
* @see OrderService#getOneOrder(Long)
* @see OrderService#updateOrder(Long, Order)
*/
@Operation(summary = "Endpoint for ADMIN", security = @SecurityRequirement(name = "bearerAuth"))
@PreAuthorize("hasRole('ADMIN')")
@PutMapping("/order/{id}")
public ResponseEntity<?> updateOrder(@PathVariable(name = "id") Long id, @RequestBody Order entity) {
Optional<Order> entityOld = orderService.getOneOrder(id);
if (entityOld.isPresent()) {
return ResponseEntity.ok(Map.of("Message", "Updated order", "order",
new OrderUserDTO(id, entity.isMaked(), entity.getSlot(),entity.getTotalPrice(),entity.getActualDate())));
} else {
return createErrorResponse("The order not exists", HttpStatus.NOT_FOUND);
}
}
/**
* Deletes an existing order based on the provided order ID. It's for ADMIN
*
* @param id The identifier of the order to be deleted.
* @return ResponseEntity indicating the success or failure of the delete operation.
* @see OrderService#getOneOrder(Long)
* @see OrderService#deleteOrder(Long)
*/
@Transactional
@Operation(summary = "Endpoint for ADMIN", security = @SecurityRequirement(name = "bearerAuth"))
@PreAuthorize("hasRole('ADMIN')")
@DeleteMapping("/order/{id}")
public ResponseEntity<?> deleteOrder(@PathVariable(name = "id") Long id) {
Optional<Order> entity = orderService.getOneOrder(id);
if (entity.isPresent()) {
Order order = entity.get();
order.setActualDate(null);
order.setSlot(null);
orderService.deleteOrder(id);
return ResponseEntity.status(204).body(Map.of("Message", "Order deleted"));
} else {
return createErrorResponse("The order not exists", HttpStatus.BAD_REQUEST);
}
}
/**
* Retrieves a paginated list of orders suitable for a cook, including
* associated dishes. It's for CHEF
*
* @param page The page number for pagination (default is 0).
* @param size The number of orders per page (default is 8).
* @return ResponseEntity containing a paginated list of OrderCookDTO objects.
* @see OrderService#getAllOrdersForCook()
* @see OrderController#mapToOrderCookDTO(Order)
* @see OrderController#paginate(List, Pageable)
* @see OrderCookDTO
*/
@Transactional
@Operation(summary = "Endpoint for CHEF and ADMIN", security = @SecurityRequirement(name = "bearerAuth"))
@GetMapping("/orders/chef")
public ResponseEntity<Page<OrderCookDTO>> getAllOrdersForChef(
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "8") int size) {
List<Order> ordersForCook = orderService.getAllOrdersForCook();
List<Order> filteredOrders = ordersForCook.stream()
.filter(order -> order.getActualDate() != null)
.collect(Collectors.toList());
Pageable pageable = PageRequest.of(page, size);
Page<Order> paginatedOrders = paginate(filteredOrders, pageable);
List<OrderCookDTO> orderCookDTOList = paginatedOrders.getContent().stream()
.map(this::mapToOrderCookDTOWithDishes)
.collect(Collectors.toList());
return ResponseEntity.ok(new PageImpl<>(orderCookDTOList, pageable, filteredOrders.size()));
}
private OrderCookDTO mapToOrderCookDTOWithDishes(Order order) {
OrderCookDTO orderCookDTO = new OrderCookDTO();
orderCookDTO.setOrderId(order.getId());
orderCookDTO.setMaked(order.isMaked());
orderCookDTO.setSlot(order.getSlot());
orderCookDTO.setActualDate(order.getActualDate());
orderCookDTO.setTotalPrice(order.getTotalPrice());
List<ListOrder> listOrders = order.getListOrder(); | List<Dish> dishDTOList = listOrders.stream() | 0 | 2023-11-10 16:09:43+00:00 | 12k |
kotmatross28729/EnviroMine-continuation | src/main/java/enviromine/client/gui/SaveController.java | [
{
"identifier": "HUDRegistry",
"path": "src/main/java/enviromine/client/gui/hud/HUDRegistry.java",
"snippet": "public class HUDRegistry {\n protected static List<HudItem> hudItemList = new ArrayList<HudItem>();\n protected static boolean initialLoadComplete = false;\n protected static List<HudI... | import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import enviromine.client.gui.hud.HUDRegistry;
import enviromine.client.gui.hud.HudItem;
import enviromine.core.EM_ConfigHandler.EnumLogVerbosity;
import enviromine.core.EM_Settings;
import enviromine.core.EnviroMine;
import net.minecraft.client.Minecraft;
import net.minecraft.crash.CrashReport;
import net.minecraft.nbt.CompressedStreamTools;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.ReportedException; | 8,055 | package enviromine.client.gui;
@SideOnly(Side.CLIENT)
public class SaveController {
/**
* Configuration version number. If changed the version file will be reset to defaults to prevent glitches
*/
static final String CONFIG_VERSION = "1.0.0";
/**
* The version of the configs last loaded from file. This will be compared to the version number above when determining whether a reset is necessary
*/
static String LOADED_VERSION = "1.0.0";
protected static final String dirName = Minecraft.getMinecraft().mcDataDir + File.separator + "config" + File.separator + "enviromine";
protected static File dir = new File(dirName);
public static String UISettingsData = "UI_Settings";
public static boolean loadConfig(String name) {
return loadConfig(name, null);
}
public static boolean loadConfig(String name, String dirName) {
if (dirName != null) {
dir = new File(Minecraft.getMinecraft().mcDataDir + File.separator + dirName);
}
String fileName = name + ".dat";
File file = new File(dir, fileName);
if (!file.exists())
{
if (EM_Settings.loggerVerbosity >= EnumLogVerbosity.NORMAL.getLevel()) EnviroMine.logger.warn("Config load canceled, file ("+ file.getAbsolutePath() +") does not exist. This is normal for first run.");
return false;
} else {
if (EM_Settings.loggerVerbosity >= EnumLogVerbosity.ALL.getLevel()) EnviroMine.logger.info("Config load successful.");
}
try {
NBTTagCompound nbt = CompressedStreamTools.readCompressed(new FileInputStream(file));
if (nbt.hasNoTags() || !nbt.hasKey(UISettingsData))
{
return false;
}
UI_Settings.readFromNBT(nbt.getCompoundTag(UISettingsData)); | package enviromine.client.gui;
@SideOnly(Side.CLIENT)
public class SaveController {
/**
* Configuration version number. If changed the version file will be reset to defaults to prevent glitches
*/
static final String CONFIG_VERSION = "1.0.0";
/**
* The version of the configs last loaded from file. This will be compared to the version number above when determining whether a reset is necessary
*/
static String LOADED_VERSION = "1.0.0";
protected static final String dirName = Minecraft.getMinecraft().mcDataDir + File.separator + "config" + File.separator + "enviromine";
protected static File dir = new File(dirName);
public static String UISettingsData = "UI_Settings";
public static boolean loadConfig(String name) {
return loadConfig(name, null);
}
public static boolean loadConfig(String name, String dirName) {
if (dirName != null) {
dir = new File(Minecraft.getMinecraft().mcDataDir + File.separator + dirName);
}
String fileName = name + ".dat";
File file = new File(dir, fileName);
if (!file.exists())
{
if (EM_Settings.loggerVerbosity >= EnumLogVerbosity.NORMAL.getLevel()) EnviroMine.logger.warn("Config load canceled, file ("+ file.getAbsolutePath() +") does not exist. This is normal for first run.");
return false;
} else {
if (EM_Settings.loggerVerbosity >= EnumLogVerbosity.ALL.getLevel()) EnviroMine.logger.info("Config load successful.");
}
try {
NBTTagCompound nbt = CompressedStreamTools.readCompressed(new FileInputStream(file));
if (nbt.hasNoTags() || !nbt.hasKey(UISettingsData))
{
return false;
}
UI_Settings.readFromNBT(nbt.getCompoundTag(UISettingsData)); | HUDRegistry.readFromNBT(nbt.getCompoundTag(UISettingsData)); | 0 | 2023-11-16 18:15:29+00:00 | 12k |
spring-projects/spring-rewrite-commons | spring-rewrite-commons-launcher/src/test/java/org/springframework/rewrite/parsers/RewriteProjectParserParityTest.java | [
{
"identifier": "ComparingParserFactory",
"path": "spring-rewrite-commons-launcher/src/test/java/org/springframework/rewrite/parsers/maven/ComparingParserFactory.java",
"snippet": "public class ComparingParserFactory {\n\n\t@NotNull\n\tpublic RewriteMavenProjectParser createComparingParser() {\n\t\tretu... | import org.intellij.lang.annotations.Language;
import org.jetbrains.annotations.NotNull;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.junit.jupiter.api.io.TempDir;
import org.junitpioneer.jupiter.Issue;
import org.openrewrite.ExecutionContext;
import org.openrewrite.InMemoryExecutionContext;
import org.openrewrite.Parser;
import org.openrewrite.SourceFile;
import org.openrewrite.shaded.jgit.api.errors.GitAPIException;
import org.openrewrite.tree.ParsingEventListener;
import org.openrewrite.tree.ParsingExecutionContextView;
import org.springframework.rewrite.parsers.maven.ComparingParserFactory;
import org.springframework.rewrite.parsers.maven.RewriteMavenProjectParser;
import org.springframework.rewrite.test.util.DummyResource;
import org.springframework.rewrite.test.util.ParserParityTestHelper;
import org.springframework.rewrite.test.util.TestProjectHelper;
import java.nio.file.Path;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.AssertionsForClassTypes.fail; | 7,819 | /*
* Copyright 2021 - 2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 org.springframework.rewrite.parsers;
/**
* Test parity between OpenRewrite parser logic and RewriteProjectParser.
*
* RewriteMavenProjectParser resembles the parser logic from OpenRewrite's Maven plugin
*
* @author Fabian Krüger
*/
@DisabledOnOs(value = OS.WINDOWS, disabledReason = "The repository URIs of dependencies differ.")
@Issue("https://github.com/spring-projects/spring-rewrite-commons/issues/12")
class RewriteProjectParserParityTest {
@Test
@DisplayName("Parsing Simplistic Maven Project ")
void parsingSimplisticMavenProject(@TempDir Path tempDir) throws GitAPIException {
@Language("xml")
String pomXml = """
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>root-project</artifactId>
<version>1.0.0</version>
<properties>
<maven.compiler.target>17</maven.compiler.target>
<maven.compiler.source>17</maven.compiler.source>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<repositories>
<repository>
<id>jcenter</id>
<name>jcenter</name>
<url>https://jcenter.bintray.com</url>
</repository>
<repository>
<id>mavencentral</id>
<name>mavencentral</name>
<url>https://repo.maven.apache.org/maven2</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>3.1.1</version>
</dependency>
</dependencies>
</project>
""";
@Language("java")
String javaClass = """
package com.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MyMain {
public static void main(String[] args){
SpringApplication.run(MyMain.class, args);
}
}
""";
TestProjectHelper.createTestProject(tempDir) | /*
* Copyright 2021 - 2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 org.springframework.rewrite.parsers;
/**
* Test parity between OpenRewrite parser logic and RewriteProjectParser.
*
* RewriteMavenProjectParser resembles the parser logic from OpenRewrite's Maven plugin
*
* @author Fabian Krüger
*/
@DisabledOnOs(value = OS.WINDOWS, disabledReason = "The repository URIs of dependencies differ.")
@Issue("https://github.com/spring-projects/spring-rewrite-commons/issues/12")
class RewriteProjectParserParityTest {
@Test
@DisplayName("Parsing Simplistic Maven Project ")
void parsingSimplisticMavenProject(@TempDir Path tempDir) throws GitAPIException {
@Language("xml")
String pomXml = """
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>root-project</artifactId>
<version>1.0.0</version>
<properties>
<maven.compiler.target>17</maven.compiler.target>
<maven.compiler.source>17</maven.compiler.source>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<repositories>
<repository>
<id>jcenter</id>
<name>jcenter</name>
<url>https://jcenter.bintray.com</url>
</repository>
<repository>
<id>mavencentral</id>
<name>mavencentral</name>
<url>https://repo.maven.apache.org/maven2</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>3.1.1</version>
</dependency>
</dependencies>
</project>
""";
@Language("java")
String javaClass = """
package com.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MyMain {
public static void main(String[] args){
SpringApplication.run(MyMain.class, args);
}
}
""";
TestProjectHelper.createTestProject(tempDir) | .withResources(new DummyResource(tempDir.resolve("src/main/java/com/example/MyMain.java"), javaClass), | 2 | 2023-11-14 23:02:37+00:00 | 12k |
exadel-inc/etoolbox-anydiff | core/src/test/java/com/exadel/etoolbox/anydiff/runner/FilterHelperTest.java | [
{
"identifier": "AnyDiff",
"path": "core/src/main/java/com/exadel/etoolbox/anydiff/AnyDiff.java",
"snippet": "public class AnyDiff {\n\n private String[] leftStrings;\n private Path[] leftPaths;\n private String leftLabel;\n private String[] rightStrings;\n private Path[] rightPaths;\n ... | import java.util.List;
import java.util.function.Predicate;
import com.exadel.etoolbox.anydiff.AnyDiff;
import com.exadel.etoolbox.anydiff.ContentType;
import com.exadel.etoolbox.anydiff.comparison.DiffTask;
import com.exadel.etoolbox.anydiff.diff.Diff;
import com.exadel.etoolbox.anydiff.diff.DiffEntry;
import com.exadel.etoolbox.anydiff.diff.EntryHolder;
import com.exadel.etoolbox.anydiff.diff.Fragment;
import com.exadel.etoolbox.anydiff.diff.FragmentHolder;
import com.exadel.etoolbox.anydiff.diff.FragmentPair;
import com.exadel.etoolbox.anydiff.diff.MarkupFragment;
import com.exadel.etoolbox.anydiff.filter.Filter;
import lombok.RequiredArgsConstructor;
import org.junit.Assert;
import org.junit.Test;
import java.util.Arrays;
import java.util.Collections; | 10,145 |
@Test
public void shouldFilterMarkupByFragmentPair() {
List<? extends DiffEntry> entries = DiffTask
.builder()
.contentType(ContentType.HTML)
.leftContent("<div class=\"lorem\">Lorem <span>ipsum</span> dolor sit amet</div> consectetur adipiscing elit")
.rightContent("<div class=\"lorum\">Lorem <span>dolorum</span> dolor sat amet</div> consectetur adipiscing elet")
.build()
.run()
.children();
Assert.assertEquals(3, entries.size());
DiffEntry block0 = entries.get(0);
Predicate<DiffEntry> processingFilter = FilterHelper.getEntryFilter(Arrays.asList(new SkipNone(), new SkipMarkupFragments()));
boolean testResult = processingFilter.test(block0);
List<Fragment> fragments = block0.as(EntryHolder.class).children().get(1).as(FragmentHolder.class).getFragments();
Assert.assertTrue(testResult);
Assert.assertTrue(fragments.stream().noneMatch(Fragment::isPending));
DiffEntry block1 = entries.get(1);
processingFilter = FilterHelper.getEntryFilter(Arrays.asList(
new SkipMarkupFragments(),
new SkipFragmentPair("sit", "sat")
));
testResult = processingFilter.test(block1);
Assert.assertFalse(testResult);
DiffEntry block2 = entries.get(2);
processingFilter = FilterHelper.getEntryFilter(Arrays.asList(
new SkipMarkupFragments(),
new SkipFragmentPair("elit", "elet")
));
testResult = processingFilter.test(block2);
Assert.assertFalse(testResult);
}
@Test
public void shouldFilterByFragment() {
List<? extends DiffEntry> entries = DiffTask
.builder()
.leftContent(LEFT)
.rightContent(RIGHT)
.build()
.run()
.children();
Assert.assertEquals(1, entries.size());
Predicate<DiffEntry> processingFilter = FilterHelper.getEntryFilter(Collections.singletonList(new SkipFragment("sit")));
Assert.assertTrue(processingFilter.test(entries.get(0)));
processingFilter = FilterHelper.getEntryFilter(Arrays.asList(new SkipFragment("sit"), new SkipFragment("sat")));
Assert.assertFalse(processingFilter.test(entries.get(0)));
}
/* ----------
Rule cases
---------- */
private static class SkipNone implements Filter {
}
private static class SkipAnyDiff implements Filter {
@Override
public boolean skipDiff(Diff value) {
return true;
}
}
private static class SkipBlock implements Filter {
@Override
public boolean skipBlock(DiffEntry value) {
return value.getLeft().contains("sit") && value.getLeft().contains("elit");
}
}
@RequiredArgsConstructor
private static class SkipWhenContainsFragment implements Filter {
private final String fragment;
@Override
public boolean skipLine(DiffEntry value) {
return value instanceof FragmentHolder
&& ((FragmentHolder) value)
.getLeftFragments()
.stream()
.anyMatch(f -> f.isDelete() && f.toString().equals(fragment));
}
}
@RequiredArgsConstructor
private static class SkipFragment implements Filter {
private final String fragment;
@Override
public boolean skipFragment(Fragment value) {
return fragment.equals(value.toString());
}
}
@RequiredArgsConstructor
private static class SkipFragmentPair implements Filter {
private final String leftSample;
private final String rightSample;
@Override
public boolean skipFragments(FragmentPair value) {
return value.getLeftFragment().equals(leftSample) && value.getRightFragment().equals(rightSample);
}
}
private static class SkipMarkupFragments implements Filter {
@Override
public boolean acceptFragments(FragmentPair value) {
return value.getLeftFragment().equals("lorem")
&& value.getRightFragment().toString().equals("lorum");
}
@Override
public boolean skipFragments(FragmentPair value) { | /*
* 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.exadel.etoolbox.anydiff.runner;
public class FilterHelperTest {
static final String LEFT = "Lorem ipsum\nDolor sit amet\nConsectetur adipiscing elit";
static final String RIGHT = "Lorem ipsum\nDolor sat amet\nConsectetur adipiscing elit";
@Test
public void shouldNotFilterWhenNoRuleMatches() {
List<? extends DiffEntry> entries = DiffTask.builder().leftContent(LEFT).rightContent(RIGHT).build().run().children();
Assert.assertEquals(1, entries.size()); // Number of blocks
Assert.assertEquals(3, entries.get(0).as(EntryHolder.class).children().size()); // Number of lines in a block
DiffEntry block = entries.get(0);
Predicate<DiffEntry> processingFilter = FilterHelper.getEntryFilter(Collections.singletonList(new SkipNone()));
Assert.assertTrue(processingFilter.test(block));
}
@Test
public void shouldFilterFullDiff() {
List<Diff> result = new AnyDiff()
.left(LEFT)
.right(RIGHT)
.filter(Collections.singletonList(new SkipAnyDiff()))
.compare();
Assert.assertTrue(result.isEmpty());
}
@Test
public void shouldFilterByBlock() {
List<? extends DiffEntry> entries = DiffTask
.builder()
.leftContent(LEFT)
.rightContent(RIGHT.replace("elit", "ilet"))
.build()
.run()
.children();
Assert.assertEquals(1, entries.size());
DiffEntry block = entries.get(0);
Predicate<DiffEntry> processingFilter = FilterHelper.getEntryFilter(Collections.singletonList(new SkipBlock()));
Assert.assertFalse(processingFilter.test(block));
}
@Test
public void shouldFilterByLine() {
List<? extends DiffEntry> entries = DiffTask
.builder()
.leftContent(LEFT)
.rightContent(RIGHT)
.build()
.run()
.children();
Assert.assertEquals(1, entries.size());
DiffEntry block = entries.get(0);
Predicate<DiffEntry> processingFilter = FilterHelper.getEntryFilter(Collections.singletonList(new SkipWhenContainsFragment("sit")));
Assert.assertFalse(processingFilter.test(block));
}
@Test
public void shouldFilterByFragmentPair() {
List<? extends DiffEntry> entries = DiffTask
.builder()
.leftContent(LEFT)
.rightContent(RIGHT)
.build()
.run()
.children();
Assert.assertEquals(1, entries.size());
DiffEntry block = entries.get(0);
Predicate<DiffEntry> processingFilter = FilterHelper.getEntryFilter(Arrays.asList(
new SkipNone(),
new SkipFragmentPair("sit", "sat")));
Assert.assertFalse(processingFilter.test(block));
}
@Test
public void shouldFilterMarkupByFragmentPair() {
List<? extends DiffEntry> entries = DiffTask
.builder()
.contentType(ContentType.HTML)
.leftContent("<div class=\"lorem\">Lorem <span>ipsum</span> dolor sit amet</div> consectetur adipiscing elit")
.rightContent("<div class=\"lorum\">Lorem <span>dolorum</span> dolor sat amet</div> consectetur adipiscing elet")
.build()
.run()
.children();
Assert.assertEquals(3, entries.size());
DiffEntry block0 = entries.get(0);
Predicate<DiffEntry> processingFilter = FilterHelper.getEntryFilter(Arrays.asList(new SkipNone(), new SkipMarkupFragments()));
boolean testResult = processingFilter.test(block0);
List<Fragment> fragments = block0.as(EntryHolder.class).children().get(1).as(FragmentHolder.class).getFragments();
Assert.assertTrue(testResult);
Assert.assertTrue(fragments.stream().noneMatch(Fragment::isPending));
DiffEntry block1 = entries.get(1);
processingFilter = FilterHelper.getEntryFilter(Arrays.asList(
new SkipMarkupFragments(),
new SkipFragmentPair("sit", "sat")
));
testResult = processingFilter.test(block1);
Assert.assertFalse(testResult);
DiffEntry block2 = entries.get(2);
processingFilter = FilterHelper.getEntryFilter(Arrays.asList(
new SkipMarkupFragments(),
new SkipFragmentPair("elit", "elet")
));
testResult = processingFilter.test(block2);
Assert.assertFalse(testResult);
}
@Test
public void shouldFilterByFragment() {
List<? extends DiffEntry> entries = DiffTask
.builder()
.leftContent(LEFT)
.rightContent(RIGHT)
.build()
.run()
.children();
Assert.assertEquals(1, entries.size());
Predicate<DiffEntry> processingFilter = FilterHelper.getEntryFilter(Collections.singletonList(new SkipFragment("sit")));
Assert.assertTrue(processingFilter.test(entries.get(0)));
processingFilter = FilterHelper.getEntryFilter(Arrays.asList(new SkipFragment("sit"), new SkipFragment("sat")));
Assert.assertFalse(processingFilter.test(entries.get(0)));
}
/* ----------
Rule cases
---------- */
private static class SkipNone implements Filter {
}
private static class SkipAnyDiff implements Filter {
@Override
public boolean skipDiff(Diff value) {
return true;
}
}
private static class SkipBlock implements Filter {
@Override
public boolean skipBlock(DiffEntry value) {
return value.getLeft().contains("sit") && value.getLeft().contains("elit");
}
}
@RequiredArgsConstructor
private static class SkipWhenContainsFragment implements Filter {
private final String fragment;
@Override
public boolean skipLine(DiffEntry value) {
return value instanceof FragmentHolder
&& ((FragmentHolder) value)
.getLeftFragments()
.stream()
.anyMatch(f -> f.isDelete() && f.toString().equals(fragment));
}
}
@RequiredArgsConstructor
private static class SkipFragment implements Filter {
private final String fragment;
@Override
public boolean skipFragment(Fragment value) {
return fragment.equals(value.toString());
}
}
@RequiredArgsConstructor
private static class SkipFragmentPair implements Filter {
private final String leftSample;
private final String rightSample;
@Override
public boolean skipFragments(FragmentPair value) {
return value.getLeftFragment().equals(leftSample) && value.getRightFragment().equals(rightSample);
}
}
private static class SkipMarkupFragments implements Filter {
@Override
public boolean acceptFragments(FragmentPair value) {
return value.getLeftFragment().equals("lorem")
&& value.getRightFragment().toString().equals("lorum");
}
@Override
public boolean skipFragments(FragmentPair value) { | return value.getLeftFragment().as(MarkupFragment.class).isTagContent("span") | 9 | 2023-11-16 14:29:45+00:00 | 12k |
Walter-Stroebel/Jllama | src/main/java/nl/infcomtec/jllama/OllamaChatFrame.java | [
{
"identifier": "ImageObject",
"path": "src/main/java/nl/infcomtec/simpleimage/ImageObject.java",
"snippet": "public class ImageObject extends Image {\n\n private BufferedImage image;\n private final Semaphore lock = new Semaphore(0);\n private final List<ImageObjectListener> listeners = new Li... | import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JEditorPane;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JToolBar;
import javax.swing.SwingWorker;
import javax.swing.UIManager;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.StyleSheet;
import nl.infcomtec.simpleimage.ImageObject;
import nl.infcomtec.simpleimage.ImageViewer;
import nl.infcomtec.tools.PandocConverter; | 7,509 |
@Override
public void mouseReleased(MouseEvent e) {
if (e.isPopupTrigger()) {
popupMenu.show(e.getComponent(), e.getX(), e.getY());
}
}
});
JScrollPane pane = new JScrollPane(chat);
pane.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createLineBorder(new Color(0, 0, 128), 5),
"Chat"));
cont.add(pane, BorderLayout.CENTER);
Box bottom = Box.createHorizontalBox();
input.setLineWrap(true);
input.setWrapStyleWord(true);
bottom.add(new JScrollPane(input));
bottom.add(Box.createHorizontalStrut(10));
bottom.add(new JButton(new Interact()));
bottom.add(new JButton(new AbstractAction("\u2191 image") {
@Override
public void actionPerformed(ActionEvent ae) {
JFileChooser fileChooser = new JFileChooser();
int returnValue = fileChooser.showOpenDialog(frame);
if (returnValue == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
try {
BufferedImage originalImage = ImageIO.read(selectedFile);
if (originalImage.getHeight() != 256 || originalImage.getWidth() != 256) {
Image scaledInstance = originalImage.getScaledInstance(256, 256, BufferedImage.SCALE_SMOOTH);
BufferedImage resizedImage = new BufferedImage(256, 256, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = resizedImage.createGraphics();
g2d.drawImage(scaledInstance, 0, 0, null);
g2d.dispose();
uplImage = resizedImage;
} else {
uplImage = originalImage;
}
updateSideBar(null);
} catch (IOException ex) {
Logger.getLogger(OllamaChatFrame.class.getName()).log(Level.SEVERE, null, ex);
uplImage = null;
}
}
}
}));
bottom.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createLineBorder(new Color(135, 206, 250), 5),
"Input"));
cont.add(bottom, BorderLayout.SOUTH);
cont.add(sideBar(), BorderLayout.EAST);
frame.pack();
if (EventQueue.isDispatchThread()) {
finishInit();
} else {
try {
EventQueue.invokeAndWait(new Runnable() {
@Override
public void run() {
finishInit();
}
});
} catch (Exception ex) {
Logger.getLogger(OllamaChatFrame.class.getName()).log(Level.SEVERE, null, ex);
System.exit(1);
}
}
}
private void buttonBar() {
buttons.add(new AbstractAction("Exit") {
@Override
public void actionPerformed(ActionEvent ae) {
System.exit(0);
}
});
buttons.add(new JToolBar.Separator());
String lsHost = Ollama.config.getLastEndpoint();
for (String e : Ollama.getAvailableModels().keySet()) {
addToHosts(e);
}
client = new OllamaClient(lsHost);
models.removeAllItems();
for (AvailableModels.AvailableModel am : Ollama.getAvailableModels().get(lsHost).models) {
models.addItem(am.name);
}
if (null != Ollama.config.lastModel) {
models.setSelectedItem(Ollama.config.lastModel);
}
models.invalidate();
hosts.setSelectedItem(lsHost);
hosts.addActionListener(new AddSelectHost());
hosts.setEditable(true);
buttons.add(new JLabel("Hosts:"));
buttons.add(hosts);
buttons.add(new JToolBar.Separator());
buttons.add(new JLabel("Models:"));
buttons.add(models);
buttons.add(new JToolBar.Separator());
buttons.add(new AbstractAction("HTML") {
@Override
public void actionPerformed(ActionEvent ae) {
String markDown = chat.getText();
JFrame html = new JFrame("HTML");
html.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
html.getContentPane().setLayout(new BorderLayout());
JEditorPane pane = new JEditorPane();
pane.setContentType("text/html");
HTMLEditorKit kit = new HTMLEditorKit() {
@Override
public StyleSheet getStyleSheet() {
StyleSheet styleSheet = super.getStyleSheet();
styleSheet.addRule("body { font-family: 'Arial'; font-size: " + Math.round(Ollama.config.fontSize) + "pt; }");
return styleSheet;
}
};
pane.setEditorKit(kit); | package nl.infcomtec.jllama;
/**
* This is a FULL Ollama chat window. It allow to chat with any model available
* at will.<p>
* Note that this displays some extra information along with the actual chat
* which allows one to get a good insight in how the model performs.</p>
*
* @author Walter Stroebel
*/
public class OllamaChatFrame {
private final JFrame frame;
private final JToolBar buttons;
private final JTextArea chat;
private final JTextArea input;
private OllamaClient client;
private final JComboBox<String> hosts;
private final JComboBox<String> models;
private JLabel curCtxSize;
private JLabel outTokens;
private JLabel inTokens;
private final AtomicBoolean autoMode = new AtomicBoolean(false);
private final ExecutorService pool = Executors.newCachedThreadPool();
private JLabel tokensSec;
private JLabel modFamily;
private JLabel modFamilies;
private JLabel modFormat;
private JLabel modParmSize;
private JLabel modQuant;
private JLabel prevImage;
private BufferedImage uplImage;
/**
* Ties all the bits and pieces together into a GUI.
*/
public OllamaChatFrame() {
setupGUI(Ollama.config.fontSize);
this.modQuant = new JLabel();
this.modParmSize = new JLabel();
this.modFormat = new JLabel();
this.modFamilies = new JLabel();
this.modFamily = new JLabel();
this.prevImage = new JLabel();
this.models = new JComboBox<>();
this.hosts = new JComboBox<>();
this.buttons = new JToolBar();
this.input = new JTextArea(4, 80);
this.chat = new JTextArea();
frame = new JFrame("Ollama chat");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container cont = frame.getContentPane();
cont.setLayout(new BorderLayout());
buttonBar();
cont.add(buttons, BorderLayout.NORTH);
chat.setLineWrap(true);
chat.setWrapStyleWord(true);
final JPopupMenu popupMenu = new JPopupMenu();
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(new AbstractAction("Copy") {
@Override
public void actionPerformed(ActionEvent ae) {
String selectedText = chat.getSelectedText();
if (null != selectedText) {
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(new StringSelection(selectedText), null);
}
}
});
popupMenu.add(copy);
chat.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
if (e.isPopupTrigger()) {
popupMenu.show(e.getComponent(), e.getX(), e.getY());
}
}
@Override
public void mouseReleased(MouseEvent e) {
if (e.isPopupTrigger()) {
popupMenu.show(e.getComponent(), e.getX(), e.getY());
}
}
});
JScrollPane pane = new JScrollPane(chat);
pane.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createLineBorder(new Color(0, 0, 128), 5),
"Chat"));
cont.add(pane, BorderLayout.CENTER);
Box bottom = Box.createHorizontalBox();
input.setLineWrap(true);
input.setWrapStyleWord(true);
bottom.add(new JScrollPane(input));
bottom.add(Box.createHorizontalStrut(10));
bottom.add(new JButton(new Interact()));
bottom.add(new JButton(new AbstractAction("\u2191 image") {
@Override
public void actionPerformed(ActionEvent ae) {
JFileChooser fileChooser = new JFileChooser();
int returnValue = fileChooser.showOpenDialog(frame);
if (returnValue == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
try {
BufferedImage originalImage = ImageIO.read(selectedFile);
if (originalImage.getHeight() != 256 || originalImage.getWidth() != 256) {
Image scaledInstance = originalImage.getScaledInstance(256, 256, BufferedImage.SCALE_SMOOTH);
BufferedImage resizedImage = new BufferedImage(256, 256, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = resizedImage.createGraphics();
g2d.drawImage(scaledInstance, 0, 0, null);
g2d.dispose();
uplImage = resizedImage;
} else {
uplImage = originalImage;
}
updateSideBar(null);
} catch (IOException ex) {
Logger.getLogger(OllamaChatFrame.class.getName()).log(Level.SEVERE, null, ex);
uplImage = null;
}
}
}
}));
bottom.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createLineBorder(new Color(135, 206, 250), 5),
"Input"));
cont.add(bottom, BorderLayout.SOUTH);
cont.add(sideBar(), BorderLayout.EAST);
frame.pack();
if (EventQueue.isDispatchThread()) {
finishInit();
} else {
try {
EventQueue.invokeAndWait(new Runnable() {
@Override
public void run() {
finishInit();
}
});
} catch (Exception ex) {
Logger.getLogger(OllamaChatFrame.class.getName()).log(Level.SEVERE, null, ex);
System.exit(1);
}
}
}
private void buttonBar() {
buttons.add(new AbstractAction("Exit") {
@Override
public void actionPerformed(ActionEvent ae) {
System.exit(0);
}
});
buttons.add(new JToolBar.Separator());
String lsHost = Ollama.config.getLastEndpoint();
for (String e : Ollama.getAvailableModels().keySet()) {
addToHosts(e);
}
client = new OllamaClient(lsHost);
models.removeAllItems();
for (AvailableModels.AvailableModel am : Ollama.getAvailableModels().get(lsHost).models) {
models.addItem(am.name);
}
if (null != Ollama.config.lastModel) {
models.setSelectedItem(Ollama.config.lastModel);
}
models.invalidate();
hosts.setSelectedItem(lsHost);
hosts.addActionListener(new AddSelectHost());
hosts.setEditable(true);
buttons.add(new JLabel("Hosts:"));
buttons.add(hosts);
buttons.add(new JToolBar.Separator());
buttons.add(new JLabel("Models:"));
buttons.add(models);
buttons.add(new JToolBar.Separator());
buttons.add(new AbstractAction("HTML") {
@Override
public void actionPerformed(ActionEvent ae) {
String markDown = chat.getText();
JFrame html = new JFrame("HTML");
html.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
html.getContentPane().setLayout(new BorderLayout());
JEditorPane pane = new JEditorPane();
pane.setContentType("text/html");
HTMLEditorKit kit = new HTMLEditorKit() {
@Override
public StyleSheet getStyleSheet() {
StyleSheet styleSheet = super.getStyleSheet();
styleSheet.addRule("body { font-family: 'Arial'; font-size: " + Math.round(Ollama.config.fontSize) + "pt; }");
return styleSheet;
}
};
pane.setEditorKit(kit); | pane.setText(new PandocConverter().convertMarkdownToHTML(markDown)); | 2 | 2023-11-16 00:37:47+00:00 | 12k |
JustARandomGuyNo512/Gunscraft | src/main/java/sheridan/gunscraft/render/TransformData.java | [
{
"identifier": "ClientProxy",
"path": "src/main/java/sheridan/gunscraft/ClientProxy.java",
"snippet": "public class ClientProxy extends CommonProxy{\n\n public static HashMap<Item, TransformData> transformDataMap = new HashMap<>();\n public static HashMap<Item, IGunModel> gunModelMap = new HashMa... | import com.mojang.blaze3d.matrix.MatrixStack;
import net.minecraft.client.renderer.model.ItemCameraTransforms;
import net.minecraft.client.renderer.model.ModelRenderer;
import net.minecraft.util.math.vector.Quaternion;
import net.minecraft.util.math.vector.Vector3f;
import sheridan.gunscraft.ClientProxy;
import sheridan.gunscraft.animation.recoilAnimation.RecoilAnimationData;
import sheridan.gunscraft.render.fx.muzzleFlash.MuzzleFlashTrans;
import java.util.HashMap;
import java.util.Map; | 7,581 | package sheridan.gunscraft.render;
public class TransformData {
public static final float BASE_SIZE = 0.09f;
public static final float BASE_ARM_SIZE = 6f;
public static final int RIGHT_SIDE_RIGHT_HAND = 0, RIGHT_SIDE_LEFT_HAND = 1, LEFT_SIDE = 2;
public float[][][] FPTrans;
public float[][][] TPTrans;
public float[][] GUITrans;
public float[][] FrameTrans;
public float[][] GroundTrans;
public float[][][] FPHandPoseTrans;
public float[] aimingTrans;
public float[] bulletShellTrans;
public MuzzleFlashFransEntry muzzleFlashTransEntry = new MuzzleFlashFransEntry();
public RecoilAnimationData recoilAnimationData;
public BulletShellAniData bulletShellAniData;
public TransformData setBulletShellAniData(BulletShellAniData bulletShellAniData) {
this.bulletShellAniData = bulletShellAniData;
return this;
}
public TransformData setRecoilAnimationData(RecoilAnimationData recoilAnimationData) {
this.recoilAnimationData = recoilAnimationData;
return this;
}
public TransformData setBulletShellTrans(float[] bulletShellTrans) {
this.bulletShellTrans = bulletShellTrans;
return this;
}
public RecoilAnimationData getRecoilAnimationData() {
return recoilAnimationData;
}
public TransformData registerMuzzleFlash(String name, TransPair pair) {
this.muzzleFlashTransEntry.register(name, pair);
return this;
}
public TransformData setAimingTrans(float[] trans) {
this.aimingTrans = trans;
return this;
}
| package sheridan.gunscraft.render;
public class TransformData {
public static final float BASE_SIZE = 0.09f;
public static final float BASE_ARM_SIZE = 6f;
public static final int RIGHT_SIDE_RIGHT_HAND = 0, RIGHT_SIDE_LEFT_HAND = 1, LEFT_SIDE = 2;
public float[][][] FPTrans;
public float[][][] TPTrans;
public float[][] GUITrans;
public float[][] FrameTrans;
public float[][] GroundTrans;
public float[][][] FPHandPoseTrans;
public float[] aimingTrans;
public float[] bulletShellTrans;
public MuzzleFlashFransEntry muzzleFlashTransEntry = new MuzzleFlashFransEntry();
public RecoilAnimationData recoilAnimationData;
public BulletShellAniData bulletShellAniData;
public TransformData setBulletShellAniData(BulletShellAniData bulletShellAniData) {
this.bulletShellAniData = bulletShellAniData;
return this;
}
public TransformData setRecoilAnimationData(RecoilAnimationData recoilAnimationData) {
this.recoilAnimationData = recoilAnimationData;
return this;
}
public TransformData setBulletShellTrans(float[] bulletShellTrans) {
this.bulletShellTrans = bulletShellTrans;
return this;
}
public RecoilAnimationData getRecoilAnimationData() {
return recoilAnimationData;
}
public TransformData registerMuzzleFlash(String name, TransPair pair) {
this.muzzleFlashTransEntry.register(name, pair);
return this;
}
public TransformData setAimingTrans(float[] trans) {
this.aimingTrans = trans;
return this;
}
| public MuzzleFlashTrans getMuzzleFlashTrans(String name) { | 2 | 2023-11-14 14:00:55+00:00 | 12k |
zpascual/5419-Arm-Example | src/main/java/com/team5419/frc2023/subsystems/ServoMotorSubsystem.java | [
{
"identifier": "TalonFXFactory",
"path": "src/main/java/com/team254/lib/drivers/TalonFXFactory.java",
"snippet": "public class TalonFXFactory {\n\n private final static int kTimeoutMs = 100;\n\n public static class Configuration {\n public NeutralMode NEUTRAL_MODE = NeutralMode.Coast;\n ... | import com.ctre.phoenix.motorcontrol.*;
import com.ctre.phoenix.motorcontrol.can.TalonFX;
import com.team254.lib.drivers.TalonFXFactory;
import com.team254.lib.drivers.TalonUtil;
import com.team254.lib.motion.MotionProfileConstraints;
import com.team254.lib.motion.MotionState;
import com.team254.lib.motion.SetpointGenerator;
import com.team254.lib.util.ReflectingCSVWriter;
import com.team254.lib.util.Util;
import com.team5419.frc2023.loops.ILooper;
import com.team5419.frc2023.loops.Loop;
import edu.wpi.first.wpilibj.DriverStation;
import edu.wpi.first.wpilibj.Timer; | 8,601 | mConstants.kName + ": Could not set deadband: ");
TalonUtil.checkError(
mMaster.configMotionCruiseVelocity(mConstants.kCruiseVelocity, mConstants.kLongCANTimeoutMs),
mConstants.kName + ": Could not set cruise velocity: ");
TalonUtil.checkError(mMaster.configMotionAcceleration(mConstants.kAcceleration, mConstants.kLongCANTimeoutMs),
mConstants.kName + ": Could not set acceleration: ");
TalonUtil.checkError(mMaster.configOpenloopRamp(mConstants.kRampRate, mConstants.kLongCANTimeoutMs),
mConstants.kName + ": Could not set voltage ramp rate: ");
TalonUtil.checkError(mMaster.configClosedloopRamp(mConstants.kRampRate, mConstants.kLongCANTimeoutMs),
mConstants.kName + ": Could not set closed loop ramp rate: ");
TalonUtil.checkError(mMaster.configSupplyCurrentLimit(new SupplyCurrentLimitConfiguration(
mConstants.kEnableSupplyCurrentLimit,
mConstants.kSupplyContinuousCurrentLimit,
mConstants.kSupplyPeakCurrentLimit,
mConstants.kSupplyPeakCurrentDuration)),
mConstants.kName + ": Could not set supply current limit.");
TalonUtil.checkError(mMaster.configStatorCurrentLimit(new StatorCurrentLimitConfiguration(
mConstants.kEnableStatorCurrentLimit,
mConstants.kStatorContinuousCurrentLimit,
mConstants.kStatorPeakCurrentLimit,
mConstants.kStatorPeakCurrentDuration)),
mConstants.kName + ": Could not set stator current limit.");
mMaster.configVoltageMeasurementFilter(8);
TalonUtil.checkError(
mMaster.configVoltageCompSaturation(mConstants.kMaxVoltage, mConstants.kLongCANTimeoutMs),
mConstants.kName + ": Could not set voltage comp saturation.");
mMaster.enableVoltageCompensation(true);
mMaster.setInverted(mConstants.kMasterConstants.invert_motor);
mMaster.setSensorPhase(mConstants.kMasterConstants.invert_sensor_phase);
mMaster.setNeutralMode(NeutralMode.Brake);
mMaster.setStatusFramePeriod(StatusFrameEnhanced.Status_2_Feedback0, 5, 20);
mMaster.setStatusFramePeriod(StatusFrameEnhanced.Status_10_MotionMagic, 1000, 20);
mMaster.setStatusFramePeriod(StatusFrameEnhanced.Status_8_PulseWidth, mConstants.kStatusFrame8UpdateRate, 20);
// Start with kMotionProfileSlot.
mMaster.selectProfileSlot(kMotionProfileSlot, 0);
for (int i = 0; i < mSlaves.length; ++i) {
mSlaves[i] = TalonFXFactory.createPermanentSlaveTalon(mConstants.kSlaveConstants[i].id, mConstants.kMasterConstants.id);
mSlaves[i].setInverted(mConstants.kSlaveConstants[i].invert_motor);
mSlaves[i].setNeutralMode(NeutralMode.Brake);
mSlaves[i].follow(mMaster);
}
// Send a neutral command.
stop();
}
public static class PeriodicIO {
// INPUTS
public double timestamp;
public double position_ticks;
public double position_units;
public double velocity_ticks_per_100ms;
public double active_trajectory_position; // ticks
public double active_trajectory_velocity; // ticks/100ms
public double active_trajectory_acceleration; // ticks/100ms/s
public double output_percent;
public double output_voltage;
public double master_current;
public double error_ticks;
public int encoder_wraps;
public int absolute_pulse_offset = 0;
// public int absolute_pulse_position;
public int absolute_pulse_position_modded;
public boolean reset_occured;
// OUTPUTS
public double demand;
public double feedforward;
}
protected enum ControlState {
OPEN_LOOP, MOTION_MAGIC, POSITION_PID, MOTION_PROFILING
}
protected PeriodicIO mPeriodicIO = new PeriodicIO();
protected ControlState mControlState = ControlState.OPEN_LOOP;
protected ReflectingCSVWriter<PeriodicIO> mCSVWriter = null;
protected boolean mHasBeenZeroed = false;
protected StickyFaults mFaults = new StickyFaults();
protected SetpointGenerator mSetpointGenerator = new SetpointGenerator();
protected MotionProfileConstraints mMotionProfileConstraints;
@Override
public synchronized void readPeriodicInputs() {
mPeriodicIO.timestamp = Timer.getFPGATimestamp();
if (mMaster.hasResetOccurred()) {
DriverStation.reportError(mConstants.kName + ": Talon Reset! ", false);
mPeriodicIO.reset_occured = true;
return;
} else {
mPeriodicIO.reset_occured = false;
}
mMaster.getStickyFaults(mFaults);
if (mFaults.hasAnyFault()) {
DriverStation.reportError(mConstants.kName + ": Talon Fault! " + mFaults.toString(), false);
mMaster.clearStickyFaults(0);
}
if (mMaster.getControlMode() == ControlMode.MotionMagic) {
mPeriodicIO.active_trajectory_position = mMaster.getActiveTrajectoryPosition();
if (mPeriodicIO.active_trajectory_position < mReverseSoftLimitTicks) {
DriverStation.reportError(mConstants.kName + ": Active trajectory past reverse soft limit!", false);
} else if (mPeriodicIO.active_trajectory_position > mForwardSoftLimitTicks) {
DriverStation.reportError(mConstants.kName + ": Active trajectory past forward soft limit!", false);
}
final double newVel = mMaster.getActiveTrajectoryVelocity(); | package com.team5419.frc2023.subsystems;
/**
* Abstract base class for a subsystem with a single sensor servo-mechanism.
*/
public abstract class ServoMotorSubsystem extends Subsystem {
protected static final int kMotionProfileSlot = 0;
protected static final int kPositionPIDSlot = 1;
// Recommend initializing in a static block!
public static class TalonFXConstants {
public int id = -1;
public boolean invert_motor = false;
public boolean invert_sensor_phase = false;
public int encoder_ppr = 2048;
}
// Recommend initializing in a static block!
public static class ServoMotorSubsystemConstants {
public String kName = "ERROR_ASSIGN_A_NAME";
public double kLooperDt = 0.01;
public int kCANTimeoutMs = 10; // use for important on the fly updates
public int kLongCANTimeoutMs = 100; // use for constructors
public TalonFXConstants kMasterConstants = new TalonFXConstants();
public TalonFXConstants[] kSlaveConstants = new TalonFXConstants[0];
public double kHomePosition = 0.0; // Units
public double kTicksPerUnitDistance = 1.0;
public double kKp = 0; // Raw output / raw error
public double kKi = 0; // Raw output / sum of raw error
public double kKd = 0; // Raw output / (err - prevErr)
public double kKf = 0; // Raw output / velocity in ticks/100ms
public double kKa = 0; // Raw output / accel in (ticks/100ms) / s
public double kMaxIntegralAccumulator = 0;
public int kIZone = 0; // Ticks
public int kDeadband = 0; // Ticks
public double kPositionKp = 0;
public double kPositionKi = 0;
public double kPositionKd = 0;
public double kPositionKf = 0;
public double kPositionMaxIntegralAccumulator = 0;
public int kPositionIZone = 0; // Ticks
public int kPositionDeadband = 0; // Ticks
public int kCruiseVelocity = 0; // Ticks / 100ms
public int kAcceleration = 0; // Ticks / 100ms / s
public double kRampRate = 0.0; // s
public double kMaxVoltage = 12.0;
public int kSupplyContinuousCurrentLimit = 20; // amps
public int kSupplyPeakCurrentLimit = 60; // amps
public double kSupplyPeakCurrentDuration = 0.2; // seconds
public boolean kEnableSupplyCurrentLimit = false;
public int kStatorContinuousCurrentLimit = 20; // amps
public int kStatorPeakCurrentLimit = 60; // amps
public double kStatorPeakCurrentDuration = 0.2; // seconds
public boolean kEnableStatorCurrentLimit = false;
public double kMaxUnitsLimit = Double.POSITIVE_INFINITY;
public double kMinUnitsLimit = Double.NEGATIVE_INFINITY;
public int kStatusFrame8UpdateRate = 1000;
public boolean kRecoverPositionOnReset = false;
}
protected final ServoMotorSubsystemConstants mConstants;
protected final TalonFX mMaster;
protected final TalonFX[] mSlaves;
protected MotionState mMotionStateSetpoint = null;
protected final int mForwardSoftLimitTicks;
protected final int mReverseSoftLimitTicks;
protected ServoMotorSubsystem(final ServoMotorSubsystemConstants constants) {
mConstants = constants;
mMaster = TalonFXFactory.createDefaultTalon(mConstants.kMasterConstants.id);
mSlaves = new TalonFX[mConstants.kSlaveConstants.length];
TalonUtil.checkError(mMaster.configSelectedFeedbackSensor(FeedbackDevice.IntegratedSensor, 0,
mConstants.kLongCANTimeoutMs), mConstants.kName + ": Could not detect encoder: ");
mForwardSoftLimitTicks = (int) ((mConstants.kMaxUnitsLimit - mConstants.kHomePosition) * mConstants.kTicksPerUnitDistance);
TalonUtil.checkError(
mMaster.configForwardSoftLimitThreshold(mForwardSoftLimitTicks, mConstants.kLongCANTimeoutMs),
mConstants.kName + ": Could not set forward soft limit: ");
TalonUtil.checkError(mMaster.configForwardSoftLimitEnable(true, mConstants.kLongCANTimeoutMs),
mConstants.kName + ": Could not enable forward soft limit: ");
mReverseSoftLimitTicks = (int) ((mConstants.kMinUnitsLimit - mConstants.kHomePosition) * mConstants.kTicksPerUnitDistance);
TalonUtil.checkError(
mMaster.configReverseSoftLimitThreshold(mReverseSoftLimitTicks, mConstants.kLongCANTimeoutMs),
mConstants.kName + ": Could not set reverse soft limit: ");
TalonUtil.checkError(mMaster.configReverseSoftLimitEnable(true, mConstants.kLongCANTimeoutMs),
mConstants.kName + ": Could not enable reverse soft limit: ");
TalonUtil.checkError(mMaster.configVoltageCompSaturation(12.0, mConstants.kLongCANTimeoutMs),
mConstants.kName + ": Could not set voltage compensation saturation: ");
TalonUtil.checkError(mMaster.config_kP(kMotionProfileSlot, mConstants.kKp, mConstants.kLongCANTimeoutMs),
mConstants.kName + ": could not set kP: ");
TalonUtil.checkError(mMaster.config_kI(kMotionProfileSlot, mConstants.kKi, mConstants.kLongCANTimeoutMs),
mConstants.kName + ": could not set kI: ");
TalonUtil.checkError(mMaster.config_kD(kMotionProfileSlot, mConstants.kKd, mConstants.kLongCANTimeoutMs),
mConstants.kName + ": could not set kD: ");
TalonUtil.checkError(mMaster.config_kF(kMotionProfileSlot, mConstants.kKf, mConstants.kLongCANTimeoutMs),
mConstants.kName + ": Could not set kF: ");
TalonUtil.checkError(mMaster.configMaxIntegralAccumulator(kMotionProfileSlot, mConstants.kMaxIntegralAccumulator,
mConstants.kLongCANTimeoutMs), mConstants.kName + ": Could not set max integral: ");
TalonUtil.checkError(mMaster.config_IntegralZone(kMotionProfileSlot, mConstants.kIZone, mConstants.kLongCANTimeoutMs),
mConstants.kName + ": Could not set i zone: ");
TalonUtil.checkError(
mMaster.configAllowableClosedloopError(kMotionProfileSlot, mConstants.kDeadband, mConstants.kLongCANTimeoutMs),
mConstants.kName + ": Could not set deadband: ");
TalonUtil.checkError(mMaster.config_kP(kPositionPIDSlot, mConstants.kPositionKp, mConstants.kLongCANTimeoutMs),
mConstants.kName + ": could not set kP: ");
TalonUtil.checkError(mMaster.config_kI(kPositionPIDSlot, mConstants.kPositionKi, mConstants.kLongCANTimeoutMs),
mConstants.kName + ": could not set kI: ");
TalonUtil.checkError(mMaster.config_kD(kPositionPIDSlot, mConstants.kPositionKd, mConstants.kLongCANTimeoutMs),
mConstants.kName + ": could not set kD: ");
TalonUtil.checkError(mMaster.config_kF(kPositionPIDSlot, mConstants.kPositionKf, mConstants.kLongCANTimeoutMs),
mConstants.kName + ": Could not set kF: ");
TalonUtil.checkError(mMaster.configMaxIntegralAccumulator(kPositionPIDSlot, mConstants.kPositionMaxIntegralAccumulator,
mConstants.kLongCANTimeoutMs), mConstants.kName + ": Could not set max integral: ");
TalonUtil.checkError(mMaster.config_IntegralZone(kPositionPIDSlot, mConstants.kPositionIZone, mConstants.kLongCANTimeoutMs),
mConstants.kName + ": Could not set i zone: ");
TalonUtil.checkError(
mMaster.configAllowableClosedloopError(kPositionPIDSlot, mConstants.kPositionDeadband, mConstants.kLongCANTimeoutMs),
mConstants.kName + ": Could not set deadband: ");
TalonUtil.checkError(
mMaster.configMotionCruiseVelocity(mConstants.kCruiseVelocity, mConstants.kLongCANTimeoutMs),
mConstants.kName + ": Could not set cruise velocity: ");
TalonUtil.checkError(mMaster.configMotionAcceleration(mConstants.kAcceleration, mConstants.kLongCANTimeoutMs),
mConstants.kName + ": Could not set acceleration: ");
TalonUtil.checkError(mMaster.configOpenloopRamp(mConstants.kRampRate, mConstants.kLongCANTimeoutMs),
mConstants.kName + ": Could not set voltage ramp rate: ");
TalonUtil.checkError(mMaster.configClosedloopRamp(mConstants.kRampRate, mConstants.kLongCANTimeoutMs),
mConstants.kName + ": Could not set closed loop ramp rate: ");
TalonUtil.checkError(mMaster.configSupplyCurrentLimit(new SupplyCurrentLimitConfiguration(
mConstants.kEnableSupplyCurrentLimit,
mConstants.kSupplyContinuousCurrentLimit,
mConstants.kSupplyPeakCurrentLimit,
mConstants.kSupplyPeakCurrentDuration)),
mConstants.kName + ": Could not set supply current limit.");
TalonUtil.checkError(mMaster.configStatorCurrentLimit(new StatorCurrentLimitConfiguration(
mConstants.kEnableStatorCurrentLimit,
mConstants.kStatorContinuousCurrentLimit,
mConstants.kStatorPeakCurrentLimit,
mConstants.kStatorPeakCurrentDuration)),
mConstants.kName + ": Could not set stator current limit.");
mMaster.configVoltageMeasurementFilter(8);
TalonUtil.checkError(
mMaster.configVoltageCompSaturation(mConstants.kMaxVoltage, mConstants.kLongCANTimeoutMs),
mConstants.kName + ": Could not set voltage comp saturation.");
mMaster.enableVoltageCompensation(true);
mMaster.setInverted(mConstants.kMasterConstants.invert_motor);
mMaster.setSensorPhase(mConstants.kMasterConstants.invert_sensor_phase);
mMaster.setNeutralMode(NeutralMode.Brake);
mMaster.setStatusFramePeriod(StatusFrameEnhanced.Status_2_Feedback0, 5, 20);
mMaster.setStatusFramePeriod(StatusFrameEnhanced.Status_10_MotionMagic, 1000, 20);
mMaster.setStatusFramePeriod(StatusFrameEnhanced.Status_8_PulseWidth, mConstants.kStatusFrame8UpdateRate, 20);
// Start with kMotionProfileSlot.
mMaster.selectProfileSlot(kMotionProfileSlot, 0);
for (int i = 0; i < mSlaves.length; ++i) {
mSlaves[i] = TalonFXFactory.createPermanentSlaveTalon(mConstants.kSlaveConstants[i].id, mConstants.kMasterConstants.id);
mSlaves[i].setInverted(mConstants.kSlaveConstants[i].invert_motor);
mSlaves[i].setNeutralMode(NeutralMode.Brake);
mSlaves[i].follow(mMaster);
}
// Send a neutral command.
stop();
}
public static class PeriodicIO {
// INPUTS
public double timestamp;
public double position_ticks;
public double position_units;
public double velocity_ticks_per_100ms;
public double active_trajectory_position; // ticks
public double active_trajectory_velocity; // ticks/100ms
public double active_trajectory_acceleration; // ticks/100ms/s
public double output_percent;
public double output_voltage;
public double master_current;
public double error_ticks;
public int encoder_wraps;
public int absolute_pulse_offset = 0;
// public int absolute_pulse_position;
public int absolute_pulse_position_modded;
public boolean reset_occured;
// OUTPUTS
public double demand;
public double feedforward;
}
protected enum ControlState {
OPEN_LOOP, MOTION_MAGIC, POSITION_PID, MOTION_PROFILING
}
protected PeriodicIO mPeriodicIO = new PeriodicIO();
protected ControlState mControlState = ControlState.OPEN_LOOP;
protected ReflectingCSVWriter<PeriodicIO> mCSVWriter = null;
protected boolean mHasBeenZeroed = false;
protected StickyFaults mFaults = new StickyFaults();
protected SetpointGenerator mSetpointGenerator = new SetpointGenerator();
protected MotionProfileConstraints mMotionProfileConstraints;
@Override
public synchronized void readPeriodicInputs() {
mPeriodicIO.timestamp = Timer.getFPGATimestamp();
if (mMaster.hasResetOccurred()) {
DriverStation.reportError(mConstants.kName + ": Talon Reset! ", false);
mPeriodicIO.reset_occured = true;
return;
} else {
mPeriodicIO.reset_occured = false;
}
mMaster.getStickyFaults(mFaults);
if (mFaults.hasAnyFault()) {
DriverStation.reportError(mConstants.kName + ": Talon Fault! " + mFaults.toString(), false);
mMaster.clearStickyFaults(0);
}
if (mMaster.getControlMode() == ControlMode.MotionMagic) {
mPeriodicIO.active_trajectory_position = mMaster.getActiveTrajectoryPosition();
if (mPeriodicIO.active_trajectory_position < mReverseSoftLimitTicks) {
DriverStation.reportError(mConstants.kName + ": Active trajectory past reverse soft limit!", false);
} else if (mPeriodicIO.active_trajectory_position > mForwardSoftLimitTicks) {
DriverStation.reportError(mConstants.kName + ": Active trajectory past forward soft limit!", false);
}
final double newVel = mMaster.getActiveTrajectoryVelocity(); | if (Util.epsilonEquals(newVel, mConstants.kCruiseVelocity, Math.max(1, mConstants.kDeadband)) || Util | 6 | 2023-11-14 06:44:40+00:00 | 12k |
threethan/QuestAudioPatcher | app/src/main/java/com/threethan/questpatcher/activities/InstallerFilePickerActivity.java | [
{
"identifier": "InstallerFilePickerAdapter",
"path": "app/src/main/java/com/threethan/questpatcher/adapters/InstallerFilePickerAdapter.java",
"snippet": "public class InstallerFilePickerAdapter extends RecyclerView.Adapter<InstallerFilePickerAdapter.ViewHolder> {\n\n private static ClickListener cli... | import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatImageButton;
import androidx.appcompat.widget.LinearLayoutCompat;
import androidx.appcompat.widget.PopupMenu;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.threethan.questpatcher.R;
import com.threethan.questpatcher.adapters.InstallerFilePickerAdapter;
import com.threethan.questpatcher.utils.APKData;
import com.threethan.questpatcher.utils.APKExplorer;
import com.threethan.questpatcher.utils.Common;
import com.threethan.questpatcher.utils.SplitAPKInstaller;
import com.google.android.material.card.MaterialCardView;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.textview.MaterialTextView;
import java.io.File;
import java.util.Objects;
import in.sunilpaulmathew.sCommon.CommonUtils.sCommonUtils;
import in.sunilpaulmathew.sCommon.CommonUtils.sExecutor;
import in.sunilpaulmathew.sCommon.PermissionUtils.sPermissionUtils; | 8,949 | package com.threethan.questpatcher.activities;
/*
* Created by APK Explorer & Editor <apkeditor@protonmail.com> on March 21, 2021
*/
public class InstallerFilePickerActivity extends AppCompatActivity {
private LinearLayoutCompat mProgressLayout;
private InstallerFilePickerAdapter mRecycleViewAdapter;
private MaterialTextView mTitle;
private RecyclerView mRecyclerView;
public static final String TITLE_INTENT = "title";
@SuppressLint("StringFormatInvalid")
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_installerfilepicker);
AppCompatImageButton mBack = findViewById(R.id.back);
mTitle = findViewById(R.id.title);
AppCompatImageButton mSortButton = findViewById(R.id.sort);
Common.initializeView(findViewById(android.R.id.content), R.id.select);
mProgressLayout = findViewById(R.id.progress_layout);
mRecyclerView = findViewById(R.id.recycler_view);
mBack.setOnClickListener(v -> super.onBackPressed());
if (Build.VERSION.SDK_INT < 29 && sPermissionUtils.isPermissionDenied(android.Manifest.permission.WRITE_EXTERNAL_STORAGE,this)) {
LinearLayoutCompat mPermissionLayout = findViewById(R.id.permission_layout);
View mPermissionGrant = findViewById(R.id.grant_card);
mPermissionLayout.setVisibility(View.VISIBLE);
mRecyclerView.setVisibility(View.GONE);
mPermissionGrant.setOnClickListener(v -> sPermissionUtils.requestPermission(
new String[] {
android.Manifest.permission.WRITE_EXTERNAL_STORAGE
},this));
return;
}
mRecyclerView.setLayoutManager(new GridLayoutManager(this, APKExplorer.getSpanCount(this)));
mRecycleViewAdapter = new InstallerFilePickerAdapter(APKExplorer.getData(getFilesList(), false, this));
mRecyclerView.setAdapter(mRecycleViewAdapter);
if (getIntent().getStringExtra(TITLE_INTENT) != null) {
mTitle.setText(getIntent().getStringExtra(TITLE_INTENT));
} else {
mTitle.setText(Common.getPath().equals(Environment.getExternalStorageDirectory().toString() + File.separator) ? getString(R.string.sdcard) : new File(Common.getPath()).getName());
}
mRecycleViewAdapter.setOnItemClickListener((position, v) -> {
if (new File(APKExplorer.getData(getFilesList(), false, this).get(position)).isDirectory()) {
Common.setPath(APKExplorer.getData(getFilesList(), false, this).get(position));
reload(this);
} else if (APKExplorer.getData(getFilesList(), false, this).get(position).endsWith(".apks") || APKExplorer.getData(getFilesList(), false,
this).get(position).endsWith(".apkm") || APKExplorer.getData(getFilesList(), false, this).get(position).endsWith(".xapk")) {
new MaterialAlertDialogBuilder(this)
.setMessage(getString(R.string.bundle_install_question, new File(APKExplorer.getData(getFilesList(), false, this).get(position)).getName()))
.setNegativeButton(getString(R.string.cancel), (dialogInterface, i) -> {
}) | package com.threethan.questpatcher.activities;
/*
* Created by APK Explorer & Editor <apkeditor@protonmail.com> on March 21, 2021
*/
public class InstallerFilePickerActivity extends AppCompatActivity {
private LinearLayoutCompat mProgressLayout;
private InstallerFilePickerAdapter mRecycleViewAdapter;
private MaterialTextView mTitle;
private RecyclerView mRecyclerView;
public static final String TITLE_INTENT = "title";
@SuppressLint("StringFormatInvalid")
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_installerfilepicker);
AppCompatImageButton mBack = findViewById(R.id.back);
mTitle = findViewById(R.id.title);
AppCompatImageButton mSortButton = findViewById(R.id.sort);
Common.initializeView(findViewById(android.R.id.content), R.id.select);
mProgressLayout = findViewById(R.id.progress_layout);
mRecyclerView = findViewById(R.id.recycler_view);
mBack.setOnClickListener(v -> super.onBackPressed());
if (Build.VERSION.SDK_INT < 29 && sPermissionUtils.isPermissionDenied(android.Manifest.permission.WRITE_EXTERNAL_STORAGE,this)) {
LinearLayoutCompat mPermissionLayout = findViewById(R.id.permission_layout);
View mPermissionGrant = findViewById(R.id.grant_card);
mPermissionLayout.setVisibility(View.VISIBLE);
mRecyclerView.setVisibility(View.GONE);
mPermissionGrant.setOnClickListener(v -> sPermissionUtils.requestPermission(
new String[] {
android.Manifest.permission.WRITE_EXTERNAL_STORAGE
},this));
return;
}
mRecyclerView.setLayoutManager(new GridLayoutManager(this, APKExplorer.getSpanCount(this)));
mRecycleViewAdapter = new InstallerFilePickerAdapter(APKExplorer.getData(getFilesList(), false, this));
mRecyclerView.setAdapter(mRecycleViewAdapter);
if (getIntent().getStringExtra(TITLE_INTENT) != null) {
mTitle.setText(getIntent().getStringExtra(TITLE_INTENT));
} else {
mTitle.setText(Common.getPath().equals(Environment.getExternalStorageDirectory().toString() + File.separator) ? getString(R.string.sdcard) : new File(Common.getPath()).getName());
}
mRecycleViewAdapter.setOnItemClickListener((position, v) -> {
if (new File(APKExplorer.getData(getFilesList(), false, this).get(position)).isDirectory()) {
Common.setPath(APKExplorer.getData(getFilesList(), false, this).get(position));
reload(this);
} else if (APKExplorer.getData(getFilesList(), false, this).get(position).endsWith(".apks") || APKExplorer.getData(getFilesList(), false,
this).get(position).endsWith(".apkm") || APKExplorer.getData(getFilesList(), false, this).get(position).endsWith(".xapk")) {
new MaterialAlertDialogBuilder(this)
.setMessage(getString(R.string.bundle_install_question, new File(APKExplorer.getData(getFilesList(), false, this).get(position)).getName()))
.setNegativeButton(getString(R.string.cancel), (dialogInterface, i) -> {
}) | .setPositiveButton(getString(R.string.install), (dialogInterface, i) -> SplitAPKInstaller.handleAppBundle(true, APKExplorer.getData( | 4 | 2023-11-18 15:13:30+00:00 | 12k |
jenkinsci/harbor-plugin | src/main/java/io/jenkins/plugins/harbor/steps/WaitForHarborWebhookExecution.java | [
{
"identifier": "HarborException",
"path": "src/main/java/io/jenkins/plugins/harbor/HarborException.java",
"snippet": "public class HarborException extends RuntimeException {\n public HarborException(String message) {\n super(message);\n }\n\n public HarborException(String message, Throw... | import com.cloudbees.plugins.credentials.CredentialsProvider;
import com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials;
import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.AbortException;
import hudson.EnvVars;
import hudson.Launcher;
import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.util.ArgumentListBuilder;
import io.jenkins.plugins.harbor.HarborException;
import io.jenkins.plugins.harbor.action.HarborBuildBadgeAction;
import io.jenkins.plugins.harbor.action.HarborWebHookAction;
import io.jenkins.plugins.harbor.action.HarborWebhookEvent;
import io.jenkins.plugins.harbor.action.model.EventType;
import io.jenkins.plugins.harbor.action.model.Resource;
import io.jenkins.plugins.harbor.action.model.VulnerabilityScanStatus;
import io.jenkins.plugins.harbor.client.HarborClientImpl;
import io.jenkins.plugins.harbor.client.models.Artifact;
import io.jenkins.plugins.harbor.client.models.NativeReportSummary;
import io.jenkins.plugins.harbor.client.models.Severity;
import io.jenkins.plugins.harbor.configuration.HarborPluginGlobalConfiguration;
import io.jenkins.plugins.harbor.configuration.HarborServer;
import io.jenkins.plugins.harbor.util.HarborConstants;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.function.Consumer;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.jenkinsci.plugins.workflow.graph.FlowNode;
import org.jenkinsci.plugins.workflow.steps.StepContext;
import org.jenkinsci.plugins.workflow.steps.StepExecution;
import org.jenkinsci.plugins.workflow.support.actions.PauseAction; | 8,809 | package io.jenkins.plugins.harbor.steps;
public class WaitForHarborWebhookExecution extends StepExecution implements Consumer<HarborWebhookEvent> {
private static final long serialVersionUID = 1L;
private static final Logger logger = Logger.getLogger(WaitForHarborWebhookExecution.class.getName());
private static final int MAX_LOG_LINES = 1000;
private static final String BUILD_IMAGE_NAME_PATTERN = "#\\d+ naming to (\\S+/\\S+/\\S+:\\S+) .*done";
private static final String BUILD_IMAGE_DIGEST_PATTERN = "(\\d+): digest: (sha256:[a-f0-9]+) size: (\\d+)";
private final WaitForHarborWebhookStep waitForHarborWebhookStep;
private Image image;
public WaitForHarborWebhookExecution(StepContext context, WaitForHarborWebhookStep waitForHarborWebhookStep) {
super(context);
this.waitForHarborWebhookStep = waitForHarborWebhookStep;
}
@Override
public boolean start() throws Exception {
processStepParameters();
if (!checkScanCompleted()) {
HarborWebhookEvent harborWebhookEvent =
HarborWebHookAction.get().getWebhookEventForDigest(image.getImageDigest());
if (harborWebhookEvent != null) {
validateWebhookAndCheckSeverityIfValid(harborWebhookEvent, true);
return true;
} else {
getContextClass(FlowNode.class).addAction(new PauseAction("Harbor Scanner analysis"));
return false;
}
} else {
return true;
}
}
private void processStepParameters() throws IOException {
String foundImageName = waitForHarborWebhookStep.getFullImageName();
String foundImageDigest = null;
if (foundImageName == null) {
List<String> lastConsoleLogLines = getContextClass(Run.class).getLog(MAX_LOG_LINES);
Pattern namePattern = Pattern.compile(BUILD_IMAGE_NAME_PATTERN);
Pattern digestPattern = Pattern.compile(BUILD_IMAGE_DIGEST_PATTERN);
for (String line : lastConsoleLogLines) {
Matcher nameMatcher = namePattern.matcher(line);
Matcher digestMatcher = digestPattern.matcher(line);
if (nameMatcher.find()) {
foundImageName = nameMatcher.group(1);
}
if (digestMatcher.find()) {
foundImageDigest = digestMatcher.group(2);
}
}
} else {
foundImageDigest = getDigestByFullImageName(foundImageName);
}
if (foundImageName == null || foundImageDigest == null) {
throw new ImageInfoExtractionException(String.format(
"Failed to extract image name(%s) or digest(%s). Image not found.",
foundImageName, foundImageDigest));
}
this.image = new Image(foundImageName, foundImageDigest);
getContextClass(Run.class)
.addAction(new HarborBuildBadgeAction(String.format(
"https://%s/harbor/projects/%s/repositories/%s/artifacts-tab/artifacts/%s",
image.getRegistry(), image.getProjects(), image.getRepository(), foundImageDigest)));
}
private String getDigestByFullImageName(String fullImageName) {
ArgumentListBuilder argumentListBuilder = new ArgumentListBuilder();
argumentListBuilder.add("docker", "inspect", "-f", "{{.RepoDigests}}", fullImageName);
ByteArrayOutputStream output = new ByteArrayOutputStream();
ByteArrayOutputStream error = new ByteArrayOutputStream();
try {
int status = getContextClass(Launcher.class)
.launch()
.cmds(argumentListBuilder)
.envs(getContextClass(EnvVars.class))
.quiet(true)
.stdout(output)
.stderr(error)
.start()
.join();
if (status == 0) {
String charsetName = Charset.defaultCharset().name();
String repoDigests = output.toString(charsetName).trim();
for (String repoDigest :
repoDigests.substring(1, repoDigests.length() - 1).split(" ")) {
if (repoDigest.startsWith(fullImageName.split(":")[0])) {
return repoDigest.split("@")[1];
}
}
throw new HarborException(
String.format("Unable to get matching image digest. repoDigests: %s%n", repoDigests));
} else {
throw new HarborException("Run docker command fail, Unable to get image digest.");
}
} catch (UnsupportedEncodingException e) {
throw new HarborException("Encoding error, unable to read command result.", e);
} catch (IOException | InterruptedException e) {
throw new HarborException("Run command error, Unable to get command execution results", e);
}
}
private boolean checkScanCompleted() {
HarborWebHookAction.get().addListener(this);
writeLogToConsole(
"Checking scan status of Harbor artifact '%s' on server '%s'%n",
image.getImageName(), image.getRegistry());
try {
HarborServer harborServer =
HarborPluginGlobalConfiguration.getHarborServerByName(waitForHarborWebhookStep.getServer());
HarborClientImpl harborAPIClient = new HarborClientImpl(
harborServer.getBaseUrl(),
getCredentials(waitForHarborWebhookStep.getCredentialsId()),
harborServer.isSkipTlsVerify(),
harborServer.isDebugLogging());
HashMap<String, String> extraParams = new HashMap<String, String>() {
{
put("with_scan_overview", "true");
put("page_size", "15");
put("page", "1");
}
};
Artifact artifact = harborAPIClient.getArtifact(
image.getProjects(), image.getRepository(), image.getImageDigest(), extraParams);
logger.info(artifact.toString()); | package io.jenkins.plugins.harbor.steps;
public class WaitForHarborWebhookExecution extends StepExecution implements Consumer<HarborWebhookEvent> {
private static final long serialVersionUID = 1L;
private static final Logger logger = Logger.getLogger(WaitForHarborWebhookExecution.class.getName());
private static final int MAX_LOG_LINES = 1000;
private static final String BUILD_IMAGE_NAME_PATTERN = "#\\d+ naming to (\\S+/\\S+/\\S+:\\S+) .*done";
private static final String BUILD_IMAGE_DIGEST_PATTERN = "(\\d+): digest: (sha256:[a-f0-9]+) size: (\\d+)";
private final WaitForHarborWebhookStep waitForHarborWebhookStep;
private Image image;
public WaitForHarborWebhookExecution(StepContext context, WaitForHarborWebhookStep waitForHarborWebhookStep) {
super(context);
this.waitForHarborWebhookStep = waitForHarborWebhookStep;
}
@Override
public boolean start() throws Exception {
processStepParameters();
if (!checkScanCompleted()) {
HarborWebhookEvent harborWebhookEvent =
HarborWebHookAction.get().getWebhookEventForDigest(image.getImageDigest());
if (harborWebhookEvent != null) {
validateWebhookAndCheckSeverityIfValid(harborWebhookEvent, true);
return true;
} else {
getContextClass(FlowNode.class).addAction(new PauseAction("Harbor Scanner analysis"));
return false;
}
} else {
return true;
}
}
private void processStepParameters() throws IOException {
String foundImageName = waitForHarborWebhookStep.getFullImageName();
String foundImageDigest = null;
if (foundImageName == null) {
List<String> lastConsoleLogLines = getContextClass(Run.class).getLog(MAX_LOG_LINES);
Pattern namePattern = Pattern.compile(BUILD_IMAGE_NAME_PATTERN);
Pattern digestPattern = Pattern.compile(BUILD_IMAGE_DIGEST_PATTERN);
for (String line : lastConsoleLogLines) {
Matcher nameMatcher = namePattern.matcher(line);
Matcher digestMatcher = digestPattern.matcher(line);
if (nameMatcher.find()) {
foundImageName = nameMatcher.group(1);
}
if (digestMatcher.find()) {
foundImageDigest = digestMatcher.group(2);
}
}
} else {
foundImageDigest = getDigestByFullImageName(foundImageName);
}
if (foundImageName == null || foundImageDigest == null) {
throw new ImageInfoExtractionException(String.format(
"Failed to extract image name(%s) or digest(%s). Image not found.",
foundImageName, foundImageDigest));
}
this.image = new Image(foundImageName, foundImageDigest);
getContextClass(Run.class)
.addAction(new HarborBuildBadgeAction(String.format(
"https://%s/harbor/projects/%s/repositories/%s/artifacts-tab/artifacts/%s",
image.getRegistry(), image.getProjects(), image.getRepository(), foundImageDigest)));
}
private String getDigestByFullImageName(String fullImageName) {
ArgumentListBuilder argumentListBuilder = new ArgumentListBuilder();
argumentListBuilder.add("docker", "inspect", "-f", "{{.RepoDigests}}", fullImageName);
ByteArrayOutputStream output = new ByteArrayOutputStream();
ByteArrayOutputStream error = new ByteArrayOutputStream();
try {
int status = getContextClass(Launcher.class)
.launch()
.cmds(argumentListBuilder)
.envs(getContextClass(EnvVars.class))
.quiet(true)
.stdout(output)
.stderr(error)
.start()
.join();
if (status == 0) {
String charsetName = Charset.defaultCharset().name();
String repoDigests = output.toString(charsetName).trim();
for (String repoDigest :
repoDigests.substring(1, repoDigests.length() - 1).split(" ")) {
if (repoDigest.startsWith(fullImageName.split(":")[0])) {
return repoDigest.split("@")[1];
}
}
throw new HarborException(
String.format("Unable to get matching image digest. repoDigests: %s%n", repoDigests));
} else {
throw new HarborException("Run docker command fail, Unable to get image digest.");
}
} catch (UnsupportedEncodingException e) {
throw new HarborException("Encoding error, unable to read command result.", e);
} catch (IOException | InterruptedException e) {
throw new HarborException("Run command error, Unable to get command execution results", e);
}
}
private boolean checkScanCompleted() {
HarborWebHookAction.get().addListener(this);
writeLogToConsole(
"Checking scan status of Harbor artifact '%s' on server '%s'%n",
image.getImageName(), image.getRegistry());
try {
HarborServer harborServer =
HarborPluginGlobalConfiguration.getHarborServerByName(waitForHarborWebhookStep.getServer());
HarborClientImpl harborAPIClient = new HarborClientImpl(
harborServer.getBaseUrl(),
getCredentials(waitForHarborWebhookStep.getCredentialsId()),
harborServer.isSkipTlsVerify(),
harborServer.isDebugLogging());
HashMap<String, String> extraParams = new HashMap<String, String>() {
{
put("with_scan_overview", "true");
put("page_size", "15");
put("page", "1");
}
};
Artifact artifact = harborAPIClient.getArtifact(
image.getProjects(), image.getRepository(), image.getImageDigest(), extraParams);
logger.info(artifact.toString()); | HashMap<String, NativeReportSummary> scanOverview = artifact.getScanOverview(); | 9 | 2023-11-11 14:54:53+00:00 | 12k |
Mapty231/SpawnFix | src/main/java/me/tye/spawnfix/commands/Commands.java | [
{
"identifier": "Config",
"path": "src/main/java/me/tye/spawnfix/utils/Config.java",
"snippet": "public enum Config {\n\n default_worldName(String.class),\n default_x(Double.class),\n default_y(Double.class),\n default_z(Double.class),\n default_yaw(Float.class),\n default_pitch(Float.class),\n\n ... | import me.tye.spawnfix.utils.Config;
import me.tye.spawnfix.utils.Key;
import me.tye.spawnfix.utils.Lang;
import me.tye.spawnfix.utils.Util;
import org.bukkit.Location;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import java.util.logging.Level;
import static me.tye.spawnfix.utils.Util.*; | 10,570 | package me.tye.spawnfix.commands;
public class Commands implements CommandExecutor {
@Override
public boolean onCommand(@NotNull CommandSender commandSender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {
if (!commandSender.hasPermission("sf")) return true;
if (args.length != 1) return true;
switch (args[0]) {
//Sets the new spawn to the players position.
case "setSpawn" -> {
if (!(commandSender instanceof Player)) return true;
Player player = (Player) commandSender;
Location currentLocation = player.getLocation();
String worldName = currentLocation.getWorld().getName();
double x = currentLocation.getX();
double y = currentLocation.getY();
double z = currentLocation.getZ();
float yaw = currentLocation.getYaw();
float pitch = currentLocation.getPitch();
try {
writeYamlData("default.worldName", worldName, configFile);
writeYamlData("default.x", String.valueOf(x), configFile);
writeYamlData("default.y", String.valueOf(y), configFile);
writeYamlData("default.z", String.valueOf(z), configFile);
writeYamlData("default.yaw", String.valueOf(yaw), configFile);
writeYamlData("default.pitch", String.valueOf(pitch), configFile);
} catch (IOException e) {
player.sendMessage(Lang.commands_unableToSet.getResponse(Key.filePath.replaceWith(configFile.getAbsolutePath())));
log.log(Level.WARNING, "", e);
return true;
}
//reloads the config values
Config.load();
player.sendMessage(Lang.commands_setSpawn.getResponse());
}
//Teleports the player to the set spawn.
case "tp" -> {
if (!(commandSender instanceof Player)) return true;
Player player = (Player) commandSender;
| package me.tye.spawnfix.commands;
public class Commands implements CommandExecutor {
@Override
public boolean onCommand(@NotNull CommandSender commandSender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {
if (!commandSender.hasPermission("sf")) return true;
if (args.length != 1) return true;
switch (args[0]) {
//Sets the new spawn to the players position.
case "setSpawn" -> {
if (!(commandSender instanceof Player)) return true;
Player player = (Player) commandSender;
Location currentLocation = player.getLocation();
String worldName = currentLocation.getWorld().getName();
double x = currentLocation.getX();
double y = currentLocation.getY();
double z = currentLocation.getZ();
float yaw = currentLocation.getYaw();
float pitch = currentLocation.getPitch();
try {
writeYamlData("default.worldName", worldName, configFile);
writeYamlData("default.x", String.valueOf(x), configFile);
writeYamlData("default.y", String.valueOf(y), configFile);
writeYamlData("default.z", String.valueOf(z), configFile);
writeYamlData("default.yaw", String.valueOf(yaw), configFile);
writeYamlData("default.pitch", String.valueOf(pitch), configFile);
} catch (IOException e) {
player.sendMessage(Lang.commands_unableToSet.getResponse(Key.filePath.replaceWith(configFile.getAbsolutePath())));
log.log(Level.WARNING, "", e);
return true;
}
//reloads the config values
Config.load();
player.sendMessage(Lang.commands_setSpawn.getResponse());
}
//Teleports the player to the set spawn.
case "tp" -> {
if (!(commandSender instanceof Player)) return true;
Player player = (Player) commandSender;
| player.teleport(Util.getDefaultSpawn()); | 4 | 2023-11-13 23:53:25+00:00 | 12k |
wangxianhui111/xuechengzaixian | xuecheng-plus-content/xuecheng-plus-content-service/src/main/java/com/xuecheng/content/service/impl/CoursePublishServiceImpl.java | [
{
"identifier": "XueChengPlusException",
"path": "xuecheng-plus-base/src/main/java/com/xuecheng/base/exception/XueChengPlusException.java",
"snippet": "public class XueChengPlusException extends RuntimeException {\n private static final long serialVersionUID = 5565760508056698922L;\n private Strin... | import com.alibaba.fastjson.JSON;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.content.config.MultipartSupportConfig;
import com.xuecheng.content.feignclient.MediaServiceClient;
import com.xuecheng.content.feignclient.SearchServiceClient;
import com.xuecheng.content.feignclient.po.CourseIndex;
import com.xuecheng.content.mapper.CourseBaseMapper;
import com.xuecheng.content.mapper.CourseMarketMapper;
import com.xuecheng.content.mapper.CoursePublishMapper;
import com.xuecheng.content.mapper.CoursePublishPreMapper;
import com.xuecheng.content.model.dto.CourseBaseInfoDto;
import com.xuecheng.content.model.dto.CoursePreviewDto;
import com.xuecheng.content.model.dto.TeachplanDto;
import com.xuecheng.content.model.po.CourseBase;
import com.xuecheng.content.model.po.CourseMarket;
import com.xuecheng.content.model.po.CoursePublish;
import com.xuecheng.content.model.po.CoursePublishPre;
import com.xuecheng.content.service.CourseBaseInfoService;
import com.xuecheng.content.service.CoursePublishService;
import com.xuecheng.content.service.TeachplanService;
import com.xuecheng.messagesdk.model.po.MqMessage;
import com.xuecheng.messagesdk.service.MqMessageService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit; | 10,779 | String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
// 将静态化内容输出到文件中
InputStream inputStream = IOUtils.toInputStream(content, StandardCharsets.UTF_8);
// 创建静态化文件
file = File.createTempFile("course", "html");
log.debug("课程静态化,生成静态化文件:{}", file.getAbsolutePath());
// 输出流
FileOutputStream outputStream = new FileOutputStream(file);
IOUtils.copy(inputStream, outputStream);
} catch (Exception e) {
e.printStackTrace();
}
return file;
}
@Override
public void uploadCourseHtml(Long courseId, File file) {
MultipartFile multipartFile = MultipartSupportConfig.getMultipartFile(file);
String course = mediaServiceClient.uploadFile(multipartFile, "course", courseId + ".html");
if (course == null) {
XueChengPlusException.cast("远程调用媒资服务上传文件失败");
}
}
@Override
public Boolean saveCourseIndex(Long courseId) {
// 1.取出课程发布信息
CoursePublish coursePublish = coursePublishMapper.selectById(courseId);
// 2.拷贝至课程索引对象
CourseIndex courseIndex = new CourseIndex();
BeanUtils.copyProperties(coursePublish, courseIndex);
// 3.远程调用搜索服务 api 添加课程信息到索引
Boolean success = searchServiceClient.add(courseIndex);
if (!success) {
XueChengPlusException.cast("添加课程索引失败");
}
return true;
}
@Override
public CoursePublish getCoursePublish(Long courseId) {
return coursePublishMapper.selectById(courseId);
}
@Override
public CoursePublish getCoursePublishCache(Long courseId) {
// 查询缓存
String key = "course_" + courseId;
String jsonStr = stringRedisTemplate.opsForValue().get(key);
// 缓存命中
if (StringUtils.isNotEmpty(jsonStr)) {
if (jsonStr.equals("null")) { // 如果为null字符串,表明数据库中不存在此课程,直接返回(解决缓存穿透)
return null;
}
return JSON.parseObject(jsonStr, CoursePublish.class);
}
// 缓存未命中,查询数据库并添加到缓存中
// 每一门课程设置一个锁
RLock lock = redissonClient.getLock("coursequerylock:" + courseId);
// 阻塞等待获取锁
lock.lock();
try {
// 检查是否已经存在(双从检查)
jsonStr = stringRedisTemplate.opsForValue().get(key);
if (StringUtils.isNotEmpty(jsonStr)) {
return JSON.parseObject(jsonStr, CoursePublish.class);
}
// 查询数据库
CoursePublish coursePublish = getCoursePublish(courseId);
// 当 coursePublish 为空时,缓存 null 字符串
stringRedisTemplate.opsForValue().set(key, JSON.toJSONString(coursePublish), 1, TimeUnit.DAYS);
return coursePublish;
} catch (Exception e) {
log.error("查询课程发布信息失败:", e);
throw new XueChengPlusException("课程发布信息查询异常:" + e.getMessage());
} finally {
// 释放锁
lock.unlock();
}
}
/**
* 保存课程发布信息
*
* @param courseId 课程 id
* @author Wuxy
* @since 2022/9/20 16:32
*/
private void saveCoursePublish(Long courseId) {
// 查询课程预发布信息
CoursePublishPre coursePublishPre = coursePublishPreMapper.selectById(courseId);
if (coursePublishPre == null) {
XueChengPlusException.cast("课程预发布数据为空");
}
CoursePublish coursePublish = new CoursePublish();
// 属性拷贝
BeanUtils.copyProperties(coursePublishPre, coursePublish);
coursePublish.setStatus("203002");
CoursePublish coursePublishUpdate = coursePublishMapper.selectById(courseId);
if (coursePublishUpdate == null) {
// 插入新的课程发布记录
coursePublishMapper.insert(coursePublish);
} else {
// 更新课程发布记录
coursePublishMapper.updateById(coursePublish);
}
// 更新课程基本表的发布状态
CourseBase courseBase = courseBaseMapper.selectById(courseId);
courseBase.setStatus("203002");
courseBaseMapper.updateById(courseBase);
}
/**
* 保存消息表记录,稍后实现
*
* @param courseId 课程 id
* @author Mr.W
* @since 2022/9/20 16:32
*/
private void saveCoursePublishMessage(Long courseId) { | package com.xuecheng.content.service.impl;
/**
* @author Wuxy
* @version 1.0
* @ClassName CoursePublishServiceImpl
* @since 2023/1/30 15:45
*/
@Slf4j
@Service
public class CoursePublishServiceImpl implements CoursePublishService {
@Resource
private CourseBaseMapper courseBaseMapper;
@Resource
private CourseMarketMapper courseMarketMapper;
@Resource
private CoursePublishMapper coursePublishMapper;
@Resource
private CoursePublishPreMapper coursePublishPreMapper;
@Autowired
private CourseBaseInfoService courseBaseInfoService;
@Autowired
private TeachplanService teachplanService;
@Autowired
private MqMessageService mqMessageService;
@Autowired
private MediaServiceClient mediaServiceClient;
@Autowired
private SearchServiceClient searchServiceClient;
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Autowired
private RedissonClient redissonClient;
@Override
public CoursePreviewDto getCoursePreviewInfo(Long courseId) {
// 查询课程发布信息
CoursePublish coursePublish = getCoursePublishCache(courseId);
// 课程基本信息
CourseBaseInfoDto courseBaseInfo = new CourseBaseInfoDto();
BeanUtils.copyProperties(coursePublish, courseBaseInfo);
// 课程计划信息
List<TeachplanDto> teachplans = JSON.parseArray(coursePublish.getTeachplan(), TeachplanDto.class);
// 创建课程预览信息
CoursePreviewDto coursePreviewDto = new CoursePreviewDto();
coursePreviewDto.setCourseBase(courseBaseInfo);
coursePreviewDto.setTeachplans(teachplans);
return coursePreviewDto;
}
@Override
public CoursePreviewDto getOpenCoursePreviewInfo(Long courseId) {
// 课程基本信息
CourseBaseInfoDto courseBaseInfo = courseBaseInfoService.queryCourseBaseById(courseId);
// 课程计划信息
List<TeachplanDto> teachplans = teachplanService.findTeachplanTree(courseId);
// 创建课程预览信息
CoursePreviewDto coursePreviewDto = new CoursePreviewDto();
coursePreviewDto.setCourseBase(courseBaseInfo);
coursePreviewDto.setTeachplans(teachplans);
return coursePreviewDto;
}
@Override
public void commitAudit(Long companyId, Long courseId) {
// 课程基本信息
CourseBase courseBase = courseBaseMapper.selectById(courseId);
// 课程审核状态
String auditStatus = courseBase.getAuditStatus();
if ("202003".equals(auditStatus)) {
XueChengPlusException.cast("当前为等待审核状态,审核完成可以再次提交。");
}
// 本机构只允许提交本机构的课程
if (!companyId.equals(courseBase.getCompanyId())) {
XueChengPlusException.cast("不允许提交其它机构的课程。");
}
// 课程图片是否填写
if (StringUtils.isEmpty(courseBase.getPic())) {
XueChengPlusException.cast("提交失败,请上传课程图片");
}
// 添加课程预发布记录
CoursePublishPre coursePublishPre = new CoursePublishPre();
// 课程基本信息和营销信息
CourseBaseInfoDto courseBaseInfoDto = courseBaseInfoService.queryCourseBaseById(courseId);
BeanUtils.copyProperties(courseBaseInfoDto, coursePublishPre);
// 课程营销信息
CourseMarket courseMarket = courseMarketMapper.selectById(courseId);
// 转为 JSON
String courseMarketJson = JSON.toJSONString(courseMarket);
// 将课程营销信息放入课程预发布表
coursePublishPre.setMarket(courseMarketJson);
// 查询课程计划信息
List<TeachplanDto> teachplanTree = teachplanService.findTeachplanTree(courseId);
if (teachplanTree == null || teachplanTree.isEmpty()) {
XueChengPlusException.cast("提交失败,还没有添加课程计划");
}
// 转 json
String teachplanJson = JSON.toJSONString(teachplanTree);
coursePublishPre.setTeachplan(teachplanJson);
// 设置预发布记录状态
coursePublishPre.setStatus("202003");
// 教学机构id
coursePublishPre.setCompanyId(companyId);
// 提交时间
coursePublishPre.setCreateDate(LocalDateTime.now());
CoursePublishPre coursePublishPreUpdate = coursePublishPreMapper.selectById(companyId);
if (coursePublishPreUpdate == null) {
// 添加课程预发布记录
coursePublishPreMapper.insert(coursePublishPre);
} else {
// 更新课程预发布记录
coursePublishPreMapper.updateById(coursePublishPre);
}
// 更新课程基本表的审核状态
courseBase.setAuditStatus("202003");
courseBaseMapper.updateById(courseBase);
}
@Transactional
@Override
public void publish(Long companyId, Long courseId) {
// 查询课程预发布表
CoursePublishPre coursePublishPre = coursePublishPreMapper.selectById(courseId);
if (coursePublishPre == null) {
XueChengPlusException.cast("请先提交课程审核,审核通过才可以发布");
}
// 本机构只允许提交本机构的课程
if (!companyId.equals(coursePublishPre.getCompanyId())) {
XueChengPlusException.cast("不允许提交其它机构的课程。");
}
// 获得课程审核状态
String status = coursePublishPre.getStatus();
// 审核通过才可以进行发布
if (!"202004".equals(status)) {
XueChengPlusException.cast("操作失败,课程审核通过方可发布。");
}
// 保存课程发布信息
saveCoursePublish(courseId);
// 保存消息表
saveCoursePublishMessage(courseId);
// 删除课程预发布表记录
coursePublishPreMapper.deleteById(courseId);
}
@Override
public File generateCourseHtml(Long courseId) {
// 静态化文件
File file = null;
try {
// 配置 freemarker
Configuration configuration = new Configuration(Configuration.getVersion());
// 加载模板,选指定模板路径,classpath 下 templates 下
// 得到 classpath
String classpath = this.getClass().getResource("/").getPath();
configuration.setDirectoryForTemplateLoading(new File(classpath + "/templates/"));
// 设置字符编码
configuration.setDefaultEncoding("utf-8");
// 指定模板文件名称
Template template = configuration.getTemplate("course_template.ftl");
// 准备数据
CoursePreviewDto coursePreviewInfo = this.getCoursePreviewInfo(courseId);
Map<String, Object> map = new HashMap<>();
map.put("model", coursePreviewInfo);
// 静态化
String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
// 将静态化内容输出到文件中
InputStream inputStream = IOUtils.toInputStream(content, StandardCharsets.UTF_8);
// 创建静态化文件
file = File.createTempFile("course", "html");
log.debug("课程静态化,生成静态化文件:{}", file.getAbsolutePath());
// 输出流
FileOutputStream outputStream = new FileOutputStream(file);
IOUtils.copy(inputStream, outputStream);
} catch (Exception e) {
e.printStackTrace();
}
return file;
}
@Override
public void uploadCourseHtml(Long courseId, File file) {
MultipartFile multipartFile = MultipartSupportConfig.getMultipartFile(file);
String course = mediaServiceClient.uploadFile(multipartFile, "course", courseId + ".html");
if (course == null) {
XueChengPlusException.cast("远程调用媒资服务上传文件失败");
}
}
@Override
public Boolean saveCourseIndex(Long courseId) {
// 1.取出课程发布信息
CoursePublish coursePublish = coursePublishMapper.selectById(courseId);
// 2.拷贝至课程索引对象
CourseIndex courseIndex = new CourseIndex();
BeanUtils.copyProperties(coursePublish, courseIndex);
// 3.远程调用搜索服务 api 添加课程信息到索引
Boolean success = searchServiceClient.add(courseIndex);
if (!success) {
XueChengPlusException.cast("添加课程索引失败");
}
return true;
}
@Override
public CoursePublish getCoursePublish(Long courseId) {
return coursePublishMapper.selectById(courseId);
}
@Override
public CoursePublish getCoursePublishCache(Long courseId) {
// 查询缓存
String key = "course_" + courseId;
String jsonStr = stringRedisTemplate.opsForValue().get(key);
// 缓存命中
if (StringUtils.isNotEmpty(jsonStr)) {
if (jsonStr.equals("null")) { // 如果为null字符串,表明数据库中不存在此课程,直接返回(解决缓存穿透)
return null;
}
return JSON.parseObject(jsonStr, CoursePublish.class);
}
// 缓存未命中,查询数据库并添加到缓存中
// 每一门课程设置一个锁
RLock lock = redissonClient.getLock("coursequerylock:" + courseId);
// 阻塞等待获取锁
lock.lock();
try {
// 检查是否已经存在(双从检查)
jsonStr = stringRedisTemplate.opsForValue().get(key);
if (StringUtils.isNotEmpty(jsonStr)) {
return JSON.parseObject(jsonStr, CoursePublish.class);
}
// 查询数据库
CoursePublish coursePublish = getCoursePublish(courseId);
// 当 coursePublish 为空时,缓存 null 字符串
stringRedisTemplate.opsForValue().set(key, JSON.toJSONString(coursePublish), 1, TimeUnit.DAYS);
return coursePublish;
} catch (Exception e) {
log.error("查询课程发布信息失败:", e);
throw new XueChengPlusException("课程发布信息查询异常:" + e.getMessage());
} finally {
// 释放锁
lock.unlock();
}
}
/**
* 保存课程发布信息
*
* @param courseId 课程 id
* @author Wuxy
* @since 2022/9/20 16:32
*/
private void saveCoursePublish(Long courseId) {
// 查询课程预发布信息
CoursePublishPre coursePublishPre = coursePublishPreMapper.selectById(courseId);
if (coursePublishPre == null) {
XueChengPlusException.cast("课程预发布数据为空");
}
CoursePublish coursePublish = new CoursePublish();
// 属性拷贝
BeanUtils.copyProperties(coursePublishPre, coursePublish);
coursePublish.setStatus("203002");
CoursePublish coursePublishUpdate = coursePublishMapper.selectById(courseId);
if (coursePublishUpdate == null) {
// 插入新的课程发布记录
coursePublishMapper.insert(coursePublish);
} else {
// 更新课程发布记录
coursePublishMapper.updateById(coursePublish);
}
// 更新课程基本表的发布状态
CourseBase courseBase = courseBaseMapper.selectById(courseId);
courseBase.setStatus("203002");
courseBaseMapper.updateById(courseBase);
}
/**
* 保存消息表记录,稍后实现
*
* @param courseId 课程 id
* @author Mr.W
* @since 2022/9/20 16:32
*/
private void saveCoursePublishMessage(Long courseId) { | MqMessage mqMessage = mqMessageService.addMessage("course_publish", String.valueOf(courseId), null, null); | 19 | 2023-11-13 11:39:35+00:00 | 12k |
jensjeflensje/minecraft_typewriter | src/main/java/dev/jensderuiter/minecrafttypewriter/command/SpawnCommand.java | [
{
"identifier": "TypewriterPlugin",
"path": "src/main/java/dev/jensderuiter/minecrafttypewriter/TypewriterPlugin.java",
"snippet": "public final class TypewriterPlugin extends JavaPlugin {\n\n public static HashMap<Player, TypeWriter> playerWriters;\n\n @Getter\n private static TypewriterPlugin... | import dev.jensderuiter.minecrafttypewriter.TypewriterPlugin;
import dev.jensderuiter.minecrafttypewriter.typewriter.TypeWriter;
import dev.jensderuiter.minecrafttypewriter.typewriter.type.WoodenTypeWriter;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; | 7,525 | package dev.jensderuiter.minecrafttypewriter.command;
public class SpawnCommand implements CommandExecutor {
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (!(sender instanceof Player)) return true;
Player player = (Player) sender;
| package dev.jensderuiter.minecrafttypewriter.command;
public class SpawnCommand implements CommandExecutor {
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (!(sender instanceof Player)) return true;
Player player = (Player) sender;
| if (TypewriterPlugin.playerWriters.get(player) != null) return true; | 0 | 2023-11-18 20:44:30+00:00 | 12k |
ZhiQinIsZhen/dubbo-springboot3 | dubbo-service/dubbo-service-staff/staff-biz/src/main/java/com/liyz/boot3/service/staff/provider/auth/RemoteAuthServiceImpl.java | [
{
"identifier": "BeanUtil",
"path": "dubbo-common/dubbo-common-service/src/main/java/com/liyz/boot3/common/service/util/BeanUtil.java",
"snippet": "@UtilityClass\npublic final class BeanUtil {\n\n /**\n * 单个对象拷贝\n *\n * @param source 原对象\n * @param targetSupplier 目标对象\n * @return ... | import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.liyz.boot3.common.service.util.BeanUtil;
import com.liyz.boot3.common.util.DateUtil;
import com.liyz.boot3.common.util.PatternUtil;
import com.liyz.boot3.service.auth.bo.AuthUserBO;
import com.liyz.boot3.service.auth.bo.AuthUserLoginBO;
import com.liyz.boot3.service.auth.bo.AuthUserLogoutBO;
import com.liyz.boot3.service.auth.bo.AuthUserRegisterBO;
import com.liyz.boot3.service.auth.enums.Device;
import com.liyz.boot3.service.auth.enums.LoginType;
import com.liyz.boot3.service.auth.exception.AuthExceptionCodeEnum;
import com.liyz.boot3.service.auth.exception.RemoteAuthServiceException;
import com.liyz.boot3.service.auth.remote.RemoteAuthService;
import com.liyz.boot3.service.staff.model.*;
import com.liyz.boot3.service.staff.model.base.StaffAuthBaseDO;
import com.liyz.boot3.service.staff.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;
import java.util.*;
import java.util.function.BiConsumer;
import java.util.stream.Collectors; | 8,947 | package com.liyz.boot3.service.staff.provider.auth;
/**
* Desc:
*
* @author lyz
* @version 1.0.0
* @date 2023/3/10 11:10
*/
@Slf4j
@DubboService(tag = "staff") | package com.liyz.boot3.service.staff.provider.auth;
/**
* Desc:
*
* @author lyz
* @version 1.0.0
* @date 2023/3/10 11:10
*/
@Slf4j
@DubboService(tag = "staff") | public class RemoteAuthServiceImpl implements RemoteAuthService { | 11 | 2023-11-13 01:28:21+00:00 | 12k |
martin-bian/DimpleBlog | dimple-system/src/main/java/com/dimple/modules/system/service/impl/DictServiceImpl.java | [
{
"identifier": "Dict",
"path": "dimple-system/src/main/java/com/dimple/modules/system/domain/Dict.java",
"snippet": "@Entity\n@Getter\n@Setter\n@Table(name = \"sys_dict\")\npublic class Dict extends BaseEntity implements Serializable {\n\n @Id\n @Column(name = \"dict_id\")\n @NotNull(groups = ... | import cn.hutool.core.collection.CollectionUtil;
import com.dimple.modules.system.domain.Dict;
import com.dimple.modules.system.repository.DictRepository;
import com.dimple.modules.system.service.DictService;
import com.dimple.modules.system.service.dto.DictDTO;
import com.dimple.modules.system.service.dto.DictDetailDTO;
import com.dimple.modules.system.service.dto.DictQueryCriteria;
import com.dimple.modules.system.service.mapstruct.DictMapper;
import com.dimple.utils.FileUtil;
import com.dimple.utils.PageUtil;
import com.dimple.utils.QueryHelp;
import com.dimple.utils.RedisUtils;
import com.dimple.utils.ValidationUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set; | 10,739 | package com.dimple.modules.system.service.impl;
/**
* @className: DictServiceImpl
* @description:
* @author: Dimple
* @date: 06/17/20
*/
@Service
@RequiredArgsConstructor
@CacheConfig(cacheNames = "dict")
public class DictServiceImpl implements DictService {
| package com.dimple.modules.system.service.impl;
/**
* @className: DictServiceImpl
* @description:
* @author: Dimple
* @date: 06/17/20
*/
@Service
@RequiredArgsConstructor
@CacheConfig(cacheNames = "dict")
public class DictServiceImpl implements DictService {
| private final DictRepository dictRepository; | 1 | 2023-11-10 03:30:36+00:00 | 12k |
LazyCoder0101/LazyCoder | ui-code-generation/src/main/java/com/lazycoder/uicodegeneration/component/operation/component/typeset/format/additional/AdditionalSetCodeControlPane.java | [
{
"identifier": "MarkElementName",
"path": "database/src/main/java/com/lazycoder/database/common/MarkElementName.java",
"snippet": "public class MarkElementName {\n\n\t/**\n\t * 引入标记\n\t */\n\tpublic static final String IMPORT_MARK = \"importMark\";\n\n\t/**\n\t * 初始化标记\n\t */\n\tpublic static final Str... | import com.lazycoder.database.common.MarkElementName;
import com.lazycoder.database.model.featureSelectionModel.FormatTypeFeatureSelectionModel;
import com.lazycoder.service.service.SysService;
import com.lazycoder.service.vo.meta.AdditionalSetMetaModel;
import com.lazycoder.uicodegeneration.PathFind;
import com.lazycoder.uicodegeneration.component.operation.container.AdditionalSetContainer;
import com.lazycoder.uicodegeneration.component.operation.container.sendparam.AdditionalSetTypeOperatingContainerParam;
import com.lazycoder.uicodegeneration.generalframe.operation.component.AbstractCodeControlPane;
import com.lazycoder.uicodegeneration.proj.stostr.operation.base.AbstractOperatingContainerModel;
import com.lazycoder.uicodegeneration.proj.stostr.operation.base.BaseFormatStructureModel;
import com.lazycoder.uicodegeneration.proj.stostr.operation.container.AdditionalSetOpratingContainerModel;
import com.lazycoder.uicodegeneration.proj.stostr.operation.containerput.AdditionalSetTypeContainerModel;
import java.util.ArrayList; | 9,516 | package com.lazycoder.uicodegeneration.component.operation.component.typeset.format.additional;
public class AdditionalSetCodeControlPane extends AbstractCodeControlPane {
/**
*
*/
private static final long serialVersionUID = 2381228844809378537L;
private AdditionalSetTypeOperatingContainerParam additionalSetTypeOperatingContainerParam;
public AdditionalSetCodeControlPane(AdditionalSetTypeOperatingContainerParam additionalSetTypeOperatingContainerParam) {
// TODO Auto-generated constructor stub
super(additionalSetTypeOperatingContainerParam.getFormatControlPane(), 20);
additionalSetTypeOperatingContainerParam.setCodeControlPane(this);
this.additionalSetTypeOperatingContainerParam = additionalSetTypeOperatingContainerParam;
PathFind pathFind = new PathFind(MarkElementName.ADDITIONAL_SET_TYPE_MARK, PathFind.COMMAND_TYPE);
setPathFind(pathFind);
}
/**
* 根据模型还原内容
*
* @param codeControlPaneModel
*/
public void restoreContent(AdditionalSetTypeContainerModel codeControlPaneModel) {
AdditionalSetContainer container;
ArrayList<AbstractOperatingContainerModel> containerList = codeControlPaneModel.getContainerList();
for (BaseFormatStructureModel baseFormatStructureModel : containerList) {
if (baseFormatStructureModel instanceof AdditionalSetOpratingContainerModel) {
this.additionalSetTypeOperatingContainerParam.setCodeControlPane(this);
container = new AdditionalSetContainer(additionalSetTypeOperatingContainerParam,
(AdditionalSetOpratingContainerModel) baseFormatStructureModel, true);
addContainer(container);
}
}
}
public AdditionalSetContainer addOpratingPane(FormatTypeFeatureSelectionModel featureSelectionModel, boolean canBeDelOrNot) {
additionalSetTypeOperatingContainerParam.setFeatureSelectionModel(featureSelectionModel);
additionalSetTypeOperatingContainerParam.setCodeControlPane(this);
additionalSetTypeOperatingContainerParam.setAdditionalSetType(featureSelectionModel.getTypeName());
AdditionalSetContainer container = null; | package com.lazycoder.uicodegeneration.component.operation.component.typeset.format.additional;
public class AdditionalSetCodeControlPane extends AbstractCodeControlPane {
/**
*
*/
private static final long serialVersionUID = 2381228844809378537L;
private AdditionalSetTypeOperatingContainerParam additionalSetTypeOperatingContainerParam;
public AdditionalSetCodeControlPane(AdditionalSetTypeOperatingContainerParam additionalSetTypeOperatingContainerParam) {
// TODO Auto-generated constructor stub
super(additionalSetTypeOperatingContainerParam.getFormatControlPane(), 20);
additionalSetTypeOperatingContainerParam.setCodeControlPane(this);
this.additionalSetTypeOperatingContainerParam = additionalSetTypeOperatingContainerParam;
PathFind pathFind = new PathFind(MarkElementName.ADDITIONAL_SET_TYPE_MARK, PathFind.COMMAND_TYPE);
setPathFind(pathFind);
}
/**
* 根据模型还原内容
*
* @param codeControlPaneModel
*/
public void restoreContent(AdditionalSetTypeContainerModel codeControlPaneModel) {
AdditionalSetContainer container;
ArrayList<AbstractOperatingContainerModel> containerList = codeControlPaneModel.getContainerList();
for (BaseFormatStructureModel baseFormatStructureModel : containerList) {
if (baseFormatStructureModel instanceof AdditionalSetOpratingContainerModel) {
this.additionalSetTypeOperatingContainerParam.setCodeControlPane(this);
container = new AdditionalSetContainer(additionalSetTypeOperatingContainerParam,
(AdditionalSetOpratingContainerModel) baseFormatStructureModel, true);
addContainer(container);
}
}
}
public AdditionalSetContainer addOpratingPane(FormatTypeFeatureSelectionModel featureSelectionModel, boolean canBeDelOrNot) {
additionalSetTypeOperatingContainerParam.setFeatureSelectionModel(featureSelectionModel);
additionalSetTypeOperatingContainerParam.setCodeControlPane(this);
additionalSetTypeOperatingContainerParam.setAdditionalSetType(featureSelectionModel.getTypeName());
AdditionalSetContainer container = null; | AdditionalSetMetaModel metaModel = SysService.ADDITIONAL_SET_SERVICE | 2 | 2023-11-16 11:55:06+00:00 | 12k |
kash-developer/HomeDeviceEmulator | app/src/main/java/kr/or/kashi/hde/MainFragment.java | [
{
"identifier": "PropertyMap",
"path": "app/src/main/java/kr/or/kashi/hde/base/PropertyMap.java",
"snippet": "public abstract class PropertyMap {\n /** Get the value of a property */\n public <E> E get(String name, Class<E> clazz) {\n return (E) get(name).getValue();\n }\n\n /** Put n... | import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Checkable;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.ToggleButton;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import kr.or.kashi.hde.base.PropertyMap;
import kr.or.kashi.hde.test.DeviceTestCallback;
import kr.or.kashi.hde.util.DebugLog;
import kr.or.kashi.hde.util.LocalPreferences;
import kr.or.kashi.hde.util.LocalPreferences.Pref;
import kr.or.kashi.hde.util.Utils;
import kr.or.kashi.hde.widget.CheckableListAdapter;
import kr.or.kashi.hde.widget.CustomLayoutManager;
import kr.or.kashi.hde.widget.DebugLogView;
import kr.or.kashi.hde.widget.DeviceInfoView;
import kr.or.kashi.hde.widget.DeviceListAdapter;
import kr.or.kashi.hde.widget.DeviceTestPartView;
import kr.or.kashi.hde.widget.HomeDeviceView;
import kr.or.kashi.hde.widget.NullRecyclerViewAdapter; | 8,806 | /*
* Copyright (C) 2023 Korea Association of AI Smart Home.
* Copyright (C) 2023 KyungDong Navien Co, 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 kr.or.kashi.hde;
public class MainFragment extends Fragment {
private static final String TAG = "HomeTestFragment";
private static final String SAVED_DEVICES_FILENAME = "saved_devices";
private final Context mContext;
private final HomeNetwork mNetwork;
private HomeDevice mSelectedDevice;
private CheckBox mEventLogCheck;
private CheckBox mTxRxLogCheck;
private ToggleButton mAutoScrollToggle; | /*
* Copyright (C) 2023 Korea Association of AI Smart Home.
* Copyright (C) 2023 KyungDong Navien Co, 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 kr.or.kashi.hde;
public class MainFragment extends Fragment {
private static final String TAG = "HomeTestFragment";
private static final String SAVED_DEVICES_FILENAME = "saved_devices";
private final Context mContext;
private final HomeNetwork mNetwork;
private HomeDevice mSelectedDevice;
private CheckBox mEventLogCheck;
private CheckBox mTxRxLogCheck;
private ToggleButton mAutoScrollToggle; | private DebugLogView mDebugLogView; | 8 | 2023-11-10 01:19:44+00:00 | 12k |
erhenjt/twoyi2 | app/src/main/java/io/twoyi/ui/SelectAppActivity.java | [
{
"identifier": "AppKV",
"path": "app/src/main/java/io/twoyi/utils/AppKV.java",
"snippet": "public class AppKV {\n\n\n private static final String PREF_NAME = \"app_kv\";\n\n public static final String ADD_APP_NOT_SHOW_SYSTEM= \"add_app_not_show_system\";\n public static final String ADD_APP_NO... | import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ClipData;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.ColorStateList;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.net.Uri;
import android.os.Bundle;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.core.view.MenuItemCompat;
import androidx.core.widget.CompoundButtonCompat;
import com.afollestad.materialdialogs.MaterialDialog;
import com.github.clans.fab.FloatingActionButton;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import io.twoyi.R;
import io.twoyi.utils.AppKV;
import io.twoyi.utils.CacheManager;
import io.twoyi.utils.IOUtils;
import io.twoyi.utils.Installer;
import io.twoyi.utils.UIHelper;
import io.twoyi.utils.image.GlideModule; | 7,705 | @Override
public boolean onQueryTextSubmit(String query) {
return false;
}
// 随着输入改变文本
@Override
public boolean onQueryTextChange(String newText) {
filterListByText(newText);
return false;
}
});
searchView.setOnCloseListener(() -> {
mDisplayItems.clear();
mDisplayItems.addAll(mAllApps);
notifyDataSetChangedWithSort();
return false;
});
setFilterMenuItem(menu, R.id.menu_not_show_system, AppKV.ADD_APP_NOT_SHOW_SYSTEM, true);
setFilterMenuItem(menu, R.id.menu_not_show_32bit, AppKV.ADD_APP_NOT_SHOW_32BIT, true);
return super.onCreateOptionsMenu(menu);
}
private MenuItem setFilterMenuItem(Menu menu, int id, String key, boolean defalutValue) {
MenuItem menuItem = menu.findItem(id);
menuItem.setChecked(AppKV.getBooleanConfig(getApplicationContext(), key, defalutValue));
menuItem.setOnMenuItemClickListener(item -> {
boolean checked = !item.isChecked();
item.setChecked(checked);
AppKV.setBooleanConfig(getApplicationContext(), key, checked);
// 重新加载所有配置
// loadAsync 的时候会检查这个标记
loadAsync();
return true;
});
return menuItem;
}
private void filterListByText(String query) {
if (TextUtils.isEmpty(query)) {
mDisplayItems.clear();
mDisplayItems.addAll(mAllApps);
notifyDataSetChangedWithSort();
return;
}
List<AppItem> newApps = new ArrayList<>();
Set<CharSequence> pkgs = new HashSet<>();
for (AppItem mAllApp : mAllApps) {
pkgs.add(mAllApp.pkg);
}
for (AppItem appItem : mAllApps) {
String name = appItem.name.toString().toLowerCase(Locale.ROOT);
String pkg = appItem.pkg.toString().toLowerCase(Locale.ROOT);
String queryLower = query.toLowerCase(Locale.ROOT);
if (name.contains(queryLower) || pkg.contains(queryLower)) {
newApps.add(appItem);
}
if (appItem.selected && !pkgs.contains(appItem.pkg)) {
newApps.add(appItem);
}
}
mDisplayItems.clear();
mDisplayItems.addAll(newApps);
notifyDataSetChangedWithSort();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (!(requestCode == REQUEST_GET_FILE && resultCode == Activity.RESULT_OK)) {
return;
}
if (data == null) {
return;
}
ClipData clipData = data.getClipData();
List<Uri> fileUris = new ArrayList<>();
if (clipData == null) {
// single file
fileUris.add(data.getData());
} else {
// multiple file
int itemCount = clipData.getItemCount();
for (int i = 0; i < itemCount; i++) {
ClipData.Item item = clipData.getItemAt(i);
Uri uri = item.getUri();
fileUris.add(uri);
}
}
if (fileUris.isEmpty()) {
Toast.makeText(getApplicationContext(), R.string.select_app_app_not_found, Toast.LENGTH_SHORT).show();
return;
}
ProgressDialog dialog = UIHelper.getProgressDialog(this);
dialog.setCancelable(false);
dialog.show();
// start copy and install
UIHelper.defer().when(() -> {
List<File> files = copyFilesFromUri(fileUris);
Log.i(TAG, "files copied: " + files);
boolean allValid = Installer.checkFile(getApplicationContext(), files);
if (!allValid) { | /*
* 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 io.twoyi.ui;
/**
* @author weishu
* @date 2018/7/21.
*/
public class SelectAppActivity extends AppCompatActivity {
private static final String TAG = "SelectAppActivity";
private static final int REQUEST_GET_FILE = 1;
private static int TAG_KEY = R.id.create_app_list;
private ListAppAdapter mAdapter;
private final List<AppItem> mDisplayItems = new ArrayList<>();
private final List<AppItem> mAllApps = new ArrayList<>();
private AppItem mSelectItem;
private TextView mEmptyView;
private final Set<String> specifiedPackages = new HashSet<>();
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_createapp);
ListView mListView = findViewById(R.id.create_app_list);
mAdapter = new ListAppAdapter();
mListView.setAdapter(mAdapter);
mEmptyView = findViewById(R.id.empty_view);
mListView.setEmptyView(mEmptyView);
FloatingActionButton mFloatButton = findViewById(R.id.create_app_from_external);
mFloatButton.setColorNormalResId(R.color.colorPrimary);
mFloatButton.setColorPressedResId(R.color.colorPrimaryOpacity);
mFloatButton.setOnClickListener((v) -> {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setType("application/vnd.android.package-archive"); // apk file
intent.addCategory(Intent.CATEGORY_OPENABLE);
try {
startActivityForResult(intent, REQUEST_GET_FILE);
} catch (Throwable ignored) {
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_SHORT).show();
}
});
TextView createApp = findViewById(R.id.create_app_btn);
createApp.setBackgroundResource(R.color.colorPrimary);
createApp.setText(R.string.select_app_button);
createApp.setOnClickListener((v) -> {
Set<AppItem> selectedApps = new HashSet<>();
for (AppItem displayItem : mDisplayItems) {
if (displayItem.selected) {
selectedApps.add(displayItem);
}
}
if (selectedApps.isEmpty()) {
Toast.makeText(this, R.string.select_app_tips, Toast.LENGTH_SHORT).show();
return;
}
selectComplete(selectedApps);
});
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
// actionBar.setBackgroundDrawable(getResources().getDrawable(R.color.colorPrimary));
actionBar.setTitle(R.string.create_app_activity);
}
Intent intent = getIntent();
if (intent != null) {
Uri data = intent.getData();
if (data != null && TextUtils.equals(data.getScheme(), "package")) {
String schemeSpecificPart = data.getSchemeSpecificPart();
if (schemeSpecificPart != null) {
String[] split = schemeSpecificPart.split("\\|");
specifiedPackages.clear();
specifiedPackages.addAll(Arrays.asList(split));
}
}
}
if (true) {
int size = specifiedPackages.size();
if (size > 1) {
specifiedPackages.clear();
}
}
loadAsync();
}
private void selectComplete(Set<AppItem> pkgs) {
if (pkgs.size() != 1) {
// TODO: support install mutilpe apps together
Toast.makeText(getApplicationContext(), R.string.please_install_one_by_one, Toast.LENGTH_SHORT).show();
return;
}
ProgressDialog progressDialog = UIHelper.getProgressDialog(this);
progressDialog.setCancelable(false);
progressDialog.show();
for (AppItem pkg : pkgs) {
List<File> apks = new ArrayList<>();
ApplicationInfo applicationInfo = pkg.applicationInfo;
// main apk
String sourceDir = applicationInfo.sourceDir;
apks.add(new File(sourceDir));
String[] splitSourceDirs = applicationInfo.splitSourceDirs;
if (splitSourceDirs != null) {
for (String splitSourceDir : splitSourceDirs) {
apks.add(new File(splitSourceDir));
}
}
startInstall(apks, progressDialog, false);
}
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.search_menu, menu);
MenuItem searchItem = menu.findItem(R.id.menu_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
// 当SearchView获得焦点时弹出软键盘的类型,就是设置输入类型
searchView.setIconified(false);
searchView.onActionViewExpanded();
searchView.setInputType(EditorInfo.TYPE_CLASS_TEXT);
// 设置回车键表示查询操作
searchView.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
// 为searchView添加事件
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
// 输入后点击回车改变文本
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
// 随着输入改变文本
@Override
public boolean onQueryTextChange(String newText) {
filterListByText(newText);
return false;
}
});
searchView.setOnCloseListener(() -> {
mDisplayItems.clear();
mDisplayItems.addAll(mAllApps);
notifyDataSetChangedWithSort();
return false;
});
setFilterMenuItem(menu, R.id.menu_not_show_system, AppKV.ADD_APP_NOT_SHOW_SYSTEM, true);
setFilterMenuItem(menu, R.id.menu_not_show_32bit, AppKV.ADD_APP_NOT_SHOW_32BIT, true);
return super.onCreateOptionsMenu(menu);
}
private MenuItem setFilterMenuItem(Menu menu, int id, String key, boolean defalutValue) {
MenuItem menuItem = menu.findItem(id);
menuItem.setChecked(AppKV.getBooleanConfig(getApplicationContext(), key, defalutValue));
menuItem.setOnMenuItemClickListener(item -> {
boolean checked = !item.isChecked();
item.setChecked(checked);
AppKV.setBooleanConfig(getApplicationContext(), key, checked);
// 重新加载所有配置
// loadAsync 的时候会检查这个标记
loadAsync();
return true;
});
return menuItem;
}
private void filterListByText(String query) {
if (TextUtils.isEmpty(query)) {
mDisplayItems.clear();
mDisplayItems.addAll(mAllApps);
notifyDataSetChangedWithSort();
return;
}
List<AppItem> newApps = new ArrayList<>();
Set<CharSequence> pkgs = new HashSet<>();
for (AppItem mAllApp : mAllApps) {
pkgs.add(mAllApp.pkg);
}
for (AppItem appItem : mAllApps) {
String name = appItem.name.toString().toLowerCase(Locale.ROOT);
String pkg = appItem.pkg.toString().toLowerCase(Locale.ROOT);
String queryLower = query.toLowerCase(Locale.ROOT);
if (name.contains(queryLower) || pkg.contains(queryLower)) {
newApps.add(appItem);
}
if (appItem.selected && !pkgs.contains(appItem.pkg)) {
newApps.add(appItem);
}
}
mDisplayItems.clear();
mDisplayItems.addAll(newApps);
notifyDataSetChangedWithSort();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (!(requestCode == REQUEST_GET_FILE && resultCode == Activity.RESULT_OK)) {
return;
}
if (data == null) {
return;
}
ClipData clipData = data.getClipData();
List<Uri> fileUris = new ArrayList<>();
if (clipData == null) {
// single file
fileUris.add(data.getData());
} else {
// multiple file
int itemCount = clipData.getItemCount();
for (int i = 0; i < itemCount; i++) {
ClipData.Item item = clipData.getItemAt(i);
Uri uri = item.getUri();
fileUris.add(uri);
}
}
if (fileUris.isEmpty()) {
Toast.makeText(getApplicationContext(), R.string.select_app_app_not_found, Toast.LENGTH_SHORT).show();
return;
}
ProgressDialog dialog = UIHelper.getProgressDialog(this);
dialog.setCancelable(false);
dialog.show();
// start copy and install
UIHelper.defer().when(() -> {
List<File> files = copyFilesFromUri(fileUris);
Log.i(TAG, "files copied: " + files);
boolean allValid = Installer.checkFile(getApplicationContext(), files);
if (!allValid) { | IOUtils.deleteAll(files); | 2 | 2023-11-11 22:08:20+00:00 | 12k |
EmonerRobotics/2023Robot | src/main/java/frc/robot/RobotContainer.java | [
{
"identifier": "IntakeConstants",
"path": "src/main/java/frc/robot/Constants.java",
"snippet": "public final class IntakeConstants{\n\n public static final double kEncoderTick2Meter = 1.0 / 4096.0 * 0.1 * Math.PI;\n\n //üst sistem joystick sabitleri\n public static final int Joystick2 = 1; //usb por... | import edu.wpi.first.math.geometry.Pose2d;
import edu.wpi.first.math.geometry.Rotation2d;
import edu.wpi.first.math.geometry.Translation2d;
import edu.wpi.first.wpilibj.DriverStation;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.shuffleboard.Shuffleboard;
import edu.wpi.first.wpilibj.shuffleboard.ShuffleboardTab;
import edu.wpi.first.wpilibj.smartdashboard.Field2d;
import edu.wpi.first.wpilibj.smartdashboard.FieldObject2d;
import edu.wpi.first.wpilibj.smartdashboard.SendableChooser;
import edu.wpi.first.wpilibj2.command.Command;
import edu.wpi.first.wpilibj2.command.InstantCommand;
import edu.wpi.first.wpilibj2.command.RunCommand;
import edu.wpi.first.wpilibj2.command.SequentialCommandGroup;
import edu.wpi.first.wpilibj2.command.WaitCommand;
import edu.wpi.first.wpilibj2.command.button.JoystickButton;
import frc.robot.Constants.IntakeConstants;
import frc.robot.commands.AutoElevator;
import frc.robot.commands.AutoIntake;
import frc.robot.commands.DriveWithJoysticks;
import frc.robot.commands.GetInRange;
import frc.robot.commands.IntakeCommand;
import frc.robot.commands.LiftCommand;
import frc.robot.commands.PneumaticCommand;
import frc.robot.commands.AutoElevator.ElevatorPosition;
import frc.robot.commands.AutoIntake.IntakePosition;
import frc.robot.commands.GetInRange.LimelightPositionCheck;
import frc.robot.commands.autonomous.AutoBalance;
import frc.robot.commands.autonomous.AutoCommand;
import frc.robot.commands.autonomous.OnePieceCharge;
import frc.robot.poseestimation.PoseEstimation;
import frc.robot.subsystems.IntakeSubsystem;
import frc.robot.subsystems.LiftSubsystem;
import frc.robot.subsystems.LimelightSubsystem;
import frc.robot.subsystems.PneumaticSubsystem;
import frc.robot.subsystems.drivetrain.Drivetrain;
import frc.robot.utils.AllianceUtils;
import com.pathplanner.lib.server.PathPlannerServer; | 10,373 | // Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
package frc.robot;
/**
* This class is where the bulk of the robot should be declared. Since Command-based is a
* "declarative" paradigm, very little robot logic should actually be handled in the {@link Robot}
* periodic methods (other than the scheduler calls). Instead, the structure of the robot (including
* subsystems, commands, and trigger mappings) should be declared here.
*/
public class RobotContainer {
//Limelight
public static final LimelightSubsystem limelightSubsystem = new LimelightSubsystem();
//Intake | // Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
package frc.robot;
/**
* This class is where the bulk of the robot should be declared. Since Command-based is a
* "declarative" paradigm, very little robot logic should actually be handled in the {@link Robot}
* periodic methods (other than the scheduler calls). Instead, the structure of the robot (including
* subsystems, commands, and trigger mappings) should be declared here.
*/
public class RobotContainer {
//Limelight
public static final LimelightSubsystem limelightSubsystem = new LimelightSubsystem();
//Intake | public static final IntakeSubsystem intakeSubsystem = new IntakeSubsystem(); | 15 | 2023-11-18 14:02:20+00:00 | 12k |
NewXdOnTop/skyblock-remake | src/main/java/com/sweattypalms/skyblock/core/items/builder/abilities/AbilityManager.java | [
{
"identifier": "SkyblockInteractEvent",
"path": "src/main/java/com/sweattypalms/skyblock/core/events/def/SkyblockInteractEvent.java",
"snippet": "public class SkyblockInteractEvent extends SkyblockPlayerEvent implements Cancellable {\n\n private static final HandlerList HANDLERS = new HandlerList();... | import com.sweattypalms.skyblock.core.events.def.SkyblockInteractEvent;
import com.sweattypalms.skyblock.core.events.def.SkyblockPlayerDamageEntityEvent;
import com.sweattypalms.skyblock.core.helpers.MozangStuff;
import com.sweattypalms.skyblock.core.items.builder.SkyblockItem;
import com.sweattypalms.skyblock.core.items.builder.abilities.types.*;
import com.sweattypalms.skyblock.core.items.builder.item.IShortBow;
import com.sweattypalms.skyblock.core.player.SkyblockPlayer;
import com.sweattypalms.skyblock.core.player.sub.stats.Stats;
import org.bukkit.*;
import org.bukkit.block.Block;
import org.bukkit.entity.*;
import org.bukkit.event.Event;
import org.bukkit.util.Vector;
import java.util.ArrayList;
import java.util.List; | 9,007 | package com.sweattypalms.skyblock.core.items.builder.abilities;
public class AbilityManager {
public static final Ability LAPIS_ARMOR_ABILITY = new LAPIS_ARMOR_ABILITY();
public static Ability UNDEAD_SWORD_ABILITY = new DamageAbility() {
@Override
public String getName() {
return "Undead Sword";
}
@Override
public boolean nameVisible() {
return false;
}
@Override
public List<String> getDescription() {
return new ArrayList<>();
}
@Override
public boolean preCalc() {
return true;
}
@Override
public boolean trigger(Event event) {
if (!(event instanceof SkyblockPlayerDamageEntityEvent skyblockPlayerDamageEntityEvent)) return false;
List<EntityType> whitelistedEntities = List.of(
EntityType.SKELETON,
EntityType.ZOMBIE,
EntityType.WITHER,
EntityType.PIG_ZOMBIE
);
return whitelistedEntities.contains(skyblockPlayerDamageEntityEvent.getEntity().getType());
}
@Override
public void apply(Event event) {
if (!(event instanceof SkyblockPlayerDamageEntityEvent skyblockPlayerDamageEntityEvent)) return;
/* Multiplicitive, Makes the weapon deal 2x damage */
skyblockPlayerDamageEntityEvent.addMultiplicativeMultiplierPercent(100);
}
};
public static Ability LIGHTNING_ARMOR_ABILITY = new FullSetBonus() {
@Override
public String getName() {
return "Lightning";
}
@Override
public List<String> getDescription() {
return new ArrayList<>(List.of(
"$7Striking an enemy has a $a25% $7chance",
"$7when full set is equipped."
));
}
@Override
public void apply(Event event) {
if (!(event instanceof SkyblockPlayerDamageEntityEvent skyblockPlayerDamageEntityEvent)) return;
if (skyblockPlayerDamageEntityEvent.getSkyblockPlayer().getRandom().nextInt(100) > 25) return;
skyblockPlayerDamageEntityEvent.getEntity().getWorld().strikeLightningEffect(skyblockPlayerDamageEntityEvent.getEntity().getLocation());
}
};
public static class LAPIS_ARMOR_ABILITY implements FullSetBonus, PassiveAbility {
@Override
public String getName() {
return "Health";
}
@Override
public List<String> getDescription() {
return new ArrayList<>(List.of(
"$7Increases the wearer's maximum",
Stats.HEALTH.getSymbol() + "Health $7by $a60"
));
}
@Override
public void onTick(SkyblockPlayer player) {
double currentMaxHealth = player.getStatsManager().getMaxStats().get(Stats.HEALTH);
player.getStatsManager().setMaxStat(Stats.HEALTH, currentMaxHealth + 60);
}
}
public static abstract class TELEPORT_ABILITY implements ITriggerableAbility, IUsageCost {
private final int range;
public TELEPORT_ABILITY(int range) {
this.range = range;
}
@Override
public void apply(Event event) {
if (!(event instanceof SkyblockInteractEvent skyblockInteractEvent)) return;
SkyblockPlayer skyblockPlayer = skyblockInteractEvent.getSkyblockPlayer();
Player player = skyblockPlayer.getPlayer();
// check if player is looking down, if so, don't teleport.
List<Material> whitelistedMaterials = List.of(
Material.AIR,
Material.WATER,
Material.LAVA
);
Location start = player.getEyeLocation();
Vector direction = start.getDirection();
for (int i = 0; i < range; i++) {
start.add(direction);
Block block = start.getBlock();
if (!whitelistedMaterials.contains(block.getType())) {
start.subtract(direction);
player.sendMessage(ChatColor.RED + "There are blocks in the way!");
break;
}
}
start = start.getBlock().getLocation();
start = start.add(0.5, 0, 0.5);
start.setYaw(player.getLocation().getYaw());
start.setPitch(player.getLocation().getPitch());
player.teleport(start);
}
@Override
public TriggerType getTriggerType() {
return TriggerType.RIGHT_CLICK;
}
@Override
public boolean trigger(Event event) {
if (!(event instanceof SkyblockInteractEvent skyblockInteractEvent)) return false;
return skyblockInteractEvent.getInteractType() == TriggerType.RIGHT_CLICK;
}
}
public static abstract class SHORT_BOW implements ITriggerableAbility {
@Override
public boolean nameVisible() {
return false;
}
@Override
public String getName() {
return "Shortbow";
}
@Override
public List<String> getDescription() {
return new ArrayList<>(List.of(
"Shoot instantly. Lore not visible."
));
}
@Override
public TriggerType getTriggerType() {
return TriggerType.NONE;
}
@Override
public boolean trigger(Event event) {
if (!(event instanceof SkyblockInteractEvent skyblockInteractEvent)) return false;
SkyblockItem skyblockItem = skyblockInteractEvent.getSkyblockPlayer().getInventoryManager().getSkyblockItemInHand();
TriggerType triggerType = skyblockInteractEvent.getInteractType(); | package com.sweattypalms.skyblock.core.items.builder.abilities;
public class AbilityManager {
public static final Ability LAPIS_ARMOR_ABILITY = new LAPIS_ARMOR_ABILITY();
public static Ability UNDEAD_SWORD_ABILITY = new DamageAbility() {
@Override
public String getName() {
return "Undead Sword";
}
@Override
public boolean nameVisible() {
return false;
}
@Override
public List<String> getDescription() {
return new ArrayList<>();
}
@Override
public boolean preCalc() {
return true;
}
@Override
public boolean trigger(Event event) {
if (!(event instanceof SkyblockPlayerDamageEntityEvent skyblockPlayerDamageEntityEvent)) return false;
List<EntityType> whitelistedEntities = List.of(
EntityType.SKELETON,
EntityType.ZOMBIE,
EntityType.WITHER,
EntityType.PIG_ZOMBIE
);
return whitelistedEntities.contains(skyblockPlayerDamageEntityEvent.getEntity().getType());
}
@Override
public void apply(Event event) {
if (!(event instanceof SkyblockPlayerDamageEntityEvent skyblockPlayerDamageEntityEvent)) return;
/* Multiplicitive, Makes the weapon deal 2x damage */
skyblockPlayerDamageEntityEvent.addMultiplicativeMultiplierPercent(100);
}
};
public static Ability LIGHTNING_ARMOR_ABILITY = new FullSetBonus() {
@Override
public String getName() {
return "Lightning";
}
@Override
public List<String> getDescription() {
return new ArrayList<>(List.of(
"$7Striking an enemy has a $a25% $7chance",
"$7when full set is equipped."
));
}
@Override
public void apply(Event event) {
if (!(event instanceof SkyblockPlayerDamageEntityEvent skyblockPlayerDamageEntityEvent)) return;
if (skyblockPlayerDamageEntityEvent.getSkyblockPlayer().getRandom().nextInt(100) > 25) return;
skyblockPlayerDamageEntityEvent.getEntity().getWorld().strikeLightningEffect(skyblockPlayerDamageEntityEvent.getEntity().getLocation());
}
};
public static class LAPIS_ARMOR_ABILITY implements FullSetBonus, PassiveAbility {
@Override
public String getName() {
return "Health";
}
@Override
public List<String> getDescription() {
return new ArrayList<>(List.of(
"$7Increases the wearer's maximum",
Stats.HEALTH.getSymbol() + "Health $7by $a60"
));
}
@Override
public void onTick(SkyblockPlayer player) {
double currentMaxHealth = player.getStatsManager().getMaxStats().get(Stats.HEALTH);
player.getStatsManager().setMaxStat(Stats.HEALTH, currentMaxHealth + 60);
}
}
public static abstract class TELEPORT_ABILITY implements ITriggerableAbility, IUsageCost {
private final int range;
public TELEPORT_ABILITY(int range) {
this.range = range;
}
@Override
public void apply(Event event) {
if (!(event instanceof SkyblockInteractEvent skyblockInteractEvent)) return;
SkyblockPlayer skyblockPlayer = skyblockInteractEvent.getSkyblockPlayer();
Player player = skyblockPlayer.getPlayer();
// check if player is looking down, if so, don't teleport.
List<Material> whitelistedMaterials = List.of(
Material.AIR,
Material.WATER,
Material.LAVA
);
Location start = player.getEyeLocation();
Vector direction = start.getDirection();
for (int i = 0; i < range; i++) {
start.add(direction);
Block block = start.getBlock();
if (!whitelistedMaterials.contains(block.getType())) {
start.subtract(direction);
player.sendMessage(ChatColor.RED + "There are blocks in the way!");
break;
}
}
start = start.getBlock().getLocation();
start = start.add(0.5, 0, 0.5);
start.setYaw(player.getLocation().getYaw());
start.setPitch(player.getLocation().getPitch());
player.teleport(start);
}
@Override
public TriggerType getTriggerType() {
return TriggerType.RIGHT_CLICK;
}
@Override
public boolean trigger(Event event) {
if (!(event instanceof SkyblockInteractEvent skyblockInteractEvent)) return false;
return skyblockInteractEvent.getInteractType() == TriggerType.RIGHT_CLICK;
}
}
public static abstract class SHORT_BOW implements ITriggerableAbility {
@Override
public boolean nameVisible() {
return false;
}
@Override
public String getName() {
return "Shortbow";
}
@Override
public List<String> getDescription() {
return new ArrayList<>(List.of(
"Shoot instantly. Lore not visible."
));
}
@Override
public TriggerType getTriggerType() {
return TriggerType.NONE;
}
@Override
public boolean trigger(Event event) {
if (!(event instanceof SkyblockInteractEvent skyblockInteractEvent)) return false;
SkyblockItem skyblockItem = skyblockInteractEvent.getSkyblockPlayer().getInventoryManager().getSkyblockItemInHand();
TriggerType triggerType = skyblockInteractEvent.getInteractType(); | boolean shortBow = skyblockItem instanceof IShortBow; | 4 | 2023-11-15 15:05:58+00:00 | 12k |
cometcake575/Origins-Reborn | src/main/java/com/starshootercity/abilities/BreakSpeedModifierAbility.java | [
{
"identifier": "Origin",
"path": "src/main/java/com/starshootercity/Origin.java",
"snippet": "public class Origin {\n private final ItemStack icon;\n private final int position;\n private final char impact;\n private final String name;\n private final List<Key> abilities;\n private fi... | import com.destroystokyo.paper.event.server.ServerTickEndEvent;
import com.starshootercity.Origin;
import com.starshootercity.OriginSwapper;
import com.starshootercity.OriginsReborn;
import com.starshootercity.SavedPotionEffect;
import org.bukkit.Bukkit;
import org.bukkit.FluidCollisionMode;
import org.bukkit.Material;
import org.bukkit.Tag;
import org.bukkit.block.Block;
import org.bukkit.craftbukkit.v1_20_R3.block.CraftBlockState;
import org.bukkit.craftbukkit.v1_20_R3.inventory.CraftItemStack;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockDamageAbortEvent;
import org.bukkit.event.block.BlockDamageEvent;
import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.Damageable;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger; | 8,344 | package com.starshootercity.abilities;
public interface BreakSpeedModifierAbility extends Ability {
BlockMiningContext provideContextFor(Player player);
boolean shouldActivate(Player player);
class BlockMiningContext {
private final PotionEffect slowDigging;
private final PotionEffect fastDigging;
private final PotionEffect conduitPower;
private final ItemStack heldItem;
private final boolean underwater;
private final boolean aquaAffinity;
private final boolean onGround;
public BlockMiningContext(ItemStack heldItem, @Nullable PotionEffect slowDigging, @Nullable PotionEffect fastDigging, @Nullable PotionEffect conduitPower, boolean underwater, boolean aquaAffinity, boolean onGround) {
this.heldItem = heldItem;
this.slowDigging = slowDigging;
this.fastDigging = fastDigging;
this.conduitPower = conduitPower;
this.underwater = underwater;
this.aquaAffinity = aquaAffinity;
this.onGround = onGround;
}
public boolean isOnGround() {
return onGround;
}
public boolean hasAquaAffinity() {
return aquaAffinity;
}
public boolean isUnderwater() {
return underwater;
}
public ItemStack getHeldItem() {
return heldItem;
}
public boolean hasDigSpeed() {
return fastDigging != null || conduitPower != null;
}
public boolean hasDigSlowdown() {
return slowDigging != null;
}
public int getDigSlowdown() {
if (slowDigging == null) return 0;
return slowDigging.getAmplifier();
}
public int getDigSpeedAmplification() {
int i = 0;
int j = 0;
if (fastDigging != null) {
i = fastDigging.getAmplifier();
}
if (conduitPower != null) {
j = conduitPower.getAmplifier();
}
return Math.max(i, j);
}
}
class BreakSpeedModifierAbilityListener implements Listener {
Random random = new Random();
@EventHandler
public void onBlockDamage(BlockDamageEvent event) {
if (blockbreakingTasks.containsKey(event.getPlayer())) {
cancelTask(blockbreakingTasks.get(event.getPlayer()));
blockbreakingTasks.remove(event.getPlayer());
}
Bukkit.getScheduler().scheduleSyncDelayedTask(OriginsReborn.getInstance(), () -> {
| package com.starshootercity.abilities;
public interface BreakSpeedModifierAbility extends Ability {
BlockMiningContext provideContextFor(Player player);
boolean shouldActivate(Player player);
class BlockMiningContext {
private final PotionEffect slowDigging;
private final PotionEffect fastDigging;
private final PotionEffect conduitPower;
private final ItemStack heldItem;
private final boolean underwater;
private final boolean aquaAffinity;
private final boolean onGround;
public BlockMiningContext(ItemStack heldItem, @Nullable PotionEffect slowDigging, @Nullable PotionEffect fastDigging, @Nullable PotionEffect conduitPower, boolean underwater, boolean aquaAffinity, boolean onGround) {
this.heldItem = heldItem;
this.slowDigging = slowDigging;
this.fastDigging = fastDigging;
this.conduitPower = conduitPower;
this.underwater = underwater;
this.aquaAffinity = aquaAffinity;
this.onGround = onGround;
}
public boolean isOnGround() {
return onGround;
}
public boolean hasAquaAffinity() {
return aquaAffinity;
}
public boolean isUnderwater() {
return underwater;
}
public ItemStack getHeldItem() {
return heldItem;
}
public boolean hasDigSpeed() {
return fastDigging != null || conduitPower != null;
}
public boolean hasDigSlowdown() {
return slowDigging != null;
}
public int getDigSlowdown() {
if (slowDigging == null) return 0;
return slowDigging.getAmplifier();
}
public int getDigSpeedAmplification() {
int i = 0;
int j = 0;
if (fastDigging != null) {
i = fastDigging.getAmplifier();
}
if (conduitPower != null) {
j = conduitPower.getAmplifier();
}
return Math.max(i, j);
}
}
class BreakSpeedModifierAbilityListener implements Listener {
Random random = new Random();
@EventHandler
public void onBlockDamage(BlockDamageEvent event) {
if (blockbreakingTasks.containsKey(event.getPlayer())) {
cancelTask(blockbreakingTasks.get(event.getPlayer()));
blockbreakingTasks.remove(event.getPlayer());
}
Bukkit.getScheduler().scheduleSyncDelayedTask(OriginsReborn.getInstance(), () -> {
| Origin origin = OriginSwapper.getOrigin(event.getPlayer()); | 0 | 2023-11-10 21:39:16+00:00 | 12k |
Hikaito/Fox-Engine | src/system/gui/project/ProjectFileSelection.java | [
{
"identifier": "ProjectManager",
"path": "src/system/project/ProjectManager.java",
"snippet": "public class ProjectManager {\n\n // UUID methods\n public String getUUID(){return root.getUUID();}\n public boolean matchesUUID(String other){\n return root.getUUID().equals(other);\n }\n\... | import system.project.ProjectManager;
import system.setting.CoreGlobal;
import system.layerTree.data.Folder;
import system.layerTree.data.Layer;
import system.backbone.EventE;
import system.project.treeElements.ProjectFile;
import system.project.treeElements.ProjectFolder;
import system.project.treeElements.ProjectRoot;
import system.project.treeElements.ProjectUnitCore;
import javax.swing.*;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeSelectionModel;
import java.awt.*;
import java.awt.event.WindowEvent;
import java.io.IOException; | 8,929 | package system.gui.project;
//====================================================================================================
// Authors: Hikaito
// Project: Fox Engine
//====================================================================================================
public class ProjectFileSelection {
private final JFrame jFrame;
protected ProjectManager source;
JPanel editorPane = null; // used for resetting display
JPanel imageDisplay = null; // used for resetting display
JSplitPane splitPane = null;
DefaultMutableTreeNode treeRoot = null;
JTree tree;
// used for drawing background decision
private final boolean[] color; | package system.gui.project;
//====================================================================================================
// Authors: Hikaito
// Project: Fox Engine
//====================================================================================================
public class ProjectFileSelection {
private final JFrame jFrame;
protected ProjectManager source;
JPanel editorPane = null; // used for resetting display
JPanel imageDisplay = null; // used for resetting display
JSplitPane splitPane = null;
DefaultMutableTreeNode treeRoot = null;
JTree tree;
// used for drawing background decision
private final boolean[] color; | private Layer layer = null; | 3 | 2023-11-12 21:12:21+00:00 | 12k |
ebandal/jDwgParser | src/structure/Dwg.java | [
{
"identifier": "DecodeCallback",
"path": "src/decode/DecodeCallback.java",
"snippet": "public interface DecodeCallback {\n public void onDecoded(String name, Object value, int retBitOffset);\n}"
},
{
"identifier": "DecoderR14",
"path": "src/decode/DecoderR14.java",
"snippet": "public... | import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.time.temporal.JulianFields;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import decode.DecodeCallback;
import decode.DecoderR14;
import decode.DecoderR2004;
import decode.DwgParseException;
import structure.header.FileHeader;
import structure.sectionpage.DataSectionPage;
import structure.sectionpage.HeaderVariables;
import structure.sectionpage.SystemSectionPage; | 8,704 | package structure;
public class Dwg {
private static final Logger log = Logger.getLogger(Dwg.class.getName());
public FileHeader header;
public HeaderVariables headerVariables;
public List<SystemSectionPage> systemSectionPageList;
public List<DataSectionPage> dataSectionPageList;
| package structure;
public class Dwg {
private static final Logger log = Logger.getLogger(Dwg.class.getName());
public FileHeader header;
public HeaderVariables headerVariables;
public List<SystemSectionPage> systemSectionPageList;
public List<DataSectionPage> dataSectionPageList;
| public void decode(File dwgFile) throws DwgParseException { | 3 | 2023-11-11 13:57:18+00:00 | 12k |
Nel1yMinecraft/Grim | src/main/java/ac/grim/grimac/utils/nmsutil/BlockProperties.java | [
{
"identifier": "GrimPlayer",
"path": "src/main/java/ac/grim/grimac/player/GrimPlayer.java",
"snippet": "public class GrimPlayer {\n public final UUID playerUUID;\n public final int entityID;\n public final Player bukkitPlayer;\n // Determining player ping\n // The difference between keep... | import ac.grim.grimac.player.GrimPlayer;
import ac.grim.grimac.utils.data.packetentity.PacketEntityHorse;
import ac.grim.grimac.utils.data.packetentity.PacketEntityStrider;
import ac.grim.grimac.utils.enums.EntityType;
import ac.grim.grimac.utils.math.GrimMath;
import io.github.retrooper.packetevents.utils.player.ClientVersion;
import org.bukkit.Material;
import org.bukkit.enchantments.Enchantment; | 7,759 | package ac.grim.grimac.utils.nmsutil;
public class BlockProperties {
private static final Material ICE = XMaterial.ICE.parseMaterial();
private static final Material SLIME = XMaterial.SLIME_BLOCK.parseMaterial();
private static final Material PACKED_ICE = XMaterial.PACKED_ICE.parseMaterial();
private static final Material FROSTED_ICE = XMaterial.FROSTED_ICE.parseMaterial();
private static final Material BLUE_ICE = XMaterial.BLUE_ICE.parseMaterial();
private static final Material SOUL_SAND = XMaterial.SOUL_SAND.parseMaterial();
private static final Material HONEY_BLOCK = XMaterial.HONEY_BLOCK.parseMaterial();
// WATER and STATIONARY_WATER on 1.12
// WATER and BUBBLE_COLUMN on 1.13
private static final Material water;
private static final Material alsoWater;
static {
if (XMaterial.isNewVersion()) {
water = Material.WATER;
alsoWater = Material.BUBBLE_COLUMN;
} else {
water = Material.WATER;
alsoWater = Materials.matchLegacy("STATIONARY_WATER");
}
}
public static float getBlockFrictionUnderPlayer(GrimPlayer player) {
if (player.isGliding || player.specialFlying) return 1.0f;
double searchBelowAmount = 0.5000001;
if (player.getClientVersion().isOlderThan(ClientVersion.v_1_15))
searchBelowAmount = 1;
Material material = player.compensatedWorld.getBukkitMaterialAt(player.lastX, player.lastY - searchBelowAmount, player.lastZ);
return getMaterialFriction(player, material);
}
public static float getMaterialFriction(GrimPlayer player, Material material) {
float friction = 0.6f;
if (material == ICE) friction = 0.98f;
if (material == SLIME && player.getClientVersion().isNewerThanOrEquals(ClientVersion.v_1_8)) friction = 0.8f;
// ViaVersion honey block replacement
if (material == HONEY_BLOCK && player.getClientVersion().isOlderThan(ClientVersion.v_1_15))
friction = 0.8f;
if (material == PACKED_ICE) friction = 0.98f;
if (material == FROSTED_ICE) friction = 0.98f;
if (material == BLUE_ICE) {
friction = 0.98f;
if (player.getClientVersion().isNewerThanOrEquals(ClientVersion.v_1_13)) friction = 0.989f;
}
return friction;
}
public static float getFrictionInfluencedSpeed(float f, GrimPlayer player) {
if (player.lastOnGround) {
return (float) (player.speed * (0.21600002f / (f * f * f)));
}
// The game uses values known as flyingSpeed for some vehicles in the air
if (player.playerVehicle != null) { | package ac.grim.grimac.utils.nmsutil;
public class BlockProperties {
private static final Material ICE = XMaterial.ICE.parseMaterial();
private static final Material SLIME = XMaterial.SLIME_BLOCK.parseMaterial();
private static final Material PACKED_ICE = XMaterial.PACKED_ICE.parseMaterial();
private static final Material FROSTED_ICE = XMaterial.FROSTED_ICE.parseMaterial();
private static final Material BLUE_ICE = XMaterial.BLUE_ICE.parseMaterial();
private static final Material SOUL_SAND = XMaterial.SOUL_SAND.parseMaterial();
private static final Material HONEY_BLOCK = XMaterial.HONEY_BLOCK.parseMaterial();
// WATER and STATIONARY_WATER on 1.12
// WATER and BUBBLE_COLUMN on 1.13
private static final Material water;
private static final Material alsoWater;
static {
if (XMaterial.isNewVersion()) {
water = Material.WATER;
alsoWater = Material.BUBBLE_COLUMN;
} else {
water = Material.WATER;
alsoWater = Materials.matchLegacy("STATIONARY_WATER");
}
}
public static float getBlockFrictionUnderPlayer(GrimPlayer player) {
if (player.isGliding || player.specialFlying) return 1.0f;
double searchBelowAmount = 0.5000001;
if (player.getClientVersion().isOlderThan(ClientVersion.v_1_15))
searchBelowAmount = 1;
Material material = player.compensatedWorld.getBukkitMaterialAt(player.lastX, player.lastY - searchBelowAmount, player.lastZ);
return getMaterialFriction(player, material);
}
public static float getMaterialFriction(GrimPlayer player, Material material) {
float friction = 0.6f;
if (material == ICE) friction = 0.98f;
if (material == SLIME && player.getClientVersion().isNewerThanOrEquals(ClientVersion.v_1_8)) friction = 0.8f;
// ViaVersion honey block replacement
if (material == HONEY_BLOCK && player.getClientVersion().isOlderThan(ClientVersion.v_1_15))
friction = 0.8f;
if (material == PACKED_ICE) friction = 0.98f;
if (material == FROSTED_ICE) friction = 0.98f;
if (material == BLUE_ICE) {
friction = 0.98f;
if (player.getClientVersion().isNewerThanOrEquals(ClientVersion.v_1_13)) friction = 0.989f;
}
return friction;
}
public static float getFrictionInfluencedSpeed(float f, GrimPlayer player) {
if (player.lastOnGround) {
return (float) (player.speed * (0.21600002f / (f * f * f)));
}
// The game uses values known as flyingSpeed for some vehicles in the air
if (player.playerVehicle != null) { | if (player.playerVehicle.type == EntityType.PIG || player.playerVehicle instanceof PacketEntityHorse) { | 1 | 2023-11-11 05:14:12+00:00 | 12k |
CodecNomad/CodecClient | src/main/java/com/github/codecnomad/codecclient/command/MainCommand.java | [
{
"identifier": "Client",
"path": "src/main/java/com/github/codecnomad/codecclient/Client.java",
"snippet": "@Mod(modid = \"codecclient\", useMetadata = true)\npublic class Client {\n public static Map<String, Module> modules = new HashMap<>();\n public static Minecraft mc = Minecraft.getMinecraft... | import cc.polyfrost.oneconfig.utils.commands.annotations.Command;
import cc.polyfrost.oneconfig.utils.commands.annotations.Main;
import cc.polyfrost.oneconfig.utils.commands.annotations.SubCommand;
import com.github.codecnomad.codecclient.Client;
import com.github.codecnomad.codecclient.ui.Config;
import com.github.codecnomad.codecclient.utils.Chat;
import com.github.codecnomad.codecclient.utils.Pathfinding;
import com.github.codecnomad.codecclient.utils.Render;
import com.github.codecnomad.codecclient.utils.Walker;
import net.minecraft.util.BlockPos;
import net.minecraftforge.client.event.RenderWorldLastEvent;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List; | 9,195 | package com.github.codecnomad.codecclient.command;
@SuppressWarnings("unused")
@Command(value = "codecclient", aliases = {"codec"})
public class MainCommand {
List<BlockPos> waypoints = new ArrayList<>();
@Main
public void mainCommand() { | package com.github.codecnomad.codecclient.command;
@SuppressWarnings("unused")
@Command(value = "codecclient", aliases = {"codec"})
public class MainCommand {
List<BlockPos> waypoints = new ArrayList<>();
@Main
public void mainCommand() { | Client.guiConfig.openGui(); | 0 | 2023-11-16 10:12:20+00:00 | 12k |
JohnTWD/meteor-rejects-vanillacpvp | src/main/java/anticope/rejects/modules/OreSim.java | [
{
"identifier": "MeteorRejectsAddon",
"path": "src/main/java/anticope/rejects/MeteorRejectsAddon.java",
"snippet": "public class MeteorRejectsAddon extends MeteorAddon {\n public static final Logger LOG = LoggerFactory.getLogger(\"Rejects\");\n public static final Category CATEGORY = new Category(... | import anticope.rejects.MeteorRejectsAddon;
import anticope.rejects.events.PlayerRespawnEvent;
import anticope.rejects.events.SeedChangedEvent;
import anticope.rejects.utils.Ore;
import anticope.rejects.utils.seeds.Seed;
import anticope.rejects.utils.seeds.Seeds;
import baritone.api.BaritoneAPI;
import com.seedfinding.mccore.version.MCVersion;
import meteordevelopment.meteorclient.events.render.Render3DEvent;
import meteordevelopment.meteorclient.events.world.ChunkDataEvent;
import meteordevelopment.meteorclient.events.world.TickEvent;
import meteordevelopment.meteorclient.settings.*;
import meteordevelopment.meteorclient.systems.modules.Module;
import meteordevelopment.orbit.EventHandler;
import net.minecraft.client.world.ClientWorld;
import net.minecraft.registry.RegistryKeys;
import net.minecraft.util.Identifier;
import net.minecraft.util.math.*;
import net.minecraft.util.math.random.ChunkRandom;
import net.minecraft.world.Heightmap;
import net.minecraft.world.chunk.ChunkStatus;
import java.util.*; | 7,494 | package anticope.rejects.modules;
public class OreSim extends Module {
private final HashMap<Long, HashMap<Ore, HashSet<Vec3d>>> chunkRenderers = new HashMap<>(); | package anticope.rejects.modules;
public class OreSim extends Module {
private final HashMap<Long, HashMap<Ore, HashSet<Vec3d>>> chunkRenderers = new HashMap<>(); | private Seed worldSeed = null; | 4 | 2023-11-13 08:11:28+00:00 | 12k |
intrepidLi/BUAA_Food | app/src/main/java/com/buaa/food/ui/fragment/BrowserFragment.java | [
{
"identifier": "StatusAction",
"path": "app/src/main/java/com/buaa/food/action/StatusAction.java",
"snippet": "public interface StatusAction {\n\n /**\n * 获取状态布局\n */\n StatusLayout getStatusLayout();\n\n /**\n * 显示加载中\n */\n default void showLoading() {\n showLoading... | import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.webkit.WebView;
import androidx.annotation.NonNull;
import com.buaa.food.R;
import com.buaa.food.action.StatusAction;
import com.buaa.food.aop.CheckNet;
import com.buaa.food.aop.Log;
import com.buaa.food.app.AppActivity;
import com.buaa.food.app.AppFragment;
import com.buaa.food.ui.activity.BrowserActivity;
import com.buaa.food.widget.BrowserView;
import com.buaa.food.widget.StatusLayout;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener; | 9,409 | package com.buaa.food.ui.fragment;
public final class BrowserFragment extends AppFragment<AppActivity>
implements StatusAction, OnRefreshListener {
private static final String INTENT_KEY_IN_URL = "url";
@Log
public static BrowserFragment newInstance(String url) {
BrowserFragment fragment = new BrowserFragment();
Bundle bundle = new Bundle();
bundle.putString(INTENT_KEY_IN_URL, url);
fragment.setArguments(bundle);
return fragment;
}
private StatusLayout mStatusLayout;
private SmartRefreshLayout mRefreshLayout;
private BrowserView mBrowserView;
@Override
protected int getLayoutId() {
return R.layout.browser_fragment;
}
@Override
protected void initView() {
mStatusLayout = findViewById(R.id.hl_browser_hint);
mRefreshLayout = findViewById(R.id.sl_browser_refresh);
mBrowserView = findViewById(R.id.wv_browser_view);
// 设置 WebView 生命周期回调
mBrowserView.setLifecycleOwner(this);
// 设置网页刷新监听
mRefreshLayout.setOnRefreshListener(this);
}
@Override
protected void initData() {
mBrowserView.setBrowserViewClient(new AppBrowserViewClient());
mBrowserView.setBrowserChromeClient(new BrowserView.BrowserChromeClient(mBrowserView));
mBrowserView.loadUrl(getString(INTENT_KEY_IN_URL));
showLoading();
}
@Override
public StatusLayout getStatusLayout() {
return mStatusLayout;
}
/**
* 重新加载当前页
*/
@CheckNet
private void reload() {
mBrowserView.reload();
}
/**
* {@link OnRefreshListener}
*/
@Override
public void onRefresh(@NonNull RefreshLayout refreshLayout) {
reload();
}
private class AppBrowserViewClient extends BrowserView.BrowserViewClient {
/**
* 网页加载错误时回调,这个方法会在 onPageFinished 之前调用
*/
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
// 这里为什么要用延迟呢?因为加载出错之后会先调用 onReceivedError 再调用 onPageFinished
post(() -> showError(listener -> reload()));
}
/**
* 开始加载网页
*/
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {}
/**
* 完成加载网页
*/
@Override
public void onPageFinished(WebView view, String url) {
mRefreshLayout.finishRefresh();
showComplete();
}
/**
* 跳转到其他链接
*/
@Override
public boolean shouldOverrideUrlLoading(WebView view, final String url) {
String scheme = Uri.parse(url).getScheme();
if (scheme == null) {
return true;
}
switch (scheme.toLowerCase()) {
// 如果这是跳链接操作
case "http":
case "https": | package com.buaa.food.ui.fragment;
public final class BrowserFragment extends AppFragment<AppActivity>
implements StatusAction, OnRefreshListener {
private static final String INTENT_KEY_IN_URL = "url";
@Log
public static BrowserFragment newInstance(String url) {
BrowserFragment fragment = new BrowserFragment();
Bundle bundle = new Bundle();
bundle.putString(INTENT_KEY_IN_URL, url);
fragment.setArguments(bundle);
return fragment;
}
private StatusLayout mStatusLayout;
private SmartRefreshLayout mRefreshLayout;
private BrowserView mBrowserView;
@Override
protected int getLayoutId() {
return R.layout.browser_fragment;
}
@Override
protected void initView() {
mStatusLayout = findViewById(R.id.hl_browser_hint);
mRefreshLayout = findViewById(R.id.sl_browser_refresh);
mBrowserView = findViewById(R.id.wv_browser_view);
// 设置 WebView 生命周期回调
mBrowserView.setLifecycleOwner(this);
// 设置网页刷新监听
mRefreshLayout.setOnRefreshListener(this);
}
@Override
protected void initData() {
mBrowserView.setBrowserViewClient(new AppBrowserViewClient());
mBrowserView.setBrowserChromeClient(new BrowserView.BrowserChromeClient(mBrowserView));
mBrowserView.loadUrl(getString(INTENT_KEY_IN_URL));
showLoading();
}
@Override
public StatusLayout getStatusLayout() {
return mStatusLayout;
}
/**
* 重新加载当前页
*/
@CheckNet
private void reload() {
mBrowserView.reload();
}
/**
* {@link OnRefreshListener}
*/
@Override
public void onRefresh(@NonNull RefreshLayout refreshLayout) {
reload();
}
private class AppBrowserViewClient extends BrowserView.BrowserViewClient {
/**
* 网页加载错误时回调,这个方法会在 onPageFinished 之前调用
*/
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
// 这里为什么要用延迟呢?因为加载出错之后会先调用 onReceivedError 再调用 onPageFinished
post(() -> showError(listener -> reload()));
}
/**
* 开始加载网页
*/
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {}
/**
* 完成加载网页
*/
@Override
public void onPageFinished(WebView view, String url) {
mRefreshLayout.finishRefresh();
showComplete();
}
/**
* 跳转到其他链接
*/
@Override
public boolean shouldOverrideUrlLoading(WebView view, final String url) {
String scheme = Uri.parse(url).getScheme();
if (scheme == null) {
return true;
}
switch (scheme.toLowerCase()) {
// 如果这是跳链接操作
case "http":
case "https": | BrowserActivity.start(getAttachActivity(), url); | 3 | 2023-11-14 10:04:26+00:00 | 12k |
WallasAR/GUITest | src/main/java/com/session/employee/PurchaseController.java | [
{
"identifier": "Banco",
"path": "src/main/java/com/db/bank/Banco.java",
"snippet": "public class Banco {\n Scanner scanner1 = new Scanner(System.in);\n public static Connection connection = conexao();\n Statement executar;\n {\n try {\n executar = connection.createStateme... | import com.db.bank.Banco;
import com.example.guitest.LoginController;
import com.example.guitest.Main;
import com.table.view.CarrinhoTable;
import com.table.view.ClienteTable;
import com.table.view.FuncionarioTable;
import com.table.view.MedicamentoTable;
import com.warning.alert.AlertMsg;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.collections.transformation.SortedList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;
import java.net.URL;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import java.util.Date;
import java.text.SimpleDateFormat;
import static com.db.bank.Banco.connection; | 7,292 | package com.session.employee;
public class PurchaseController implements Initializable {
@FXML
private TableView tvCarrinho;
@FXML
private TableView tvCompra;
@FXML
private TableColumn tcIdmedi;
@FXML
private TableColumn tcNomemedi;
@FXML
private TableColumn tcQuantimedi;
@FXML
private TableColumn tcTipomedi;
@FXML
private TableColumn tcPreçomedi;
@FXML
private TableColumn tcUser;
@FXML
private TableColumn tfUser;
@FXML
private TableColumn tfIdmedi;
@FXML
private TableColumn tfNomemedi;
@FXML
private TableColumn tfQuantimedi;
@FXML
private TableColumn tfPreçomedi;
@FXML
private TextField tfSearch;
@FXML
private TextField tfIdCarrinho;
@FXML
private TextField tfNome;
@FXML
private TextField tfQuantidade;
@FXML
private TextField tfTipo;
@FXML
private TextField tfValor;
@FXML
private TextField tfId;
@FXML
private ComboBox Box;
@FXML
private Label labelShowTotal;
@FXML
protected void MainAction(MouseEvent e) {
if (AlertMsg.msgConfirm("Confimar Logout","Deseja sair para a página de login?")) {
Main.changedScene("main");
}
}
@FXML
protected void MedOrderAction(MouseEvent e) {
Main.changedScene("medOrder");
}
@FXML
protected void ClientAction(MouseEvent e) {
Main.changedScene("ClientAdmFunc");
}
public void tabelamedi() throws SQLException {
List<MedicamentoTable> medicamentos = new ArrayList<>();
String consultaSQL = "SELECT * FROM medicamentos";
Statement statement = connection.createStatement();
ResultSet resultado = statement.executeQuery(consultaSQL);
while (resultado.next()) {
int valorDaColuna1 = resultado.getInt("id");
String valorDaColuna2 = resultado.getString("nome");
int valorDaColuna3 = resultado.getInt("quantidade");
String valorDaColina4 = resultado.getString("tipo");
Float valorDaColuna5 = resultado.getFloat("valor");
MedicamentoTable medicamento = new MedicamentoTable(valorDaColuna1, valorDaColuna2, valorDaColuna3, valorDaColina4, valorDaColuna5);
medicamentos.add(medicamento);
}
ObservableList<MedicamentoTable> datamedi = FXCollections.observableList(medicamentos);
tcIdmedi.setCellValueFactory(new PropertyValueFactory<>("id"));
tcNomemedi.setCellValueFactory(new PropertyValueFactory<>("nomemedi"));
tcQuantimedi.setCellValueFactory(new PropertyValueFactory<>("quantidade"));
tcTipomedi.setCellValueFactory(new PropertyValueFactory<>("tipo"));
tcPreçomedi.setCellValueFactory(new PropertyValueFactory<>("valor"));
tvCompra.setItems(datamedi);
FilteredList<MedicamentoTable> filteredLis = new FilteredList<>(datamedi, b -> true);
tfSearch.textProperty().addListener((observable, oldValue, newValue) ->{
filteredLis.setPredicate(funcionarioTable -> {
if (newValue.isEmpty() || newValue.isBlank() || newValue == null){
return true;
}
String searchKeyowrds = newValue.toLowerCase();
if (funcionarioTable.getNomemedi().toLowerCase().indexOf(searchKeyowrds) > -1) {
return true;
} else if(funcionarioTable.getTipo().toLowerCase().indexOf(searchKeyowrds) > -1){
return true;
} else {
return false;
}
});
});
SortedList<MedicamentoTable> sortedList = new SortedList<>(filteredLis);
sortedList.comparatorProperty().bind(tvCompra.comparatorProperty());
tvCompra.setItems(sortedList);
}
// TableView Medicamentos GetItems
public void getItemsActionCompra(MouseEvent event)throws SQLException {
int index;
index = tvCompra.getSelectionModel().getSelectedIndex();
if (index <= -1){
return;
} | package com.session.employee;
public class PurchaseController implements Initializable {
@FXML
private TableView tvCarrinho;
@FXML
private TableView tvCompra;
@FXML
private TableColumn tcIdmedi;
@FXML
private TableColumn tcNomemedi;
@FXML
private TableColumn tcQuantimedi;
@FXML
private TableColumn tcTipomedi;
@FXML
private TableColumn tcPreçomedi;
@FXML
private TableColumn tcUser;
@FXML
private TableColumn tfUser;
@FXML
private TableColumn tfIdmedi;
@FXML
private TableColumn tfNomemedi;
@FXML
private TableColumn tfQuantimedi;
@FXML
private TableColumn tfPreçomedi;
@FXML
private TextField tfSearch;
@FXML
private TextField tfIdCarrinho;
@FXML
private TextField tfNome;
@FXML
private TextField tfQuantidade;
@FXML
private TextField tfTipo;
@FXML
private TextField tfValor;
@FXML
private TextField tfId;
@FXML
private ComboBox Box;
@FXML
private Label labelShowTotal;
@FXML
protected void MainAction(MouseEvent e) {
if (AlertMsg.msgConfirm("Confimar Logout","Deseja sair para a página de login?")) {
Main.changedScene("main");
}
}
@FXML
protected void MedOrderAction(MouseEvent e) {
Main.changedScene("medOrder");
}
@FXML
protected void ClientAction(MouseEvent e) {
Main.changedScene("ClientAdmFunc");
}
public void tabelamedi() throws SQLException {
List<MedicamentoTable> medicamentos = new ArrayList<>();
String consultaSQL = "SELECT * FROM medicamentos";
Statement statement = connection.createStatement();
ResultSet resultado = statement.executeQuery(consultaSQL);
while (resultado.next()) {
int valorDaColuna1 = resultado.getInt("id");
String valorDaColuna2 = resultado.getString("nome");
int valorDaColuna3 = resultado.getInt("quantidade");
String valorDaColina4 = resultado.getString("tipo");
Float valorDaColuna5 = resultado.getFloat("valor");
MedicamentoTable medicamento = new MedicamentoTable(valorDaColuna1, valorDaColuna2, valorDaColuna3, valorDaColina4, valorDaColuna5);
medicamentos.add(medicamento);
}
ObservableList<MedicamentoTable> datamedi = FXCollections.observableList(medicamentos);
tcIdmedi.setCellValueFactory(new PropertyValueFactory<>("id"));
tcNomemedi.setCellValueFactory(new PropertyValueFactory<>("nomemedi"));
tcQuantimedi.setCellValueFactory(new PropertyValueFactory<>("quantidade"));
tcTipomedi.setCellValueFactory(new PropertyValueFactory<>("tipo"));
tcPreçomedi.setCellValueFactory(new PropertyValueFactory<>("valor"));
tvCompra.setItems(datamedi);
FilteredList<MedicamentoTable> filteredLis = new FilteredList<>(datamedi, b -> true);
tfSearch.textProperty().addListener((observable, oldValue, newValue) ->{
filteredLis.setPredicate(funcionarioTable -> {
if (newValue.isEmpty() || newValue.isBlank() || newValue == null){
return true;
}
String searchKeyowrds = newValue.toLowerCase();
if (funcionarioTable.getNomemedi().toLowerCase().indexOf(searchKeyowrds) > -1) {
return true;
} else if(funcionarioTable.getTipo().toLowerCase().indexOf(searchKeyowrds) > -1){
return true;
} else {
return false;
}
});
});
SortedList<MedicamentoTable> sortedList = new SortedList<>(filteredLis);
sortedList.comparatorProperty().bind(tvCompra.comparatorProperty());
tvCompra.setItems(sortedList);
}
// TableView Medicamentos GetItems
public void getItemsActionCompra(MouseEvent event)throws SQLException {
int index;
index = tvCompra.getSelectionModel().getSelectedIndex();
if (index <= -1){
return;
} | List<ClienteTable> clientes = new ArrayList<>(); | 4 | 2023-11-16 14:55:08+00:00 | 12k |
PoluteClient/PoluteClientV1 | 1.19.4/src/main/java/net/Poluteclient/phosphor/mixin/MouseMixin.java | [
{
"identifier": "AsteriaMenu",
"path": "1.19.4/src/main/java/net/Poluteclient/phosphor/gui/PoluteMenu.java",
"snippet": "public class AsteriaMenu implements Renderable {\n private static AsteriaMenu instance;\n\n private static final AtomicBoolean clientEnabled = new AtomicBoolean(true);\n publ... | import net.Poluteclient.phosphor.api.event.events.MouseMoveEvent;
import net.Poluteclient.phosphor.api.event.events.MousePressEvent;
import net.Poluteclient.phosphor.api.event.events.MouseUpdateEvent;
import net.Poluteclient.phosphor.common.Phosphor;
import net.Poluteclient.phosphor.gui.AsteriaMenu;
import net.Poluteclient.phosphor.gui.AsteriaNewMenu;
import net.Poluteclient.phosphor.gui.CategoryTab;
import net.Poluteclient.phosphor.gui.ImguiLoader;
import net.Poluteclient.phosphor.module.modules.client.AsteriaSettingsModule;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.Mouse;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; | 10,051 | package net.Poluteclient.phosphor.mixin;
@Mixin(Mouse.class)
public class MouseMixin {
@Shadow @Final private MinecraftClient client;
@Inject(method = "onCursorPos", at = @At("HEAD"))
private void onMouseMove(long window, double mouseX, double mouseY, CallbackInfo ci) {
if (window == this.client.getWindow().getHandle())
Phosphor.EVENTBUS.post(MouseMoveEvent.get(mouseX, mouseY));
}
@Inject(method = "updateMouse", at = @At("HEAD"))
private void onMouseUpdate(CallbackInfo ci) {
Phosphor.EVENTBUS.post(MouseUpdateEvent.get());
}
@Inject(method = "onMouseButton", at = @At("HEAD"), cancellable = true)
private void onMouseButton(long window, int button, int action, int mods, CallbackInfo ci) {
AsteriaSettingsModule Polute = Phosphor.moduleManager().getModule(AsteriaSettingsModule.class);
if (Polute != null && Polute.isEnabled()) {
ci.cancel();
}
Phosphor.EVENTBUS.post(MousePressEvent.get(button, action));
}
@Inject(method = "onMouseScroll", at = @At("HEAD"), cancellable = true)
private void onMouseScroll(long window, double horizontal, double vertical, CallbackInfo ci) {
AsteriaSettingsModule Polute = Phosphor.moduleManager().getModule(AsteriaSettingsModule.class);
if (Polute != null && Polute.isEnabled()) {
double scrollY = vertical * 30;
| package net.Poluteclient.phosphor.mixin;
@Mixin(Mouse.class)
public class MouseMixin {
@Shadow @Final private MinecraftClient client;
@Inject(method = "onCursorPos", at = @At("HEAD"))
private void onMouseMove(long window, double mouseX, double mouseY, CallbackInfo ci) {
if (window == this.client.getWindow().getHandle())
Phosphor.EVENTBUS.post(MouseMoveEvent.get(mouseX, mouseY));
}
@Inject(method = "updateMouse", at = @At("HEAD"))
private void onMouseUpdate(CallbackInfo ci) {
Phosphor.EVENTBUS.post(MouseUpdateEvent.get());
}
@Inject(method = "onMouseButton", at = @At("HEAD"), cancellable = true)
private void onMouseButton(long window, int button, int action, int mods, CallbackInfo ci) {
AsteriaSettingsModule Polute = Phosphor.moduleManager().getModule(AsteriaSettingsModule.class);
if (Polute != null && Polute.isEnabled()) {
ci.cancel();
}
Phosphor.EVENTBUS.post(MousePressEvent.get(button, action));
}
@Inject(method = "onMouseScroll", at = @At("HEAD"), cancellable = true)
private void onMouseScroll(long window, double horizontal, double vertical, CallbackInfo ci) {
AsteriaSettingsModule Polute = Phosphor.moduleManager().getModule(AsteriaSettingsModule.class);
if (Polute != null && Polute.isEnabled()) {
double scrollY = vertical * 30;
| if (ImguiLoader.isRendered(AsteriaNewMenu.getInstance())) { | 1 | 2023-11-11 17:14:20+00:00 | 12k |
UselessBullets/DragonFly | src/main/java/useless/dragonfly/debug/DebugBlocks.java | [
{
"identifier": "BlockModel",
"path": "src/main/java/useless/dragonfly/debug/block/BlockModel.java",
"snippet": "public class BlockModel extends BlockTransparent {\n\tpublic useless.dragonfly.model.block.processed.BlockModel model;\n\tpublic BlockModel(String key, int id, Material material, useless.drag... | import net.minecraft.client.render.block.color.BlockColorGrass;
import net.minecraft.client.render.block.color.BlockColorWater;
import net.minecraft.client.sound.block.BlockSounds;
import net.minecraft.core.block.Block;
import net.minecraft.core.block.BlockStairs;
import net.minecraft.core.block.material.Material;
import net.minecraft.core.block.tag.BlockTags;
import turniplabs.halplibe.helper.BlockBuilder;
import useless.dragonfly.debug.block.BlockModel;
import useless.dragonfly.debug.block.BlockRotatable;
import useless.dragonfly.debug.block.metastates.BookshelfMetaState;
import useless.dragonfly.debug.block.metastates.BrewingMetaState;
import useless.dragonfly.debug.block.metastates.FenceMetaState;
import useless.dragonfly.debug.block.metastates.GrassMetaState;
import useless.dragonfly.debug.block.metastates.StairsMetaStateInterpreter;
import useless.dragonfly.helper.ModelHelper;
import useless.dragonfly.model.block.BlockModelDragonFly;
import useless.dragonfly.utilities.NamespaceId;
import useless.dragonfly.utilities.Utilities;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import static useless.dragonfly.DragonFly.MOD_ID; | 9,217 | package useless.dragonfly.debug;
public class DebugBlocks {
private static int blockId = 1000;
public static final Block testBlock = new BlockBuilder(MOD_ID)
.setBlockModel(new BlockModelDragonFly(ModelHelper.getOrCreateBlockModel(MOD_ID, "block/testblock.json")))
.build(new BlockModel("testblock" + blockId, blockId++, Material.dirt, ModelHelper.getOrCreateBlockModel(MOD_ID, "block/testblock.json")));
public static final Block testBlock2 = new BlockBuilder(MOD_ID)
.setBlockModel(new BlockModelDragonFly(ModelHelper.getOrCreateBlockModel(MOD_ID, "block/testblock2.json")))
.build(new BlockModel("testblock" + blockId, blockId++, Material.dirt, ModelHelper.getOrCreateBlockModel(MOD_ID, "block/testblock2.json")));
public static final Block testBlock3 = new BlockBuilder(MOD_ID)
.setBlockModel(new BlockModelDragonFly(ModelHelper.getOrCreateBlockModel(MOD_ID, "block/testblock3.json")))
.build(new BlockModel("testblock" + blockId, blockId++, Material.dirt, ModelHelper.getOrCreateBlockModel(MOD_ID, "block/testBlock3.json")));
public static final Block testBlock6 = new BlockBuilder(MOD_ID)
.setBlockModel(new BlockModelDragonFly(ModelHelper.getOrCreateBlockModel(MOD_ID, "block/directionPyramid.json")))
.build(new BlockModel("testblock" + blockId, blockId++, Material.dirt, ModelHelper.getOrCreateBlockModel(MOD_ID, "block/directionPyramid.json")));
public static final Block testBlock7 = new BlockBuilder(MOD_ID)
.setBlockModel(new BlockModelDragonFly(ModelHelper.getOrCreateBlockModel(MOD_ID, "block/stool.json")))
.build(new BlockModel("testblock" + blockId, blockId++, Material.dirt, ModelHelper.getOrCreateBlockModel(MOD_ID, "block/stool.json")));
public static final Block harris = new BlockBuilder(MOD_ID)
.setBlockModel(new BlockModelDragonFly(ModelHelper.getOrCreateBlockModel(MOD_ID, "block/harris.json")))
.build(new BlockModel("testblock" + blockId, blockId++, Material.dirt, ModelHelper.getOrCreateBlockModel(MOD_ID, "block/harris.json")));
public static final Block slope = new BlockBuilder(MOD_ID)
.setBlockModel(new BlockModelDragonFly(ModelHelper.getOrCreateBlockModel(MOD_ID, "block/slope.json")))
.build(new BlockModel("testblock" + blockId, blockId++, Material.dirt, ModelHelper.getOrCreateBlockModel(MOD_ID, "block/slope.json")));
public static final Block stairs = new BlockBuilder(MOD_ID)
.setBlockModel(new BlockModelDragonFly(ModelHelper.getOrCreateBlockModel(NamespaceId.coreNamespaceId, "block/cut_copper_stairs.json"),
ModelHelper.getOrCreateBlockState(MOD_ID, "test_stairs.json"), new StairsMetaStateInterpreter(), true))
.build(new BlockStairs(Block.dirt,blockId++)).withLitInteriorSurface(true);
public static final Block trel = new BlockBuilder(MOD_ID)
.setBlockModel(new BlockModelDragonFly(ModelHelper.getOrCreateBlockModel(MOD_ID, "block/bean_trellis_bottom_0.json")))
.build(new BlockModel("trel" + blockId, blockId++, Material.dirt, ModelHelper.getOrCreateBlockModel(MOD_ID, "block/bean_trellis_bottom_0.json")));
public static final Block trel1 = new BlockBuilder(MOD_ID)
.setBlockModel(new BlockModelDragonFly(ModelHelper.getOrCreateBlockModel(MOD_ID, "block/bean_trellis_bottom_1.json")))
.build(new BlockModel("trel" + blockId, blockId++, Material.dirt, ModelHelper.getOrCreateBlockModel(MOD_ID, "block/bean_trellis_bottom_1.json")));
public static final Block trel2 = new BlockBuilder(MOD_ID)
.setBlockModel(new BlockModelDragonFly(ModelHelper.getOrCreateBlockModel(MOD_ID, "block/bean_trellis_bottom_2.json")))
.build(new BlockModel("trel" + blockId, blockId++, Material.dirt, ModelHelper.getOrCreateBlockModel(MOD_ID, "block/bean_trellis_bottom_2.json")));
public static final Block sieve = new BlockBuilder(MOD_ID)
.setBlockModel(new BlockModelDragonFly(ModelHelper.getOrCreateBlockModel(MOD_ID, "block/wooden_sieve.json")))
.build(new BlockModel("sieve" + blockId, blockId++, Material.dirt, ModelHelper.getOrCreateBlockModel(MOD_ID, "block/wooden_sieve.json")));
public static final Block dirTest = new BlockBuilder(MOD_ID)
.setBlockModel(new BlockModelDragonFly(ModelHelper.getOrCreateBlockModel(MOD_ID, "block/test_block.json")))
.build(new BlockModel("dir" + blockId, blockId++, Material.dirt, ModelHelper.getOrCreateBlockModel(MOD_ID, "block/test_block.json")));
public static final Block brewing = new BlockBuilder(MOD_ID)
.setBlockModel(new BlockModelDragonFly(ModelHelper.getOrCreateBlockModel(NamespaceId.coreNamespaceId, "block/brewing_stand.json"),
ModelHelper.getOrCreateBlockState(NamespaceId.coreNamespaceId, "brewing_stand.json"), new BrewingMetaState(), true))
.build(new BlockModel("brew" + blockId, blockId++, Material.dirt, ModelHelper.getOrCreateBlockModel(NamespaceId.coreNamespaceId, "block/brewing_stand.json"))).withLitInteriorSurface(true);
public static final Block fence = new BlockBuilder(MOD_ID)
.setBlockModel(new BlockModelDragonFly(ModelHelper.getOrCreateBlockModel(NamespaceId.coreNamespaceId, "block/birch_fence_inventory.json"),
ModelHelper.getOrCreateBlockState(MOD_ID, "test_fence.json"), new FenceMetaState(), true))
.build(new BlockModel("fence" + blockId, blockId++, Material.dirt, ModelHelper.getOrCreateBlockModel(NamespaceId.coreNamespaceId, "block/birch_fence_inventory.json"))).withLitInteriorSurface(true).withTags(BlockTags.FENCES_CONNECT);
public static final Block bookshelf = new BlockBuilder(MOD_ID)
.setBlockModel(new BlockModelDragonFly(ModelHelper.getOrCreateBlockModel(NamespaceId.coreNamespaceId, "block/chiseled_bookshelf_inventory.json"), | package useless.dragonfly.debug;
public class DebugBlocks {
private static int blockId = 1000;
public static final Block testBlock = new BlockBuilder(MOD_ID)
.setBlockModel(new BlockModelDragonFly(ModelHelper.getOrCreateBlockModel(MOD_ID, "block/testblock.json")))
.build(new BlockModel("testblock" + blockId, blockId++, Material.dirt, ModelHelper.getOrCreateBlockModel(MOD_ID, "block/testblock.json")));
public static final Block testBlock2 = new BlockBuilder(MOD_ID)
.setBlockModel(new BlockModelDragonFly(ModelHelper.getOrCreateBlockModel(MOD_ID, "block/testblock2.json")))
.build(new BlockModel("testblock" + blockId, blockId++, Material.dirt, ModelHelper.getOrCreateBlockModel(MOD_ID, "block/testblock2.json")));
public static final Block testBlock3 = new BlockBuilder(MOD_ID)
.setBlockModel(new BlockModelDragonFly(ModelHelper.getOrCreateBlockModel(MOD_ID, "block/testblock3.json")))
.build(new BlockModel("testblock" + blockId, blockId++, Material.dirt, ModelHelper.getOrCreateBlockModel(MOD_ID, "block/testBlock3.json")));
public static final Block testBlock6 = new BlockBuilder(MOD_ID)
.setBlockModel(new BlockModelDragonFly(ModelHelper.getOrCreateBlockModel(MOD_ID, "block/directionPyramid.json")))
.build(new BlockModel("testblock" + blockId, blockId++, Material.dirt, ModelHelper.getOrCreateBlockModel(MOD_ID, "block/directionPyramid.json")));
public static final Block testBlock7 = new BlockBuilder(MOD_ID)
.setBlockModel(new BlockModelDragonFly(ModelHelper.getOrCreateBlockModel(MOD_ID, "block/stool.json")))
.build(new BlockModel("testblock" + blockId, blockId++, Material.dirt, ModelHelper.getOrCreateBlockModel(MOD_ID, "block/stool.json")));
public static final Block harris = new BlockBuilder(MOD_ID)
.setBlockModel(new BlockModelDragonFly(ModelHelper.getOrCreateBlockModel(MOD_ID, "block/harris.json")))
.build(new BlockModel("testblock" + blockId, blockId++, Material.dirt, ModelHelper.getOrCreateBlockModel(MOD_ID, "block/harris.json")));
public static final Block slope = new BlockBuilder(MOD_ID)
.setBlockModel(new BlockModelDragonFly(ModelHelper.getOrCreateBlockModel(MOD_ID, "block/slope.json")))
.build(new BlockModel("testblock" + blockId, blockId++, Material.dirt, ModelHelper.getOrCreateBlockModel(MOD_ID, "block/slope.json")));
public static final Block stairs = new BlockBuilder(MOD_ID)
.setBlockModel(new BlockModelDragonFly(ModelHelper.getOrCreateBlockModel(NamespaceId.coreNamespaceId, "block/cut_copper_stairs.json"),
ModelHelper.getOrCreateBlockState(MOD_ID, "test_stairs.json"), new StairsMetaStateInterpreter(), true))
.build(new BlockStairs(Block.dirt,blockId++)).withLitInteriorSurface(true);
public static final Block trel = new BlockBuilder(MOD_ID)
.setBlockModel(new BlockModelDragonFly(ModelHelper.getOrCreateBlockModel(MOD_ID, "block/bean_trellis_bottom_0.json")))
.build(new BlockModel("trel" + blockId, blockId++, Material.dirt, ModelHelper.getOrCreateBlockModel(MOD_ID, "block/bean_trellis_bottom_0.json")));
public static final Block trel1 = new BlockBuilder(MOD_ID)
.setBlockModel(new BlockModelDragonFly(ModelHelper.getOrCreateBlockModel(MOD_ID, "block/bean_trellis_bottom_1.json")))
.build(new BlockModel("trel" + blockId, blockId++, Material.dirt, ModelHelper.getOrCreateBlockModel(MOD_ID, "block/bean_trellis_bottom_1.json")));
public static final Block trel2 = new BlockBuilder(MOD_ID)
.setBlockModel(new BlockModelDragonFly(ModelHelper.getOrCreateBlockModel(MOD_ID, "block/bean_trellis_bottom_2.json")))
.build(new BlockModel("trel" + blockId, blockId++, Material.dirt, ModelHelper.getOrCreateBlockModel(MOD_ID, "block/bean_trellis_bottom_2.json")));
public static final Block sieve = new BlockBuilder(MOD_ID)
.setBlockModel(new BlockModelDragonFly(ModelHelper.getOrCreateBlockModel(MOD_ID, "block/wooden_sieve.json")))
.build(new BlockModel("sieve" + blockId, blockId++, Material.dirt, ModelHelper.getOrCreateBlockModel(MOD_ID, "block/wooden_sieve.json")));
public static final Block dirTest = new BlockBuilder(MOD_ID)
.setBlockModel(new BlockModelDragonFly(ModelHelper.getOrCreateBlockModel(MOD_ID, "block/test_block.json")))
.build(new BlockModel("dir" + blockId, blockId++, Material.dirt, ModelHelper.getOrCreateBlockModel(MOD_ID, "block/test_block.json")));
public static final Block brewing = new BlockBuilder(MOD_ID)
.setBlockModel(new BlockModelDragonFly(ModelHelper.getOrCreateBlockModel(NamespaceId.coreNamespaceId, "block/brewing_stand.json"),
ModelHelper.getOrCreateBlockState(NamespaceId.coreNamespaceId, "brewing_stand.json"), new BrewingMetaState(), true))
.build(new BlockModel("brew" + blockId, blockId++, Material.dirt, ModelHelper.getOrCreateBlockModel(NamespaceId.coreNamespaceId, "block/brewing_stand.json"))).withLitInteriorSurface(true);
public static final Block fence = new BlockBuilder(MOD_ID)
.setBlockModel(new BlockModelDragonFly(ModelHelper.getOrCreateBlockModel(NamespaceId.coreNamespaceId, "block/birch_fence_inventory.json"),
ModelHelper.getOrCreateBlockState(MOD_ID, "test_fence.json"), new FenceMetaState(), true))
.build(new BlockModel("fence" + blockId, blockId++, Material.dirt, ModelHelper.getOrCreateBlockModel(NamespaceId.coreNamespaceId, "block/birch_fence_inventory.json"))).withLitInteriorSurface(true).withTags(BlockTags.FENCES_CONNECT);
public static final Block bookshelf = new BlockBuilder(MOD_ID)
.setBlockModel(new BlockModelDragonFly(ModelHelper.getOrCreateBlockModel(NamespaceId.coreNamespaceId, "block/chiseled_bookshelf_inventory.json"), | ModelHelper.getOrCreateBlockState(NamespaceId.coreNamespaceId, "chiseled_bookshelf.json"), new BookshelfMetaState(), true)) | 2 | 2023-11-16 01:10:52+00:00 | 12k |
AntonyCheng/ai-bi | src/test/java/top/sharehome/springbootinittemplate/captcha/CaptchaTest.java | [
{
"identifier": "CaptchaCreate",
"path": "src/main/java/top/sharehome/springbootinittemplate/config/captcha/model/CaptchaCreate.java",
"snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\n@Accessors(chain = true)\npublic class CaptchaCreate implements Serializable {\n\n private static final lo... | import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import top.sharehome.springbootinittemplate.config.captcha.model.CaptchaCreate;
import top.sharehome.springbootinittemplate.config.captcha.service.CaptchaService;
import top.sharehome.springbootinittemplate.utils.redisson.cache.CacheUtils;
import top.sharehome.springbootinittemplate.utils.redisson.KeyPrefixConstants;
import javax.annotation.Resource; | 10,601 | package top.sharehome.springbootinittemplate.captcha;
/**
* 验证码测试类
*
* @author AntonyCheng
*/
@SpringBootTest
public class CaptchaTest {
@Resource | package top.sharehome.springbootinittemplate.captcha;
/**
* 验证码测试类
*
* @author AntonyCheng
*/
@SpringBootTest
public class CaptchaTest {
@Resource | private CaptchaService captchaService; | 1 | 2023-11-12 07:49:59+00:00 | 12k |
rmheuer/azalea | azalea-core/src/main/java/com/github/rmheuer/azalea/render2d/Renderer2D.java | [
{
"identifier": "ResourceUtil",
"path": "azalea-core/src/main/java/com/github/rmheuer/azalea/io/ResourceUtil.java",
"snippet": "public final class ResourceUtil {\n /**\n * Reads a resource as an {@code InputStream}.\n *\n * @param path resource path to read\n * @return stream to read ... | import com.github.rmheuer.azalea.io.ResourceUtil;
import com.github.rmheuer.azalea.render.ColorRGBA;
import com.github.rmheuer.azalea.render.Renderer;
import com.github.rmheuer.azalea.render.mesh.Mesh;
import com.github.rmheuer.azalea.render.mesh.MeshData;
import com.github.rmheuer.azalea.render.pipeline.ActivePipeline;
import com.github.rmheuer.azalea.render.pipeline.PipelineInfo;
import com.github.rmheuer.azalea.render.shader.ShaderProgram;
import com.github.rmheuer.azalea.render.texture.Bitmap;
import com.github.rmheuer.azalea.render.texture.Texture2D;
import com.github.rmheuer.azalea.utils.SafeCloseable;
import org.joml.Matrix4f;
import java.io.IOException;
import java.util.List; | 8,790 | package com.github.rmheuer.azalea.render2d;
/**
* Renderer to render {@code DrawList2D}s.
*/
public final class Renderer2D implements SafeCloseable {
public static final int MAX_TEXTURE_SLOTS = 16;
private static final String VERTEX_SHADER_PATH = "azalea/shaders/render2d/vertex.glsl";
private static final String FRAGMENT_SHADER_PATH = "azalea/shaders/render2d/fragment.glsl";
private final Renderer renderer;
private final Mesh mesh; | package com.github.rmheuer.azalea.render2d;
/**
* Renderer to render {@code DrawList2D}s.
*/
public final class Renderer2D implements SafeCloseable {
public static final int MAX_TEXTURE_SLOTS = 16;
private static final String VERTEX_SHADER_PATH = "azalea/shaders/render2d/vertex.glsl";
private static final String FRAGMENT_SHADER_PATH = "azalea/shaders/render2d/fragment.glsl";
private final Renderer renderer;
private final Mesh mesh; | private final ShaderProgram shader; | 7 | 2023-11-16 04:46:53+00:00 | 12k |
Shushandr/offroad | src/net/osmand/data/Amenity.java | [
{
"identifier": "Location",
"path": "src/net/osmand/Location.java",
"snippet": "public class Location {\n \n private String mProvider;\n private long mTime = 0;\n private double mLatitude = 0.0;\n private double mLongitude = 0.0;\n private boolean mHasAltitude = false;\n private dou... | import net.osmand.Location;
import net.osmand.osm.PoiCategory;
import net.osmand.util.Algorithms;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.zip.GZIPInputStream; | 9,998 | package net.osmand.data;
public class Amenity extends MapObject {
public static final String WEBSITE = "website";
public static final String PHONE = "phone";
public static final String DESCRIPTION = "description";
public static final String OPENING_HOURS = "opening_hours";
public static final String CONTENT = "content";
private String subType;
private PoiCategory type;
// duplicate for fast access
private String openingHours;
private Map<String, String> additionalInfo;
private AmenityRoutePoint routePoint; // for search on path
public Amenity(){
}
public static class AmenityRoutePoint {
public double deviateDistance;
public boolean deviationDirectionRight; | package net.osmand.data;
public class Amenity extends MapObject {
public static final String WEBSITE = "website";
public static final String PHONE = "phone";
public static final String DESCRIPTION = "description";
public static final String OPENING_HOURS = "opening_hours";
public static final String CONTENT = "content";
private String subType;
private PoiCategory type;
// duplicate for fast access
private String openingHours;
private Map<String, String> additionalInfo;
private AmenityRoutePoint routePoint; // for search on path
public Amenity(){
}
public static class AmenityRoutePoint {
public double deviateDistance;
public boolean deviationDirectionRight; | public Location pointA; | 0 | 2023-11-15 05:04:55+00:00 | 12k |
WuKongOpenSource/Wukong_HRM | hrm/hrm-web/src/main/java/com/kakarote/hrm/controller/HrmAttendanceGroupController.java | [
{
"identifier": "OperationLog",
"path": "common/common-log/src/main/java/com/kakarote/common/log/entity/OperationLog.java",
"snippet": "@Getter\n@Setter\npublic class OperationLog {\n //操作对象\n private Object operationObject;\n //操作详情\n private String operationInfo;\n\n private BehaviorEnu... | import com.kakarote.common.log.annotation.OperateLog;
import com.kakarote.common.log.entity.OperationLog;
import com.kakarote.common.log.entity.OperationResult;
import com.kakarote.common.log.enums.ApplyEnum;
import com.kakarote.common.log.enums.BehaviorEnum;
import com.kakarote.common.log.enums.OperateObjectEnum;
import com.kakarote.common.log.enums.OperateTypeEnum;
import com.kakarote.core.common.Result;
import com.kakarote.core.entity.BasePage;
import com.kakarote.hrm.entity.BO.QueryHrmAttendanceGroupBO;
import com.kakarote.hrm.entity.BO.SetAttendanceGroupBO;
import com.kakarote.hrm.entity.VO.HrmAttendanceGroupVO;
import com.kakarote.hrm.entity.VO.QueryMyAttendanceGroupVO;
import com.kakarote.hrm.service.IHrmAttendanceGroupService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*; | 10,521 | package com.kakarote.hrm.controller;
/**
* <p>
* 考勤组表 前端控制器
* </p>
*
* @author guomenghao
* @since 2021-08-13
*/
@RestController
@RequestMapping("/hrmAttendanceGroup")
@Api(tags = "考勤管理-考勤组")
public class HrmAttendanceGroupController {
@Autowired
private IHrmAttendanceGroupService attendanceGroupService;
@PostMapping("/queryAttendanceGroupPageList")
@ApiOperation("查询考勤组列表") | package com.kakarote.hrm.controller;
/**
* <p>
* 考勤组表 前端控制器
* </p>
*
* @author guomenghao
* @since 2021-08-13
*/
@RestController
@RequestMapping("/hrmAttendanceGroup")
@Api(tags = "考勤管理-考勤组")
public class HrmAttendanceGroupController {
@Autowired
private IHrmAttendanceGroupService attendanceGroupService;
@PostMapping("/queryAttendanceGroupPageList")
@ApiOperation("查询考勤组列表") | public Result<BasePage<HrmAttendanceGroupVO>> queryAttendanceGroupPageList(@RequestBody QueryHrmAttendanceGroupBO queryHrmAttendanceGroupBO) { | 10 | 2023-10-17 05:49:52+00:00 | 12k |
zhaoeryu/eu-backend | eu-generate/src/main/java/cn/eu/generate/service/impl/GenTableServiceImpl.java | [
{
"identifier": "EuServiceImpl",
"path": "eu-common-core/src/main/java/cn/eu/common/base/service/impl/EuServiceImpl.java",
"snippet": "public abstract class EuServiceImpl<M extends BaseMapper<T>, T> extends ServiceImpl<M, T> implements IEuService<T> {\n\n /**\n * 分页参数从1开始\n */\n protected ... | import cn.eu.common.base.service.impl.EuServiceImpl;
import cn.eu.common.model.PageResult;
import cn.eu.generate.constants.GenConstant;
import cn.eu.generate.domain.GenTable;
import cn.eu.generate.domain.GenTableColumn;
import cn.eu.generate.enums.GenMode;
import cn.eu.generate.mapper.GenTableMapper;
import cn.eu.generate.model.dto.GenerateTemplateDto;
import cn.eu.generate.model.vo.TableInfoVo;
import cn.eu.generate.service.IGenTableColumnService;
import cn.eu.generate.service.IGenTableService;
import cn.eu.generate.model.query.GenTableQueryCriteria;
import cn.eu.generate.utils.FieldTypeMappingUtil;
import cn.eu.generate.utils.GenUtil;
import cn.eu.generate.utils.VelocityHelper;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.velocity.VelocityContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream; | 7,375 | package cn.eu.generate.service.impl;
/**
* @author zhaoeryu
* @since 2023/6/27
*/
@Slf4j
@Service
public class GenTableServiceImpl extends EuServiceImpl<GenTableMapper, GenTable> implements IGenTableService {
@Autowired
GenTableMapper genTableMapper;
@Autowired
IGenTableColumnService genTableColumnService;
@Override
public PageResult<GenTable> listTables(GenTableQueryCriteria criteria, Pageable pageable) {
getPage(pageable);
List<GenTable> list = genTableMapper.selectDbTableList(criteria);
return PageResult.of(list);
}
@Override
public List<GenerateTemplateDto> preview(String tableName) {
VelocityHelper.init();
// 从数据查询列信息 | package cn.eu.generate.service.impl;
/**
* @author zhaoeryu
* @since 2023/6/27
*/
@Slf4j
@Service
public class GenTableServiceImpl extends EuServiceImpl<GenTableMapper, GenTable> implements IGenTableService {
@Autowired
GenTableMapper genTableMapper;
@Autowired
IGenTableColumnService genTableColumnService;
@Override
public PageResult<GenTable> listTables(GenTableQueryCriteria criteria, Pageable pageable) {
getPage(pageable);
List<GenTable> list = genTableMapper.selectDbTableList(criteria);
return PageResult.of(list);
}
@Override
public List<GenerateTemplateDto> preview(String tableName) {
VelocityHelper.init();
// 从数据查询列信息 | List<GenTableColumn> genTableColumns = getGenTableColumns(tableName); | 4 | 2023-10-20 07:08:37+00:00 | 12k |
Nxer/Twist-Space-Technology-Mod | src/main/java/com/Nxer/TwistSpaceTechnology/common/machine/GT_TileEntity_MoleculeDeconstructor.java | [
{
"identifier": "Mode_Default_MoleculeDeconstructor",
"path": "src/main/java/com/Nxer/TwistSpaceTechnology/common/machine/ValueEnum.java",
"snippet": "public static final byte Mode_Default_MoleculeDeconstructor = Config.Mode_Default_MoleculeDeconstructor;"
},
{
"identifier": "Parallel_PerPiece_M... | import static com.Nxer.TwistSpaceTechnology.common.machine.ValueEnum.Mode_Default_MoleculeDeconstructor;
import static com.Nxer.TwistSpaceTechnology.common.machine.ValueEnum.Parallel_PerPiece_MoleculeDeconstructor;
import static com.Nxer.TwistSpaceTechnology.common.machine.ValueEnum.PieceAmount_EnablePerfectOverclock_MoleculeDeconstructor;
import static com.Nxer.TwistSpaceTechnology.common.machine.ValueEnum.SpeedBonus_MultiplyPerTier_MoleculeDeconstructor;
import static com.Nxer.TwistSpaceTechnology.util.TextLocalization.BLUE_PRINT_INFO;
import static com.Nxer.TwistSpaceTechnology.util.TextLocalization.ModName;
import static com.Nxer.TwistSpaceTechnology.util.TextLocalization.StructureTooComplex;
import static com.Nxer.TwistSpaceTechnology.util.TextLocalization.Tooltip_MoleculeDeconstructor_00;
import static com.Nxer.TwistSpaceTechnology.util.TextLocalization.Tooltip_MoleculeDeconstructor_01;
import static com.Nxer.TwistSpaceTechnology.util.TextLocalization.Tooltip_MoleculeDeconstructor_02;
import static com.Nxer.TwistSpaceTechnology.util.TextLocalization.Tooltip_MoleculeDeconstructor_03;
import static com.Nxer.TwistSpaceTechnology.util.TextLocalization.Tooltip_MoleculeDeconstructor_04;
import static com.Nxer.TwistSpaceTechnology.util.TextLocalization.Tooltip_MoleculeDeconstructor_05;
import static com.Nxer.TwistSpaceTechnology.util.TextLocalization.Tooltip_MoleculeDeconstructor_MachineType;
import static com.Nxer.TwistSpaceTechnology.util.TextLocalization.textFrontBottom;
import static com.Nxer.TwistSpaceTechnology.util.TextLocalization.textScrewdriverChangeMode;
import static com.Nxer.TwistSpaceTechnology.util.TextLocalization.textUseBlueprint;
import static com.github.technus.tectech.thing.casing.TT_Container_Casings.sBlockCasingsTT;
import static com.gtnewhorizon.structurelib.structure.StructureUtility.ofBlock;
import static com.gtnewhorizon.structurelib.structure.StructureUtility.withChannel;
import static gregtech.api.enums.GT_HatchElement.Energy;
import static gregtech.api.enums.GT_HatchElement.ExoticEnergy;
import static gregtech.api.enums.GT_HatchElement.InputBus;
import static gregtech.api.enums.GT_HatchElement.InputHatch;
import static gregtech.api.enums.GT_HatchElement.Maintenance;
import static gregtech.api.enums.GT_HatchElement.OutputBus;
import static gregtech.api.enums.GT_HatchElement.OutputHatch;
import static gregtech.api.enums.Textures.BlockIcons.OVERLAY_FRONT_PROCESSING_ARRAY;
import static gregtech.api.enums.Textures.BlockIcons.OVERLAY_FRONT_PROCESSING_ARRAY_ACTIVE;
import static gregtech.api.enums.Textures.BlockIcons.OVERLAY_FRONT_PROCESSING_ARRAY_ACTIVE_GLOW;
import static gregtech.api.enums.Textures.BlockIcons.OVERLAY_FRONT_PROCESSING_ARRAY_GLOW;
import static gregtech.api.util.GT_StructureUtility.ofFrame;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.util.StatCollector;
import net.minecraftforge.common.util.ForgeDirection;
import com.Nxer.TwistSpaceTechnology.common.machine.multiMachineClasses.GTCM_MultiMachineBase;
import com.github.bartimaeusnek.bartworks.API.BorosilicateGlass;
import com.gtnewhorizon.structurelib.alignment.constructable.IConstructable;
import com.gtnewhorizon.structurelib.alignment.constructable.ISurvivalConstructable;
import com.gtnewhorizon.structurelib.structure.IItemSource;
import com.gtnewhorizon.structurelib.structure.IStructureDefinition;
import com.gtnewhorizon.structurelib.structure.StructureDefinition;
import gregtech.api.GregTech_API;
import gregtech.api.enums.Materials;
import gregtech.api.enums.Textures;
import gregtech.api.interfaces.ITexture;
import gregtech.api.interfaces.metatileentity.IMetaTileEntity;
import gregtech.api.interfaces.tileentity.IGregTechTileEntity;
import gregtech.api.metatileentity.implementations.GT_MetaTileEntity_Hatch;
import gregtech.api.recipe.RecipeMap;
import gregtech.api.render.TextureFactory;
import gregtech.api.util.GT_HatchElementBuilder;
import gregtech.api.util.GT_Multiblock_Tooltip_Builder;
import gregtech.api.util.GT_Utility;
import gtPlusPlus.api.recipe.GTPPRecipeMaps; | 7,603 | "IFD AAA DFI",
"IFD A A DFI",
"IFD CCC DFI",
"CCD DCC"
}};
private final String[][] shapeMiddle = new String[][]{{
" ",
" ",
" ",
" ",
" ",
" ",
" AAA ",
" A A ",
" CCC ",
" "
},{
"IIIIIIIIIIIIIII",
"I FFF I",
"I DDD I",
"I I",
"I I",
"I I",
"IFD AAA DFI",
"IFD A A DFI",
"IFD CCC DFI",
"CCD DCC"
},{
" ",
" FFF ",
" DED ",
" B ",
" B ",
" B ",
" FD AEA DF ",
" FEBBBE EBBBEF ",
" FD CCC DF ",
"CCD DCC"
},{
"IIIIIIIIIIIIIII",
"I FFF I",
"I DDD I",
"I I",
"I I",
"I I",
"IFD AAA DFI",
"IFD A A DFI",
"IFD CCC DFI",
"CCD DCC"
}};
private final String[][] shapeEnd = new String[][]{{
" ",
" ",
" ",
" ",
" ",
" ",
" FFF ",
" FFF ",
" FFF ",
" GGG "
}};
@Override
public boolean addToMachineList(IGregTechTileEntity aTileEntity, int aBaseCasingIndex) {
return super.addToMachineList(aTileEntity, aBaseCasingIndex)
|| addExoticEnergyInputToMachineList(aTileEntity, aBaseCasingIndex);
}
// spotless:on
// endregion
// region Overrides
@Override
public String[] getInfoData() {
String[] origin = super.getInfoData();
String[] ret = new String[origin.length + 3];
System.arraycopy(origin, 0, ret, 0, origin.length);
ret[origin.length] = EnumChatFormatting.AQUA + "Parallels: "
+ EnumChatFormatting.GOLD
+ this.getMaxParallelRecipes();
ret[origin.length + 1] = EnumChatFormatting.AQUA + "Speed multiplier: "
+ EnumChatFormatting.GOLD
+ this.getSpeedBonus();
ret[origin.length + 2] = EnumChatFormatting.AQUA + "Pieces: " + EnumChatFormatting.GOLD + this.piece;
return ret;
}
@Override
public void saveNBTData(NBTTagCompound aNBT) {
super.saveNBTData(aNBT);
aNBT.setInteger("piece", piece);
aNBT.setByte("mode", mode);
}
@Override
public void loadNBTData(final NBTTagCompound aNBT) {
super.loadNBTData(aNBT);
piece = aNBT.getInteger("piece");
mode = aNBT.getByte("mode");
}
@Override
protected GT_Multiblock_Tooltip_Builder createTooltip() {
final GT_Multiblock_Tooltip_Builder tt = new GT_Multiblock_Tooltip_Builder();
tt.addMachineType(Tooltip_MoleculeDeconstructor_MachineType)
.addInfo(Tooltip_MoleculeDeconstructor_00)
.addInfo(Tooltip_MoleculeDeconstructor_01)
.addInfo(Tooltip_MoleculeDeconstructor_02)
.addInfo(Tooltip_MoleculeDeconstructor_03)
.addInfo(Tooltip_MoleculeDeconstructor_04)
.addInfo(Tooltip_MoleculeDeconstructor_05)
.addInfo(textScrewdriverChangeMode)
.addSeparator()
.addInfo(StructureTooComplex)
.addInfo(BLUE_PRINT_INFO) | package com.Nxer.TwistSpaceTechnology.common.machine;
public class GT_TileEntity_MoleculeDeconstructor extends GTCM_MultiMachineBase<GT_TileEntity_MoleculeDeconstructor>
implements IConstructable, ISurvivalConstructable {
// region Class Constructor
public GT_TileEntity_MoleculeDeconstructor(int aID, String aName, String aNameRegional) {
super(aID, aName, aNameRegional);
}
public GT_TileEntity_MoleculeDeconstructor(String aName) {
super(aName);
}
// endregion
// region Processing Logic
private byte glassTier = 0;
private int piece = 1;
private byte mode = Mode_Default_MoleculeDeconstructor;
@Override
protected boolean isEnablePerfectOverclock() {
return piece >= PieceAmount_EnablePerfectOverclock_MoleculeDeconstructor;
}
protected int getMaxParallelRecipes() {
return Parallel_PerPiece_MoleculeDeconstructor * this.piece;
}
protected float getSpeedBonus() {
return (float) (Math
.pow(SpeedBonus_MultiplyPerTier_MoleculeDeconstructor, GT_Utility.getTier(this.getMaxInputEu())));
}
@Override
public RecipeMap<?> getRecipeMap() {
switch (mode) {
case 1:
return GTPPRecipeMaps.centrifugeNonCellRecipes;
default:
return GTPPRecipeMaps.electrolyzerNonCellRecipes;
}
}
@Override
public final void onScrewdriverRightClick(ForgeDirection side, EntityPlayer aPlayer, float aX, float aY, float aZ) {
if (getBaseMetaTileEntity().isServerSide()) {
this.mode = (byte) ((this.mode + 1) % 2);
GT_Utility.sendChatToPlayer(
aPlayer,
StatCollector.translateToLocal("MoleculeDeconstructor.modeMsg." + this.mode));
}
}
@Override
public boolean checkMachine(IGregTechTileEntity aBaseMetaTileEntity, ItemStack aStack) {
this.glassTier = 0;
this.piece = 1;
if (!checkPiece(STRUCTURE_PIECE_MAIN, horizontalOffSet, verticalOffSet, depthOffSet)) {
return false;
}
while (checkPiece(STRUCTURE_PIECE_MIDDLE, horizontalOffSet, verticalOffSet, depthOffSet - piece * 4)) {
this.piece++;
}
if (!checkPiece(STRUCTURE_PIECE_END, horizontalOffSet, verticalOffSet, depthOffSet - piece * 4)) {
return false;
}
if (this.glassTier <= 0) return false;
if (glassTier < 12) {
for (GT_MetaTileEntity_Hatch hatch : this.mExoticEnergyHatches) {
if (this.glassTier < hatch.mTier) {
return false;
}
}
}
return true;
}
// endregion
// region Structure
// spotless:off
@Override
public void construct(ItemStack stackSize, boolean hintsOnly) {
this.buildPiece(STRUCTURE_PIECE_MAIN, stackSize, hintsOnly, horizontalOffSet, verticalOffSet, depthOffSet);
int piece = stackSize.stackSize;
for (int i=1; i<piece; i++){
this.buildPiece(STRUCTURE_PIECE_MIDDLE, stackSize, hintsOnly, horizontalOffSet, verticalOffSet, depthOffSet - i*4);
}
this.buildPiece(STRUCTURE_PIECE_END, stackSize, hintsOnly, horizontalOffSet, verticalOffSet, depthOffSet - piece*4);
}
@Override
public int survivalConstruct(ItemStack stackSize, int elementBudget, IItemSource source, EntityPlayerMP actor) {
if (this.mMachine) return -1;
int built = 0;
built += survivialBuildPiece(
STRUCTURE_PIECE_MAIN,
stackSize,
horizontalOffSet,
verticalOffSet,
depthOffSet,
elementBudget,
source,
actor,
false,
true);
int piece = stackSize.stackSize;
if (piece>1) {
for (int i = 1; i < piece; i++) {
built += survivialBuildPiece(
STRUCTURE_PIECE_MIDDLE,
stackSize,
horizontalOffSet,
verticalOffSet,
depthOffSet - i * 4,
elementBudget,
source,
actor,
false,
true);
}
}
built += survivialBuildPiece(
STRUCTURE_PIECE_END,
stackSize,
horizontalOffSet,
verticalOffSet,
depthOffSet - piece*4,
elementBudget,
source,
actor,
false,
true);
return built;
}
private static final String STRUCTURE_PIECE_MAIN = "mainMoleculeDeconstructor";
private static final String STRUCTURE_PIECE_MIDDLE = "middleMoleculeDeconstructor";
private static final String STRUCTURE_PIECE_END = "endMoleculeDeconstructor";
private final int horizontalOffSet = 7;
private final int verticalOffSet = 9;
private final int depthOffSet = 0;
@Override
public IStructureDefinition<GT_TileEntity_MoleculeDeconstructor> getStructureDefinition() {
return StructureDefinition.<GT_TileEntity_MoleculeDeconstructor>builder()
.addShape(STRUCTURE_PIECE_MAIN, shapeMain)
.addShape(STRUCTURE_PIECE_MIDDLE, shapeMiddle)
.addShape(STRUCTURE_PIECE_END, shapeEnd)
.addElement('A',
withChannel("glass",
BorosilicateGlass.ofBoroGlass(
(byte) 0,
(byte) 1,
Byte.MAX_VALUE,
(te, t) -> te.glassTier = t,
te -> te.glassTier
)))
.addElement('B', ofBlock(GregTech_API.sBlockCasings2, 15))
.addElement('C', ofBlock(GregTech_API.sBlockCasings4, 14))
.addElement('D',
GT_HatchElementBuilder.<GT_TileEntity_MoleculeDeconstructor>builder()
.atLeast(Energy.or(ExoticEnergy))
.adder(GT_TileEntity_MoleculeDeconstructor::addToMachineList)
.dot(1)
.casingIndex(1024)
.buildAndChain(sBlockCasingsTT, 0))
.addElement('E', ofBlock(sBlockCasingsTT, 8))
.addElement('F',
GT_HatchElementBuilder.<GT_TileEntity_MoleculeDeconstructor>builder()
.atLeast(OutputBus, OutputHatch)
.adder(GT_TileEntity_MoleculeDeconstructor::addToMachineList)
.dot(2)
.casingIndex(62)
.buildAndChain(GregTech_API.sBlockCasings4, 14))
.addElement('G',
GT_HatchElementBuilder.<GT_TileEntity_MoleculeDeconstructor>builder()
.atLeast(Maintenance)
.adder(GT_TileEntity_MoleculeDeconstructor::addToMachineList)
.dot(3)
.casingIndex(62)
.buildAndChain(GregTech_API.sBlockCasings4, 14))
.addElement('H',
GT_HatchElementBuilder.<GT_TileEntity_MoleculeDeconstructor>builder()
.atLeast(InputBus, InputHatch)
.adder(GT_TileEntity_MoleculeDeconstructor::addToMachineList)
.dot(4)
.casingIndex(62)
.buildAndChain(GregTech_API.sBlockCasings4, 14))
.addElement('I', ofFrame(Materials.CosmicNeutronium))
.build();
}
/*
Blocks:
A -> ofBlock...(BW_GlasBlocks, 14, ...); // glass
B -> ofBlock...(gt.blockcasings2, 15, ...);
C -> ofBlock...(gt.blockcasings4, 14, ...);
D -> ofBlock...(gt.blockcasingsTT, 0, ...); // energy
E -> ofBlock...(gt.blockcasingsTT, 8, ...);
F -> ofBlock...(gt.blockcasings4, 14, ...); // output
G -> ofBlock...(gt.blockcasings4, 14, ...); // maintenance
H -> ofBlock...(gt.blockcasings4, 14, ...); // input
I -> ofFrame...();
*/
private final String[][] shapeMain = new String[][]{{
" ",
" ",
" ",
" ",
" ",
" ",
" HHH ",
" HHH ",
" HHH ",
" G~G "
},{
"IIIIIIIIIIIIIII",
"I FFF I",
"I DDD I",
"I I",
"I I",
"I I",
"IFD AAA DFI",
"IFD A A DFI",
"IFD CCC DFI",
"CCD DCC"
},{
" ",
" FFF ",
" DED ",
" B ",
" B ",
" B ",
" FD AEA DF ",
" FEBBBE EBBBEF ",
" FD CCC DF ",
"CCD DCC"
},{
"IIIIIIIIIIIIIII",
"I FFF I",
"I DDD I",
"I I",
"I I",
"I I",
"IFD AAA DFI",
"IFD A A DFI",
"IFD CCC DFI",
"CCD DCC"
}};
private final String[][] shapeMiddle = new String[][]{{
" ",
" ",
" ",
" ",
" ",
" ",
" AAA ",
" A A ",
" CCC ",
" "
},{
"IIIIIIIIIIIIIII",
"I FFF I",
"I DDD I",
"I I",
"I I",
"I I",
"IFD AAA DFI",
"IFD A A DFI",
"IFD CCC DFI",
"CCD DCC"
},{
" ",
" FFF ",
" DED ",
" B ",
" B ",
" B ",
" FD AEA DF ",
" FEBBBE EBBBEF ",
" FD CCC DF ",
"CCD DCC"
},{
"IIIIIIIIIIIIIII",
"I FFF I",
"I DDD I",
"I I",
"I I",
"I I",
"IFD AAA DFI",
"IFD A A DFI",
"IFD CCC DFI",
"CCD DCC"
}};
private final String[][] shapeEnd = new String[][]{{
" ",
" ",
" ",
" ",
" ",
" ",
" FFF ",
" FFF ",
" FFF ",
" GGG "
}};
@Override
public boolean addToMachineList(IGregTechTileEntity aTileEntity, int aBaseCasingIndex) {
return super.addToMachineList(aTileEntity, aBaseCasingIndex)
|| addExoticEnergyInputToMachineList(aTileEntity, aBaseCasingIndex);
}
// spotless:on
// endregion
// region Overrides
@Override
public String[] getInfoData() {
String[] origin = super.getInfoData();
String[] ret = new String[origin.length + 3];
System.arraycopy(origin, 0, ret, 0, origin.length);
ret[origin.length] = EnumChatFormatting.AQUA + "Parallels: "
+ EnumChatFormatting.GOLD
+ this.getMaxParallelRecipes();
ret[origin.length + 1] = EnumChatFormatting.AQUA + "Speed multiplier: "
+ EnumChatFormatting.GOLD
+ this.getSpeedBonus();
ret[origin.length + 2] = EnumChatFormatting.AQUA + "Pieces: " + EnumChatFormatting.GOLD + this.piece;
return ret;
}
@Override
public void saveNBTData(NBTTagCompound aNBT) {
super.saveNBTData(aNBT);
aNBT.setInteger("piece", piece);
aNBT.setByte("mode", mode);
}
@Override
public void loadNBTData(final NBTTagCompound aNBT) {
super.loadNBTData(aNBT);
piece = aNBT.getInteger("piece");
mode = aNBT.getByte("mode");
}
@Override
protected GT_Multiblock_Tooltip_Builder createTooltip() {
final GT_Multiblock_Tooltip_Builder tt = new GT_Multiblock_Tooltip_Builder();
tt.addMachineType(Tooltip_MoleculeDeconstructor_MachineType)
.addInfo(Tooltip_MoleculeDeconstructor_00)
.addInfo(Tooltip_MoleculeDeconstructor_01)
.addInfo(Tooltip_MoleculeDeconstructor_02)
.addInfo(Tooltip_MoleculeDeconstructor_03)
.addInfo(Tooltip_MoleculeDeconstructor_04)
.addInfo(Tooltip_MoleculeDeconstructor_05)
.addInfo(textScrewdriverChangeMode)
.addSeparator()
.addInfo(StructureTooComplex)
.addInfo(BLUE_PRINT_INFO) | .addController(textFrontBottom) | 14 | 2023-10-16 09:57:15+00:00 | 12k |
wyjsonGo/GoRouter | GoRouter-Api/src/main/java/com/wyjson/router/model/Card.java | [
{
"identifier": "GoRouter",
"path": "GoRouter-Api/src/main/java/com/wyjson/router/GoRouter.java",
"snippet": "public final class GoRouter {\n\n private final Handler mHandler = new Handler(Looper.getMainLooper());\n private volatile static ThreadPoolExecutor executor = DefaultPoolExecutor.getInsta... | import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.SparseArray;
import androidx.activity.result.ActivityResultLauncher;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityOptionsCompat;
import com.wyjson.router.GoRouter;
import com.wyjson.router.callback.GoCallback;
import com.wyjson.router.core.RouteCenter;
import com.wyjson.router.enums.RouteType;
import com.wyjson.router.exception.NoFoundRouteException;
import com.wyjson.router.exception.RouterException;
import com.wyjson.router.interfaces.IJsonService;
import com.wyjson.router.utils.TextUtils;
import java.io.Serializable;
import java.util.ArrayList; | 8,245 | package com.wyjson.router.model;
public final class Card extends CardMeta {
private Uri uri;
private Bundle mBundle;
private int flags = 0;
private boolean greenChannel;// 绿色通道(跳过所有的拦截器)
private String action;
private Context context;
private IJsonService jsonService;
private int enterAnim = -1;// 转场动画
private int exitAnim = -1;
private ActivityOptionsCompat activityOptionsCompat;// 转场动画(API16+)
private Throwable interceptorException;// 拦截执行中断异常信息
private int timeout = 300;// go() timeout, TimeUnit.Second
public void setUri(Uri uri) {
if (uri == null || TextUtils.isEmpty(uri.toString()) || TextUtils.isEmpty(uri.getPath())) {
throw new RouterException("uri Parameter is invalid!");
}
this.uri = uri;
setPath(uri.getPath());
}
public Uri getUri() {
return uri;
}
public ActivityOptionsCompat getActivityOptionsCompat() {
return activityOptionsCompat;
}
public int getEnterAnim() {
return enterAnim;
}
public int getExitAnim() {
return exitAnim;
}
public Card(Uri uri) {
setUri(uri);
this.mBundle = new Bundle();
}
public Card(String path, Bundle bundle) {
setPath(path);
this.mBundle = (null == bundle ? new Bundle() : bundle);
}
@Nullable
public Object go() {
return go(null, this, -1, null, null);
}
@Nullable
public Object go(Context context) {
return go(context, this, -1, null, null);
}
@Nullable | package com.wyjson.router.model;
public final class Card extends CardMeta {
private Uri uri;
private Bundle mBundle;
private int flags = 0;
private boolean greenChannel;// 绿色通道(跳过所有的拦截器)
private String action;
private Context context;
private IJsonService jsonService;
private int enterAnim = -1;// 转场动画
private int exitAnim = -1;
private ActivityOptionsCompat activityOptionsCompat;// 转场动画(API16+)
private Throwable interceptorException;// 拦截执行中断异常信息
private int timeout = 300;// go() timeout, TimeUnit.Second
public void setUri(Uri uri) {
if (uri == null || TextUtils.isEmpty(uri.toString()) || TextUtils.isEmpty(uri.getPath())) {
throw new RouterException("uri Parameter is invalid!");
}
this.uri = uri;
setPath(uri.getPath());
}
public Uri getUri() {
return uri;
}
public ActivityOptionsCompat getActivityOptionsCompat() {
return activityOptionsCompat;
}
public int getEnterAnim() {
return enterAnim;
}
public int getExitAnim() {
return exitAnim;
}
public Card(Uri uri) {
setUri(uri);
this.mBundle = new Bundle();
}
public Card(String path, Bundle bundle) {
setPath(path);
this.mBundle = (null == bundle ? new Bundle() : bundle);
}
@Nullable
public Object go() {
return go(null, this, -1, null, null);
}
@Nullable
public Object go(Context context) {
return go(context, this, -1, null, null);
}
@Nullable | public Object go(Context context, GoCallback callback) { | 1 | 2023-10-18 13:52:07+00:00 | 12k |
trpc-group/trpc-java | trpc-test/trpc-test-integration/src/integration-test/java/com/tencent/trpc/integration/test/stub/StreamingEchoAPI.java | [
{
"identifier": "RpcContext",
"path": "trpc-core/src/main/java/com/tencent/trpc/core/rpc/RpcContext.java",
"snippet": "public abstract class RpcContext {\n\n /**\n * [Framework usage]: Parameter sharing during context transfer, ServerContext.newClientContext will pass t\n * his information.\n... | import com.tencent.trpc.core.rpc.RpcContext;
import com.tencent.trpc.core.rpc.anno.TRpcMethod;
import com.tencent.trpc.core.rpc.anno.TRpcService;
import com.tencent.trpc.integration.test.stub.EchoService.EchoRequest;
import com.tencent.trpc.integration.test.stub.EchoService.EchoResponse;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono; | 9,790 | /*
* Tencent is pleased to support the open source community by making tRPC available.
*
* Copyright (C) 2023 THL A29 Limited, a Tencent company.
* All rights reserved.
*
* If you have downloaded a copy of the tRPC source code from Tencent,
* please note that tRPC source code is licensed under the Apache 2.0 License,
* A copy of the Apache 2.0 License can be found in the LICENSE file.
*/
package com.tencent.trpc.integration.test.stub;
/**
* Generated by trpc-java-codegen
*/
@TRpcService(name = "com.tencent.trpc.integration.test.StreamingEcho")
public interface StreamingEchoAPI {
/**
* clientStreamEcho
*
* @param context context
* @param request request
* @return {@link EchoResponse}
*/
@TRpcMethod(name = "clientStreamEcho") | /*
* Tencent is pleased to support the open source community by making tRPC available.
*
* Copyright (C) 2023 THL A29 Limited, a Tencent company.
* All rights reserved.
*
* If you have downloaded a copy of the tRPC source code from Tencent,
* please note that tRPC source code is licensed under the Apache 2.0 License,
* A copy of the Apache 2.0 License can be found in the LICENSE file.
*/
package com.tencent.trpc.integration.test.stub;
/**
* Generated by trpc-java-codegen
*/
@TRpcService(name = "com.tencent.trpc.integration.test.StreamingEcho")
public interface StreamingEchoAPI {
/**
* clientStreamEcho
*
* @param context context
* @param request request
* @return {@link EchoResponse}
*/
@TRpcMethod(name = "clientStreamEcho") | Mono<EchoResponse> clientStreamEcho(RpcContext context, Publisher<EchoRequest> request); | 2 | 2023-10-19 10:54:11+00:00 | 12k |
freedom-introvert/YouTubeSendCommentAntiFraud | YTSendCommAntiFraud/app/src/main/java/icu/freedomintrovert/YTSendCommAntiFraud/DialogCommentChecker.java | [
{
"identifier": "Comment",
"path": "YTSendCommAntiFraud/app/src/main/java/icu/freedomintrovert/YTSendCommAntiFraud/comment/Comment.java",
"snippet": "public class Comment {\r\n public String commentText;\r\n public String commentId;\r\n\r\n public Comment() {\r\n }\r\n\r\n\r\n public Comm... | import android.app.NotificationManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Base64;
import android.view.View;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import java.util.Date;
import java.util.Locale;
import icu.freedomintrovert.YTSendCommAntiFraud.comment.Comment;
import icu.freedomintrovert.YTSendCommAntiFraud.comment.HistoryComment;
import icu.freedomintrovert.YTSendCommAntiFraud.comment.VideoComment;
import icu.freedomintrovert.YTSendCommAntiFraud.comment.VideoCommentSection;
import icu.freedomintrovert.YTSendCommAntiFraud.db.StatisticsDB;
import icu.freedomintrovert.YTSendCommAntiFraud.grpcApi.nestedIntoBase64.SortBy;
import icu.freedomintrovert.YTSendCommAntiFraud.rxObservables.FindCommentObservableOnSubscribe;
import icu.freedomintrovert.YTSendCommAntiFraud.utils.OkHttpUtils;
import icu.freedomintrovert.YTSendCommAntiFraud.utils.ProtobufUtils;
import icu.freedomintrovert.YTSendCommAntiFraud.view.ProgressBarDialog;
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.disposables.CompositeDisposable;
import io.reactivex.rxjava3.observers.DisposableObserver;
import io.reactivex.rxjava3.schedulers.Schedulers;
| 10,586 | package icu.freedomintrovert.YTSendCommAntiFraud;
public class DialogCommentChecker {
Context context;
StatisticsDB statisticsDB;
Config config;
CompositeDisposable compositeDisposable = new CompositeDisposable();
public DialogCommentChecker(Context context, StatisticsDB statisticsDB, Config config) {
this.context = context;
this.statisticsDB = statisticsDB;
this.config = config;
}
public void check(Comment comment, String videoId, int commentSectionType, byte[] context1, Bundle headers, boolean needToWait, OnExitListener onExitListener, Date sendDate){
VideoCommentSection videoCommentSection = new VideoCommentSection(OkHttpUtils.getOkHttpClient(),
context1,
ProtobufUtils.escapeBase64(Base64.encodeToString(ProtobufUtils.generateContinuation(videoId, SortBy.latest).toByteArray(), Base64.DEFAULT)),
headers,
true);
String msg = context.getString(R.string.wait_xxx_ms);
long waitTime = config.getWaitTimeAfterCommentSent();
ProgressBarDialog progressBarDialog = new ProgressBarDialog.Builder(context)
.setTitle(context.getString(R.string.checking))
.setMessage(String.format(Locale.getDefault(), msg, 0, waitTime))
.setIndeterminate(true)
.setPositiveButton(context.getString(R.string.waiting_in_the_background),null)
.setCancelable(false)
.show();
FindCommentObservableOnSubscribe findCommentObservableOnSubscribe = new FindCommentObservableOnSubscribe(videoCommentSection, new VideoComment(comment.commentText, comment.commentId, videoId), statisticsDB, config, needToWait, sendDate);
Observable<FindCommentObservableOnSubscribe.BaseNextValue> observable = Observable.create(findCommentObservableOnSubscribe);
DisposableObserver<FindCommentObservableOnSubscribe.BaseNextValue> disposableObserver = new DisposableObserver<>() {
@Override
protected void onStart() {
progressBarDialog.setIndeterminate(false);
}
@Override
public void onNext(@NonNull FindCommentObservableOnSubscribe.BaseNextValue value) {
if (value instanceof FindCommentObservableOnSubscribe.OnNewSleepProgressValue) {
FindCommentObservableOnSubscribe.OnNewSleepProgressValue progressValue = (FindCommentObservableOnSubscribe.OnNewSleepProgressValue) value;
progressBarDialog.setMessage(String.format(Locale.getDefault(), msg, progressValue.waitedTime, waitTime));
progressBarDialog.setProgress(progressValue.progress);
} else if (value instanceof FindCommentObservableOnSubscribe.OnStartCheckValue) {
progressBarDialog.getButton(DialogInterface.BUTTON_POSITIVE).setEnabled(false);
progressBarDialog.setIndeterminate(true);
} else if (value instanceof FindCommentObservableOnSubscribe.OnNextPageFormHasAccountValue) {
FindCommentObservableOnSubscribe.OnNextPageFormHasAccountValue nextPageValue = (FindCommentObservableOnSubscribe.OnNextPageFormHasAccountValue) value;
progressBarDialog.setMessage(String.format(Locale.getDefault(), context.getString(R.string.find_has_account_comment_list_dialog), nextPageValue.pageNumber));
} else if (value instanceof FindCommentObservableOnSubscribe.OnNextPageFormNotAccountValue) {
FindCommentObservableOnSubscribe.OnNextPageFormNotAccountValue nextPageValue = (FindCommentObservableOnSubscribe.OnNextPageFormNotAccountValue) value;
progressBarDialog.setMessage(String.format(Locale.getDefault(), context.getString(R.string.find_not_account_comment_list_dialog), nextPageValue.pageNumber));
} else if (value instanceof FindCommentObservableOnSubscribe.OnFondYourCommentFromHasAccountVale) {
progressBarDialog.setMessage(context.getString(R.string.continue_to_check_if_is_shadow_banned_dialog));
} else if (value instanceof FindCommentObservableOnSubscribe.OnSearchAgainProgressForNoAnchorValue){
FindCommentObservableOnSubscribe.OnSearchAgainProgressForNoAnchorValue value1 = (FindCommentObservableOnSubscribe.OnSearchAgainProgressForNoAnchorValue) value;
progressBarDialog.setMessage(String.format(Locale.getDefault(), context.getString(R.string.OnSearchAgainProgressForNoAnchor), value1.retry, value1.totalRetry, value1.waitedTime, value1.interval));
progressBarDialog.setIndeterminate(false);
progressBarDialog.setProgress(value1.progress);
} else if (value instanceof FindCommentObservableOnSubscribe.OnSearchAgainProgressValue) {
FindCommentObservableOnSubscribe.OnSearchAgainProgressValue value1 = (FindCommentObservableOnSubscribe.OnSearchAgainProgressValue) value;
progressBarDialog.setMessage(String.format(Locale.getDefault(), context.getString(R.string.OnSearchAgainProgress), value1.retry, value1.totalRetry, value1.waitedTime, value1.interval));
progressBarDialog.setIndeterminate(false);
progressBarDialog.setProgress(value1.progress);
} else if (value instanceof FindCommentObservableOnSubscribe.OnSearchAgainGetCommentsValue) {
FindCommentObservableOnSubscribe.OnSearchAgainGetCommentsValue value1 = (FindCommentObservableOnSubscribe.OnSearchAgainGetCommentsValue) value;
progressBarDialog.setMessage(String.format(Locale.getDefault(), context.getString(R.string.OnSearchAgainGetComments), value1.pageNumber));
progressBarDialog.setIndeterminate(true);
} else if (value instanceof FindCommentObservableOnSubscribe.OnReCheckIfIsDeletedValue){
FindCommentObservableOnSubscribe.OnReCheckIfIsDeletedValue value1 = (FindCommentObservableOnSubscribe.OnReCheckIfIsDeletedValue) value;
progressBarDialog.setMessage(String.format(Locale.getDefault(),context.getString(R.string.OnReCheckIfIsDeleted),value1.pageNumber));
} else if (value instanceof FindCommentObservableOnSubscribe.OnYourCommentIsDeleteStateValue) {
progressBarDialog.dismiss();
| package icu.freedomintrovert.YTSendCommAntiFraud;
public class DialogCommentChecker {
Context context;
StatisticsDB statisticsDB;
Config config;
CompositeDisposable compositeDisposable = new CompositeDisposable();
public DialogCommentChecker(Context context, StatisticsDB statisticsDB, Config config) {
this.context = context;
this.statisticsDB = statisticsDB;
this.config = config;
}
public void check(Comment comment, String videoId, int commentSectionType, byte[] context1, Bundle headers, boolean needToWait, OnExitListener onExitListener, Date sendDate){
VideoCommentSection videoCommentSection = new VideoCommentSection(OkHttpUtils.getOkHttpClient(),
context1,
ProtobufUtils.escapeBase64(Base64.encodeToString(ProtobufUtils.generateContinuation(videoId, SortBy.latest).toByteArray(), Base64.DEFAULT)),
headers,
true);
String msg = context.getString(R.string.wait_xxx_ms);
long waitTime = config.getWaitTimeAfterCommentSent();
ProgressBarDialog progressBarDialog = new ProgressBarDialog.Builder(context)
.setTitle(context.getString(R.string.checking))
.setMessage(String.format(Locale.getDefault(), msg, 0, waitTime))
.setIndeterminate(true)
.setPositiveButton(context.getString(R.string.waiting_in_the_background),null)
.setCancelable(false)
.show();
FindCommentObservableOnSubscribe findCommentObservableOnSubscribe = new FindCommentObservableOnSubscribe(videoCommentSection, new VideoComment(comment.commentText, comment.commentId, videoId), statisticsDB, config, needToWait, sendDate);
Observable<FindCommentObservableOnSubscribe.BaseNextValue> observable = Observable.create(findCommentObservableOnSubscribe);
DisposableObserver<FindCommentObservableOnSubscribe.BaseNextValue> disposableObserver = new DisposableObserver<>() {
@Override
protected void onStart() {
progressBarDialog.setIndeterminate(false);
}
@Override
public void onNext(@NonNull FindCommentObservableOnSubscribe.BaseNextValue value) {
if (value instanceof FindCommentObservableOnSubscribe.OnNewSleepProgressValue) {
FindCommentObservableOnSubscribe.OnNewSleepProgressValue progressValue = (FindCommentObservableOnSubscribe.OnNewSleepProgressValue) value;
progressBarDialog.setMessage(String.format(Locale.getDefault(), msg, progressValue.waitedTime, waitTime));
progressBarDialog.setProgress(progressValue.progress);
} else if (value instanceof FindCommentObservableOnSubscribe.OnStartCheckValue) {
progressBarDialog.getButton(DialogInterface.BUTTON_POSITIVE).setEnabled(false);
progressBarDialog.setIndeterminate(true);
} else if (value instanceof FindCommentObservableOnSubscribe.OnNextPageFormHasAccountValue) {
FindCommentObservableOnSubscribe.OnNextPageFormHasAccountValue nextPageValue = (FindCommentObservableOnSubscribe.OnNextPageFormHasAccountValue) value;
progressBarDialog.setMessage(String.format(Locale.getDefault(), context.getString(R.string.find_has_account_comment_list_dialog), nextPageValue.pageNumber));
} else if (value instanceof FindCommentObservableOnSubscribe.OnNextPageFormNotAccountValue) {
FindCommentObservableOnSubscribe.OnNextPageFormNotAccountValue nextPageValue = (FindCommentObservableOnSubscribe.OnNextPageFormNotAccountValue) value;
progressBarDialog.setMessage(String.format(Locale.getDefault(), context.getString(R.string.find_not_account_comment_list_dialog), nextPageValue.pageNumber));
} else if (value instanceof FindCommentObservableOnSubscribe.OnFondYourCommentFromHasAccountVale) {
progressBarDialog.setMessage(context.getString(R.string.continue_to_check_if_is_shadow_banned_dialog));
} else if (value instanceof FindCommentObservableOnSubscribe.OnSearchAgainProgressForNoAnchorValue){
FindCommentObservableOnSubscribe.OnSearchAgainProgressForNoAnchorValue value1 = (FindCommentObservableOnSubscribe.OnSearchAgainProgressForNoAnchorValue) value;
progressBarDialog.setMessage(String.format(Locale.getDefault(), context.getString(R.string.OnSearchAgainProgressForNoAnchor), value1.retry, value1.totalRetry, value1.waitedTime, value1.interval));
progressBarDialog.setIndeterminate(false);
progressBarDialog.setProgress(value1.progress);
} else if (value instanceof FindCommentObservableOnSubscribe.OnSearchAgainProgressValue) {
FindCommentObservableOnSubscribe.OnSearchAgainProgressValue value1 = (FindCommentObservableOnSubscribe.OnSearchAgainProgressValue) value;
progressBarDialog.setMessage(String.format(Locale.getDefault(), context.getString(R.string.OnSearchAgainProgress), value1.retry, value1.totalRetry, value1.waitedTime, value1.interval));
progressBarDialog.setIndeterminate(false);
progressBarDialog.setProgress(value1.progress);
} else if (value instanceof FindCommentObservableOnSubscribe.OnSearchAgainGetCommentsValue) {
FindCommentObservableOnSubscribe.OnSearchAgainGetCommentsValue value1 = (FindCommentObservableOnSubscribe.OnSearchAgainGetCommentsValue) value;
progressBarDialog.setMessage(String.format(Locale.getDefault(), context.getString(R.string.OnSearchAgainGetComments), value1.pageNumber));
progressBarDialog.setIndeterminate(true);
} else if (value instanceof FindCommentObservableOnSubscribe.OnReCheckIfIsDeletedValue){
FindCommentObservableOnSubscribe.OnReCheckIfIsDeletedValue value1 = (FindCommentObservableOnSubscribe.OnReCheckIfIsDeletedValue) value;
progressBarDialog.setMessage(String.format(Locale.getDefault(),context.getString(R.string.OnReCheckIfIsDeleted),value1.pageNumber));
} else if (value instanceof FindCommentObservableOnSubscribe.OnYourCommentIsDeleteStateValue) {
progressBarDialog.dismiss();
| dialogState(context.getString(R.string.check_result), context.getString(R.string.comment_has_been_deleted) + comment.commentText, HistoryComment.STATE_DELETED,onExitListener);
| 1 | 2023-10-15 01:18:28+00:00 | 12k |
New-Barams/This-Year-Ajaja-BE | src/main/java/com/newbarams/ajaja/module/plan/application/LoadPlanService.java | [
{
"identifier": "ErrorCode",
"path": "src/main/java/com/newbarams/ajaja/global/exception/ErrorCode.java",
"snippet": "@Getter\n@RequiredArgsConstructor\npublic enum ErrorCode {\n\t// 400\n\tBEAN_VALIDATION_FAIL_EXCEPTION(BAD_REQUEST, \"올바르지 않은 데이터입니다.\"),\n\tINVALID_REQUEST(BAD_REQUEST, \"올바른 형식의 데이터가 입... | import static com.newbarams.ajaja.global.exception.ErrorCode.*;
import java.util.List;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.newbarams.ajaja.global.exception.AjajaException;
import com.newbarams.ajaja.module.feedback.application.model.PlanFeedbackInfo;
import com.newbarams.ajaja.module.plan.domain.Plan;
import com.newbarams.ajaja.module.plan.domain.PlanRepository;
import com.newbarams.ajaja.module.plan.dto.PlanRequest;
import com.newbarams.ajaja.module.plan.dto.PlanResponse;
import com.newbarams.ajaja.module.plan.infra.PlanQueryRepository;
import com.newbarams.ajaja.module.plan.mapper.PlanMapper;
import lombok.RequiredArgsConstructor; | 7,290 | package com.newbarams.ajaja.module.plan.application;
@Service
@RequiredArgsConstructor
@Transactional(readOnly = true)
public class LoadPlanService {
private final PlanRepository planRepository;
private final PlanQueryRepository planQueryRepository;
private final PlanMapper planMapper;
public PlanResponse.Detail loadByIdAndOptionalUser(Long userId, Long id) {
return planQueryRepository.findPlanDetailByIdAndOptionalUser(userId, id)
.orElseThrow(() -> AjajaException.withId(id, NOT_FOUND_PLAN));
}
public Plan loadByUserIdAndPlanId(Long userId, Long id) {
return planQueryRepository.findByUserIdAndPlanId(userId, id);
}
public Plan loadPlanOrElseThrow(Long id) {
return planRepository.findById(id)
.orElseThrow(() -> AjajaException.withId(id, NOT_FOUND_PLAN));
}
public PlanFeedbackInfo loadPlanFeedbackInfoByPlanId(Long userId, Long planId) {
Plan plan = loadByUserIdAndPlanId(userId, planId);
return planMapper.toModel(plan);
}
| package com.newbarams.ajaja.module.plan.application;
@Service
@RequiredArgsConstructor
@Transactional(readOnly = true)
public class LoadPlanService {
private final PlanRepository planRepository;
private final PlanQueryRepository planQueryRepository;
private final PlanMapper planMapper;
public PlanResponse.Detail loadByIdAndOptionalUser(Long userId, Long id) {
return planQueryRepository.findPlanDetailByIdAndOptionalUser(userId, id)
.orElseThrow(() -> AjajaException.withId(id, NOT_FOUND_PLAN));
}
public Plan loadByUserIdAndPlanId(Long userId, Long id) {
return planQueryRepository.findByUserIdAndPlanId(userId, id);
}
public Plan loadPlanOrElseThrow(Long id) {
return planRepository.findById(id)
.orElseThrow(() -> AjajaException.withId(id, NOT_FOUND_PLAN));
}
public PlanFeedbackInfo loadPlanFeedbackInfoByPlanId(Long userId, Long planId) {
Plan plan = loadByUserIdAndPlanId(userId, planId);
return planMapper.toModel(plan);
}
| public List<PlanResponse.GetAll> loadAllPlans(PlanRequest.GetAll request) { | 4 | 2023-10-23 07:24:17+00:00 | 12k |
eclipse-jgit/jgit | org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/BasePackBitmapIndexTest.java | [
{
"identifier": "StoredBitmap",
"path": "org.eclipse.jgit/src/org/eclipse/jgit/internal/storage/file/BasePackBitmapIndex.java",
"snippet": "static final class StoredBitmap extends ObjectIdOwnerMap.Entry {\n\tprivate volatile Object bitmapContainer;\n\tprivate final int flags;\n\n\tStoredBitmap(AnyObject... | import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.eclipse.jgit.internal.storage.file.BasePackBitmapIndex.StoredBitmap;
import org.eclipse.jgit.lib.AnyObjectId;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.ObjectIdOwnerMap;
import org.junit.Before;
import org.junit.Test;
import com.googlecode.javaewah.EWAHCompressedBitmap; | 10,667 | /*
* Copyright (c) 2023, Google LLC and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Distribution License v. 1.0 which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
package org.eclipse.jgit.internal.storage.file;
public class BasePackBitmapIndexTest {
private ObjectId baseOid;
| /*
* Copyright (c) 2023, Google LLC and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Distribution License v. 1.0 which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
package org.eclipse.jgit.internal.storage.file;
public class BasePackBitmapIndexTest {
private ObjectId baseOid;
| private StoredBitmap baseBitmap; | 0 | 2023-10-20 15:09:17+00:00 | 12k |
starfish-studios/Naturalist | common/src/main/java/com/starfish_studios/naturalist/common/entity/Firefly.java | [
{
"identifier": "FlyingWanderGoal",
"path": "common/src/main/java/com/starfish_studios/naturalist/common/entity/core/ai/goal/FlyingWanderGoal.java",
"snippet": "public class FlyingWanderGoal extends Goal {\n protected final PathfinderMob mob;\n\n public FlyingWanderGoal(PathfinderMob mob) {\n ... | import com.starfish_studios.naturalist.common.entity.core.ai.goal.FlyingWanderGoal;
import com.starfish_studios.naturalist.core.registry.NaturalistSoundEvents;
import com.starfish_studios.naturalist.core.registry.NaturalistTags;
import net.minecraft.core.BlockPos;
import net.minecraft.core.particles.BlockParticleOption;
import net.minecraft.core.particles.ParticleTypes;
import net.minecraft.network.syncher.EntityDataAccessor;
import net.minecraft.network.syncher.EntityDataSerializers;
import net.minecraft.network.syncher.SynchedEntityData;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.sounds.SoundSource;
import net.minecraft.util.Mth;
import net.minecraft.util.RandomSource;
import net.minecraft.world.damagesource.DamageSource;
import net.minecraft.world.entity.*;
import net.minecraft.world.entity.ai.attributes.AttributeSupplier;
import net.minecraft.world.entity.ai.attributes.Attributes;
import net.minecraft.world.entity.ai.control.FlyingMoveControl;
import net.minecraft.world.entity.ai.goal.FloatGoal;
import net.minecraft.world.entity.ai.goal.MoveToBlockGoal;
import net.minecraft.world.entity.ai.navigation.FlyingPathNavigation;
import net.minecraft.world.entity.ai.navigation.PathNavigation;
import net.minecraft.world.entity.animal.Animal;
import net.minecraft.world.entity.animal.FlyingAnimal;
import net.minecraft.world.entity.monster.Monster;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.LevelReader;
import net.minecraft.world.level.ServerLevelAccessor;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.pathfinder.BlockPathTypes;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import software.bernie.geckolib3.core.IAnimatable;
import software.bernie.geckolib3.core.PlayState;
import software.bernie.geckolib3.core.builder.AnimationBuilder;
import software.bernie.geckolib3.core.controller.AnimationController;
import software.bernie.geckolib3.core.event.predicate.AnimationEvent;
import software.bernie.geckolib3.core.manager.AnimationData;
import software.bernie.geckolib3.core.manager.AnimationFactory;
import software.bernie.geckolib3.util.GeckoLibUtil; | 8,045 | package com.starfish_studios.naturalist.common.entity;
public class Firefly extends Animal implements FlyingAnimal, IAnimatable {
private static final EntityDataAccessor<Integer> GLOW_TICKS_REMAINING = SynchedEntityData.defineId(Firefly.class, EntityDataSerializers.INT);
private static final EntityDataAccessor<Integer> SUN_TICKS = SynchedEntityData.defineId(Firefly.class, EntityDataSerializers.INT);
private final AnimationFactory factory = GeckoLibUtil.createFactory(this);
@Override
@NotNull
public MobType getMobType() {
return MobType.ARTHROPOD;
}
public Firefly(EntityType<? extends Animal> entityType, Level level) {
super(entityType, level);
this.moveControl = new FlyingMoveControl(this, 20, true);
this.setPathfindingMalus(BlockPathTypes.DANGER_FIRE, -1.0F);
this.setPathfindingMalus(BlockPathTypes.WATER, -1.0F);
this.setPathfindingMalus(BlockPathTypes.WATER_BORDER, 16.0F);
this.setPathfindingMalus(BlockPathTypes.COCOA, -1.0F);
this.setPathfindingMalus(BlockPathTypes.FENCE, -1.0F);
}
@Override
protected PathNavigation createNavigation(Level pLevel) {
FlyingPathNavigation navigation = new FlyingPathNavigation(this, pLevel) {
public boolean isStableDestination(BlockPos pPos) {
return !this.level.getBlockState(pPos.below()).isAir();
}
};
navigation.setCanOpenDoors(false);
navigation.setCanFloat(false);
navigation.setCanPassDoors(true);
return navigation;
}
@Override
protected float getStandingEyeHeight(Pose pPose, EntityDimensions pSize) {
return pSize.height * 0.5F;
}
@Override
public boolean causeFallDamage(float pFallDistance, float pMultiplier, DamageSource pSource) {
return false;
}
@Override
protected void checkFallDamage(double pY, boolean pOnGround, BlockState pState, BlockPos pPos) {
}
@Override
protected void registerGoals() {
super.registerGoals();
this.goalSelector.addGoal(1, new FireflyHideInGrassGoal(this, 1.2F, 10, 4));
this.goalSelector.addGoal(2, new FlyingWanderGoal(this));
this.goalSelector.addGoal(3, new FloatGoal(this));
}
public static AttributeSupplier.Builder createAttributes() {
return Mob.createMobAttributes().add(Attributes.MAX_HEALTH, 6.0D).add(Attributes.FLYING_SPEED, 0.6F).add(Attributes.MOVEMENT_SPEED, 0.3F);
}
public static boolean checkFireflySpawnRules(EntityType<? extends Firefly> pType, ServerLevelAccessor pLevel, MobSpawnType pReason, BlockPos pPos, RandomSource pRandom) {
return Monster.isDarkEnoughToSpawn(pLevel, pPos, pRandom) && pLevel.getBlockState(pPos.below()).is(NaturalistTags.BlockTags.FIREFLIES_SPAWNABLE_ON);
}
@Nullable
@Override
public AgeableMob getBreedOffspring(ServerLevel p_146743_, AgeableMob p_146744_) {
return null;
}
@Override
public boolean isFood(ItemStack pStack) {
return false;
}
@Override
protected void defineSynchedData() {
super.defineSynchedData();
this.entityData.define(GLOW_TICKS_REMAINING, 0);
this.entityData.define(SUN_TICKS, 0);
}
public boolean isGlowing() {
return this.entityData.get(GLOW_TICKS_REMAINING) > 0;
}
public int getGlowTicksRemaining() {
return this.entityData.get(GLOW_TICKS_REMAINING);
}
private void setGlowTicks(int ticks) {
this.entityData.set(GLOW_TICKS_REMAINING, ticks);
}
public int getSunTicks() {
return this.entityData.get(SUN_TICKS);
}
private void setSunTicks(int ticks) {
this.entityData.set(SUN_TICKS, ticks);
}
@Override
public void aiStep() {
super.aiStep();
int ticks = this.getGlowTicksRemaining();
if (ticks > 0) {
this.setGlowTicks(ticks - 1);
}
if (this.canGlow()) {
if (this.random.nextFloat() <= 0.01 && !this.isGlowing()) {
this.setGlowTicks(40 + this.random.nextInt(20));
}
}
if (this.isSunBurnTick()) {
this.setSunTicks(this.getSunTicks() + 1);
if (this.getSunTicks() > 600) {
BlockPos pos = this.blockPosition();
if (!level.isClientSide) {
for(int i = 0; i < 20; ++i) {
double x = random.nextGaussian() * 0.02D;
double y = random.nextGaussian() * 0.02D;
double z = random.nextGaussian() * 0.02D;
((ServerLevel)level).sendParticles(ParticleTypes.POOF, pos.getX() + 0.5D, pos.getY(), pos.getZ() + 0.5D, 1, x, y, z, 0.15F);
}
} | package com.starfish_studios.naturalist.common.entity;
public class Firefly extends Animal implements FlyingAnimal, IAnimatable {
private static final EntityDataAccessor<Integer> GLOW_TICKS_REMAINING = SynchedEntityData.defineId(Firefly.class, EntityDataSerializers.INT);
private static final EntityDataAccessor<Integer> SUN_TICKS = SynchedEntityData.defineId(Firefly.class, EntityDataSerializers.INT);
private final AnimationFactory factory = GeckoLibUtil.createFactory(this);
@Override
@NotNull
public MobType getMobType() {
return MobType.ARTHROPOD;
}
public Firefly(EntityType<? extends Animal> entityType, Level level) {
super(entityType, level);
this.moveControl = new FlyingMoveControl(this, 20, true);
this.setPathfindingMalus(BlockPathTypes.DANGER_FIRE, -1.0F);
this.setPathfindingMalus(BlockPathTypes.WATER, -1.0F);
this.setPathfindingMalus(BlockPathTypes.WATER_BORDER, 16.0F);
this.setPathfindingMalus(BlockPathTypes.COCOA, -1.0F);
this.setPathfindingMalus(BlockPathTypes.FENCE, -1.0F);
}
@Override
protected PathNavigation createNavigation(Level pLevel) {
FlyingPathNavigation navigation = new FlyingPathNavigation(this, pLevel) {
public boolean isStableDestination(BlockPos pPos) {
return !this.level.getBlockState(pPos.below()).isAir();
}
};
navigation.setCanOpenDoors(false);
navigation.setCanFloat(false);
navigation.setCanPassDoors(true);
return navigation;
}
@Override
protected float getStandingEyeHeight(Pose pPose, EntityDimensions pSize) {
return pSize.height * 0.5F;
}
@Override
public boolean causeFallDamage(float pFallDistance, float pMultiplier, DamageSource pSource) {
return false;
}
@Override
protected void checkFallDamage(double pY, boolean pOnGround, BlockState pState, BlockPos pPos) {
}
@Override
protected void registerGoals() {
super.registerGoals();
this.goalSelector.addGoal(1, new FireflyHideInGrassGoal(this, 1.2F, 10, 4));
this.goalSelector.addGoal(2, new FlyingWanderGoal(this));
this.goalSelector.addGoal(3, new FloatGoal(this));
}
public static AttributeSupplier.Builder createAttributes() {
return Mob.createMobAttributes().add(Attributes.MAX_HEALTH, 6.0D).add(Attributes.FLYING_SPEED, 0.6F).add(Attributes.MOVEMENT_SPEED, 0.3F);
}
public static boolean checkFireflySpawnRules(EntityType<? extends Firefly> pType, ServerLevelAccessor pLevel, MobSpawnType pReason, BlockPos pPos, RandomSource pRandom) {
return Monster.isDarkEnoughToSpawn(pLevel, pPos, pRandom) && pLevel.getBlockState(pPos.below()).is(NaturalistTags.BlockTags.FIREFLIES_SPAWNABLE_ON);
}
@Nullable
@Override
public AgeableMob getBreedOffspring(ServerLevel p_146743_, AgeableMob p_146744_) {
return null;
}
@Override
public boolean isFood(ItemStack pStack) {
return false;
}
@Override
protected void defineSynchedData() {
super.defineSynchedData();
this.entityData.define(GLOW_TICKS_REMAINING, 0);
this.entityData.define(SUN_TICKS, 0);
}
public boolean isGlowing() {
return this.entityData.get(GLOW_TICKS_REMAINING) > 0;
}
public int getGlowTicksRemaining() {
return this.entityData.get(GLOW_TICKS_REMAINING);
}
private void setGlowTicks(int ticks) {
this.entityData.set(GLOW_TICKS_REMAINING, ticks);
}
public int getSunTicks() {
return this.entityData.get(SUN_TICKS);
}
private void setSunTicks(int ticks) {
this.entityData.set(SUN_TICKS, ticks);
}
@Override
public void aiStep() {
super.aiStep();
int ticks = this.getGlowTicksRemaining();
if (ticks > 0) {
this.setGlowTicks(ticks - 1);
}
if (this.canGlow()) {
if (this.random.nextFloat() <= 0.01 && !this.isGlowing()) {
this.setGlowTicks(40 + this.random.nextInt(20));
}
}
if (this.isSunBurnTick()) {
this.setSunTicks(this.getSunTicks() + 1);
if (this.getSunTicks() > 600) {
BlockPos pos = this.blockPosition();
if (!level.isClientSide) {
for(int i = 0; i < 20; ++i) {
double x = random.nextGaussian() * 0.02D;
double y = random.nextGaussian() * 0.02D;
double z = random.nextGaussian() * 0.02D;
((ServerLevel)level).sendParticles(ParticleTypes.POOF, pos.getX() + 0.5D, pos.getY(), pos.getZ() + 0.5D, 1, x, y, z, 0.15F);
}
} | level.playSound(null, this.blockPosition(), NaturalistSoundEvents.FIREFLY_HIDE.get(), SoundSource.NEUTRAL, 0.7F, 0.9F + level.random.nextFloat() * 0.2F); | 1 | 2023-10-16 21:54:32+00:00 | 12k |
A1anSong/jd_unidbg | unidbg-ios/src/main/java/com/github/unidbg/file/ios/BaseDarwinFileIO.java | [
{
"identifier": "Emulator",
"path": "unidbg-api/src/main/java/com/github/unidbg/Emulator.java",
"snippet": "public interface Emulator<T extends NewFileIO> extends Closeable, ArmDisassembler, Serializable {\n\n int getPointerSize();\n\n boolean is64Bit();\n boolean is32Bit();\n\n int getPageA... | import com.alibaba.fastjson.JSON;
import com.github.unidbg.Emulator;
import com.github.unidbg.file.BaseFileIO;
import com.github.unidbg.file.UnidbgFileFilter;
import com.github.unidbg.ios.file.DirectoryFileIO;
import com.github.unidbg.ios.struct.attr.AttrList;
import com.github.unidbg.ios.struct.attr.AttrReference;
import com.github.unidbg.ios.struct.attr.AttributeSet;
import com.github.unidbg.ios.struct.attr.Dev;
import com.github.unidbg.ios.struct.attr.FinderInfo;
import com.github.unidbg.ios.struct.attr.Fsid;
import com.github.unidbg.ios.struct.attr.ObjId;
import com.github.unidbg.ios.struct.attr.ObjType;
import com.github.unidbg.ios.struct.attr.UserAccess;
import com.github.unidbg.ios.struct.kernel.StatFS;
import com.github.unidbg.pointer.UnidbgStructure;
import com.github.unidbg.unix.UnixEmulator;
import com.github.unidbg.unix.struct.TimeSpec32;
import com.sun.jna.Pointer;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List; | 7,777 | package com.github.unidbg.file.ios;
public abstract class BaseDarwinFileIO extends BaseFileIO implements DarwinFileIO {
private static final Log log = LogFactory.getLog(BaseDarwinFileIO.class);
public static File createAttrFile(File dest) {
if (!dest.exists()) {
throw new IllegalStateException("dest=" + dest);
}
File file;
if (dest.isDirectory()) {
file = new File(dest, UnidbgFileFilter.UNIDBG_PREFIX + ".json");
} else {
file = new File(dest.getParentFile(), UnidbgFileFilter.UNIDBG_PREFIX + "_" + dest.getName() + ".json");
}
return file;
}
public BaseDarwinFileIO(int oflags) {
super(oflags);
}
public int fstat(Emulator<?> emulator, StatStructure stat) {
throw new UnsupportedOperationException(getClass().getName());
}
private int protectionClass;
@Override
public int fcntl(Emulator<?> emulator, int cmd, long arg) {
if (cmd == F_NOCACHE) {
return 0;
}
if (cmd == F_SETLK) {
return 0;
}
if (cmd == F_SETLKW) {
return 0;
}
if (cmd == F_SETPROTECTIONCLASS) {
protectionClass = (int) arg;
return 0;
}
if (cmd == F_GETPROTECTIONCLASS) {
return protectionClass;
}
if(cmd == F_SINGLE_WRITER) {
return 0;
}
if (cmd == F_PREALLOCATE) {
return 0;
}
return super.fcntl(emulator, cmd, arg);
}
public int fstatfs(StatFS statFS) {
throw new UnsupportedOperationException(getClass().getName() + " path=" + getPath());
}
@Override
public int getattrlist(AttrList attrList, Pointer attrBuf, int attrBufSize) {
if (attrList.bitmapcount != ATTR_BIT_MAP_COUNT) {
throw new UnsupportedOperationException("bitmapcount=" + attrList.bitmapcount);
}
AttributeSet attributeSet = attrList.attributeSet;
Pointer pointer = attrBuf.share(4);
List<UnidbgStructure> list = new ArrayList<>();
List<AttrReference> attrReferenceList = new ArrayList<>();
AttributeSet returnedAttributeSet = null;
if ((attributeSet.commonattr & ATTR_CMN_RETURNED_ATTRS) != 0) {
returnedAttributeSet = new AttributeSet(pointer);
pointer = pointer.share(returnedAttributeSet.size());
list.add(returnedAttributeSet);
attributeSet.commonattr &= ~ATTR_CMN_RETURNED_ATTRS;
}
if((attributeSet.commonattr & ATTR_CMN_NAME) != 0) {
String name = FilenameUtils.getName(getPath());
byte[] bytes = name.getBytes(StandardCharsets.UTF_8);
AttrReference attrReference = new AttrReference(pointer, bytes);
attrReferenceList.add(attrReference);
pointer = pointer.share(attrReference.size());
list.add(attrReference);
attributeSet.commonattr &= ~ATTR_CMN_NAME;
if (returnedAttributeSet != null) {
returnedAttributeSet.commonattr |= ATTR_CMN_NAME;
}
}
if((attributeSet.commonattr & ATTR_CMN_DEVID) != 0) { | package com.github.unidbg.file.ios;
public abstract class BaseDarwinFileIO extends BaseFileIO implements DarwinFileIO {
private static final Log log = LogFactory.getLog(BaseDarwinFileIO.class);
public static File createAttrFile(File dest) {
if (!dest.exists()) {
throw new IllegalStateException("dest=" + dest);
}
File file;
if (dest.isDirectory()) {
file = new File(dest, UnidbgFileFilter.UNIDBG_PREFIX + ".json");
} else {
file = new File(dest.getParentFile(), UnidbgFileFilter.UNIDBG_PREFIX + "_" + dest.getName() + ".json");
}
return file;
}
public BaseDarwinFileIO(int oflags) {
super(oflags);
}
public int fstat(Emulator<?> emulator, StatStructure stat) {
throw new UnsupportedOperationException(getClass().getName());
}
private int protectionClass;
@Override
public int fcntl(Emulator<?> emulator, int cmd, long arg) {
if (cmd == F_NOCACHE) {
return 0;
}
if (cmd == F_SETLK) {
return 0;
}
if (cmd == F_SETLKW) {
return 0;
}
if (cmd == F_SETPROTECTIONCLASS) {
protectionClass = (int) arg;
return 0;
}
if (cmd == F_GETPROTECTIONCLASS) {
return protectionClass;
}
if(cmd == F_SINGLE_WRITER) {
return 0;
}
if (cmd == F_PREALLOCATE) {
return 0;
}
return super.fcntl(emulator, cmd, arg);
}
public int fstatfs(StatFS statFS) {
throw new UnsupportedOperationException(getClass().getName() + " path=" + getPath());
}
@Override
public int getattrlist(AttrList attrList, Pointer attrBuf, int attrBufSize) {
if (attrList.bitmapcount != ATTR_BIT_MAP_COUNT) {
throw new UnsupportedOperationException("bitmapcount=" + attrList.bitmapcount);
}
AttributeSet attributeSet = attrList.attributeSet;
Pointer pointer = attrBuf.share(4);
List<UnidbgStructure> list = new ArrayList<>();
List<AttrReference> attrReferenceList = new ArrayList<>();
AttributeSet returnedAttributeSet = null;
if ((attributeSet.commonattr & ATTR_CMN_RETURNED_ATTRS) != 0) {
returnedAttributeSet = new AttributeSet(pointer);
pointer = pointer.share(returnedAttributeSet.size());
list.add(returnedAttributeSet);
attributeSet.commonattr &= ~ATTR_CMN_RETURNED_ATTRS;
}
if((attributeSet.commonattr & ATTR_CMN_NAME) != 0) {
String name = FilenameUtils.getName(getPath());
byte[] bytes = name.getBytes(StandardCharsets.UTF_8);
AttrReference attrReference = new AttrReference(pointer, bytes);
attrReferenceList.add(attrReference);
pointer = pointer.share(attrReference.size());
list.add(attrReference);
attributeSet.commonattr &= ~ATTR_CMN_NAME;
if (returnedAttributeSet != null) {
returnedAttributeSet.commonattr |= ATTR_CMN_NAME;
}
}
if((attributeSet.commonattr & ATTR_CMN_DEVID) != 0) { | Dev dev = new Dev(pointer); | 7 | 2023-10-17 06:13:28+00:00 | 12k |
aabssmc/Skuishy | src/main/java/lol/aabss/skuishy/Skuishy.java | [
{
"identifier": "CustomEvents",
"path": "src/main/java/lol/aabss/skuishy/events/CustomEvents.java",
"snippet": "public class CustomEvents implements Listener {\n\n @EventHandler\n public void onShieldBreak(PlayerItemCooldownEvent e) {\n if (e.getType() == Material.SHIELD) {\n if ... | import ch.njol.skript.Skript;
import ch.njol.skript.SkriptAddon;
import lol.aabss.skuishy.events.CustomEvents;
import lol.aabss.skuishy.hooks.Metrics;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandExecutor;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.IOException; | 7,551 | package lol.aabss.skuishy;
public class Skuishy extends JavaPlugin implements CommandExecutor {
public static Skuishy instance;
private SkriptAddon addon;
public void onEnable() { | package lol.aabss.skuishy;
public class Skuishy extends JavaPlugin implements CommandExecutor {
public static Skuishy instance;
private SkriptAddon addon;
public void onEnable() { | getServer().getPluginManager().registerEvents(new CustomEvents(), this); | 0 | 2023-10-24 23:48:14+00:00 | 12k |
histevehu/12306 | business/src/main/java/com/steve/train/business/service/TrainCarriageService.java | [
{
"identifier": "TrainCarriage",
"path": "business/src/main/java/com/steve/train/business/domain/TrainCarriage.java",
"snippet": "public class TrainCarriage {\n private Long id;\n\n private String trainCode;\n\n private Integer index;\n\n private String seatType;\n\n private Integer seatC... | import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.steve.train.business.domain.TrainCarriage;
import com.steve.train.business.domain.TrainCarriageExample;
import com.steve.train.business.mapper.TrainCarriageMapper;
import com.steve.train.business.req.TrainCarriageQueryReq;
import com.steve.train.business.req.TrainCarriageSaveReq;
import com.steve.train.business.resp.TrainCarriageQueryResp;
import com.steve.train.common.enums.SeatColEnum;
import com.steve.train.common.exception.BusinessException;
import com.steve.train.common.exception.BusinessExceptionEnum;
import com.steve.train.common.resp.PageResp;
import com.steve.train.common.util.SnowFlakeUtil;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import java.util.List; | 10,317 | package com.steve.train.business.service;
/*
* @author : Steve Hu
* @date : 2023-10-29 10:31:17
* @description: 火车车厢服务(FreeMarker生成)
*/
@Service
public class TrainCarriageService {
private static final Logger LOG = LoggerFactory.getLogger(TrainCarriageService.class);
@Resource
private TrainCarriageMapper trainCarriageMapper;
public void save(TrainCarriageSaveReq req) {
DateTime now = DateTime.now();
// 自动计算出列数和总座位数
List<SeatColEnum> seatColEnums = SeatColEnum.getColsByType(req.getSeatType());
req.setColCount(seatColEnums.size());
req.setSeatCount(req.getColCount() * req.getRowCount());
TrainCarriage trainCarriage = BeanUtil.copyProperties(req, TrainCarriage.class);
if (ObjectUtil.isNull(trainCarriage.getId())) {
// 保存之前,先校验唯一键是否存在
TrainCarriage trainCarriageDB = selectByUnique(req.getTrainCode(), req.getIndex());
if (ObjectUtil.isNotEmpty(trainCarriageDB)) {
throw new BusinessException(BusinessExceptionEnum.BUSINESS_TRAIN_CARRIAGE_INDEX_UNIQUE_ERROR);
}
trainCarriage.setId(SnowFlakeUtil.getSnowFlakeNextId());
trainCarriage.setCreateTime(now);
trainCarriage.setUpdateTime(now);
trainCarriageMapper.insert(trainCarriage);
} else {
trainCarriage.setUpdateTime(now);
trainCarriageMapper.updateByPrimaryKey(trainCarriage);
}
}
public PageResp<TrainCarriageQueryResp> queryList(TrainCarriageQueryReq req) { | package com.steve.train.business.service;
/*
* @author : Steve Hu
* @date : 2023-10-29 10:31:17
* @description: 火车车厢服务(FreeMarker生成)
*/
@Service
public class TrainCarriageService {
private static final Logger LOG = LoggerFactory.getLogger(TrainCarriageService.class);
@Resource
private TrainCarriageMapper trainCarriageMapper;
public void save(TrainCarriageSaveReq req) {
DateTime now = DateTime.now();
// 自动计算出列数和总座位数
List<SeatColEnum> seatColEnums = SeatColEnum.getColsByType(req.getSeatType());
req.setColCount(seatColEnums.size());
req.setSeatCount(req.getColCount() * req.getRowCount());
TrainCarriage trainCarriage = BeanUtil.copyProperties(req, TrainCarriage.class);
if (ObjectUtil.isNull(trainCarriage.getId())) {
// 保存之前,先校验唯一键是否存在
TrainCarriage trainCarriageDB = selectByUnique(req.getTrainCode(), req.getIndex());
if (ObjectUtil.isNotEmpty(trainCarriageDB)) {
throw new BusinessException(BusinessExceptionEnum.BUSINESS_TRAIN_CARRIAGE_INDEX_UNIQUE_ERROR);
}
trainCarriage.setId(SnowFlakeUtil.getSnowFlakeNextId());
trainCarriage.setCreateTime(now);
trainCarriage.setUpdateTime(now);
trainCarriageMapper.insert(trainCarriage);
} else {
trainCarriage.setUpdateTime(now);
trainCarriageMapper.updateByPrimaryKey(trainCarriage);
}
}
public PageResp<TrainCarriageQueryResp> queryList(TrainCarriageQueryReq req) { | TrainCarriageExample trainCarriageExample = new TrainCarriageExample(); | 1 | 2023-10-23 01:20:56+00:00 | 12k |
team-moabam/moabam-BE | src/test/java/com/moabam/api/presentation/NotificationControllerTest.java | [
{
"identifier": "Member",
"path": "src/main/java/com/moabam/api/domain/member/Member.java",
"snippet": "@Entity\n@Getter\n@Table(name = \"member\")\n@SQLDelete(sql = \"UPDATE member SET deleted_at = CURRENT_TIMESTAMP where id = ?\")\n@NoArgsConstructor(access = AccessLevel.PROTECTED)\npublic class Membe... | import static org.mockito.BDDMockito.*;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.*;
import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.*;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.*;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.transaction.annotation.Transactional;
import com.google.firebase.messaging.FirebaseMessaging;
import com.google.firebase.messaging.Message;
import com.moabam.api.domain.member.Member;
import com.moabam.api.domain.member.repository.MemberRepository;
import com.moabam.api.domain.notification.repository.NotificationRepository;
import com.moabam.api.domain.room.Room;
import com.moabam.api.domain.room.repository.RoomRepository;
import com.moabam.api.infrastructure.fcm.FcmRepository;
import com.moabam.api.infrastructure.fcm.FcmService;
import com.moabam.api.infrastructure.redis.ValueRedisRepository;
import com.moabam.global.error.model.ErrorMessage;
import com.moabam.support.annotation.WithMember;
import com.moabam.support.common.WithoutFilterSupporter;
import com.moabam.support.fixture.MemberFixture;
import com.moabam.support.fixture.RoomFixture;
import com.moabam.support.snippet.ErrorSnippet; | 8,614 | package com.moabam.api.presentation;
@Transactional
@SpringBootTest
@AutoConfigureMockMvc
@AutoConfigureRestDocs
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class NotificationControllerTest extends WithoutFilterSupporter {
@Autowired
MockMvc mockMvc;
@Autowired
MemberRepository memberRepository;
@Autowired | package com.moabam.api.presentation;
@Transactional
@SpringBootTest
@AutoConfigureMockMvc
@AutoConfigureRestDocs
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class NotificationControllerTest extends WithoutFilterSupporter {
@Autowired
MockMvc mockMvc;
@Autowired
MemberRepository memberRepository;
@Autowired | RoomRepository roomRepository; | 4 | 2023-10-20 06:15:43+00:00 | 12k |
liukanshan1/PrivateTrace-Core | src/main/java/Priloc/protocol/Main2.java | [
{
"identifier": "Circle",
"path": "src/main/java/Priloc/area/basic/Circle.java",
"snippet": "public class Circle implements Serializable {\n private Point center;\n private double radius;\n public static final circleFilter DISTANCE_FILTER = new distantFilter();\n public static final circleFi... | import Priloc.area.basic.Circle;
import Priloc.area.basic.EncryptedCircle;
import Priloc.area.shape.Polygon;
import Priloc.area.shape.Shape;
import Priloc.area.shape.Triangle;
import Priloc.data.EncTrajectory;
import Priloc.data.TimeLocationData;
import Priloc.data.Trajectory;
import Priloc.geo.Location;
import Priloc.utils.Constant;
import Priloc.utils.Pair;
import Priloc.utils.User;
import org.springframework.util.StopWatch;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import static Priloc.protocol.Main.getEncTrajectories; | 8,862 | package Priloc.protocol;
public class Main2 {
public static void main(String[] args) throws Exception {
System.out.println(Constant.toStr());
User.pai.setDecryption(User.prikey);
ExecutorService pool = Executors.newFixedThreadPool(Constant.THREAD);
StopWatch stopWatch = new StopWatch();
// Part-1 范围比较
// 生成范围
stopWatch.start("创建范围");
Location l1 = new Location(39.913385, 116.415884);
Location l2 = new Location(39.915744, 116.417761);
Location l3 = new Location(39.91306, 116.419576);
Triangle triangle = new Triangle(l1, l2, l3); // 王府井 市中心三角
l1 = new Location(40.004086, 116.393274);
l2 = new Location(39.994413, 116.393884);
l3 = new Location(39.994911, 116.407646);
Location l4 = new Location(40.004721, 116.407036);
Polygon p1 = new Polygon(l1, l2, l3, l4); // 国家体育中心鸟巢
Shape[] shapes = new Shape[2];
shapes[0] = triangle;
shapes[1] = p1;
stopWatch.stop();
System.out.println(stopWatch.getTotalTimeSeconds());
// 拟合
Future<Circle[]>[] futures = new Future[shapes.length];
Circle[][] temp = new Circle[shapes.length][];
stopWatch.start("拟合");
for (int i = 0; i < shapes.length; i++) {
futures[i] = pool.submit(shapes[i]::fit);
}
for (int i = 0; i < shapes.length; i++) {
temp[i] = futures[i].get();
}
stopWatch.stop();
List<Circle> cs = new ArrayList<>();
for (int i = 0; i < shapes.length; i++) {
System.out.println("拟合效果:" + shapes[i].checkCoverage(10000000, temp[i]));
cs.addAll(Arrays.asList(temp[i]));
}
Circle[] circles = cs.toArray(new Circle[cs.size()]);
System.out.println(stopWatch.getTotalTimeSeconds());
// 加密
EncryptedCircle[] encCircles = new EncryptedCircle[circles.length];
Future<EncryptedCircle>[] future = new Future[circles.length];
stopWatch.start("加密");
for (int i = 0; i < circles.length; i++) {
future[i] = pool.submit(circles[i]::enc);
}
for (int i = 0; i < circles.length; i++) {
encCircles[i] = future[i].get();
}
stopWatch.stop();
CCircleTree cCircleTree = new CCircleTree();
for (int i = 0; i < encCircles.length; i++) {
cCircleTree.add(new EncTrajectory(encCircles[i]));
}
System.out.println(stopWatch.getTotalTimeSeconds());
// 建立范围树
stopWatch.start("建立范围树");
cCircleTree.init(true);
stopWatch.stop();
System.out.println(stopWatch.getTotalTimeSeconds());
// 初始化阴性 | package Priloc.protocol;
public class Main2 {
public static void main(String[] args) throws Exception {
System.out.println(Constant.toStr());
User.pai.setDecryption(User.prikey);
ExecutorService pool = Executors.newFixedThreadPool(Constant.THREAD);
StopWatch stopWatch = new StopWatch();
// Part-1 范围比较
// 生成范围
stopWatch.start("创建范围");
Location l1 = new Location(39.913385, 116.415884);
Location l2 = new Location(39.915744, 116.417761);
Location l3 = new Location(39.91306, 116.419576);
Triangle triangle = new Triangle(l1, l2, l3); // 王府井 市中心三角
l1 = new Location(40.004086, 116.393274);
l2 = new Location(39.994413, 116.393884);
l3 = new Location(39.994911, 116.407646);
Location l4 = new Location(40.004721, 116.407036);
Polygon p1 = new Polygon(l1, l2, l3, l4); // 国家体育中心鸟巢
Shape[] shapes = new Shape[2];
shapes[0] = triangle;
shapes[1] = p1;
stopWatch.stop();
System.out.println(stopWatch.getTotalTimeSeconds());
// 拟合
Future<Circle[]>[] futures = new Future[shapes.length];
Circle[][] temp = new Circle[shapes.length][];
stopWatch.start("拟合");
for (int i = 0; i < shapes.length; i++) {
futures[i] = pool.submit(shapes[i]::fit);
}
for (int i = 0; i < shapes.length; i++) {
temp[i] = futures[i].get();
}
stopWatch.stop();
List<Circle> cs = new ArrayList<>();
for (int i = 0; i < shapes.length; i++) {
System.out.println("拟合效果:" + shapes[i].checkCoverage(10000000, temp[i]));
cs.addAll(Arrays.asList(temp[i]));
}
Circle[] circles = cs.toArray(new Circle[cs.size()]);
System.out.println(stopWatch.getTotalTimeSeconds());
// 加密
EncryptedCircle[] encCircles = new EncryptedCircle[circles.length];
Future<EncryptedCircle>[] future = new Future[circles.length];
stopWatch.start("加密");
for (int i = 0; i < circles.length; i++) {
future[i] = pool.submit(circles[i]::enc);
}
for (int i = 0; i < circles.length; i++) {
encCircles[i] = future[i].get();
}
stopWatch.stop();
CCircleTree cCircleTree = new CCircleTree();
for (int i = 0; i < encCircles.length; i++) {
cCircleTree.add(new EncTrajectory(encCircles[i]));
}
System.out.println(stopWatch.getTotalTimeSeconds());
// 建立范围树
stopWatch.start("建立范围树");
cCircleTree.init(true);
stopWatch.stop();
System.out.println(stopWatch.getTotalTimeSeconds());
// 初始化阴性 | Pair<EncTrajectory[], Trajectory[]> pair1 = getEncTrajectories(pool, stopWatch); | 12 | 2023-10-22 06:28:51+00:00 | 12k |
tuxming/xmfx | BaseUI/src/main/java/com/xm2013/jfx/control/pager/XmPager.java | [
{
"identifier": "FxKit",
"path": "BaseUI/src/main/java/com/xm2013/jfx/common/FxKit.java",
"snippet": "public class FxKit {\n\n /** The Constant DOUBLE_ARROW_RIGHT. */\n public static final String DOUBLE_ARROW_RIGHT = \"<svg version=\\\"1.1\\\" xmlns=\\\"http://www.w3.org/2000/svg\\\" p-id=\\\"1050... | import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.css.CssMetaData;
import javafx.css.Styleable;
import javafx.css.StyleableProperty;
import javafx.css.converter.BooleanConverter;
import javafx.css.converter.EnumConverter;
import javafx.scene.AccessibleRole;
import javafx.scene.control.Skin;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import com.xm2013.jfx.common.FxKit;
import com.xm2013.jfx.control.base.CssKeys;
import com.xm2013.jfx.control.base.HueType;
import com.xm2013.jfx.control.base.SizeType;
import com.xm2013.jfx.control.base.XmControl;
import javafx.beans.property.*; | 10,601 | /*
* MIT License
*
* Copyright (c) 2023 tuxming@sina.com / wechat: t5x5m5
*
* 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 com.xm2013.jfx.control.pager;
/**
* 分页组件
*/
public class XmPager extends XmControl {
public XmPager(){
this(50);
}
/**
* 总条数
* @param total int
*/
public XmPager(int total) {
super();
this.init(total);
}
private void init(int total){
setTotal(total);
getStyleClass().add("xm-pager");
getStylesheets().add(FxKit.USER_AGENT_STYLESHEET);
setAccessibleRole(AccessibleRole.PAGINATION); | /*
* MIT License
*
* Copyright (c) 2023 tuxming@sina.com / wechat: t5x5m5
*
* 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 com.xm2013.jfx.control.pager;
/**
* 分页组件
*/
public class XmPager extends XmControl {
public XmPager(){
this(50);
}
/**
* 总条数
* @param total int
*/
public XmPager(int total) {
super();
this.init(total);
}
private void init(int total){
setTotal(total);
getStyleClass().add("xm-pager");
getStylesheets().add(FxKit.USER_AGENT_STYLESHEET);
setAccessibleRole(AccessibleRole.PAGINATION); | setHueType(HueType.LIGHT); | 2 | 2023-10-17 08:57:08+00:00 | 12k |
Dwight-Studio/JArmEmu | src/main/java/fr/dwightstudio/jarmemu/gui/controllers/StackController.java | [
{
"identifier": "AbstractJArmEmuModule",
"path": "src/main/java/fr/dwightstudio/jarmemu/gui/AbstractJArmEmuModule.java",
"snippet": "public class AbstractJArmEmuModule implements Initializable {\n\n protected final JArmEmuApplication application;\n\n public AbstractJArmEmuModule(JArmEmuApplication... | import atlantafx.base.theme.Styles;
import atlantafx.base.theme.Tweaks;
import fr.dwightstudio.jarmemu.gui.AbstractJArmEmuModule;
import fr.dwightstudio.jarmemu.gui.JArmEmuApplication;
import fr.dwightstudio.jarmemu.gui.factory.AddressTableCell;
import fr.dwightstudio.jarmemu.gui.factory.CursorTableCell;
import fr.dwightstudio.jarmemu.gui.factory.ValueTableCell;
import fr.dwightstudio.jarmemu.gui.view.MemoryWordView;
import fr.dwightstudio.jarmemu.sim.obj.Register;
import fr.dwightstudio.jarmemu.sim.obj.StateContainer;
import javafx.application.Platform;
import javafx.collections.ObservableList;
import javafx.geometry.Pos;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import org.kordamp.ikonli.javafx.FontIcon;
import org.kordamp.ikonli.material2.Material2OutlinedAL;
import org.kordamp.ikonli.material2.Material2OutlinedMZ;
import java.net.URL;
import java.util.ArrayList;
import java.util.ResourceBundle;
import java.util.logging.Logger; | 10,445 | /*
* ____ _ __ __ _____ __ ___
* / __ \_ __(_)___ _/ /_ / /_ / ___// /___ ______/ (_)___
* / / / / | /| / / / __ `/ __ \/ __/ \__ \/ __/ / / / __ / / __ \
* / /_/ /| |/ |/ / / /_/ / / / / /_ ___/ / /_/ /_/ / /_/ / / /_/ /
* /_____/ |__/|__/_/\__, /_/ /_/\__/ /____/\__/\__,_/\__,_/_/\____/
* /____/
* Copyright (C) 2023 Dwight Studio
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package fr.dwightstudio.jarmemu.gui.controllers;
public class StackController extends AbstractJArmEmuModule {
private static final int MAX_NUMBER = 500;
private final Logger logger = Logger.getLogger(getClass().getName());
private TableColumn<MemoryWordView, Boolean> col0;
private TableColumn<MemoryWordView, Number> col1;
private TableColumn<MemoryWordView, Number> col2;
private ObservableList<MemoryWordView> views;
private TableView<MemoryWordView> stackTable;
public StackController(JArmEmuApplication application) {
super(application);
}
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
col0 = new TableColumn<>();
col0.setGraphic(new FontIcon(Material2OutlinedAL.LOCATION_SEARCHING));
col0.setSortable(false);
col0.setEditable(false);
col0.setReorderable(false);
col0.setMaxWidth(35);
col0.getStyleClass().add(Tweaks.ALIGN_CENTER);
col0.setCellValueFactory(c -> c.getValue().getCursorProperty());
col0.setCellFactory(CursorTableCell.factory());
col1 = new TableColumn<>("Address");
col1.setGraphic(new FontIcon(Material2OutlinedAL.ALTERNATE_EMAIL));
col0.setEditable(false);
col1.setReorderable(false);
col1.setMinWidth(80);
col1.setPrefWidth(80);
col1.getStyleClass().add(Tweaks.ALIGN_CENTER);
col1.setCellValueFactory(c -> c.getValue().getAddressProperty());
col1.setCellFactory(AddressTableCell.factory());
col1.setSortType(TableColumn.SortType.ASCENDING);
col2 = new TableColumn<>("Value");
col2.setGraphic(new FontIcon(Material2OutlinedMZ.MONEY));
col2.setSortable(false);
col2.setReorderable(false);
col2.setMinWidth(80);
col2.setPrefWidth(80);
col2.getStyleClass().add(Tweaks.ALIGN_CENTER);
col2.setCellValueFactory(c -> c.getValue().getValueProperty());
col2.setCellFactory(ValueTableCell.factoryDynamicFormat(application));
stackTable = new TableView<>();
views = stackTable.getItems();
FontIcon icon = new FontIcon(Material2OutlinedAL.AUTORENEW);
HBox placeHolder = new HBox(5, icon);
icon.getStyleClass().add("medium-icon");
placeHolder.setAlignment(Pos.CENTER);
stackTable.setPlaceholder(placeHolder);
stackTable.getColumns().setAll(col0, col1, col2);
stackTable.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY_ALL_COLUMNS);
stackTable.getStyleClass().addAll(Styles.STRIPED, Styles.DENSE, Tweaks.ALIGN_CENTER, Tweaks.EDGE_TO_EDGE);
stackTable.getSelectionModel().selectFirst();
stackTable.setEditable(true);
stackTable.getSortOrder().clear();
stackTable.getSortOrder().add(col1);
AnchorPane.setTopAnchor(stackTable, 0d);
AnchorPane.setRightAnchor(stackTable, 0d);
AnchorPane.setBottomAnchor(stackTable, 0d);
AnchorPane.setLeftAnchor(stackTable, 0d);
getController().stackPane.getChildren().add(stackTable);
}
private ArrayList<Integer> getLowerValues(StateContainer container) {
ArrayList<Integer> rtn = new ArrayList<>();
int address = container.getStackAddress() - 4;
int sp = container.getSP().getData();
int number = 0;
while (container.getMemory().isWordInitiated(address) || (sp < container.getStackAddress() && address >= sp)) {
if (number > MAX_NUMBER) {
break;
}
rtn.add(address);
address -= 4;
number++;
}
return rtn;
}
private ArrayList<Integer> getHigherValues(StateContainer container) {
ArrayList<Integer> rtn = new ArrayList<>();
int address = container.getStackAddress();
int sp = container.getSP().getData();
int number = 0;
while (container.getMemory().isWordInitiated(address) || (sp > container.getStackAddress() && address <= sp)) {
if (number > MAX_NUMBER) {
break;
}
rtn.add(address);
address += 4;
number++;
}
return rtn;
}
/**
* Met à jour les registres sur le GUI avec les informations du conteneur d'état.
*
* @apiNote Attention, ne pas exécuter sur l'Application Thread (pour des raisons de performances)
* @param stateContainer le conteneur d'état
*/
public void updateGUI(StateContainer stateContainer) {
if (stateContainer == null) {
views.clear();
} else { | /*
* ____ _ __ __ _____ __ ___
* / __ \_ __(_)___ _/ /_ / /_ / ___// /___ ______/ (_)___
* / / / / | /| / / / __ `/ __ \/ __/ \__ \/ __/ / / / __ / / __ \
* / /_/ /| |/ |/ / / /_/ / / / / /_ ___/ / /_/ /_/ / /_/ / / /_/ /
* /_____/ |__/|__/_/\__, /_/ /_/\__/ /____/\__/\__,_/\__,_/_/\____/
* /____/
* Copyright (C) 2023 Dwight Studio
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package fr.dwightstudio.jarmemu.gui.controllers;
public class StackController extends AbstractJArmEmuModule {
private static final int MAX_NUMBER = 500;
private final Logger logger = Logger.getLogger(getClass().getName());
private TableColumn<MemoryWordView, Boolean> col0;
private TableColumn<MemoryWordView, Number> col1;
private TableColumn<MemoryWordView, Number> col2;
private ObservableList<MemoryWordView> views;
private TableView<MemoryWordView> stackTable;
public StackController(JArmEmuApplication application) {
super(application);
}
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
col0 = new TableColumn<>();
col0.setGraphic(new FontIcon(Material2OutlinedAL.LOCATION_SEARCHING));
col0.setSortable(false);
col0.setEditable(false);
col0.setReorderable(false);
col0.setMaxWidth(35);
col0.getStyleClass().add(Tweaks.ALIGN_CENTER);
col0.setCellValueFactory(c -> c.getValue().getCursorProperty());
col0.setCellFactory(CursorTableCell.factory());
col1 = new TableColumn<>("Address");
col1.setGraphic(new FontIcon(Material2OutlinedAL.ALTERNATE_EMAIL));
col0.setEditable(false);
col1.setReorderable(false);
col1.setMinWidth(80);
col1.setPrefWidth(80);
col1.getStyleClass().add(Tweaks.ALIGN_CENTER);
col1.setCellValueFactory(c -> c.getValue().getAddressProperty());
col1.setCellFactory(AddressTableCell.factory());
col1.setSortType(TableColumn.SortType.ASCENDING);
col2 = new TableColumn<>("Value");
col2.setGraphic(new FontIcon(Material2OutlinedMZ.MONEY));
col2.setSortable(false);
col2.setReorderable(false);
col2.setMinWidth(80);
col2.setPrefWidth(80);
col2.getStyleClass().add(Tweaks.ALIGN_CENTER);
col2.setCellValueFactory(c -> c.getValue().getValueProperty());
col2.setCellFactory(ValueTableCell.factoryDynamicFormat(application));
stackTable = new TableView<>();
views = stackTable.getItems();
FontIcon icon = new FontIcon(Material2OutlinedAL.AUTORENEW);
HBox placeHolder = new HBox(5, icon);
icon.getStyleClass().add("medium-icon");
placeHolder.setAlignment(Pos.CENTER);
stackTable.setPlaceholder(placeHolder);
stackTable.getColumns().setAll(col0, col1, col2);
stackTable.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY_ALL_COLUMNS);
stackTable.getStyleClass().addAll(Styles.STRIPED, Styles.DENSE, Tweaks.ALIGN_CENTER, Tweaks.EDGE_TO_EDGE);
stackTable.getSelectionModel().selectFirst();
stackTable.setEditable(true);
stackTable.getSortOrder().clear();
stackTable.getSortOrder().add(col1);
AnchorPane.setTopAnchor(stackTable, 0d);
AnchorPane.setRightAnchor(stackTable, 0d);
AnchorPane.setBottomAnchor(stackTable, 0d);
AnchorPane.setLeftAnchor(stackTable, 0d);
getController().stackPane.getChildren().add(stackTable);
}
private ArrayList<Integer> getLowerValues(StateContainer container) {
ArrayList<Integer> rtn = new ArrayList<>();
int address = container.getStackAddress() - 4;
int sp = container.getSP().getData();
int number = 0;
while (container.getMemory().isWordInitiated(address) || (sp < container.getStackAddress() && address >= sp)) {
if (number > MAX_NUMBER) {
break;
}
rtn.add(address);
address -= 4;
number++;
}
return rtn;
}
private ArrayList<Integer> getHigherValues(StateContainer container) {
ArrayList<Integer> rtn = new ArrayList<>();
int address = container.getStackAddress();
int sp = container.getSP().getData();
int number = 0;
while (container.getMemory().isWordInitiated(address) || (sp > container.getStackAddress() && address <= sp)) {
if (number > MAX_NUMBER) {
break;
}
rtn.add(address);
address += 4;
number++;
}
return rtn;
}
/**
* Met à jour les registres sur le GUI avec les informations du conteneur d'état.
*
* @apiNote Attention, ne pas exécuter sur l'Application Thread (pour des raisons de performances)
* @param stateContainer le conteneur d'état
*/
public void updateGUI(StateContainer stateContainer) {
if (stateContainer == null) {
views.clear();
} else { | Register sp = stateContainer.getSP(); | 6 | 2023-10-17 18:22:09+00:00 | 12k |
GTNewHorizons/FarmingForEngineers | src/main/java/com/guigs44/farmingforengineers/FarmingForEngineers.java | [
{
"identifier": "Compat",
"path": "src/main/java/com/guigs44/farmingforengineers/compat/Compat.java",
"snippet": "public class Compat {\n\n public static final String HARVESTCRAFT = \"harvestcraft\";\n public static final String MOUSETWEAKS = \"mousetweaks\";\n public static final String AGRICR... | import java.io.File;
import java.util.Optional;
import net.minecraft.block.Block;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import net.minecraftforge.common.config.Configuration;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.guigs44.farmingforengineers.compat.Compat;
import com.guigs44.farmingforengineers.compat.VanillaAddon;
import com.guigs44.farmingforengineers.entity.EntityMerchant;
import com.guigs44.farmingforengineers.network.GuiHandler;
import com.guigs44.farmingforengineers.network.NetworkHandler;
import com.guigs44.farmingforengineers.registry.AbstractRegistry;
import com.guigs44.farmingforengineers.registry.MarketRegistry;
import com.guigs44.farmingforengineers.utilities.ChatComponentBuilder;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.SidedProxy;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.event.FMLServerStartingEvent;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.PlayerEvent;
import cpw.mods.fml.common.network.NetworkRegistry;
import cpw.mods.fml.common.registry.EntityRegistry; | 8,800 | package com.guigs44.farmingforengineers;
@Mod(
modid = FarmingForEngineers.MOD_ID,
name = "Farming for Engineers",
dependencies = "after:mousetweaks[2.8,);after:forestry;after:agricraft")
// @Mod.EventBusSubscriber
public class FarmingForEngineers {
public static final String MOD_ID = "farmingforengineers";
@Mod.Instance(MOD_ID)
public static FarmingForEngineers instance;
@SidedProxy(
clientSide = "com.guigs44.farmingforengineers.client.ClientProxy",
serverSide = "com.guigs44.farmingforengineers.CommonProxy")
public static CommonProxy proxy;
public static final Logger logger = LogManager.getLogger();
public static final CreativeTabs creativeTab = new CreativeTabs(MOD_ID) {
@Override
public Item getTabIconItem() {
return Item.getItemFromBlock(FarmingForEngineers.blockMarket);
}
};
public static File configDir;
public static Block blockMarket;
@Mod.EventHandler
public void preInit(FMLPreInitializationEvent event) {
configDir = new File(event.getModConfigurationDirectory(), "FarmingForEngineers");
if (!configDir.exists() && !configDir.mkdirs()) {
throw new RuntimeException("Couldn't create Farming for Engineers configuration directory");
}
Configuration config = new Configuration(new File(configDir, "FarmingForEngineers.cfg"));
config.load();
ModConfig.preInit(config);
proxy.preInit(event);
if (config.hasChanged()) {
config.save();
}
}
@Mod.EventHandler
public void init(FMLInitializationEvent event) {
NetworkHandler.init();
NetworkRegistry.INSTANCE.registerGuiHandler(this, new GuiHandler());
new VanillaAddon();
buildSoftDependProxy(Compat.HARVESTCRAFT, "com.guigs44.farmingforengineers.compat.HarvestcraftAddon");
buildSoftDependProxy(Compat.FORESTRY, "com.guigs44.farmingforengineers.compat.ForestryAddon");
buildSoftDependProxy(Compat.AGRICRAFT, "com.guigs44.farmingforengineers.compat.AgriCraftAddon");
buildSoftDependProxy(Compat.BIOMESOPLENTY, "com.guigs44.farmingforengineers.compat.BiomesOPlentyAddon");
buildSoftDependProxy(Compat.NATURA, "com.guigs44.farmingforengineers.compat.NaturaAddon");
ModRecipes.init(); | package com.guigs44.farmingforengineers;
@Mod(
modid = FarmingForEngineers.MOD_ID,
name = "Farming for Engineers",
dependencies = "after:mousetweaks[2.8,);after:forestry;after:agricraft")
// @Mod.EventBusSubscriber
public class FarmingForEngineers {
public static final String MOD_ID = "farmingforengineers";
@Mod.Instance(MOD_ID)
public static FarmingForEngineers instance;
@SidedProxy(
clientSide = "com.guigs44.farmingforengineers.client.ClientProxy",
serverSide = "com.guigs44.farmingforengineers.CommonProxy")
public static CommonProxy proxy;
public static final Logger logger = LogManager.getLogger();
public static final CreativeTabs creativeTab = new CreativeTabs(MOD_ID) {
@Override
public Item getTabIconItem() {
return Item.getItemFromBlock(FarmingForEngineers.blockMarket);
}
};
public static File configDir;
public static Block blockMarket;
@Mod.EventHandler
public void preInit(FMLPreInitializationEvent event) {
configDir = new File(event.getModConfigurationDirectory(), "FarmingForEngineers");
if (!configDir.exists() && !configDir.mkdirs()) {
throw new RuntimeException("Couldn't create Farming for Engineers configuration directory");
}
Configuration config = new Configuration(new File(configDir, "FarmingForEngineers.cfg"));
config.load();
ModConfig.preInit(config);
proxy.preInit(event);
if (config.hasChanged()) {
config.save();
}
}
@Mod.EventHandler
public void init(FMLInitializationEvent event) {
NetworkHandler.init();
NetworkRegistry.INSTANCE.registerGuiHandler(this, new GuiHandler());
new VanillaAddon();
buildSoftDependProxy(Compat.HARVESTCRAFT, "com.guigs44.farmingforengineers.compat.HarvestcraftAddon");
buildSoftDependProxy(Compat.FORESTRY, "com.guigs44.farmingforengineers.compat.ForestryAddon");
buildSoftDependProxy(Compat.AGRICRAFT, "com.guigs44.farmingforengineers.compat.AgriCraftAddon");
buildSoftDependProxy(Compat.BIOMESOPLENTY, "com.guigs44.farmingforengineers.compat.BiomesOPlentyAddon");
buildSoftDependProxy(Compat.NATURA, "com.guigs44.farmingforengineers.compat.NaturaAddon");
ModRecipes.init(); | MarketRegistry.INSTANCE.load(configDir); | 6 | 2023-10-17 00:25:50+00:00 | 12k |
clclab/pcfg-lm | src/berkeley_parser/edu/berkeley/nlp/syntax/Trees.java | [
{
"identifier": "CollectionUtils",
"path": "src/berkeley_parser/edu/berkeley/nlp/util/CollectionUtils.java",
"snippet": "public class CollectionUtils {\n\n\tpublic interface CollectionFactory<V> {\n\n\t\tCollection<V> newCollection();\n\n\t}\n\n\tpublic static <E extends Comparable<E>> List<E> sort(Coll... | import java.io.IOException;
import java.io.PushbackReader;
import java.io.Reader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import edu.berkeley.nlp.util.CollectionUtils;
import edu.berkeley.nlp.util.Filter;
import edu.berkeley.nlp.util.Pair;
import edu.berkeley.nlp.util.StrUtils; | 7,832 | package edu.berkeley.nlp.syntax;
/**
* Tools for displaying, reading, and modifying trees.
*
* @author Dan Klein
*/
public class Trees {
public static interface TreeTransformer<E> {
Tree<E> transformTree(Tree<E> tree);
}
public static class PunctuationStripper implements TreeTransformer<String> {
public Tree<String> transformTree(Tree<String> tree) { | package edu.berkeley.nlp.syntax;
/**
* Tools for displaying, reading, and modifying trees.
*
* @author Dan Klein
*/
public class Trees {
public static interface TreeTransformer<E> {
Tree<E> transformTree(Tree<E> tree);
}
public static class PunctuationStripper implements TreeTransformer<String> {
public Tree<String> transformTree(Tree<String> tree) { | return Trees.spliceNodes(tree, new Filter<String>() { | 1 | 2023-10-22 13:13:22+00:00 | 12k |
neftalito/R-Info-Plus | arbol/sentencia/primitiva/Iniciar.java | [
{
"identifier": "DeclaracionProcesos",
"path": "arbol/DeclaracionProcesos.java",
"snippet": "public class DeclaracionProcesos extends AST {\n public ArrayList<Proceso> procesos;\n\n public ArrayList<Proceso> getProcesos() {\n return this.procesos;\n }\n\n public void setProcesos(final... | import arbol.DeclaracionProcesos;
import form.Robot;
import form.EjecucionRobot;
import arbol.Cuerpo;
import arbol.Variable;
import arbol.sentencia.Sentencia;
import java.util.ArrayList;
import arbol.DeclaracionVariable;
import arbol.DeclaracionRobots;
import arbol.Identificador;
import arbol.RobotAST; | 10,051 |
package arbol.sentencia.primitiva;
public class Iniciar extends Primitiva {
RobotAST r;
int x;
int y;
Identificador Ident;
DeclaracionRobots robAST;
DeclaracionVariable varAST;
public Iniciar(final Identificador I, final int x, final int y, final DeclaracionRobots robAST,
final DeclaracionVariable varAST) throws Exception {
this.varAST = varAST;
this.robAST = robAST;
this.Ident = I;
this.x = x;
this.y = y;
if (varAST.EstaVariable(I.toString())) {
this.r = varAST.findByName(I.toString()).getR();
System.out.println("para la variable " + I.toString() + " el robot es : " + this.r.getNombre());
return;
}
throw new Exception("El robot tiene que estar declarado en las variables");
}
@Override
public void ejecutar() throws Exception {
Robot rob = null; |
package arbol.sentencia.primitiva;
public class Iniciar extends Primitiva {
RobotAST r;
int x;
int y;
Identificador Ident;
DeclaracionRobots robAST;
DeclaracionVariable varAST;
public Iniciar(final Identificador I, final int x, final int y, final DeclaracionRobots robAST,
final DeclaracionVariable varAST) throws Exception {
this.varAST = varAST;
this.robAST = robAST;
this.Ident = I;
this.x = x;
this.y = y;
if (varAST.EstaVariable(I.toString())) {
this.r = varAST.findByName(I.toString()).getR();
System.out.println("para la variable " + I.toString() + " el robot es : " + this.r.getNombre());
return;
}
throw new Exception("El robot tiene que estar declarado en las variables");
}
@Override
public void ejecutar() throws Exception {
Robot rob = null; | Cuerpo cu = this.r.getCuerpo(); | 3 | 2023-10-20 15:45:37+00:00 | 12k |
hmcts/opal-fines-service | src/main/java/uk/gov/hmcts/opal/service/DefendantAccountService.java | [
{
"identifier": "AccountDetailsDto",
"path": "src/main/java/uk/gov/hmcts/opal/dto/AccountDetailsDto.java",
"snippet": "@Data\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\npublic class AccountDetailsDto implements ToJsonString {\n\n //defendant_accounts.account_number\n private String account... | import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.transaction.Transactional;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import uk.gov.hmcts.opal.dto.AccountDetailsDto;
import uk.gov.hmcts.opal.dto.AccountEnquiryDto;
import uk.gov.hmcts.opal.dto.AccountSearchDto;
import uk.gov.hmcts.opal.dto.AccountSearchResultsDto;
import uk.gov.hmcts.opal.dto.AccountSummaryDto;
import uk.gov.hmcts.opal.entity.DefendantAccountEntity;
import uk.gov.hmcts.opal.entity.DefendantAccountPartiesEntity;
import uk.gov.hmcts.opal.entity.DefendantAccountSummary;
import uk.gov.hmcts.opal.entity.EnforcersEntity;
import uk.gov.hmcts.opal.entity.NoteEntity;
import uk.gov.hmcts.opal.entity.PartyEntity;
import uk.gov.hmcts.opal.entity.PaymentTermsEntity;
import uk.gov.hmcts.opal.repository.DebtorDetailRepository;
import uk.gov.hmcts.opal.repository.DefendantAccountPartiesRepository;
import uk.gov.hmcts.opal.repository.DefendantAccountRepository;
import uk.gov.hmcts.opal.repository.EnforcersRepository;
import uk.gov.hmcts.opal.repository.NoteRepository;
import uk.gov.hmcts.opal.repository.PaymentTermsRepository;
import uk.gov.hmcts.opal.repository.jpa.DefendantAccountSpecs;
import uk.gov.hmcts.opal.entity.DefendantAccountSummary.PartyLink;
import uk.gov.hmcts.opal.entity.DefendantAccountSummary.PartyDefendantAccountSummary;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import static uk.gov.hmcts.opal.dto.ToJsonString.newObjectMapper; | 7,308 | package uk.gov.hmcts.opal.service;
@Service
@Transactional
@Slf4j
@RequiredArgsConstructor
public class DefendantAccountService {
private final DefendantAccountRepository defendantAccountRepository;
| package uk.gov.hmcts.opal.service;
@Service
@Transactional
@Slf4j
@RequiredArgsConstructor
public class DefendantAccountService {
private final DefendantAccountRepository defendantAccountRepository;
| private final DefendantAccountPartiesRepository defendantAccountPartiesRepository; | 13 | 2023-10-23 14:12:11+00:00 | 12k |
moonstoneid/aero-cast | apps/feed-aggregator/src/main/java/com/moonstoneid/aerocast/aggregator/service/SubscriberService.java | [
{
"identifier": "ConflictException",
"path": "apps/feed-aggregator/src/main/java/com/moonstoneid/aerocast/aggregator/error/ConflictException.java",
"snippet": "public class ConflictException extends RuntimeException {\n\n public ConflictException(String message) {\n super(message);\n }\n\n}... | import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import com.moonstoneid.aerocast.aggregator.error.ConflictException;
import com.moonstoneid.aerocast.aggregator.error.NotFoundException;
import com.moonstoneid.aerocast.aggregator.eth.EthSubscriberAdapter;
import com.moonstoneid.aerocast.common.eth.EthUtil;
import com.moonstoneid.aerocast.common.eth.contracts.FeedSubscriber;
import com.moonstoneid.aerocast.aggregator.model.Subscriber;
import com.moonstoneid.aerocast.aggregator.model.Subscription;
import com.moonstoneid.aerocast.aggregator.repo.SubscriberRepo;
import com.moonstoneid.aerocast.aggregator.repo.SubscriptionRepo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.stereotype.Service; | 9,894 | package com.moonstoneid.aerocast.aggregator.service;
@Service
@Slf4j
public class SubscriberService implements EthSubscriberAdapter.EventCallback {
public interface EventListener {
void onSubscriptionChange(String subContractAddr);
}
private final SubscriberRepo subscriberRepo;
private final SubscriptionRepo subscriptionRepo;
private final PublisherService publisherService;
private final EthSubscriberAdapter ethSubscriberAdapter;
private final List<EventListener> eventListeners = new ArrayList<>();
public SubscriberService(SubscriberRepo subscriberRepo, SubscriptionRepo subscriptionRepo,
PublisherService publisherService, EthSubscriberAdapter ethSubscriberAdapter) {
this.subscriberRepo = subscriberRepo;
this.subscriptionRepo = subscriptionRepo;
this.publisherService = publisherService;
this.ethSubscriberAdapter = ethSubscriberAdapter;
}
public void registerEventListener(EventListener listener) {
eventListeners.add(listener);
}
public void unregisterEventListener(EventListener listener) {
eventListeners.remove(listener);
}
// Register listeners after Spring Boot has started
@org.springframework.context.event.EventListener(ApplicationReadyEvent.class)
public void initEventListener() {
getSubscribers().forEach(s -> ethSubscriberAdapter.registerSubscriptionEventListener(
s.getContractAddress(), s.getBlockNumber(), this));
}
@Override
public void onCreateSubscription(String subContractAddr, String blockNumber,
String pubContractAddr) {
String contractAddr = subContractAddr.toLowerCase();
updateSubscriberEventBlockNumber(contractAddr, blockNumber);
createSubscription(contractAddr, pubContractAddr);
eventListeners.forEach(l -> l.onSubscriptionChange(subContractAddr));
}
@Override
public void onRemoveSubscription(String subContractAddr, String blockNumber,
String pubContractAddr) {
String contractAddr = subContractAddr.toLowerCase();
updateSubscriberEventBlockNumber(contractAddr, blockNumber);
removeSubscription(contractAddr, pubContractAddr);
eventListeners.forEach(l -> l.onSubscriptionChange(subContractAddr));
}
public List<Subscriber> getSubscribers() {
return subscriberRepo.findAll();
}
private Optional<Subscriber> findSubscriber(String subAccountAddr) {
String accountAddr = subAccountAddr.toLowerCase();
return subscriberRepo.findById(accountAddr);
}
public Subscriber getSubscriber(String subAccountAddr) {
Optional<Subscriber> subscriber = findSubscriber(subAccountAddr);
return subscriber
.orElseThrow(() -> new NotFoundException("Subscriber was not found!"));
}
public void createSubscriber(String subAccountAddr) {
String accountAddr = subAccountAddr.toLowerCase();
log.info("Trying to create subscriber '{}' ...", EthUtil.shortenAddress(accountAddr));
String currentBlockNum = ethSubscriberAdapter.getCurrentBlockNumber();
// Check if subscriber exists
if (subscriberRepo.existsById(accountAddr)) {
log.error("Subscriber '{}' already exists!", EthUtil.shortenAddress(subAccountAddr)); | package com.moonstoneid.aerocast.aggregator.service;
@Service
@Slf4j
public class SubscriberService implements EthSubscriberAdapter.EventCallback {
public interface EventListener {
void onSubscriptionChange(String subContractAddr);
}
private final SubscriberRepo subscriberRepo;
private final SubscriptionRepo subscriptionRepo;
private final PublisherService publisherService;
private final EthSubscriberAdapter ethSubscriberAdapter;
private final List<EventListener> eventListeners = new ArrayList<>();
public SubscriberService(SubscriberRepo subscriberRepo, SubscriptionRepo subscriptionRepo,
PublisherService publisherService, EthSubscriberAdapter ethSubscriberAdapter) {
this.subscriberRepo = subscriberRepo;
this.subscriptionRepo = subscriptionRepo;
this.publisherService = publisherService;
this.ethSubscriberAdapter = ethSubscriberAdapter;
}
public void registerEventListener(EventListener listener) {
eventListeners.add(listener);
}
public void unregisterEventListener(EventListener listener) {
eventListeners.remove(listener);
}
// Register listeners after Spring Boot has started
@org.springframework.context.event.EventListener(ApplicationReadyEvent.class)
public void initEventListener() {
getSubscribers().forEach(s -> ethSubscriberAdapter.registerSubscriptionEventListener(
s.getContractAddress(), s.getBlockNumber(), this));
}
@Override
public void onCreateSubscription(String subContractAddr, String blockNumber,
String pubContractAddr) {
String contractAddr = subContractAddr.toLowerCase();
updateSubscriberEventBlockNumber(contractAddr, blockNumber);
createSubscription(contractAddr, pubContractAddr);
eventListeners.forEach(l -> l.onSubscriptionChange(subContractAddr));
}
@Override
public void onRemoveSubscription(String subContractAddr, String blockNumber,
String pubContractAddr) {
String contractAddr = subContractAddr.toLowerCase();
updateSubscriberEventBlockNumber(contractAddr, blockNumber);
removeSubscription(contractAddr, pubContractAddr);
eventListeners.forEach(l -> l.onSubscriptionChange(subContractAddr));
}
public List<Subscriber> getSubscribers() {
return subscriberRepo.findAll();
}
private Optional<Subscriber> findSubscriber(String subAccountAddr) {
String accountAddr = subAccountAddr.toLowerCase();
return subscriberRepo.findById(accountAddr);
}
public Subscriber getSubscriber(String subAccountAddr) {
Optional<Subscriber> subscriber = findSubscriber(subAccountAddr);
return subscriber
.orElseThrow(() -> new NotFoundException("Subscriber was not found!"));
}
public void createSubscriber(String subAccountAddr) {
String accountAddr = subAccountAddr.toLowerCase();
log.info("Trying to create subscriber '{}' ...", EthUtil.shortenAddress(accountAddr));
String currentBlockNum = ethSubscriberAdapter.getCurrentBlockNumber();
// Check if subscriber exists
if (subscriberRepo.existsById(accountAddr)) {
log.error("Subscriber '{}' already exists!", EthUtil.shortenAddress(subAccountAddr)); | throw new ConflictException("Subscriber already exists!"); | 0 | 2023-10-23 20:33:07+00:00 | 12k |
UnityFoundation-io/Libre311 | app/src/main/java/app/service/servicerequest/ServiceRequestService.java | [
{
"identifier": "DownloadRequestsArgumentsDTO",
"path": "app/src/main/java/app/dto/download/DownloadRequestsArgumentsDTO.java",
"snippet": "@Introspected\npublic class DownloadRequestsArgumentsDTO {\n\n @Nullable\n @QueryValue(value = \"jurisdiction_id\")\n private String jurisdictionId;\n\n ... | import app.dto.download.DownloadRequestsArgumentsDTO;
import app.dto.download.DownloadServiceRequestDTO;
import app.dto.servicerequest.*;
import app.model.service.Service;
import app.model.service.ServiceRepository;
import app.model.service.servicedefinition.AttributeDataType;
import app.model.service.servicedefinition.AttributeValue;
import app.model.service.servicedefinition.ServiceDefinition;
import app.model.service.servicedefinition.ServiceDefinitionAttribute;
import app.model.servicerequest.ServiceRequest;
import app.model.servicerequest.ServiceRequestRepository;
import app.model.servicerequest.ServiceRequestStatus;
import app.recaptcha.ReCaptchaService;
import app.service.storage.StorageUrlUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.opencsv.bean.StatefulBeanToCsv;
import com.opencsv.bean.StatefulBeanToCsvBuilder;
import com.opencsv.exceptions.CsvDataTypeMismatchException;
import com.opencsv.exceptions.CsvRequiredFieldEmptyException;
import io.micronaut.core.util.StringUtils;
import io.micronaut.data.model.Page;
import io.micronaut.data.model.Pageable;
import io.micronaut.data.model.Sort;
import io.micronaut.http.HttpRequest;
import io.micronaut.http.server.types.files.StreamedFile;
import jakarta.inject.Singleton;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.net.MalformedURLException;
import java.time.Instant;
import java.time.format.DateTimeParseException;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream; | 8,162 | // Copyright 2023 Libre311 Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package app.service.servicerequest;
@Singleton
public class ServiceRequestService {
private static final Logger LOG = LoggerFactory.getLogger(ServiceRequestService.class);
private final ServiceRequestRepository serviceRequestRepository; | // Copyright 2023 Libre311 Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package app.service.servicerequest;
@Singleton
public class ServiceRequestService {
private static final Logger LOG = LoggerFactory.getLogger(ServiceRequestService.class);
private final ServiceRequestRepository serviceRequestRepository; | private final ServiceRepository serviceRepository; | 3 | 2023-10-18 15:37:36+00:00 | 12k |
JonnyOnlineYT/xenza | temp/src/minecraft/net/minecraft/client/renderer/entity/RenderSnowMan.java | [
{
"identifier": "ModelSnowMan",
"path": "src/minecraft/net/minecraft/client/model/ModelSnowMan.java",
"snippet": "public class ModelSnowMan extends ModelBase {\n public ModelRenderer body;\n public ModelRenderer bottomBody;\n public ModelRenderer head;\n public ModelRenderer rightHand;\n publi... | import net.minecraft.client.model.ModelSnowMan;
import net.minecraft.client.renderer.entity.RenderLiving;
import net.minecraft.client.renderer.entity.RenderManager;
import net.minecraft.client.renderer.entity.layers.LayerSnowmanHead;
import net.minecraft.entity.monster.EntitySnowman;
import net.minecraft.util.ResourceLocation; | 10,456 | package net.minecraft.client.renderer.entity;
public class RenderSnowMan extends RenderLiving<EntitySnowman> {
private static final ResourceLocation field_110895_a = new ResourceLocation("textures/entity/snowman.png");
public RenderSnowMan(RenderManager p_i46140_1_) {
super(p_i46140_1_, new ModelSnowMan(), 0.5F); | package net.minecraft.client.renderer.entity;
public class RenderSnowMan extends RenderLiving<EntitySnowman> {
private static final ResourceLocation field_110895_a = new ResourceLocation("textures/entity/snowman.png");
public RenderSnowMan(RenderManager p_i46140_1_) {
super(p_i46140_1_, new ModelSnowMan(), 0.5F); | this.func_177094_a(new LayerSnowmanHead(this)); | 3 | 2023-10-15 00:21:15+00:00 | 12k |
LeGhast/Miniaturise | src/main/java/de/leghast/miniaturise/command/SelectCommand.java | [
{
"identifier": "Miniaturise",
"path": "src/main/java/de/leghast/miniaturise/Miniaturise.java",
"snippet": "public final class Miniaturise extends JavaPlugin {\n\n private MiniatureManager miniatureManager;\n private RegionManager regionManager;\n private SettingsManager settingsManager;\n\n ... | import de.leghast.miniaturise.Miniaturise;
import de.leghast.miniaturise.instance.miniature.Miniature;
import de.leghast.miniaturise.instance.miniature.PlacedMiniature;
import de.leghast.miniaturise.instance.region.Region;
import de.leghast.miniaturise.manager.ConfigManager;
import de.leghast.miniaturise.util.Util;
import org.bukkit.Chunk;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.BlockDisplay;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List; | 10,793 | package de.leghast.miniaturise.command;
public class SelectCommand implements CommandExecutor {
private Miniaturise main;
public SelectCommand(Miniaturise main){
this.main = main;
}
@Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String s, @NotNull String[] args) {
if(sender instanceof Player player){
if(player.hasPermission("miniaturise.use")){
if(main.getRegionManager().hasSelectedLocations(player.getUniqueId())){
if(main.getRegionManager().getSelectedLocations(player.getUniqueId()).isValid()){
try{
Region region = new Region(main.getRegionManager().getSelectedLocations(player.getUniqueId()));
if(main.getRegionManager().hasRegion(player.getUniqueId())) {
main.getRegionManager().getRegions().replace(player.getUniqueId(), region);
}else{
main.getRegionManager().addRegion(player.getUniqueId(), region);
} | package de.leghast.miniaturise.command;
public class SelectCommand implements CommandExecutor {
private Miniaturise main;
public SelectCommand(Miniaturise main){
this.main = main;
}
@Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String s, @NotNull String[] args) {
if(sender instanceof Player player){
if(player.hasPermission("miniaturise.use")){
if(main.getRegionManager().hasSelectedLocations(player.getUniqueId())){
if(main.getRegionManager().getSelectedLocations(player.getUniqueId()).isValid()){
try{
Region region = new Region(main.getRegionManager().getSelectedLocations(player.getUniqueId()));
if(main.getRegionManager().hasRegion(player.getUniqueId())) {
main.getRegionManager().getRegions().replace(player.getUniqueId(), region);
}else{
main.getRegionManager().addRegion(player.getUniqueId(), region);
} | Miniature miniature = new Miniature(region, player.getLocation(), ConfigManager.getDefaultSize()); | 1 | 2023-10-15 09:08:33+00:00 | 12k |
mosaic-addons/traffic-state-estimation | src/main/java/com/dcaiti/mosaic/app/tse/config/CTseServerApp.java | [
{
"identifier": "FcdRecord",
"path": "src/main/java/com/dcaiti/mosaic/app/fxd/data/FcdRecord.java",
"snippet": "public class FcdRecord extends FxdRecord {\n\n /**\n * List of vehicles perceived during the collection of FCD in the form of {@link VehicleObject VehicleObjects}.\n */\n private... | import com.google.gson.TypeAdapterFactory;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.internal.bind.ObjectTypeAdapter;
import com.google.gson.reflect.TypeToken;
import org.apache.commons.lang3.builder.ToStringBuilder;
import static org.apache.commons.lang3.builder.ToStringStyle.SHORT_PREFIX_STYLE;
import com.dcaiti.mosaic.app.fxd.data.FcdRecord;
import com.dcaiti.mosaic.app.fxd.data.FcdTraversal;
import com.dcaiti.mosaic.app.fxd.messages.FcdUpdateMessage;
import com.dcaiti.mosaic.app.tse.TseServerApp;
import com.dcaiti.mosaic.app.tse.gson.TimeBasedProcessorTypeAdapterFactory;
import com.dcaiti.mosaic.app.tse.gson.TraversalBasedProcessorTypeAdapterFactory;
import com.dcaiti.mosaic.app.tse.persistence.FcdDataStorage;
import com.dcaiti.mosaic.app.tse.processors.SpatioTemporalProcessor;
import com.dcaiti.mosaic.app.tse.processors.ThresholdProcessor;
import com.google.gson.Gson;
import com.google.gson.ToNumberPolicy;
import com.google.gson.TypeAdapter; | 8,560 | /*
* Copyright (c) 2023 Fraunhofer FOKUS and others. All rights reserved.
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*
* Contact: mosaic@fokus.fraunhofer.de
*/
package com.dcaiti.mosaic.app.tse.config;
/**
* An extension of {@link CFxdReceiverApp}, holding the configuration of the {@link TseServerApp},
* which manly includes configuration parameters for the database.
* Additionally, the {@link TypeAdapterFactory TypeAdapterFactories} for the relevant
* {@link com.dcaiti.mosaic.app.tse.processors.FxdProcessor processors} is added.
*/
@JsonAdapter(CTseServerApp.TypeExtendingTypeAdapterFactory.class)
public class CTseServerApp extends CFxdReceiverApp<FcdRecord, FcdTraversal, FcdUpdateMessage> {
/**
* Implementation to be used for the {@link FcdDataStorage}.
*/
public FcdDataStorage fcdDataStorage = null;
/**
* Set to {@code true}, if the database should be kept and not reset before every simulation.
* Can be useful to be used as a threshold from a prior long simulation in a shorter new simulation on the same network.
*/
public boolean isPersistent = false;
/**
* Optional path to the database file. If no path is configured,
* the database will be created in the application directory.
*/
public String databasePath = null;
/**
* Optional path to the db file. If there is none, one will be created.
*/
public String databaseFileName = null;
/**
* If {@code true}, all {@link FcdRecord FcdRecords} will be stored to the database.
* Can be turned off, to safe storage and compute time, as metrics are computed from memory, not from records in the database.
*/
public boolean storeRawFcd = false;
@Override
public String toString() {
return new ToStringBuilder(this, SHORT_PREFIX_STYLE)
.appendSuper(super.toString())
.append("isPersistent", isPersistent)
.append("databasePath", databasePath)
.append("databaseFileName", databaseFileName)
.toString();
}
/**
* This {@link TypeAdapterFactory} is used to register additional package search information
* to the {@link TimeBasedProcessorTypeAdapterFactory} and {@link TraversalBasedProcessorTypeAdapterFactory}.
*/
static class TypeExtendingTypeAdapterFactory implements TypeAdapterFactory {
static {
TimeBasedProcessorTypeAdapterFactory.registerAdditionalPackageForSearch(ThresholdProcessor.class.getPackage()); | /*
* Copyright (c) 2023 Fraunhofer FOKUS and others. All rights reserved.
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*
* Contact: mosaic@fokus.fraunhofer.de
*/
package com.dcaiti.mosaic.app.tse.config;
/**
* An extension of {@link CFxdReceiverApp}, holding the configuration of the {@link TseServerApp},
* which manly includes configuration parameters for the database.
* Additionally, the {@link TypeAdapterFactory TypeAdapterFactories} for the relevant
* {@link com.dcaiti.mosaic.app.tse.processors.FxdProcessor processors} is added.
*/
@JsonAdapter(CTseServerApp.TypeExtendingTypeAdapterFactory.class)
public class CTseServerApp extends CFxdReceiverApp<FcdRecord, FcdTraversal, FcdUpdateMessage> {
/**
* Implementation to be used for the {@link FcdDataStorage}.
*/
public FcdDataStorage fcdDataStorage = null;
/**
* Set to {@code true}, if the database should be kept and not reset before every simulation.
* Can be useful to be used as a threshold from a prior long simulation in a shorter new simulation on the same network.
*/
public boolean isPersistent = false;
/**
* Optional path to the database file. If no path is configured,
* the database will be created in the application directory.
*/
public String databasePath = null;
/**
* Optional path to the db file. If there is none, one will be created.
*/
public String databaseFileName = null;
/**
* If {@code true}, all {@link FcdRecord FcdRecords} will be stored to the database.
* Can be turned off, to safe storage and compute time, as metrics are computed from memory, not from records in the database.
*/
public boolean storeRawFcd = false;
@Override
public String toString() {
return new ToStringBuilder(this, SHORT_PREFIX_STYLE)
.appendSuper(super.toString())
.append("isPersistent", isPersistent)
.append("databasePath", databasePath)
.append("databaseFileName", databaseFileName)
.toString();
}
/**
* This {@link TypeAdapterFactory} is used to register additional package search information
* to the {@link TimeBasedProcessorTypeAdapterFactory} and {@link TraversalBasedProcessorTypeAdapterFactory}.
*/
static class TypeExtendingTypeAdapterFactory implements TypeAdapterFactory {
static {
TimeBasedProcessorTypeAdapterFactory.registerAdditionalPackageForSearch(ThresholdProcessor.class.getPackage()); | TraversalBasedProcessorTypeAdapterFactory.registerAdditionalPackageForSearch(SpatioTemporalProcessor.class.getPackage()); | 7 | 2023-10-23 16:39:40+00:00 | 12k |
Primogem-Craft-Development/Primogem-Craft-Fabric | src/main/java/com/primogemstudio/primogemcraft/items/instances/materials/nagadus/NagadusEmeraldShovelItem.java | [
{
"identifier": "PrimogemCraftBlocks",
"path": "src/main/java/com/primogemstudio/primogemcraft/blocks/PrimogemCraftBlocks.java",
"snippet": "public class PrimogemCraftBlocks {\n public static final DendroCoreBlock DENDRO_CORE_BLOCK = registerWithItem(\"dendro_core_block\", new DendroCoreBlock());\n ... | import com.primogemstudio.primogemcraft.blocks.PrimogemCraftBlocks;
import com.primogemstudio.primogemcraft.items.PrimogemCraftItems;
import com.primogemstudio.primogemcraft.sounds.PrimogemCraftSounds;
import net.minecraft.core.BlockPos;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.sounds.SoundSource;
import net.minecraft.util.RandomSource;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.item.ItemEntity;
import net.minecraft.world.item.*;
import net.minecraft.world.item.context.UseOnContext;
import net.minecraft.world.item.crafting.Ingredient;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.state.BlockState;
import org.jetbrains.annotations.NotNull;
import java.util.List; | 9,923 | package com.primogemstudio.primogemcraft.items.instances.materials.nagadus;
public class NagadusEmeraldShovelItem extends ShovelItem {
public NagadusEmeraldShovelItem() {
super(new Tier() {
public int getUses() {
return 1561;
}
public float getSpeed() {
return 1f;
}
public float getAttackDamageBonus() {
return 0f;
}
public int getLevel() {
return 4;
}
public int getEnchantmentValue() {
return 5;
}
public @NotNull Ingredient getRepairIngredient() { | package com.primogemstudio.primogemcraft.items.instances.materials.nagadus;
public class NagadusEmeraldShovelItem extends ShovelItem {
public NagadusEmeraldShovelItem() {
super(new Tier() {
public int getUses() {
return 1561;
}
public float getSpeed() {
return 1f;
}
public float getAttackDamageBonus() {
return 0f;
}
public int getLevel() {
return 4;
}
public int getEnchantmentValue() {
return 5;
}
public @NotNull Ingredient getRepairIngredient() { | return Ingredient.of(new ItemStack(PrimogemCraftItems.PRIMOGEM_ITEM), new ItemStack(PrimogemCraftItems.NAGADUS_EMERALD_SLIVER_ITEM)); | 1 | 2023-10-15 08:07:06+00:00 | 12k |
turtleisaac/PokEditor | src/main/java/io/github/turtleisaac/pokeditor/gui/PokeditorManager.java | [
{
"identifier": "DataManager",
"path": "src/main/java/io/github/turtleisaac/pokeditor/DataManager.java",
"snippet": "public class DataManager\n{\n public static final String SHEET_STRINGS_PATH = \"pokeditor/sheet_strings\";\n\n public static DefaultSheetPanel<PersonalData, ?> createPersonalSheet(P... | import com.formdev.flatlaf.extras.FlatSVGIcon;
import io.github.turtleisaac.nds4j.NintendoDsRom;
import io.github.turtleisaac.nds4j.framework.GenericNtrFile;
import io.github.turtleisaac.nds4j.images.IndexedImage;
import io.github.turtleisaac.nds4j.images.Palette;
import io.github.turtleisaac.nds4j.ui.PanelManager;
import io.github.turtleisaac.nds4j.ui.ThemeUtils;
import io.github.turtleisaac.nds4j.ui.Tool;
import io.github.turtleisaac.pokeditor.DataManager;
import io.github.turtleisaac.pokeditor.formats.GenericFileData;
import io.github.turtleisaac.pokeditor.formats.evolutions.EvolutionData;
import io.github.turtleisaac.pokeditor.formats.learnsets.LearnsetData;
import io.github.turtleisaac.pokeditor.formats.moves.MoveData;
import io.github.turtleisaac.pokeditor.formats.personal.PersonalData;
import io.github.turtleisaac.pokeditor.formats.pokemon_sprites.PokemonSpriteData;
import io.github.turtleisaac.pokeditor.formats.scripts.GenericScriptData;
import io.github.turtleisaac.pokeditor.formats.text.TextBankData;
import io.github.turtleisaac.pokeditor.gamedata.*;
import io.github.turtleisaac.pokeditor.gui.editors.data.DefaultDataEditorPanel;
import io.github.turtleisaac.pokeditor.gui.sheets.DefaultSheetPanel;
import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;
import java.util.List; | 8,774 | package io.github.turtleisaac.pokeditor.gui;
public class PokeditorManager extends PanelManager
{
private static final Dimension dimension = new Dimension(1200, 714);
public static final FlatSVGIcon sheetExportIcon;
public static final FlatSVGIcon sheetImportIcon;
public static final FlatSVGIcon rowRemoveIcon;
public static final FlatSVGIcon rowInsertIcon;
public static final FlatSVGIcon searchIcon;
public static final FlatSVGIcon clipboardIcon;
public static final FlatSVGIcon copyIcon;
public static final Color[] typeColors = new Color[]{new Color(201, 201, 201),
new Color(173, 96, 94),
new Color(165, 218, 218),
new Color(184, 121, 240),
new Color(200, 164, 117),
new Color(184, 146, 48),
new Color(157, 195, 132),
new Color(139, 125, 190),
new Color(153, 153, 153),
new Color(230, 199, 255),
new Color(189, 75, 49),
new Color(88, 132, 225),
new Color(120, 166, 90),
new Color(249, 218, 120),
new Color(223, 151, 143),
new Color(70, 185, 185),
new Color(98, 98, 246),
new Color(102, 102, 102),
};
public static final Color[] darkModeTypeColors = new Color[]{new Color(116, 116, 116),
new Color(130, 72, 71),
new Color(101, 133, 133),
new Color(86, 57, 112),
new Color(157, 129, 92),
new Color(99, 79, 26),
new Color(123, 152, 103),
new Color(77, 69, 105),
new Color(68, 68, 68),
new Color(192, 166, 212), //
new Color(61, 24, 16), //
new Color(55, 82, 140), //
new Color(59, 81, 44),
new Color(163, 144, 79),
new Color(180, 122, 116),
new Color(38, 100, 100),
new Color(30, 30, 76),
new Color(17, 17, 17),
};
static {
try {
sheetExportIcon = new FlatSVGIcon(PokeditorManager.class.getResourceAsStream("/pokeditor/icons/svg/table-export.svg"));
sheetImportIcon = new FlatSVGIcon(PokeditorManager.class.getResourceAsStream("/pokeditor/icons/svg/table-import.svg"));
rowRemoveIcon = new FlatSVGIcon(PokeditorManager.class.getResourceAsStream("/pokeditor/icons/svg/row-remove.svg"));
rowInsertIcon = new FlatSVGIcon(PokeditorManager.class.getResourceAsStream("/pokeditor/icons/svg/row-insert-bottom.svg"));
searchIcon = new FlatSVGIcon(PokeditorManager.class.getResourceAsStream("/pokeditor/icons/svg/list-search.svg"));
clipboardIcon = new FlatSVGIcon(PokeditorManager.class.getResourceAsStream("/pokeditor/icons/svg/clipboard-copy.svg"));
copyIcon = new FlatSVGIcon(PokeditorManager.class.getResourceAsStream("/pokeditor/icons/svg/copy.svg"));
sheetExportIcon.setColorFilter(ThemeUtils.iconColorFilter);
sheetImportIcon.setColorFilter(ThemeUtils.iconColorFilter);
rowRemoveIcon.setColorFilter(ThemeUtils.iconColorFilter);
rowInsertIcon.setColorFilter(ThemeUtils.iconColorFilter);
searchIcon.setColorFilter(ThemeUtils.iconColorFilter);
clipboardIcon.setColorFilter(ThemeUtils.iconColorFilter);
copyIcon.setColorFilter(ThemeUtils.iconColorFilter);
/*
this code determines if the label foreground color is closer to/further from black/white, then uses that
to select which set of colors to use for the types on the sheets (lighter or darker)
(the idea being a darker theme tends to have a lighter text foreground color)
*/
Color c = UIManager.getColor("Label.foreground");
double diff = (double) (c.getRed() + c.getBlue() + c.getGreen()) / 3;
if (Math.max(diff, 255 - diff) == diff)
{
System.arraycopy(darkModeTypeColors, 0, typeColors, 0, typeColors.length);
}
}
catch(IOException e) {
throw new RuntimeException(e);
}
}
private List<JPanel> panels;
private NintendoDsRom rom;
private Game baseRom;
private boolean gitEnabled;
public PokeditorManager(Tool tool)
{
super(tool, "PokEditor");
rom = tool.getRom();
baseRom = Game.parseBaseRom(rom.getGameCode());
gitEnabled = tool.isGitEnabled();
GameFiles.initialize(baseRom);
TextFiles.initialize(baseRom);
GameCodeBinaries.initialize(baseRom);
Tables.initialize(baseRom);
| package io.github.turtleisaac.pokeditor.gui;
public class PokeditorManager extends PanelManager
{
private static final Dimension dimension = new Dimension(1200, 714);
public static final FlatSVGIcon sheetExportIcon;
public static final FlatSVGIcon sheetImportIcon;
public static final FlatSVGIcon rowRemoveIcon;
public static final FlatSVGIcon rowInsertIcon;
public static final FlatSVGIcon searchIcon;
public static final FlatSVGIcon clipboardIcon;
public static final FlatSVGIcon copyIcon;
public static final Color[] typeColors = new Color[]{new Color(201, 201, 201),
new Color(173, 96, 94),
new Color(165, 218, 218),
new Color(184, 121, 240),
new Color(200, 164, 117),
new Color(184, 146, 48),
new Color(157, 195, 132),
new Color(139, 125, 190),
new Color(153, 153, 153),
new Color(230, 199, 255),
new Color(189, 75, 49),
new Color(88, 132, 225),
new Color(120, 166, 90),
new Color(249, 218, 120),
new Color(223, 151, 143),
new Color(70, 185, 185),
new Color(98, 98, 246),
new Color(102, 102, 102),
};
public static final Color[] darkModeTypeColors = new Color[]{new Color(116, 116, 116),
new Color(130, 72, 71),
new Color(101, 133, 133),
new Color(86, 57, 112),
new Color(157, 129, 92),
new Color(99, 79, 26),
new Color(123, 152, 103),
new Color(77, 69, 105),
new Color(68, 68, 68),
new Color(192, 166, 212), //
new Color(61, 24, 16), //
new Color(55, 82, 140), //
new Color(59, 81, 44),
new Color(163, 144, 79),
new Color(180, 122, 116),
new Color(38, 100, 100),
new Color(30, 30, 76),
new Color(17, 17, 17),
};
static {
try {
sheetExportIcon = new FlatSVGIcon(PokeditorManager.class.getResourceAsStream("/pokeditor/icons/svg/table-export.svg"));
sheetImportIcon = new FlatSVGIcon(PokeditorManager.class.getResourceAsStream("/pokeditor/icons/svg/table-import.svg"));
rowRemoveIcon = new FlatSVGIcon(PokeditorManager.class.getResourceAsStream("/pokeditor/icons/svg/row-remove.svg"));
rowInsertIcon = new FlatSVGIcon(PokeditorManager.class.getResourceAsStream("/pokeditor/icons/svg/row-insert-bottom.svg"));
searchIcon = new FlatSVGIcon(PokeditorManager.class.getResourceAsStream("/pokeditor/icons/svg/list-search.svg"));
clipboardIcon = new FlatSVGIcon(PokeditorManager.class.getResourceAsStream("/pokeditor/icons/svg/clipboard-copy.svg"));
copyIcon = new FlatSVGIcon(PokeditorManager.class.getResourceAsStream("/pokeditor/icons/svg/copy.svg"));
sheetExportIcon.setColorFilter(ThemeUtils.iconColorFilter);
sheetImportIcon.setColorFilter(ThemeUtils.iconColorFilter);
rowRemoveIcon.setColorFilter(ThemeUtils.iconColorFilter);
rowInsertIcon.setColorFilter(ThemeUtils.iconColorFilter);
searchIcon.setColorFilter(ThemeUtils.iconColorFilter);
clipboardIcon.setColorFilter(ThemeUtils.iconColorFilter);
copyIcon.setColorFilter(ThemeUtils.iconColorFilter);
/*
this code determines if the label foreground color is closer to/further from black/white, then uses that
to select which set of colors to use for the types on the sheets (lighter or darker)
(the idea being a darker theme tends to have a lighter text foreground color)
*/
Color c = UIManager.getColor("Label.foreground");
double diff = (double) (c.getRed() + c.getBlue() + c.getGreen()) / 3;
if (Math.max(diff, 255 - diff) == diff)
{
System.arraycopy(darkModeTypeColors, 0, typeColors, 0, typeColors.length);
}
}
catch(IOException e) {
throw new RuntimeException(e);
}
}
private List<JPanel> panels;
private NintendoDsRom rom;
private Game baseRom;
private boolean gitEnabled;
public PokeditorManager(Tool tool)
{
super(tool, "PokEditor");
rom = tool.getRom();
baseRom = Game.parseBaseRom(rom.getGameCode());
gitEnabled = tool.isGitEnabled();
GameFiles.initialize(baseRom);
TextFiles.initialize(baseRom);
GameCodeBinaries.initialize(baseRom);
Tables.initialize(baseRom);
| DataManager.codeBinarySetup(rom); | 0 | 2023-10-15 05:00:57+00:00 | 12k |
eclipse-egit/egit | org.eclipse.egit.gitflow.ui/src/org/eclipse/egit/gitflow/ui/internal/dialogs/DecoratedBranchLabelProvider.java | [
{
"identifier": "Activator",
"path": "org.eclipse.egit.ui/src/org/eclipse/egit/ui/Activator.java",
"snippet": "public class Activator extends AbstractUIPlugin {\n\n\t/** The plug-in ID for the EGit UI. */\n\tpublic static final String PLUGIN_ID = \"org.eclipse.egit.ui\"; //$NON-NLS-1$\n\n\t/**\n\t * Th... | import java.io.IOException;
import org.eclipse.egit.ui.Activator;
import org.eclipse.egit.ui.internal.UIIcons;
import org.eclipse.jface.resource.ResourceManager;
import org.eclipse.jface.viewers.ColumnLabelProvider;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.swt.graphics.Image; | 8,740 | /*******************************************************************************
* Copyright (C) 2016, Max Hohenegger <eclipse@hohenegger.eu>
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License 2.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*******************************************************************************/
package org.eclipse.egit.gitflow.ui.internal.dialogs;
class DecoratedBranchLabelProvider extends ColumnLabelProvider {
private ResourceManager resourceManager = Activator.getDefault().getResourceManager();
private Repository repository;
private String prefix;
public DecoratedBranchLabelProvider(Repository repository, String prefix) {
this.repository = repository;
this.prefix = prefix;
}
@Override
public String getText(Object element) {
if (element instanceof Ref) {
String name = ((Ref) element).getName();
return name.substring(prefix.length());
}
return super.getText(element);
}
@Override
public Image getImage(Object element) {
if (element instanceof Ref) {
return decorateImage((Ref) element);
}
return super.getImage(element);
}
private Image decorateImage(Ref node) {
String refName = node.getName();
String branchName;
String compareString;
try {
branchName = repository.getFullBranch();
compareString = refName;
} catch (IOException e) { | /*******************************************************************************
* Copyright (C) 2016, Max Hohenegger <eclipse@hohenegger.eu>
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License 2.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*******************************************************************************/
package org.eclipse.egit.gitflow.ui.internal.dialogs;
class DecoratedBranchLabelProvider extends ColumnLabelProvider {
private ResourceManager resourceManager = Activator.getDefault().getResourceManager();
private Repository repository;
private String prefix;
public DecoratedBranchLabelProvider(Repository repository, String prefix) {
this.repository = repository;
this.prefix = prefix;
}
@Override
public String getText(Object element) {
if (element instanceof Ref) {
String name = ((Ref) element).getName();
return name.substring(prefix.length());
}
return super.getText(element);
}
@Override
public Image getImage(Object element) {
if (element instanceof Ref) {
return decorateImage((Ref) element);
}
return super.getImage(element);
}
private Image decorateImage(Ref node) {
String refName = node.getName();
String branchName;
String compareString;
try {
branchName = repository.getFullBranch();
compareString = refName;
} catch (IOException e) { | return UIIcons.getImage(resourceManager, UIIcons.BRANCH); | 1 | 2023-10-20 15:17:51+00:00 | 12k |
leforero4-ui/unico_proyecto_con_todos_los_patrones_de_diseno_en_java | src/main/application/driver/adapter/usecase/Game.java | [
{
"identifier": "BigBoard",
"path": "src/main/application/driver/adapter/usecase/board/BigBoard.java",
"snippet": "public class BigBoard implements BoardCollection<Enemy> {\n private final Enemy[][] squares;\n private final PatternsIterator<Enemy> iterator;\n private static final int ROWS = 8;\... | import java.util.ArrayList;
import java.util.List;
import main.application.driver.adapter.usecase.board.BigBoard;
import main.application.driver.adapter.usecase.expression.ConjunctionExpression;
import main.application.driver.adapter.usecase.expression.Context;
import main.application.driver.adapter.usecase.expression.AlternativeExpression;
import main.application.driver.adapter.usecase.expression.EnemyExpression;
import main.application.driver.adapter.usecase.factory_enemies.EnemyBasicMethod;
import main.application.driver.adapter.usecase.factory_enemies.EnemyHighMethod;
import main.application.driver.adapter.usecase.factory_enemies.EnemyMiddleMethod;
import main.application.driver.adapter.usecase.mission.BasicMission;
import main.application.driver.adapter.usecase.mission.HighMission;
import main.application.driver.adapter.usecase.mission.MiddleMission;
import main.application.driver.port.usecase.EnemyMethod;
import main.application.driver.port.usecase.Expression;
import main.application.driver.port.usecase.GameableUseCase;
import main.application.driver.port.usecase.iterator.BoardCollection;
import main.application.driver.port.usecase.iterator.PatternsIterator;
import main.domain.model.ArmyFactory;
import main.domain.model.CaretakerPlayer;
import main.domain.model.Command;
import main.domain.model.Enemy;
import main.domain.model.FavorableEnvironment;
import main.domain.model.Healable;
import main.domain.model.Mission;
import main.domain.model.Player;
import main.domain.model.Player.MementoPlayer;
import main.domain.model.command.Attack;
import main.domain.model.command.HealingPlayer;
import main.domain.model.Visitor; | 8,916 | @Override
public void calculateFreezing() {
this.frostbite.calculateFreezing();
}
@Override
public boolean isFrozen() {
return this.frostbite.isFrozen();
}
@Override
public int getTurnsForDefrost() {
return this.frostbite.getTurnsForDefrost();
}
@Override
public void plusTurnFrozen() {
this.frostbite.plusTurnFrozen();
}
private void deleteEnemy(final Enemy enemy) {
while (this.enemyIterator.hasNext()) {
if(this.enemyIterator.getNext().equals(enemy)) {
this.enemyIterator.remove();
break;
}
}
this.enemyIterator.reset();
}
@Override
public String getStringAvatarSquares() {
final StringBuilder squares = new StringBuilder();
while (this.enemyIterator.hasNext()) {
squares.append(this.enemyIterator.getAvatarSquareNext());
}
this.enemyIterator.reset();
return "B=bomba,M=multiples disparos,F=fortaleza,V=veneno,A=aire,N=naval,S=soldado,E=escuadrón,J=Jefe\r\n"
+ "\r\n"
+ "tablero:{fila-columna:avatar:vida:ataque}\r\n"
+ "\r\n"
+ "enemigos: " + squares.toString() + "\r\n"
+ "\r\n"
+ "jugador: {X-X:" + this.player.getAvatar() + ":" + this.player.getLife() + ":" + this.player.getAttackLevel() + "}\r\n";
}
@Override
public String getStringAvatarPlayer() {
return "jugador: {X-X:" + this.player.getAvatar() + ":" + this.player.getLife() + ":" + this.player.getAttackLevel() + "}\r\n";
}
@Override
public void removeDeadEnemies() {
while (this.enemyIterator.hasNext()) {
final Enemy enemy = this.enemyIterator.getNext();
if (enemy.getLife() <= 0) {
this.enemyIterator.remove();
}
}
this.enemyIterator.reset();
}
@Override
public void healing() {
final Visitor healable = new Healable();
while (this.enemyIterator.hasNext()) {
final Enemy enemy = this.enemyIterator.getNext();
enemy.acceptVisit(healable);
}
this.enemyIterator.reset();
final Command healingCommand = new HealingPlayer(this.player);
if (this.frostbite.isFrozen()) {
this.frostbite.addCommand(healingCommand);
} else {
healingCommand.execute();
}
}
@Override
public String getEnemies(final String stringExpression) {
final Expression expression = this.parseExpression(this.prepareStringExpression(stringExpression));
final Context context = new Context(this.getAvatarSquares());
final StringBuilder avatarSquaresStringBuilder = new StringBuilder();
List<String> avatarSquares = expression.interpret(context);
avatarSquares.forEach(avatarSquare -> avatarSquaresStringBuilder.append(avatarSquare + "\r\n"));
return avatarSquaresStringBuilder.toString();
}
private List<String> getAvatarSquares() {
final List<String> avatarSquares = new ArrayList<>();
while (this.enemyIterator.hasNext()) {
avatarSquares.add(this.enemyIterator.getAvatarSquareNext());
}
this.enemyIterator.reset();
return avatarSquares;
}
private String prepareStringExpression(String stringExpression) {
stringExpression = stringExpression.substring("buscar:".length());
stringExpression = stringExpression.replaceAll("\\(", " \\( ");
stringExpression = stringExpression.replaceAll("\\)", " \\) ");
stringExpression = stringExpression.replaceAll(" ", " ");
stringExpression = stringExpression.trim();
return stringExpression;
}
//recurrencia
private Expression parseExpression(final String input) {
final String[] tokens = input.split(" ", 3);
String firstToken = tokens[0];
if (firstToken.equalsIgnoreCase("(")) {
final String[] seconPartToken = input.split(" ", 2);
return this.parseExpression(seconPartToken[1]);
}
if (tokens.length != 3) { | package main.application.driver.adapter.usecase;
public class Game implements GameableUseCase {
private final ArmyFactory armyFactory;
private EnemyMethod enemyMethod;
private final Player player;
private BoardCollection<Enemy> board;
private PatternsIterator<Enemy> enemyIterator;
private FavorableEnvironment favorableEnvironments;
private final Frostbite frostbite;
private final CaretakerPlayer caretakerPlayer;
private Mission mission;
private int level;
public Game(final ArmyFactory armyFactory, final Player player) {
this.armyFactory = armyFactory;
this.player = player;
this.frostbite = new Frostbite();
this.caretakerPlayer = new CaretakerPlayer();
}
@Override
public void startGame() {
this.enemyMethod = new EnemyBasicMethod(armyFactory);
this.board = new BigBoard(this.enemyMethod.createEnemies());
this.enemyIterator = this.board.getIterator();
this.mission = new BasicMission(this.board);
this.favorableEnvironments = this.enemyMethod.createFavorableEnvironments();
this.level = 1;
}
@Override
public boolean verifyAnUpLevel() {
if (this.mission.isMissionComplete()) {
if (this.level == 1) {
this.enemyMethod = new EnemyMiddleMethod(armyFactory);
this.board = new BigBoard(this.enemyMethod.createEnemies());
this.enemyIterator = this.board.getIterator();
this.mission = new MiddleMission(this.board);
this.favorableEnvironments = this.enemyMethod.createFavorableEnvironments();
} else {
this.enemyMethod = new EnemyHighMethod(armyFactory);
this.board = new BigBoard(this.enemyMethod.createEnemies());
this.enemyIterator = this.board.getIterator();
this.mission = new HighMission(this.board);
this.favorableEnvironments = this.enemyMethod.createFavorableEnvironments();
}
++this.level;
return true;
}
return false;
}
@Override
public boolean isGameCompleted() {
return this.level > 3;
}
@Override
public Boolean[] attackAndCounterAttack(final int row, final int column) {
final Enemy enemy = board.getEnemy(row, column);
return new Boolean[] {this.attack(enemy), this.eliminedEnemyFallBackCounterAttack(enemy)};
}
@Override
public Boolean[] attackWithComboAndCounterAttack(final int row, final int column) {
final Enemy enemy = board.getEnemy(row, column);
return new Boolean[] {this.combo(enemy), this.eliminedEnemyFallBackCounterAttack(enemy)};
}
private boolean eliminedEnemyFallBackCounterAttack(final Enemy enemy) {
final boolean isEnemyEliminated = enemy.getLife() <= 0;
if (isEnemyEliminated) {
this.deleteEnemy(enemy);
} else {
this.counterAttack(enemy);
}
return isEnemyEliminated;
}
private void counterAttack(final Enemy enemy) {
this.player.receiveAttack(enemy.getCounterAttackLevel(this.player.getAttackLevel()));
}
private boolean combo(final Enemy enemy) {
final int lifeBeforeAttack = enemy.getLife();
final List<Command> comboCommands = new ArrayList<>();
comboCommands.add(new Attack(this.favorableEnvironments, this.player.getAttackLevel(), enemy));
comboCommands.add(new HealingPlayer(this.player));
comboCommands.add(new Attack(this.favorableEnvironments, this.player.getAttackLevel(), enemy));
comboCommands.add(new HealingPlayer(this.player));
comboCommands.add(new Attack(this.favorableEnvironments, this.player.getAttackLevel(), enemy));
if (this.frostbite.isFrozen()) {
this.frostbite.addCommands(comboCommands);
return false;
}
comboCommands.forEach(Command::execute);
return lifeBeforeAttack != enemy.getLife();
}
private boolean attack(final Enemy enemy) {
final int lifeBeforeAttack = enemy.getLife();
final Command attackCommand = new Attack(this.favorableEnvironments, this.player.getAttackLevel(), enemy);
if (this.frostbite.isFrozen()) {
this.frostbite.addCommand(attackCommand);
return false;
}
attackCommand.execute();
return lifeBeforeAttack != enemy.getLife();
}
@Override
public void calculateFreezing() {
this.frostbite.calculateFreezing();
}
@Override
public boolean isFrozen() {
return this.frostbite.isFrozen();
}
@Override
public int getTurnsForDefrost() {
return this.frostbite.getTurnsForDefrost();
}
@Override
public void plusTurnFrozen() {
this.frostbite.plusTurnFrozen();
}
private void deleteEnemy(final Enemy enemy) {
while (this.enemyIterator.hasNext()) {
if(this.enemyIterator.getNext().equals(enemy)) {
this.enemyIterator.remove();
break;
}
}
this.enemyIterator.reset();
}
@Override
public String getStringAvatarSquares() {
final StringBuilder squares = new StringBuilder();
while (this.enemyIterator.hasNext()) {
squares.append(this.enemyIterator.getAvatarSquareNext());
}
this.enemyIterator.reset();
return "B=bomba,M=multiples disparos,F=fortaleza,V=veneno,A=aire,N=naval,S=soldado,E=escuadrón,J=Jefe\r\n"
+ "\r\n"
+ "tablero:{fila-columna:avatar:vida:ataque}\r\n"
+ "\r\n"
+ "enemigos: " + squares.toString() + "\r\n"
+ "\r\n"
+ "jugador: {X-X:" + this.player.getAvatar() + ":" + this.player.getLife() + ":" + this.player.getAttackLevel() + "}\r\n";
}
@Override
public String getStringAvatarPlayer() {
return "jugador: {X-X:" + this.player.getAvatar() + ":" + this.player.getLife() + ":" + this.player.getAttackLevel() + "}\r\n";
}
@Override
public void removeDeadEnemies() {
while (this.enemyIterator.hasNext()) {
final Enemy enemy = this.enemyIterator.getNext();
if (enemy.getLife() <= 0) {
this.enemyIterator.remove();
}
}
this.enemyIterator.reset();
}
@Override
public void healing() {
final Visitor healable = new Healable();
while (this.enemyIterator.hasNext()) {
final Enemy enemy = this.enemyIterator.getNext();
enemy.acceptVisit(healable);
}
this.enemyIterator.reset();
final Command healingCommand = new HealingPlayer(this.player);
if (this.frostbite.isFrozen()) {
this.frostbite.addCommand(healingCommand);
} else {
healingCommand.execute();
}
}
@Override
public String getEnemies(final String stringExpression) {
final Expression expression = this.parseExpression(this.prepareStringExpression(stringExpression));
final Context context = new Context(this.getAvatarSquares());
final StringBuilder avatarSquaresStringBuilder = new StringBuilder();
List<String> avatarSquares = expression.interpret(context);
avatarSquares.forEach(avatarSquare -> avatarSquaresStringBuilder.append(avatarSquare + "\r\n"));
return avatarSquaresStringBuilder.toString();
}
private List<String> getAvatarSquares() {
final List<String> avatarSquares = new ArrayList<>();
while (this.enemyIterator.hasNext()) {
avatarSquares.add(this.enemyIterator.getAvatarSquareNext());
}
this.enemyIterator.reset();
return avatarSquares;
}
private String prepareStringExpression(String stringExpression) {
stringExpression = stringExpression.substring("buscar:".length());
stringExpression = stringExpression.replaceAll("\\(", " \\( ");
stringExpression = stringExpression.replaceAll("\\)", " \\) ");
stringExpression = stringExpression.replaceAll(" ", " ");
stringExpression = stringExpression.trim();
return stringExpression;
}
//recurrencia
private Expression parseExpression(final String input) {
final String[] tokens = input.split(" ", 3);
String firstToken = tokens[0];
if (firstToken.equalsIgnoreCase("(")) {
final String[] seconPartToken = input.split(" ", 2);
return this.parseExpression(seconPartToken[1]);
}
if (tokens.length != 3) { | return new EnemyExpression(firstToken); | 4 | 2023-10-20 18:36:47+00:00 | 12k |
Squawkykaka/when_pigs_fly | src/main/java/com/squawkykaka/when_pigs_fly/WhenPigsFly.java | [
{
"identifier": "Heal_Feed",
"path": "src/main/java/com/squawkykaka/when_pigs_fly/commands/Heal_Feed.java",
"snippet": "public class Heal_Feed {\n public Heal_Feed() {\n new CommandBase(\"heal\", true) {\n @Override\n public boolean onCommand(CommandSender sender, String ... | import com.squawkykaka.when_pigs_fly.commands.Heal_Feed;
import com.squawkykaka.when_pigs_fly.commands.Menu;
import com.squawkykaka.when_pigs_fly.commands.Spawn;
import com.squawkykaka.when_pigs_fly.util.EventUtil;
import com.squawkykaka.when_pigs_fly.util.Metrics;
import org.bukkit.plugin.java.JavaPlugin; | 9,226 | package com.squawkykaka.when_pigs_fly;
public final class WhenPigsFly extends JavaPlugin {
private static WhenPigsFly instance;
@Override
public void onEnable() {
instance = this; // Set the instance to the current plugin
saveDefaultConfig();
getLogger().info("------------------------");
getLogger().info("---- Plugin Loading ----");
EventUtil.register(new AxolotlThrowListener(this));
EventUtil.register(new PluginEvents());
new Heal_Feed();
new Spawn(this); | package com.squawkykaka.when_pigs_fly;
public final class WhenPigsFly extends JavaPlugin {
private static WhenPigsFly instance;
@Override
public void onEnable() {
instance = this; // Set the instance to the current plugin
saveDefaultConfig();
getLogger().info("------------------------");
getLogger().info("---- Plugin Loading ----");
EventUtil.register(new AxolotlThrowListener(this));
EventUtil.register(new PluginEvents());
new Heal_Feed();
new Spawn(this); | new Menu(this); | 1 | 2023-10-17 02:07:39+00:00 | 12k |
greatwqs/finance-manager | src/main/java/com/github/greatwqs/app/service/impl/OrderExcelServiceImpl.java | [
{
"identifier": "AppConstants",
"path": "src/main/java/com/github/greatwqs/app/common/AppConstants.java",
"snippet": "public class AppConstants {\n\n // default locale\n public static final Locale LOCALE = new Locale(\"zh\", \"CN\");\n\n /**\n * ErrorCode i18n properties prefix key.\n *... | import com.github.greatwqs.app.common.AppConstants;
import com.github.greatwqs.app.domain.dto.OrderDownloadDto;
import com.github.greatwqs.app.domain.dto.OrderDto;
import com.github.greatwqs.app.domain.po.UserPo;
import com.github.greatwqs.app.domain.vo.OrderVo;
import com.github.greatwqs.app.domain.vo.SubjectVo;
import com.github.greatwqs.app.domain.vo.TicketTypeVo;
import com.github.greatwqs.app.manager.SubjectManager;
import com.github.greatwqs.app.manager.TicketTypeManager;
import com.github.greatwqs.app.mapper.OrderlistMapper;
import com.github.greatwqs.app.service.OrderExcelService;
import com.github.greatwqs.app.service.OrderService;
import com.github.greatwqs.app.utils.JsonUtil;
import com.github.greatwqs.app.utils.UrlUtil;
import com.github.greatwqs.app.utils.collection.Lists;
import com.github.greatwqs.app.utils.excel.ExcelExport;
import com.github.greatwqs.app.utils.excel.ExcelParseUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors; | 7,568 | package com.github.greatwqs.app.service.impl;
/**
* @author greatwqs
* Create on 2020/7/9
*/
@Slf4j
@Service
public class OrderExcelServiceImpl implements OrderExcelService {
@Autowired
private ModelMapper modelMapper;
@Autowired
private OrderlistMapper orderlistMapper;
@Autowired
private SubjectManager subjectManager;
@Autowired
private TicketTypeManager ticketTypeManager;
@Autowired
private OrderService orderService;
@Override
public void download(HttpServletResponse response, OrderDownloadDto downloadDto, | package com.github.greatwqs.app.service.impl;
/**
* @author greatwqs
* Create on 2020/7/9
*/
@Slf4j
@Service
public class OrderExcelServiceImpl implements OrderExcelService {
@Autowired
private ModelMapper modelMapper;
@Autowired
private OrderlistMapper orderlistMapper;
@Autowired
private SubjectManager subjectManager;
@Autowired
private TicketTypeManager ticketTypeManager;
@Autowired
private OrderService orderService;
@Override
public void download(HttpServletResponse response, OrderDownloadDto downloadDto, | UserPo userPo) throws IOException { | 3 | 2023-10-16 12:45:57+00:00 | 12k |
Wind-Gone/Vodka | code/src/main/java/utils/load/LoadDataWorker.java | [
{
"identifier": "NationData",
"path": "code/src/main/java/benchmark/olap/data/NationData.java",
"snippet": "public class NationData {\n public static Integer[] nationKey = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24};\n public static String[] nationNam... | import benchmark.olap.data.NationData;
import benchmark.olap.data.RegionData;
import utils.math.random.BasicRandom;
import org.apache.log4j.Logger;
import java.sql.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.io.*;
import java.util.Date; | 7,387 | "VALUES (?, ?, ?, ?, ?, ?, ?, ?)"
);
stmtOrder = dbConn.prepareStatement(
"INSERT INTO vodka_oorder (" +
" o_id, o_d_id, o_w_id, o_c_id, o_entry_d, " +
" o_carrier_id, o_ol_cnt, o_all_local, o_comment, o_shippriority) " +
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
);
stmtOrderLine = dbConn.prepareStatement(
"INSERT INTO vodka_order_line (" +
" ol_o_id, ol_d_id, ol_w_id, ol_number, ol_i_id, " +
" ol_supply_w_id, ol_delivery_d, ol_quantity, " +
" ol_amount, ol_dist_info, ol_discount, ol_shipmode," +
" ol_shipinstruct, ol_receipdate, ol_commitdate, ol_returnflag, ol_suppkey, ol_tax, access_version) " +
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
);
stmtNewOrder = dbConn.prepareStatement(
"INSERT INTO vodka_new_order (" +
" no_o_id, no_d_id, no_w_id) " +
"VALUES (?, ?, ?)"
);
stmtRegion = dbConn.prepareStatement(
"insert into vodka_region (r_regionkey,r_name,r_comment) values (?,?,?)"
);
stmtNation = dbConn.prepareStatement(
"insert into vodka_nation (n_nationkey,n_name,n_regionkey,n_comment) values (?,?,?,?)"
);
stmtSupplier = dbConn.prepareStatement(
"insert into vodka_supplier (s_suppkey,s_nationkey,s_comment, s_name, s_address, s_acctbal, s_phone) values (?, ?, ?, ?, ?, ?, ?)"
);
}
/*
* run()
*/
public void run() {
int job;
try {
while ((job = LoadData.getNextJob()) >= 0) {
if (job == 0) {
fmt.format("Worker %03d: Loading Item", worker);
System.out.println(sb.toString());
sb.setLength(0);
loadItem();
fmt.format("Worker %03d: Loading Item done", worker);
System.out.println(sb.toString());
sb.setLength(0);
fmt.format("Worker %03d: Loading Nation", worker);
System.out.println(sb.toString());
sb.setLength(0);
loadNation();
fmt.format("Worker %03d: Loading Nation done", worker);
System.out.println(sb.toString());
sb.setLength(0);
fmt.format("Worker %03d: Loading Region", worker);
System.out.println(sb.toString());
sb.setLength(0);
loadRegion();
fmt.format("Worker %03d: Loading Region done", worker);
System.out.println(sb.toString());
sb.setLength(0);
fmt.format("Worker %03d: Loading Supplier", worker);
System.out.println(sb.toString());
sb.setLength(0);
loadSupplier();
fmt.format("Worker %03d: Loading Supplier done", worker);
System.out.println(sb.toString());
sb.setLength(0);
} else {
fmt.format("Worker %03d: Loading Warehouse %6d",
worker, job);
System.out.println(sb.toString());
sb.setLength(0);
loadWarehouse(job);
fmt.format("Worker %03d: Loading Warehouse %6d done",
worker, job);
}
System.out.println(sb.toString());
sb.setLength(0);
}
/*
* Close the DB connection if in direct DB mode.
*/
if (!writeCSV)
dbConn.close();
} catch (SQLException se) {
log.info("LoadDataWorker.java: " + getSQLExceptionInfo(se));
SQLException throwables = se;
while (throwables != null) {
fmt.format("Worker %03d: ERROR: %s", worker, throwables.getMessage());
System.err.println(sb.toString());
sb.setLength(0);
throwables = throwables.getNextException();
}
} catch (Exception e) {
fmt.format("Worker %03d: ERROR: %s", worker, e.getMessage());
System.err.println(sb.toString());
sb.setLength(0);
e.printStackTrace();
}
} // End run()
private void loadRegion() {
try { | package utils.load;/*
* LoadDataWorker - Class to utils.load one Warehouse (or in a special case
* the ITEM table).
*
*
*
*/
public class LoadDataWorker implements Runnable {
private static Logger log = Logger.getLogger(LoadDataWorker.class);
private int worker;
private Connection dbConn;
private BasicRandom rnd;
private StringBuffer sb;
private Formatter fmt;
private boolean writeCSV = false;
private String csvNull = null;
private PreparedStatement stmtConfig = null;
private PreparedStatement stmtItem = null;
private PreparedStatement stmtWarehouse = null;
private PreparedStatement stmtDistrict = null;
private PreparedStatement stmtStock = null;
private PreparedStatement stmtCustomer = null;
private PreparedStatement stmtHistory = null;
private PreparedStatement stmtOrder = null;
private PreparedStatement stmtOrderLine = null;
private PreparedStatement stmtNewOrder = null;
private PreparedStatement stmtRegion = null;
private PreparedStatement stmtNation = null;
private PreparedStatement stmtSupplier = null;
private StringBuffer sbConfig = null;
private Formatter fmtConfig = null;
private StringBuffer sbItem = null;
private Formatter fmtItem = null;
private StringBuffer sbWarehouse = null;
private Formatter fmtWarehouse = null;
private StringBuffer sbDistrict = null;
private Formatter fmtDistrict = null;
private StringBuffer sbStock = null;
private Formatter fmtStock = null;
private StringBuffer sbCustomer = null;
private Formatter fmtCustomer = null;
private StringBuffer sbHistory = null;
private Formatter fmtHistory = null;
private StringBuffer sbOrder = null;
private Formatter fmtOrder = null;
private StringBuffer sbOrderLine = null;
private Formatter fmtOrderLine = null;
private StringBuffer sbNewOrder = null;
private Formatter fmtNewOrder = null;
LoadDataWorker(int worker, String csvNull, BasicRandom rnd) {
this.worker = worker;
this.csvNull = csvNull;
this.rnd = rnd;
this.sb = new StringBuffer();
this.fmt = new Formatter(sb);
this.writeCSV = true;
this.sbConfig = new StringBuffer();
this.fmtConfig = new Formatter(sbConfig);
this.sbItem = new StringBuffer();
this.fmtItem = new Formatter(sbItem);
this.sbWarehouse = new StringBuffer();
this.fmtWarehouse = new Formatter(sbWarehouse);
this.sbDistrict = new StringBuffer();
this.fmtDistrict = new Formatter(sbDistrict);
this.sbStock = new StringBuffer();
this.fmtStock = new Formatter(sbStock);
this.sbCustomer = new StringBuffer();
this.fmtCustomer = new Formatter(sbCustomer);
this.sbHistory = new StringBuffer();
this.fmtHistory = new Formatter(sbHistory);
this.sbOrder = new StringBuffer();
this.fmtOrder = new Formatter(sbOrder);
this.sbOrderLine = new StringBuffer();
this.fmtOrderLine = new Formatter(sbOrderLine);
this.sbNewOrder = new StringBuffer();
this.fmtNewOrder = new Formatter(sbNewOrder);
}
LoadDataWorker(int worker, Connection dbConn, BasicRandom rnd)
throws SQLException {
this.worker = worker;
this.dbConn = dbConn;
this.rnd = rnd;
this.sb = new StringBuffer();
this.fmt = new Formatter(sb);
stmtConfig = dbConn.prepareStatement(
"INSERT INTO vodka_config (" +
" cfg_name, cfg_value) " +
"VALUES (?, ?)"
);
stmtItem = dbConn.prepareStatement(
"INSERT INTO vodka_item (" +
" i_id, i_im_id, i_name, i_price, i_data, i_container, i_size, i_brand, i_type, i_mfgr) " +
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
);
stmtWarehouse = dbConn.prepareStatement(
"INSERT INTO vodka_warehouse (" +
" w_id, w_name, w_street_1, w_street_2, w_city, " +
" w_state, w_zip, w_tax, w_ytd) " +
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"
);
stmtStock = dbConn.prepareStatement(
"INSERT INTO vodka_stock (" +
" s_i_id, s_w_id, s_quantity, s_dist_01, s_dist_02, " +
" s_dist_03, s_dist_04, s_dist_05, s_dist_06, " +
" s_dist_07, s_dist_08, s_dist_09, s_dist_10, " +
" s_ytd, s_order_cnt, s_remote_cnt, s_data, s_supplycost,s_tocksuppkey) " +
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
);
stmtDistrict = dbConn.prepareStatement(
"INSERT INTO vodka_district (" +
" d_id, d_w_id, d_name, d_street_1, d_street_2, " +
" d_city, d_state, d_zip, d_tax, d_ytd, d_next_o_id) " +
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
);
stmtCustomer = dbConn.prepareStatement(
"INSERT INTO vodka_customer (" +
" c_id, c_d_id, c_w_id, c_first, c_middle, c_last, " +
" c_street_1, c_street_2, c_city, c_nationkey, c_zip, " +
" c_phone, c_since, c_credit, c_credit_lim, c_discount, " +
" c_balance, c_ytd_payment, c_payment_cnt, " +
" c_delivery_cnt, c_data, c_mktsegment) " +
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " +
" ?, ?, ?, ?, ?, ?, ?)"
);
stmtHistory = dbConn.prepareStatement(
"INSERT INTO vodka_history (" +
" h_c_id, h_c_d_id, h_c_w_id, h_d_id, h_w_id, " +
" h_date, h_amount, h_data) " +
"VALUES (?, ?, ?, ?, ?, ?, ?, ?)"
);
stmtOrder = dbConn.prepareStatement(
"INSERT INTO vodka_oorder (" +
" o_id, o_d_id, o_w_id, o_c_id, o_entry_d, " +
" o_carrier_id, o_ol_cnt, o_all_local, o_comment, o_shippriority) " +
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
);
stmtOrderLine = dbConn.prepareStatement(
"INSERT INTO vodka_order_line (" +
" ol_o_id, ol_d_id, ol_w_id, ol_number, ol_i_id, " +
" ol_supply_w_id, ol_delivery_d, ol_quantity, " +
" ol_amount, ol_dist_info, ol_discount, ol_shipmode," +
" ol_shipinstruct, ol_receipdate, ol_commitdate, ol_returnflag, ol_suppkey, ol_tax, access_version) " +
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
);
stmtNewOrder = dbConn.prepareStatement(
"INSERT INTO vodka_new_order (" +
" no_o_id, no_d_id, no_w_id) " +
"VALUES (?, ?, ?)"
);
stmtRegion = dbConn.prepareStatement(
"insert into vodka_region (r_regionkey,r_name,r_comment) values (?,?,?)"
);
stmtNation = dbConn.prepareStatement(
"insert into vodka_nation (n_nationkey,n_name,n_regionkey,n_comment) values (?,?,?,?)"
);
stmtSupplier = dbConn.prepareStatement(
"insert into vodka_supplier (s_suppkey,s_nationkey,s_comment, s_name, s_address, s_acctbal, s_phone) values (?, ?, ?, ?, ?, ?, ?)"
);
}
/*
* run()
*/
public void run() {
int job;
try {
while ((job = LoadData.getNextJob()) >= 0) {
if (job == 0) {
fmt.format("Worker %03d: Loading Item", worker);
System.out.println(sb.toString());
sb.setLength(0);
loadItem();
fmt.format("Worker %03d: Loading Item done", worker);
System.out.println(sb.toString());
sb.setLength(0);
fmt.format("Worker %03d: Loading Nation", worker);
System.out.println(sb.toString());
sb.setLength(0);
loadNation();
fmt.format("Worker %03d: Loading Nation done", worker);
System.out.println(sb.toString());
sb.setLength(0);
fmt.format("Worker %03d: Loading Region", worker);
System.out.println(sb.toString());
sb.setLength(0);
loadRegion();
fmt.format("Worker %03d: Loading Region done", worker);
System.out.println(sb.toString());
sb.setLength(0);
fmt.format("Worker %03d: Loading Supplier", worker);
System.out.println(sb.toString());
sb.setLength(0);
loadSupplier();
fmt.format("Worker %03d: Loading Supplier done", worker);
System.out.println(sb.toString());
sb.setLength(0);
} else {
fmt.format("Worker %03d: Loading Warehouse %6d",
worker, job);
System.out.println(sb.toString());
sb.setLength(0);
loadWarehouse(job);
fmt.format("Worker %03d: Loading Warehouse %6d done",
worker, job);
}
System.out.println(sb.toString());
sb.setLength(0);
}
/*
* Close the DB connection if in direct DB mode.
*/
if (!writeCSV)
dbConn.close();
} catch (SQLException se) {
log.info("LoadDataWorker.java: " + getSQLExceptionInfo(se));
SQLException throwables = se;
while (throwables != null) {
fmt.format("Worker %03d: ERROR: %s", worker, throwables.getMessage());
System.err.println(sb.toString());
sb.setLength(0);
throwables = throwables.getNextException();
}
} catch (Exception e) {
fmt.format("Worker %03d: ERROR: %s", worker, e.getMessage());
System.err.println(sb.toString());
sb.setLength(0);
e.printStackTrace();
}
} // End run()
private void loadRegion() {
try { | int arraySize = RegionData.regionKey.length; | 1 | 2023-10-22 11:22:32+00:00 | 12k |
ushh789/FinancialCalculator | src/main/java/com/netrunners/financialcalculator/LogicalInstrumnts/TypesOfFinancialOpearation/Credit/Credit.java | [
{
"identifier": "LogHelper",
"path": "src/main/java/com/netrunners/financialcalculator/LogicalInstrumnts/FileInstruments/LogHelper.java",
"snippet": "public class LogHelper {\n\n // Додаємо об'єкт логування\n private static final Logger logger = Logger.getLogger(LogHelper.class.getName());\n\n ... | import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.netrunners.financialcalculator.LogicalInstrumnts.FileInstruments.LogHelper;
import com.netrunners.financialcalculator.LogicalInstrumnts.FileInstruments.Savable;
import com.netrunners.financialcalculator.LogicalInstrumnts.TimeFunctions.DateTimeFunctions;
import com.netrunners.financialcalculator.LogicalInstrumnts.TimeFunctions.LocalDateAdapter;
import com.netrunners.financialcalculator.MenuControllers.ResultTableController;
import com.netrunners.financialcalculator.StartMenu;
import com.netrunners.financialcalculator.VisualInstruments.MenuActions.LanguageManager;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.time.LocalDate;
import java.util.logging.Level; | 10,457 | package com.netrunners.financialcalculator.LogicalInstrumnts.TypesOfFinancialOpearation.Credit;
public class Credit implements Savable {
protected float loan;
protected String currency;
protected float annualPercent;
protected LocalDate startDate;
protected LocalDate endDate;
protected int paymentType;
protected int contractDuration;
public Credit(float loan, String currency, float annualPercent, LocalDate startDate, LocalDate endDate, int paymentType) {
this.loan = loan;
this.currency = currency;
this.annualPercent = annualPercent;
this.startDate = startDate;
this.endDate = endDate;
this.paymentType = paymentType; | package com.netrunners.financialcalculator.LogicalInstrumnts.TypesOfFinancialOpearation.Credit;
public class Credit implements Savable {
protected float loan;
protected String currency;
protected float annualPercent;
protected LocalDate startDate;
protected LocalDate endDate;
protected int paymentType;
protected int contractDuration;
public Credit(float loan, String currency, float annualPercent, LocalDate startDate, LocalDate endDate, int paymentType) {
this.loan = loan;
this.currency = currency;
this.annualPercent = annualPercent;
this.startDate = startDate;
this.endDate = endDate;
this.paymentType = paymentType; | this.contractDuration = DateTimeFunctions.countDaysBetweenDates(startDate, endDate); | 2 | 2023-10-18 16:03:09+00:00 | 12k |
Kyrotechnic/KyroClient | Client/src/main/java/me/kyroclient/mixins/MixinMinecraft.java | [
{
"identifier": "KyroClient",
"path": "Client/src/main/java/me/kyroclient/KyroClient.java",
"snippet": "public class KyroClient {\n //Vars\n public static final String MOD_ID = \"dankers\";\n public static String VERSION = \"0.2-b3\";\n public static List<String> changelog;\n public stati... | import me.kyroclient.KyroClient;
import me.kyroclient.events.KeyboardEvent;
import me.kyroclient.events.LeftClickEvent;
import me.kyroclient.events.PostGuiOpenEvent;
import me.kyroclient.events.RightClickEvent;
import me.kyroclient.modules.combat.Aura;
import me.kyroclient.modules.player.ServerRotations;
import me.kyroclient.util.PlayerUtil;
import net.minecraft.block.material.Material;
import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.multiplayer.PlayerControllerMP;
import net.minecraft.client.multiplayer.WorldClient;
import net.minecraft.client.settings.GameSettings;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.network.play.client.C07PacketPlayerDigging;
import net.minecraft.util.BlockPos;
import net.minecraft.util.MovingObjectPosition;
import net.minecraftforge.common.MinecraftForge;
import org.lwjgl.input.Keyboard;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; | 8,161 | package me.kyroclient.mixins;
@Mixin(Minecraft.class)
public class MixinMinecraft {
@Shadow public EntityPlayerSP thePlayer;
@Shadow public GuiScreen currentScreen;
@Shadow public GameSettings gameSettings;
@Shadow public boolean inGameHasFocus;
@Shadow public MovingObjectPosition objectMouseOver;
@Shadow private Entity renderViewEntity;
@Shadow public PlayerControllerMP playerController;
@Shadow public WorldClient theWorld;
@Shadow private int leftClickCounter;
@Shadow private int rightClickDelayTimer;
@Inject(method = "startGame", at = @At("HEAD"))
public void startGame(CallbackInfo ci)
{ | package me.kyroclient.mixins;
@Mixin(Minecraft.class)
public class MixinMinecraft {
@Shadow public EntityPlayerSP thePlayer;
@Shadow public GuiScreen currentScreen;
@Shadow public GameSettings gameSettings;
@Shadow public boolean inGameHasFocus;
@Shadow public MovingObjectPosition objectMouseOver;
@Shadow private Entity renderViewEntity;
@Shadow public PlayerControllerMP playerController;
@Shadow public WorldClient theWorld;
@Shadow private int leftClickCounter;
@Shadow private int rightClickDelayTimer;
@Inject(method = "startGame", at = @At("HEAD"))
public void startGame(CallbackInfo ci)
{ | KyroClient.init(); | 0 | 2023-10-15 16:24:51+00:00 | 12k |
AstroDev2023/2023-studio-1-but-better | source/core/src/main/com/csse3200/game/entities/factories/RenderFactory.java | [
{
"identifier": "CameraComponent",
"path": "source/core/src/main/com/csse3200/game/components/CameraComponent.java",
"snippet": "public class CameraComponent extends Component {\n\tprivate final Camera camera;\n\tprivate Vector2 lastPosition;\n\tprivate Entity trackEntity;\n\n\t/**\n\t * Creates a new C... | import com.csse3200.game.components.CameraComponent;
import com.csse3200.game.entities.Entity;
import com.csse3200.game.rendering.Renderer;
import com.csse3200.game.services.ServiceLocator; | 8,697 | package com.csse3200.game.entities.factories;
public class RenderFactory {
public static Entity createCamera() {
return new Entity().addComponent(new CameraComponent());
}
public static Renderer createRenderer() {
Entity camera = createCamera(); | package com.csse3200.game.entities.factories;
public class RenderFactory {
public static Entity createCamera() {
return new Entity().addComponent(new CameraComponent());
}
public static Renderer createRenderer() {
Entity camera = createCamera(); | ServiceLocator.getEntityService().register(camera); | 3 | 2023-10-17 22:34:04+00:00 | 12k |
LuckPerms/rest-api-java-client | src/test/java/me/lucko/luckperms/rest/UserServiceTest.java | [
{
"identifier": "LuckPermsRestClient",
"path": "src/main/java/net/luckperms/rest/LuckPermsRestClient.java",
"snippet": "public interface LuckPermsRestClient extends AutoCloseable {\n\n /**\n * Creates a new client builder.\n *\n * @return the new builder\n */\n static Builder build... | import net.luckperms.rest.LuckPermsRestClient;
import net.luckperms.rest.model.Context;
import net.luckperms.rest.model.CreateGroupRequest;
import net.luckperms.rest.model.CreateTrackRequest;
import net.luckperms.rest.model.CreateUserRequest;
import net.luckperms.rest.model.DemotionResult;
import net.luckperms.rest.model.Group;
import net.luckperms.rest.model.Metadata;
import net.luckperms.rest.model.Node;
import net.luckperms.rest.model.NodeType;
import net.luckperms.rest.model.PermissionCheckRequest;
import net.luckperms.rest.model.PermissionCheckResult;
import net.luckperms.rest.model.PlayerSaveResult;
import net.luckperms.rest.model.PromotionResult;
import net.luckperms.rest.model.QueryOptions;
import net.luckperms.rest.model.TemporaryNodeMergeStrategy;
import net.luckperms.rest.model.TrackRequest;
import net.luckperms.rest.model.UpdateTrackRequest;
import net.luckperms.rest.model.UpdateUserRequest;
import net.luckperms.rest.model.User;
import net.luckperms.rest.model.UserLookupResult;
import net.luckperms.rest.model.UserSearchResult;
import org.junit.jupiter.api.Test;
import org.testcontainers.shaded.com.google.common.collect.ImmutableList;
import org.testcontainers.shaded.com.google.common.collect.ImmutableSet;
import retrofit2.Response;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue; | 7,290 | String username = randomName();
// create a user
assertTrue(client.users().create(new CreateUserRequest(uuid, username)).execute().isSuccessful());
// set some permissions
long expiryTime = (System.currentTimeMillis() / 1000L) + 60;
assertTrue(client.users().nodesAdd(uuid, ImmutableList.of(
new Node("test.node.one", true, Collections.emptySet(), null),
new Node("test.node.two", false, Collections.emptySet(), null),
new Node("test.node.three", true, Collections.singleton(new Context("server", "test")), null),
new Node("test.node.four", false, Collections.emptySet(), expiryTime),
new Node("prefix.100.&c[Admin] ", true, Collections.emptySet(), null),
new Node("suffix.100. test", true, Collections.emptySet(), null),
new Node("meta.hello.world", true, Collections.emptySet(), null)
)).execute().isSuccessful());
// searchNodesByKey
Response<List<UserSearchResult>> resp1 = client.users().searchNodesByKey("test.node.one").execute();
assertTrue(resp1.isSuccessful());
assertNotNull(resp1.body());
assertEquals(ImmutableList.of(
new UserSearchResult(uuid, ImmutableList.of(new Node("test.node.one", true, Collections.emptySet(), null)))
), resp1.body());
// searchNodesByKeyStartsWith
Response<List<UserSearchResult>> resp2 = client.users().searchNodesByKeyStartsWith("test.node").execute();
assertTrue(resp2.isSuccessful());
assertNotNull(resp2.body());
assertEquals(ImmutableList.of(
new UserSearchResult(uuid, ImmutableList.of(
new Node("test.node.one", true, Collections.emptySet(), null),
new Node("test.node.two", false, Collections.emptySet(), null),
new Node("test.node.three", true, Collections.singleton(new Context("server", "test")), null),
new Node("test.node.four", false, Collections.emptySet(), expiryTime)
))
), resp2.body());
// searchNodesByMetaKey
Response<List<UserSearchResult>> resp3 = client.users().searchNodesByMetaKey("hello").execute();
assertTrue(resp3.isSuccessful());
assertNotNull(resp3.body());
assertEquals(ImmutableList.of(
new UserSearchResult(uuid, ImmutableList.of(new Node("meta.hello.world", true, Collections.emptySet(), null)))
), resp3.body());
// searchNodesByType
Response<List<UserSearchResult>> resp4 = client.users().searchNodesByType(NodeType.PREFIX).execute();
assertTrue(resp4.isSuccessful());
assertNotNull(resp4.body());
assertEquals(ImmutableList.of(
new UserSearchResult(uuid, ImmutableList.of(new Node("prefix.100.&c[Admin] ", true, Collections.emptySet(), null)))
), resp4.body());
}
@Test
public void testUserPermissionCheck() throws IOException {
LuckPermsRestClient client = createClient();
UUID uuid = UUID.randomUUID();
String username = randomName();
// create a user
assertTrue(client.users().create(new CreateUserRequest(uuid, username)).execute().isSuccessful());
// set some permissions
assertTrue(client.users().nodesAdd(uuid, ImmutableList.of(
new Node("test.node.one", true, Collections.emptySet(), null),
new Node("test.node.two", false, Collections.emptySet(), null),
new Node("test.node.three", true, Collections.singleton(new Context("server", "test")), null)
)).execute().isSuccessful());
Response<PermissionCheckResult> resp0 = client.users().permissionCheck(uuid, "test.node.zero").execute();
assertTrue(resp0.isSuccessful());
assertNotNull(resp0.body());
assertEquals(PermissionCheckResult.Tristate.UNDEFINED, resp0.body().result());
assertNull(resp0.body().node());
Response<PermissionCheckResult> resp1 = client.users().permissionCheck(uuid, "test.node.one").execute();
assertTrue(resp1.isSuccessful());
assertNotNull(resp1.body());
assertEquals(PermissionCheckResult.Tristate.TRUE, resp1.body().result());
assertEquals(new Node("test.node.one", true, Collections.emptySet(), null), resp1.body().node());
Response<PermissionCheckResult> resp2 = client.users().permissionCheck(uuid, "test.node.two").execute();
assertTrue(resp2.isSuccessful());
assertNotNull(resp2.body());
assertEquals(PermissionCheckResult.Tristate.FALSE, resp2.body().result());
assertEquals(new Node("test.node.two", false, Collections.emptySet(), null), resp2.body().node());
Response<PermissionCheckResult> resp3 = client.users().permissionCheck(uuid, "test.node.three").execute();
assertTrue(resp3.isSuccessful());
assertNotNull(resp3.body());
assertEquals(PermissionCheckResult.Tristate.UNDEFINED, resp3.body().result());
assertNull(resp3.body().node());
Response<PermissionCheckResult> resp4 = client.users().permissionCheck(uuid, new PermissionCheckRequest(
"test.node.three",
new QueryOptions(null, null, ImmutableSet.of(new Context("server", "test"), new Context("world", "aaa")))
)).execute();
assertTrue(resp4.isSuccessful());
assertNotNull(resp4.body());
assertEquals(PermissionCheckResult.Tristate.TRUE, resp4.body().result());
assertEquals(new Node("test.node.three", true, Collections.singleton(new Context("server", "test")), null), resp4.body().node());
}
@Test
public void testUserPromoteDemote() throws IOException {
LuckPermsRestClient client = createClient();
// create a user
UUID uuid = UUID.randomUUID();
String username = randomName();
assertTrue(client.users().create(new CreateUserRequest(uuid, username)).execute().isSuccessful());
// create a track
String trackName = randomName();
assertTrue(client.tracks().create(new CreateTrackRequest(trackName)).execute().isSuccessful());
// create some groups | /*
* This file is part of LuckPerms, licensed under the MIT License.
*
* Copyright (c) lucko (Luck) <luck@lucko.me>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package me.lucko.luckperms.rest;
public class UserServiceTest extends AbstractIntegrationTest {
@Test
public void testUserCrud() throws IOException {
LuckPermsRestClient client = createClient();
UUID uuid = UUID.randomUUID();
String username = randomName();
// create
Response<PlayerSaveResult> createResp = client.users().create(new CreateUserRequest(uuid, username)).execute();
assertTrue(createResp.isSuccessful());
assertEquals(201, createResp.code());
PlayerSaveResult result = createResp.body();
assertNotNull(result);
// read
Response<User> readResp = client.users().get(uuid).execute();
assertTrue(readResp.isSuccessful());
User user = readResp.body();
assertNotNull(user);
assertEquals(uuid, user.uniqueId());
assertEquals(username, user.username());
// update
Response<Void> updateResp = client.users().update(uuid, new UpdateUserRequest(randomName())).execute();
assertTrue(updateResp.isSuccessful());
// delete
Response<Void> deleteResp = client.users().delete(uuid).execute();
assertTrue(deleteResp.isSuccessful());
}
@Test
public void testUserCreate() throws IOException {
LuckPermsRestClient client = createClient();
UUID uuid = UUID.randomUUID();
String username = randomName();
// create - clean insert
Response<PlayerSaveResult> createResp1 = client.users().create(new CreateUserRequest(uuid, username)).execute();
assertTrue(createResp1.isSuccessful());
assertEquals(201, createResp1.code());
PlayerSaveResult result1 = createResp1.body();
assertNotNull(result1);
assertEquals(ImmutableSet.of(PlayerSaveResult.Outcome.CLEAN_INSERT), result1.outcomes());
assertNull(result1.previousUsername());
assertNull(result1.otherUniqueIds());
// create - no change
Response<PlayerSaveResult> createResp2 = client.users().create(new CreateUserRequest(uuid, username)).execute();
assertTrue(createResp2.isSuccessful());
assertEquals(200, createResp2.code());
PlayerSaveResult result2 = createResp2.body();
assertNotNull(result2);
assertEquals(ImmutableSet.of(PlayerSaveResult.Outcome.NO_CHANGE), result2.outcomes());
assertNull(result2.previousUsername());
assertNull(result2.otherUniqueIds());
// create - changed username
String otherUsername = randomName();
Response<PlayerSaveResult> createResp3 = client.users().create(new CreateUserRequest(uuid, otherUsername)).execute();
assertTrue(createResp3.isSuccessful());
assertEquals(200, createResp3.code());
PlayerSaveResult result3 = createResp3.body();
assertNotNull(result3);
assertEquals(ImmutableSet.of(PlayerSaveResult.Outcome.USERNAME_UPDATED), result3.outcomes());
assertEquals(username, result3.previousUsername());
assertNull(result3.otherUniqueIds());
// create - changed uuid
UUID otherUuid = UUID.randomUUID();
Response<PlayerSaveResult> createResp4 = client.users().create(new CreateUserRequest(otherUuid, otherUsername)).execute();
assertTrue(createResp4.isSuccessful());
assertEquals(201, createResp4.code());
PlayerSaveResult result4 = createResp4.body();
assertNotNull(result4);
assertEquals(ImmutableSet.of(PlayerSaveResult.Outcome.CLEAN_INSERT, PlayerSaveResult.Outcome.OTHER_UNIQUE_IDS_PRESENT_FOR_USERNAME), result4.outcomes());
assertNull(result4.previousUsername());
assertEquals(ImmutableSet.of(uuid), result4.otherUniqueIds());
}
@Test
public void testUserList() throws IOException {
LuckPermsRestClient client = createClient();
UUID uuid = UUID.randomUUID();
String username = randomName();
// create a user & give it a permission
assertTrue(client.users().create(new CreateUserRequest(uuid, username)).execute().isSuccessful());
assertTrue(client.users().nodesAdd(uuid, new Node("test.node", true, Collections.emptySet(), null)).execute().isSuccessful());
Response<Set<UUID>> resp = client.users().list().execute();
assertTrue(resp.isSuccessful());
assertNotNull(resp.body());
assertTrue(resp.body().contains(uuid));
}
@Test
public void testUserLookup() throws IOException {
LuckPermsRestClient client = createClient();
UUID uuid = UUID.randomUUID();
String username = randomName();
// create a user
assertTrue(client.users().create(new CreateUserRequest(uuid, username)).execute().isSuccessful());
// uuid to username
Response<UserLookupResult> uuidToUsername = client.users().lookup(uuid).execute();
assertTrue(uuidToUsername.isSuccessful());
assertNotNull(uuidToUsername.body());
assertEquals(username, uuidToUsername.body().username());
// username to uuid
Response<UserLookupResult> usernameToUuid = client.users().lookup(username).execute();
assertTrue(usernameToUuid.isSuccessful());
assertNotNull(usernameToUuid.body());
assertEquals(uuid, uuidToUsername.body().uniqueId());
// not found
assertEquals(404, client.users().lookup(UUID.randomUUID()).execute().code());
assertEquals(404, client.users().lookup(randomName()).execute().code());
}
@Test
public void testUserNodes() throws IOException {
LuckPermsRestClient client = createClient();
UUID uuid = UUID.randomUUID();
String username = randomName();
// create a user
assertTrue(client.users().create(new CreateUserRequest(uuid, username)).execute().isSuccessful());
// get user nodes and validate they are as expected
List<Node> nodes = client.users().nodes(uuid).execute().body();
assertNotNull(nodes);
assertEquals(ImmutableList.of(
new Node("group.default", true, Collections.emptySet(), null)
), nodes);
long expiryTime = (System.currentTimeMillis() / 1000L) + 60;
// add a node
assertTrue(client.users().nodesAdd(uuid, new Node("test.node.one", true, Collections.emptySet(), null)).execute().isSuccessful());
// add multiple nodes
assertTrue(client.users().nodesAdd(uuid, ImmutableList.of(
new Node("test.node.two", false, Collections.emptySet(), null),
new Node("test.node.three", true, Collections.singleton(new Context("server", "test")), null),
new Node("test.node.four", false, Collections.emptySet(), expiryTime)
)).execute().isSuccessful());
// get user nodes and validate they are as expected
nodes = client.users().nodes(uuid).execute().body();
assertNotNull(nodes);
assertEquals(ImmutableSet.of(
new Node("group.default", true, Collections.emptySet(), null),
new Node("test.node.one", true, Collections.emptySet(), null),
new Node("test.node.two", false, Collections.emptySet(), null),
new Node("test.node.three", true, Collections.singleton(new Context("server", "test")), null),
new Node("test.node.four", false, Collections.emptySet(), expiryTime)
), ImmutableSet.copyOf(nodes));
// delete nodes
assertTrue(client.users().nodesDelete(uuid, ImmutableList.of(
new Node("test.node.one", true, Collections.emptySet(), null),
new Node("test.node.two", false, Collections.emptySet(), null)
)).execute().isSuccessful());
// get user nodes and validate they are as expected
nodes = client.users().nodes(uuid).execute().body();
assertNotNull(nodes);
assertEquals(ImmutableSet.of(
new Node("group.default", true, Collections.emptySet(), null),
new Node("test.node.three", true, Collections.singleton(new Context("server", "test")), null),
new Node("test.node.four", false, Collections.emptySet(), expiryTime)
), ImmutableSet.copyOf(nodes));
// add a duplicate node with a later expiry time
long laterExpiryTime = expiryTime + 60;
assertTrue(client.users().nodesAdd(uuid, new Node("test.node.four", false, Collections.emptySet(), laterExpiryTime), TemporaryNodeMergeStrategy.REPLACE_EXISTING_IF_DURATION_LONGER).execute().isSuccessful());
// get user nodes and validate they are as expected
nodes = client.users().nodes(uuid).execute().body();
assertNotNull(nodes);
assertEquals(ImmutableSet.of(
new Node("group.default", true, Collections.emptySet(), null),
new Node("test.node.three", true, Collections.singleton(new Context("server", "test")), null),
new Node("test.node.four", false, Collections.emptySet(), laterExpiryTime)
), ImmutableSet.copyOf(nodes));
long evenLaterExpiryTime = expiryTime + 60;
// add multiple nodes
assertTrue(client.users().nodesAdd(uuid, ImmutableList.of(
new Node("test.node.two", false, Collections.emptySet(), null),
new Node("test.node.three", true, Collections.singleton(new Context("server", "test")), null),
new Node("test.node.four", false, Collections.emptySet(), evenLaterExpiryTime)
), TemporaryNodeMergeStrategy.REPLACE_EXISTING_IF_DURATION_LONGER).execute().isSuccessful());
// get user nodes and validate they are as expected
nodes = client.users().nodes(uuid).execute().body();
assertNotNull(nodes);
assertEquals(ImmutableSet.of(
new Node("group.default", true, Collections.emptySet(), null),
new Node("test.node.two", false, Collections.emptySet(), null),
new Node("test.node.three", true, Collections.singleton(new Context("server", "test")), null),
new Node("test.node.four", false, Collections.emptySet(), evenLaterExpiryTime)
), ImmutableSet.copyOf(nodes));
// set nodes
assertTrue(client.users().nodesSet(uuid, ImmutableList.of(
new Node("group.default", true, Collections.emptySet(), null),
new Node("test.node.five", false, Collections.emptySet(), null),
new Node("test.node.six", true, Collections.singleton(new Context("server", "test")), null),
new Node("test.node.seven", false, Collections.emptySet(), evenLaterExpiryTime)
)).execute().isSuccessful());
// get user nodes and validate they are as expected
nodes = client.users().nodes(uuid).execute().body();
assertNotNull(nodes);
assertEquals(ImmutableSet.of(
new Node("group.default", true, Collections.emptySet(), null),
new Node("test.node.five", false, Collections.emptySet(), null),
new Node("test.node.six", true, Collections.singleton(new Context("server", "test")), null),
new Node("test.node.seven", false, Collections.emptySet(), evenLaterExpiryTime)
), ImmutableSet.copyOf(nodes));
// delete all nodes
assertTrue(client.users().nodesDelete(uuid).execute().isSuccessful());
// get user nodes and validate they are as expected
nodes = client.users().nodes(uuid).execute().body();
assertNotNull(nodes);
assertEquals(ImmutableSet.of(
new Node("group.default", true, Collections.emptySet(), null)
), ImmutableSet.copyOf(nodes));
}
@Test
public void testUserMetadata() throws IOException {
LuckPermsRestClient client = createClient();
UUID uuid = UUID.randomUUID();
String username = randomName();
// create a user
assertTrue(client.users().create(new CreateUserRequest(uuid, username)).execute().isSuccessful());
// set some permissions
assertTrue(client.users().nodesAdd(uuid, ImmutableList.of(
new Node("prefix.100.&c[Admin] ", true, Collections.emptySet(), null),
new Node("suffix.100. test", true, Collections.emptySet(), null),
new Node("meta.hello.world", true, Collections.emptySet(), null)
)).execute().isSuccessful());
// assert metadata
Response<Metadata> resp = client.users().metadata(uuid).execute();
assertTrue(resp.isSuccessful());
Metadata metadata = resp.body();
assertNotNull(metadata);
assertEquals("&c[Admin] ", metadata.prefix());
assertEquals(" test", metadata.suffix());
assertEquals("default", metadata.primaryGroup());
Map<String, String> metaMap = metadata.meta();
assertEquals("world", metaMap.get("hello"));
}
@Test
public void testUserSearch() throws IOException {
LuckPermsRestClient client = createClient();
// clear existing users
Set<UUID> existingUsers = client.users().list().execute().body();
if (existingUsers != null) {
for (UUID u : existingUsers) {
client.users().delete(u).execute();
}
}
UUID uuid = UUID.randomUUID();
String username = randomName();
// create a user
assertTrue(client.users().create(new CreateUserRequest(uuid, username)).execute().isSuccessful());
// set some permissions
long expiryTime = (System.currentTimeMillis() / 1000L) + 60;
assertTrue(client.users().nodesAdd(uuid, ImmutableList.of(
new Node("test.node.one", true, Collections.emptySet(), null),
new Node("test.node.two", false, Collections.emptySet(), null),
new Node("test.node.three", true, Collections.singleton(new Context("server", "test")), null),
new Node("test.node.four", false, Collections.emptySet(), expiryTime),
new Node("prefix.100.&c[Admin] ", true, Collections.emptySet(), null),
new Node("suffix.100. test", true, Collections.emptySet(), null),
new Node("meta.hello.world", true, Collections.emptySet(), null)
)).execute().isSuccessful());
// searchNodesByKey
Response<List<UserSearchResult>> resp1 = client.users().searchNodesByKey("test.node.one").execute();
assertTrue(resp1.isSuccessful());
assertNotNull(resp1.body());
assertEquals(ImmutableList.of(
new UserSearchResult(uuid, ImmutableList.of(new Node("test.node.one", true, Collections.emptySet(), null)))
), resp1.body());
// searchNodesByKeyStartsWith
Response<List<UserSearchResult>> resp2 = client.users().searchNodesByKeyStartsWith("test.node").execute();
assertTrue(resp2.isSuccessful());
assertNotNull(resp2.body());
assertEquals(ImmutableList.of(
new UserSearchResult(uuid, ImmutableList.of(
new Node("test.node.one", true, Collections.emptySet(), null),
new Node("test.node.two", false, Collections.emptySet(), null),
new Node("test.node.three", true, Collections.singleton(new Context("server", "test")), null),
new Node("test.node.four", false, Collections.emptySet(), expiryTime)
))
), resp2.body());
// searchNodesByMetaKey
Response<List<UserSearchResult>> resp3 = client.users().searchNodesByMetaKey("hello").execute();
assertTrue(resp3.isSuccessful());
assertNotNull(resp3.body());
assertEquals(ImmutableList.of(
new UserSearchResult(uuid, ImmutableList.of(new Node("meta.hello.world", true, Collections.emptySet(), null)))
), resp3.body());
// searchNodesByType
Response<List<UserSearchResult>> resp4 = client.users().searchNodesByType(NodeType.PREFIX).execute();
assertTrue(resp4.isSuccessful());
assertNotNull(resp4.body());
assertEquals(ImmutableList.of(
new UserSearchResult(uuid, ImmutableList.of(new Node("prefix.100.&c[Admin] ", true, Collections.emptySet(), null)))
), resp4.body());
}
@Test
public void testUserPermissionCheck() throws IOException {
LuckPermsRestClient client = createClient();
UUID uuid = UUID.randomUUID();
String username = randomName();
// create a user
assertTrue(client.users().create(new CreateUserRequest(uuid, username)).execute().isSuccessful());
// set some permissions
assertTrue(client.users().nodesAdd(uuid, ImmutableList.of(
new Node("test.node.one", true, Collections.emptySet(), null),
new Node("test.node.two", false, Collections.emptySet(), null),
new Node("test.node.three", true, Collections.singleton(new Context("server", "test")), null)
)).execute().isSuccessful());
Response<PermissionCheckResult> resp0 = client.users().permissionCheck(uuid, "test.node.zero").execute();
assertTrue(resp0.isSuccessful());
assertNotNull(resp0.body());
assertEquals(PermissionCheckResult.Tristate.UNDEFINED, resp0.body().result());
assertNull(resp0.body().node());
Response<PermissionCheckResult> resp1 = client.users().permissionCheck(uuid, "test.node.one").execute();
assertTrue(resp1.isSuccessful());
assertNotNull(resp1.body());
assertEquals(PermissionCheckResult.Tristate.TRUE, resp1.body().result());
assertEquals(new Node("test.node.one", true, Collections.emptySet(), null), resp1.body().node());
Response<PermissionCheckResult> resp2 = client.users().permissionCheck(uuid, "test.node.two").execute();
assertTrue(resp2.isSuccessful());
assertNotNull(resp2.body());
assertEquals(PermissionCheckResult.Tristate.FALSE, resp2.body().result());
assertEquals(new Node("test.node.two", false, Collections.emptySet(), null), resp2.body().node());
Response<PermissionCheckResult> resp3 = client.users().permissionCheck(uuid, "test.node.three").execute();
assertTrue(resp3.isSuccessful());
assertNotNull(resp3.body());
assertEquals(PermissionCheckResult.Tristate.UNDEFINED, resp3.body().result());
assertNull(resp3.body().node());
Response<PermissionCheckResult> resp4 = client.users().permissionCheck(uuid, new PermissionCheckRequest(
"test.node.three",
new QueryOptions(null, null, ImmutableSet.of(new Context("server", "test"), new Context("world", "aaa")))
)).execute();
assertTrue(resp4.isSuccessful());
assertNotNull(resp4.body());
assertEquals(PermissionCheckResult.Tristate.TRUE, resp4.body().result());
assertEquals(new Node("test.node.three", true, Collections.singleton(new Context("server", "test")), null), resp4.body().node());
}
@Test
public void testUserPromoteDemote() throws IOException {
LuckPermsRestClient client = createClient();
// create a user
UUID uuid = UUID.randomUUID();
String username = randomName();
assertTrue(client.users().create(new CreateUserRequest(uuid, username)).execute().isSuccessful());
// create a track
String trackName = randomName();
assertTrue(client.tracks().create(new CreateTrackRequest(trackName)).execute().isSuccessful());
// create some groups | Group group1 = Objects.requireNonNull(client.groups().create(new CreateGroupRequest(randomName())).execute().body()); | 6 | 2023-10-22 16:07:30+00:00 | 12k |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.