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
SUFIAG/Hotel-Reservation-System-Java-And-PHP
src/app/src/main/java/com/sameetasadullah/i180479_i180531/presentationLayer/Customer_Choose_Option_Screen.java
[ { "identifier": "Customer", "path": "src/app/src/main/java/com/sameetasadullah/i180479_i180531/logicLayer/Customer.java", "snippet": "public class Customer {\n private String name, address, email, password, phoneNo, CNIC, accountNo, dp;\n private int ID;\n\n //constructors\n public Customer(...
import androidx.appcompat.app.AppCompatActivity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.view.View; import android.widget.RelativeLayout; import com.sameetasadullah.i180479_i180531.R; import com.sameetasadullah.i180479_i180531.logicLayer.Customer; import com.sameetasadullah.i180479_i180531.logicLayer.HRS; import com.squareup.picasso.Picasso; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import de.hdodenhof.circleimageview.CircleImageView;
3,164
package com.sameetasadullah.i180479_i180531.presentationLayer; public class Customer_Choose_Option_Screen extends AppCompatActivity { RelativeLayout reserve_hotel, view_old_reservations; CircleImageView dp;
package com.sameetasadullah.i180479_i180531.presentationLayer; public class Customer_Choose_Option_Screen extends AppCompatActivity { RelativeLayout reserve_hotel, view_old_reservations; CircleImageView dp;
HRS hrs;
1
2023-10-25 20:58:45+00:00
4k
MachineMC/Cogwheel
cogwheel-yaml/src/main/java/org/machinemc/cogwheel/yaml/YamlConfigSerializer.java
[ { "identifier": "ConfigAdapter", "path": "cogwheel-core/src/main/java/org/machinemc/cogwheel/config/ConfigAdapter.java", "snippet": "public abstract class ConfigAdapter<T> {\n\n public abstract ConfigAdapter<T> newConfigInstance();\n\n public abstract T getConfig();\n\n public abstract Set<Stri...
import org.machinemc.cogwheel.config.ConfigAdapter; import org.machinemc.cogwheel.config.ConfigProperties; import org.machinemc.cogwheel.config.ConfigSerializer; import org.machinemc.cogwheel.yaml.wrapper.YamlObject; import org.snakeyaml.engine.v2.api.Dump; import org.snakeyaml.engine.v2.api.Load; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException;
3,193
package org.machinemc.cogwheel.yaml; public class YamlConfigSerializer extends ConfigSerializer<YamlObject> { protected YamlConfigSerializer(ConfigProperties properties) { super(properties); } @Override
package org.machinemc.cogwheel.yaml; public class YamlConfigSerializer extends ConfigSerializer<YamlObject> { protected YamlConfigSerializer(ConfigProperties properties) { super(properties); } @Override
protected ConfigAdapter<YamlObject> newAdapter() {
0
2023-10-25 11:31:02+00:00
4k
F4pl0/iex-cloud-java
src/main/java/io/github/f4pl0/companydata/CompanyData.java
[ { "identifier": "IEXHttpClient", "path": "src/main/java/io/github/f4pl0/IEXHttpClient.java", "snippet": "public class IEXHttpClient {\n private static IEXHttpClient instance;\n @IEXConfiguration\n private IEXCloudConfig config;\n\n private final CloseableHttpClient httpClient;\n\n private...
import com.fasterxml.jackson.databind.ObjectMapper; import io.github.f4pl0.IEXHttpClient; import io.github.f4pl0.companydata.data.IEXCompanyCeoCompensation; import io.github.f4pl0.companydata.data.IEXCompanyData; import io.github.f4pl0.companydata.data.IEXCompanyLogo; import io.github.f4pl0.reference.data.IEXTradeDate; import lombok.NonNull; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.util.EntityUtils; import java.io.IOException; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List;
2,666
package io.github.f4pl0.companydata; public class CompanyData { private final IEXHttpClient httpClient = IEXHttpClient.getInstance(); private final ObjectMapper mapper = new ObjectMapper(); /** * Company Information * * <p>Latest snapshot of public company information such as address, number of employees, CEO, and description.</p> * * @see <a href="https://iexcloud.io/docs/core/COMPANY#company-information">IEX Cloud API</a> * @param symbol Company symbol. * @throws IOException If the request fails. * @return A {@link io.github.f4pl0.companydata.data.IEXCompanyData} object. */ public IEXCompanyData companyData(@NonNull String symbol) throws IOException { String encodedSymbol = URLEncoder.encode(symbol, StandardCharsets.UTF_8); CloseableHttpResponse response = httpClient.execute("/data/core/company/" + encodedSymbol); List<IEXCompanyData> data = mapper.readValue( EntityUtils.toString(response.getEntity()), mapper.getTypeFactory().constructCollectionType(List.class, IEXCompanyData.class)); return data.get(0); } /** * Company Information * * <p>Latest snapshot of public company information such as address, number of employees, CEO, and description.</p> * * @see <a href="https://iexcloud.io/docs/core/COMPANY#company-information">IEX Cloud API</a> * @param symbols Company symbols. * @throws IOException If the request fails. * @return A List of {@link io.github.f4pl0.companydata.data.IEXCompanyData} objects. */ public List<IEXCompanyData> companyData(@NonNull String[] symbols) throws IOException { List<String> encodedSymbols = new ArrayList<>(symbols.length); for (String symbol : symbols) { encodedSymbols.add(URLEncoder.encode(symbol, StandardCharsets.UTF_8)); } String joinedSymbols = String.join(",", encodedSymbols); CloseableHttpResponse response = httpClient.execute("/data/core/company/" + joinedSymbols); return mapper.readValue( EntityUtils.toString(response.getEntity()), mapper.getTypeFactory().constructCollectionType(List.class, IEXCompanyData.class)); } /** * Historical Company Snapshots * * <p>Historical daily snapshot of public company information such as address, number of employees, CEO, and description.</p> * * @see <a href="https://iexcloud.io/docs/core/COMPANY_HISTORICAL#historical-company-snapshots">IEX Cloud API</a> * @param symbol Company symbol. * @throws IOException If the request fails. * @return A List of {@link io.github.f4pl0.companydata.data.IEXCompanyData} objects. */ public List<IEXCompanyData> companyDataSnapshots(@NonNull String symbol) throws IOException { String encodedSymbol = URLEncoder.encode(symbol, StandardCharsets.UTF_8); CloseableHttpResponse response = httpClient.execute("/data/core/company_historical/" + encodedSymbol); return mapper.readValue( EntityUtils.toString(response.getEntity()), mapper.getTypeFactory().constructCollectionType(List.class, IEXCompanyData.class)); } /** * Historical Company Snapshots * * <p>Historical daily snapshot of public company information such as address, number of employees, CEO, and description.</p> * * @see <a href="https://iexcloud.io/docs/core/COMPANY_HISTORICAL#historical-company-snapshots">IEX Cloud API</a> * @param symbol Company symbol. * @param last Number of records to return. * @throws IOException If the request fails. * @return A List of {@link io.github.f4pl0.companydata.data.IEXCompanyData} objects. */ public List<IEXCompanyData> companyDataSnapshots(@NonNull String symbol, int last) throws IOException { String encodedSymbol = URLEncoder.encode(symbol, StandardCharsets.UTF_8); CloseableHttpResponse response = httpClient.execute( "/data/core/company_historical/" + encodedSymbol + "?last=" + last ); return mapper.readValue( EntityUtils.toString(response.getEntity()), mapper.getTypeFactory().constructCollectionType(List.class, IEXCompanyData.class)); } /** * Historical Company Snapshots * * <p>Historical daily snapshot of public company information such as address, number of employees, CEO, and description.</p> * * @see <a href="https://iexcloud.io/docs/core/COMPANY_HISTORICAL#historical-company-snapshots">IEX Cloud API</a> * @param symbols Company symbols. * @throws IOException If the request fails. * @return A List of {@link io.github.f4pl0.companydata.data.IEXCompanyData} objects. */ public List<IEXCompanyData> companyDataSnapshots(@NonNull String[] symbols) throws IOException { List<String> encodedSymbols = new ArrayList<>(symbols.length); for (String symbol : symbols) { encodedSymbols.add(URLEncoder.encode(symbol, StandardCharsets.UTF_8)); } String joinedSymbols = String.join(",", encodedSymbols); CloseableHttpResponse response = httpClient.execute("/data/core/company_historical/" + joinedSymbols); return mapper.readValue( EntityUtils.toString(response.getEntity()), mapper.getTypeFactory().constructCollectionType(List.class, IEXCompanyData.class)); } /** * Historical Company Snapshots * * <p>Historical daily snapshot of public company information such as address, number of employees, CEO, and description.</p> * * @see <a href="https://iexcloud.io/docs/core/COMPANY_HISTORICAL#historical-company-snapshots">IEX Cloud API</a> * @param symbols Company symbols. * @param last Number of records to return. * @throws IOException If the request fails. * @return A List of {@link io.github.f4pl0.companydata.data.IEXCompanyData} objects. */ public List<IEXCompanyData> companyDataSnapshots(@NonNull String[] symbols, int last) throws IOException { List<String> encodedSymbols = new ArrayList<>(symbols.length); for (String symbol : symbols) { encodedSymbols.add(URLEncoder.encode(symbol, StandardCharsets.UTF_8)); } String joinedSymbols = String.join(",", encodedSymbols); CloseableHttpResponse response = httpClient.execute( "/data/core/company_historical/" + joinedSymbols + "?last=" + last ); return mapper.readValue( EntityUtils.toString(response.getEntity()), mapper.getTypeFactory().constructCollectionType(List.class, IEXCompanyData.class)); } /** * CEO Compensation * * <p>Returns the latest compensation information for the CEO of the company matching the symbol.</p> * * @see <a href="https://iexcloud.io/docs/core/ceo-compensation#ceo-compensation">IEX Cloud API</a> * @param symbol Company symbol. * @throws IOException If the request fails. * @return A {@link io.github.f4pl0.companydata.data.IEXCompanyCeoCompensation} object. */ public IEXCompanyCeoCompensation companyCeoCompensation(@NonNull String symbol) throws IOException { String encodedSymbol = URLEncoder.encode(symbol, StandardCharsets.UTF_8); CloseableHttpResponse response = httpClient.execute("/stock/" + encodedSymbol + "/ceo-compensation"); return mapper.readValue(EntityUtils.toString(response.getEntity()), IEXCompanyCeoCompensation.class); } /** * Company Logo * * <p>Returns a logo (if available) for the company.</p> * * @see <a href="https://iexcloud.io/docs/core/company-logo#company-logo">IEX Cloud API</a> * @param symbol Company symbol. * @throws IOException If the request fails. * @return A {@link io.github.f4pl0.companydata.data.IEXCompanyLogo} object. */
package io.github.f4pl0.companydata; public class CompanyData { private final IEXHttpClient httpClient = IEXHttpClient.getInstance(); private final ObjectMapper mapper = new ObjectMapper(); /** * Company Information * * <p>Latest snapshot of public company information such as address, number of employees, CEO, and description.</p> * * @see <a href="https://iexcloud.io/docs/core/COMPANY#company-information">IEX Cloud API</a> * @param symbol Company symbol. * @throws IOException If the request fails. * @return A {@link io.github.f4pl0.companydata.data.IEXCompanyData} object. */ public IEXCompanyData companyData(@NonNull String symbol) throws IOException { String encodedSymbol = URLEncoder.encode(symbol, StandardCharsets.UTF_8); CloseableHttpResponse response = httpClient.execute("/data/core/company/" + encodedSymbol); List<IEXCompanyData> data = mapper.readValue( EntityUtils.toString(response.getEntity()), mapper.getTypeFactory().constructCollectionType(List.class, IEXCompanyData.class)); return data.get(0); } /** * Company Information * * <p>Latest snapshot of public company information such as address, number of employees, CEO, and description.</p> * * @see <a href="https://iexcloud.io/docs/core/COMPANY#company-information">IEX Cloud API</a> * @param symbols Company symbols. * @throws IOException If the request fails. * @return A List of {@link io.github.f4pl0.companydata.data.IEXCompanyData} objects. */ public List<IEXCompanyData> companyData(@NonNull String[] symbols) throws IOException { List<String> encodedSymbols = new ArrayList<>(symbols.length); for (String symbol : symbols) { encodedSymbols.add(URLEncoder.encode(symbol, StandardCharsets.UTF_8)); } String joinedSymbols = String.join(",", encodedSymbols); CloseableHttpResponse response = httpClient.execute("/data/core/company/" + joinedSymbols); return mapper.readValue( EntityUtils.toString(response.getEntity()), mapper.getTypeFactory().constructCollectionType(List.class, IEXCompanyData.class)); } /** * Historical Company Snapshots * * <p>Historical daily snapshot of public company information such as address, number of employees, CEO, and description.</p> * * @see <a href="https://iexcloud.io/docs/core/COMPANY_HISTORICAL#historical-company-snapshots">IEX Cloud API</a> * @param symbol Company symbol. * @throws IOException If the request fails. * @return A List of {@link io.github.f4pl0.companydata.data.IEXCompanyData} objects. */ public List<IEXCompanyData> companyDataSnapshots(@NonNull String symbol) throws IOException { String encodedSymbol = URLEncoder.encode(symbol, StandardCharsets.UTF_8); CloseableHttpResponse response = httpClient.execute("/data/core/company_historical/" + encodedSymbol); return mapper.readValue( EntityUtils.toString(response.getEntity()), mapper.getTypeFactory().constructCollectionType(List.class, IEXCompanyData.class)); } /** * Historical Company Snapshots * * <p>Historical daily snapshot of public company information such as address, number of employees, CEO, and description.</p> * * @see <a href="https://iexcloud.io/docs/core/COMPANY_HISTORICAL#historical-company-snapshots">IEX Cloud API</a> * @param symbol Company symbol. * @param last Number of records to return. * @throws IOException If the request fails. * @return A List of {@link io.github.f4pl0.companydata.data.IEXCompanyData} objects. */ public List<IEXCompanyData> companyDataSnapshots(@NonNull String symbol, int last) throws IOException { String encodedSymbol = URLEncoder.encode(symbol, StandardCharsets.UTF_8); CloseableHttpResponse response = httpClient.execute( "/data/core/company_historical/" + encodedSymbol + "?last=" + last ); return mapper.readValue( EntityUtils.toString(response.getEntity()), mapper.getTypeFactory().constructCollectionType(List.class, IEXCompanyData.class)); } /** * Historical Company Snapshots * * <p>Historical daily snapshot of public company information such as address, number of employees, CEO, and description.</p> * * @see <a href="https://iexcloud.io/docs/core/COMPANY_HISTORICAL#historical-company-snapshots">IEX Cloud API</a> * @param symbols Company symbols. * @throws IOException If the request fails. * @return A List of {@link io.github.f4pl0.companydata.data.IEXCompanyData} objects. */ public List<IEXCompanyData> companyDataSnapshots(@NonNull String[] symbols) throws IOException { List<String> encodedSymbols = new ArrayList<>(symbols.length); for (String symbol : symbols) { encodedSymbols.add(URLEncoder.encode(symbol, StandardCharsets.UTF_8)); } String joinedSymbols = String.join(",", encodedSymbols); CloseableHttpResponse response = httpClient.execute("/data/core/company_historical/" + joinedSymbols); return mapper.readValue( EntityUtils.toString(response.getEntity()), mapper.getTypeFactory().constructCollectionType(List.class, IEXCompanyData.class)); } /** * Historical Company Snapshots * * <p>Historical daily snapshot of public company information such as address, number of employees, CEO, and description.</p> * * @see <a href="https://iexcloud.io/docs/core/COMPANY_HISTORICAL#historical-company-snapshots">IEX Cloud API</a> * @param symbols Company symbols. * @param last Number of records to return. * @throws IOException If the request fails. * @return A List of {@link io.github.f4pl0.companydata.data.IEXCompanyData} objects. */ public List<IEXCompanyData> companyDataSnapshots(@NonNull String[] symbols, int last) throws IOException { List<String> encodedSymbols = new ArrayList<>(symbols.length); for (String symbol : symbols) { encodedSymbols.add(URLEncoder.encode(symbol, StandardCharsets.UTF_8)); } String joinedSymbols = String.join(",", encodedSymbols); CloseableHttpResponse response = httpClient.execute( "/data/core/company_historical/" + joinedSymbols + "?last=" + last ); return mapper.readValue( EntityUtils.toString(response.getEntity()), mapper.getTypeFactory().constructCollectionType(List.class, IEXCompanyData.class)); } /** * CEO Compensation * * <p>Returns the latest compensation information for the CEO of the company matching the symbol.</p> * * @see <a href="https://iexcloud.io/docs/core/ceo-compensation#ceo-compensation">IEX Cloud API</a> * @param symbol Company symbol. * @throws IOException If the request fails. * @return A {@link io.github.f4pl0.companydata.data.IEXCompanyCeoCompensation} object. */ public IEXCompanyCeoCompensation companyCeoCompensation(@NonNull String symbol) throws IOException { String encodedSymbol = URLEncoder.encode(symbol, StandardCharsets.UTF_8); CloseableHttpResponse response = httpClient.execute("/stock/" + encodedSymbol + "/ceo-compensation"); return mapper.readValue(EntityUtils.toString(response.getEntity()), IEXCompanyCeoCompensation.class); } /** * Company Logo * * <p>Returns a logo (if available) for the company.</p> * * @see <a href="https://iexcloud.io/docs/core/company-logo#company-logo">IEX Cloud API</a> * @param symbol Company symbol. * @throws IOException If the request fails. * @return A {@link io.github.f4pl0.companydata.data.IEXCompanyLogo} object. */
public IEXCompanyLogo companyLogo(@NonNull String symbol) throws IOException {
3
2023-10-27 17:56:14+00:00
4k
frc7787/FTC-Centerstage
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/RoadRunner/trajectorysequence/TrajectorySequenceBuilder.java
[ { "identifier": "TrajectorySegment", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/RoadRunner/trajectorysequence/sequencesegment/TrajectorySegment.java", "snippet": "public final class TrajectorySegment extends SequenceSegment {\n private final Trajectory trajectory;\n\n public Tr...
import com.acmerobotics.roadrunner.geometry.Pose2d; import com.acmerobotics.roadrunner.geometry.Vector2d; import com.acmerobotics.roadrunner.path.PathContinuityViolationException; import com.acmerobotics.roadrunner.profile.MotionProfile; import com.acmerobotics.roadrunner.profile.MotionProfileGenerator; import com.acmerobotics.roadrunner.profile.MotionState; import com.acmerobotics.roadrunner.trajectory.DisplacementMarker; import com.acmerobotics.roadrunner.trajectory.DisplacementProducer; import com.acmerobotics.roadrunner.trajectory.MarkerCallback; import com.acmerobotics.roadrunner.trajectory.SpatialMarker; import com.acmerobotics.roadrunner.trajectory.TemporalMarker; import com.acmerobotics.roadrunner.trajectory.TimeProducer; import com.acmerobotics.roadrunner.trajectory.Trajectory; import com.acmerobotics.roadrunner.trajectory.TrajectoryBuilder; import com.acmerobotics.roadrunner.trajectory.TrajectoryMarker; import com.acmerobotics.roadrunner.trajectory.constraints.TrajectoryAccelerationConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.TrajectoryVelocityConstraint; import com.acmerobotics.roadrunner.util.Angle; import org.firstinspires.ftc.teamcode.RoadRunner.trajectorysequence.sequencesegment.TrajectorySegment; import org.firstinspires.ftc.teamcode.RoadRunner.trajectorysequence.sequencesegment.TurnSegment; import org.firstinspires.ftc.teamcode.RoadRunner.trajectorysequence.sequencesegment.WaitSegment; import org.firstinspires.ftc.teamcode.RoadRunner.trajectorysequence.sequencesegment.SequenceSegment; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List;
3,340
this.currentVelConstraint = this.baseVelConstraint; this.currentAccelConstraint = this.baseAccelConstraint; return this; } public TrajectorySequenceBuilder setVelConstraint(TrajectoryVelocityConstraint velConstraint) { this.currentVelConstraint = velConstraint; return this; } public TrajectorySequenceBuilder resetVelConstraint() { this.currentVelConstraint = this.baseVelConstraint; return this; } public TrajectorySequenceBuilder setAccelConstraint(TrajectoryAccelerationConstraint accelConstraint) { this.currentAccelConstraint = accelConstraint; return this; } public TrajectorySequenceBuilder resetAccelConstraint() { this.currentAccelConstraint = this.baseAccelConstraint; return this; } public TrajectorySequenceBuilder setTurnConstraint(double maxAngVel, double maxAngAccel) { this.currentTurnConstraintMaxAngVel = maxAngVel; this.currentTurnConstraintMaxAngAccel = maxAngAccel; return this; } public TrajectorySequenceBuilder resetTurnConstraint() { this.currentTurnConstraintMaxAngVel = baseTurnConstraintMaxAngVel; this.currentTurnConstraintMaxAngAccel = baseTurnConstraintMaxAngAccel; return this; } public TrajectorySequenceBuilder addTemporalMarker(MarkerCallback callback) { return this.addTemporalMarker(currentDuration, callback); } public TrajectorySequenceBuilder UNSTABLE_addTemporalMarkerOffset(double offset, MarkerCallback callback) { return this.addTemporalMarker(currentDuration + offset, callback); } public TrajectorySequenceBuilder addTemporalMarker(double time, MarkerCallback callback) { return this.addTemporalMarker(0.0, time, callback); } public TrajectorySequenceBuilder addTemporalMarker(double scale, double offset, MarkerCallback callback) { return this.addTemporalMarker(time -> scale * time + offset, callback); } public TrajectorySequenceBuilder addTemporalMarker(TimeProducer time, MarkerCallback callback) { this.temporalMarkers.add(new TemporalMarker(time, callback)); return this; } public TrajectorySequenceBuilder addSpatialMarker(Vector2d point, MarkerCallback callback) { this.spatialMarkers.add(new SpatialMarker(point, callback)); return this; } public TrajectorySequenceBuilder addDisplacementMarker(MarkerCallback callback) { return this.addDisplacementMarker(currentDisplacement, callback); } public TrajectorySequenceBuilder UNSTABLE_addDisplacementMarkerOffset(double offset, MarkerCallback callback) { return this.addDisplacementMarker(currentDisplacement + offset, callback); } public TrajectorySequenceBuilder addDisplacementMarker(double displacement, MarkerCallback callback) { return this.addDisplacementMarker(0.0, displacement, callback); } public TrajectorySequenceBuilder addDisplacementMarker(double scale, double offset, MarkerCallback callback) { return addDisplacementMarker((displacement -> scale * displacement + offset), callback); } public TrajectorySequenceBuilder addDisplacementMarker(DisplacementProducer displacement, MarkerCallback callback) { displacementMarkers.add(new DisplacementMarker(displacement, callback)); return this; } public TrajectorySequenceBuilder turn(double angle) { return turn(angle, currentTurnConstraintMaxAngVel, currentTurnConstraintMaxAngAccel); } public TrajectorySequenceBuilder turn(double angle, double maxAngVel, double maxAngAccel) { pushPath(); MotionProfile turnProfile = MotionProfileGenerator.generateSimpleMotionProfile( new MotionState(lastPose.getHeading(), 0.0, 0.0, 0.0), new MotionState(lastPose.getHeading() + angle, 0.0, 0.0, 0.0), maxAngVel, maxAngAccel ); sequenceSegments.add(new TurnSegment(lastPose, angle, turnProfile, Collections.emptyList())); lastPose = new Pose2d( lastPose.getX(), lastPose.getY(), Angle.norm(lastPose.getHeading() + angle) ); currentDuration += turnProfile.duration(); return this; } public TrajectorySequenceBuilder waitSeconds(double seconds) { pushPath();
package org.firstinspires.ftc.teamcode.RoadRunner.trajectorysequence; public class TrajectorySequenceBuilder { private final double resolution = 0.25; private final TrajectoryVelocityConstraint baseVelConstraint; private final TrajectoryAccelerationConstraint baseAccelConstraint; private TrajectoryVelocityConstraint currentVelConstraint; private TrajectoryAccelerationConstraint currentAccelConstraint; private final double baseTurnConstraintMaxAngVel; private final double baseTurnConstraintMaxAngAccel; private double currentTurnConstraintMaxAngVel; private double currentTurnConstraintMaxAngAccel; private final List<SequenceSegment> sequenceSegments; private final List<TemporalMarker> temporalMarkers; private final List<DisplacementMarker> displacementMarkers; private final List<SpatialMarker> spatialMarkers; private Pose2d lastPose; private double tangentOffset; private boolean setAbsoluteTangent; private double absoluteTangent; private TrajectoryBuilder currentTrajectoryBuilder; private double currentDuration; private double currentDisplacement; private double lastDurationTraj; private double lastDisplacementTraj; public TrajectorySequenceBuilder( Pose2d startPose, Double startTangent, TrajectoryVelocityConstraint baseVelConstraint, TrajectoryAccelerationConstraint baseAccelConstraint, double baseTurnConstraintMaxAngVel, double baseTurnConstraintMaxAngAccel ) { this.baseVelConstraint = baseVelConstraint; this.baseAccelConstraint = baseAccelConstraint; this.currentVelConstraint = baseVelConstraint; this.currentAccelConstraint = baseAccelConstraint; this.baseTurnConstraintMaxAngVel = baseTurnConstraintMaxAngVel; this.baseTurnConstraintMaxAngAccel = baseTurnConstraintMaxAngAccel; this.currentTurnConstraintMaxAngVel = baseTurnConstraintMaxAngVel; this.currentTurnConstraintMaxAngAccel = baseTurnConstraintMaxAngAccel; sequenceSegments = new ArrayList<>(); temporalMarkers = new ArrayList<>(); displacementMarkers = new ArrayList<>(); spatialMarkers = new ArrayList<>(); lastPose = startPose; tangentOffset = 0.0; setAbsoluteTangent = (startTangent != null); absoluteTangent = startTangent != null ? startTangent : 0.0; currentTrajectoryBuilder = null; currentDuration = 0.0; currentDisplacement = 0.0; lastDurationTraj = 0.0; lastDisplacementTraj = 0.0; } public TrajectorySequenceBuilder( Pose2d startPose, TrajectoryVelocityConstraint baseVelConstraint, TrajectoryAccelerationConstraint baseAccelConstraint, double baseTurnConstraintMaxAngVel, double baseTurnConstraintMaxAngAccel ) { this( startPose, null, baseVelConstraint, baseAccelConstraint, baseTurnConstraintMaxAngVel, baseTurnConstraintMaxAngAccel ); } public TrajectorySequenceBuilder lineTo(Vector2d endPosition) { return addPath(() -> currentTrajectoryBuilder.lineTo(endPosition, currentVelConstraint, currentAccelConstraint)); } public TrajectorySequenceBuilder lineTo( Vector2d endPosition, TrajectoryVelocityConstraint velConstraint, TrajectoryAccelerationConstraint accelConstraint ) { return addPath(() -> currentTrajectoryBuilder.lineTo(endPosition, velConstraint, accelConstraint)); } public TrajectorySequenceBuilder lineToConstantHeading(Vector2d endPosition) { return addPath(() -> currentTrajectoryBuilder.lineToConstantHeading(endPosition, currentVelConstraint, currentAccelConstraint)); } public TrajectorySequenceBuilder lineToConstantHeading( Vector2d endPosition, TrajectoryVelocityConstraint velConstraint, TrajectoryAccelerationConstraint accelConstraint ) { return addPath(() -> currentTrajectoryBuilder.lineToConstantHeading(endPosition, velConstraint, accelConstraint)); } public TrajectorySequenceBuilder lineToLinearHeading(Pose2d endPose) { return addPath(() -> currentTrajectoryBuilder.lineToLinearHeading(endPose, currentVelConstraint, currentAccelConstraint)); } public TrajectorySequenceBuilder lineToLinearHeading( Pose2d endPose, TrajectoryVelocityConstraint velConstraint, TrajectoryAccelerationConstraint accelConstraint ) { return addPath(() -> currentTrajectoryBuilder.lineToLinearHeading(endPose, velConstraint, accelConstraint)); } public TrajectorySequenceBuilder lineToSplineHeading(Pose2d endPose) { return addPath(() -> currentTrajectoryBuilder.lineToSplineHeading(endPose, currentVelConstraint, currentAccelConstraint)); } public TrajectorySequenceBuilder lineToSplineHeading( Pose2d endPose, TrajectoryVelocityConstraint velConstraint, TrajectoryAccelerationConstraint accelConstraint ) { return addPath(() -> currentTrajectoryBuilder.lineToSplineHeading(endPose, velConstraint, accelConstraint)); } public TrajectorySequenceBuilder strafeTo(Vector2d endPosition) { return addPath(() -> currentTrajectoryBuilder.strafeTo(endPosition, currentVelConstraint, currentAccelConstraint)); } public TrajectorySequenceBuilder strafeTo( Vector2d endPosition, TrajectoryVelocityConstraint velConstraint, TrajectoryAccelerationConstraint accelConstraint ) { return addPath(() -> currentTrajectoryBuilder.strafeTo(endPosition, velConstraint, accelConstraint)); } public TrajectorySequenceBuilder forward(double distance) { return addPath(() -> currentTrajectoryBuilder.forward(distance, currentVelConstraint, currentAccelConstraint)); } public TrajectorySequenceBuilder forward( double distance, TrajectoryVelocityConstraint velConstraint, TrajectoryAccelerationConstraint accelConstraint ) { return addPath(() -> currentTrajectoryBuilder.forward(distance, velConstraint, accelConstraint)); } public TrajectorySequenceBuilder back(double distance) { return addPath(() -> currentTrajectoryBuilder.back(distance, currentVelConstraint, currentAccelConstraint)); } public TrajectorySequenceBuilder back( double distance, TrajectoryVelocityConstraint velConstraint, TrajectoryAccelerationConstraint accelConstraint ) { return addPath(() -> currentTrajectoryBuilder.back(distance, velConstraint, accelConstraint)); } public TrajectorySequenceBuilder strafeLeft(double distance) { return addPath(() -> currentTrajectoryBuilder.strafeLeft(distance, currentVelConstraint, currentAccelConstraint)); } public TrajectorySequenceBuilder strafeLeft( double distance, TrajectoryVelocityConstraint velConstraint, TrajectoryAccelerationConstraint accelConstraint ) { return addPath(() -> currentTrajectoryBuilder.strafeLeft(distance, velConstraint, accelConstraint)); } public TrajectorySequenceBuilder strafeRight(double distance) { return addPath(() -> currentTrajectoryBuilder.strafeRight(distance, currentVelConstraint, currentAccelConstraint)); } public TrajectorySequenceBuilder strafeRight( double distance, TrajectoryVelocityConstraint velConstraint, TrajectoryAccelerationConstraint accelConstraint ) { return addPath(() -> currentTrajectoryBuilder.strafeRight(distance, velConstraint, accelConstraint)); } public TrajectorySequenceBuilder splineTo(Vector2d endPosition, double endHeading) { return addPath(() -> currentTrajectoryBuilder.splineTo(endPosition, endHeading, currentVelConstraint, currentAccelConstraint)); } public TrajectorySequenceBuilder splineTo( Vector2d endPosition, double endHeading, TrajectoryVelocityConstraint velConstraint, TrajectoryAccelerationConstraint accelConstraint ) { return addPath(() -> currentTrajectoryBuilder.splineTo(endPosition, endHeading, velConstraint, accelConstraint)); } public TrajectorySequenceBuilder splineToConstantHeading(Vector2d endPosition, double endHeading) { return addPath(() -> currentTrajectoryBuilder.splineToConstantHeading(endPosition, endHeading, currentVelConstraint, currentAccelConstraint)); } public TrajectorySequenceBuilder splineToConstantHeading( Vector2d endPosition, double endHeading, TrajectoryVelocityConstraint velConstraint, TrajectoryAccelerationConstraint accelConstraint ) { return addPath(() -> currentTrajectoryBuilder.splineToConstantHeading(endPosition, endHeading, velConstraint, accelConstraint)); } public TrajectorySequenceBuilder splineToLinearHeading(Pose2d endPose, double endHeading) { return addPath(() -> currentTrajectoryBuilder.splineToLinearHeading(endPose, endHeading, currentVelConstraint, currentAccelConstraint)); } public TrajectorySequenceBuilder splineToLinearHeading( Pose2d endPose, double endHeading, TrajectoryVelocityConstraint velConstraint, TrajectoryAccelerationConstraint accelConstraint ) { return addPath(() -> currentTrajectoryBuilder.splineToLinearHeading(endPose, endHeading, velConstraint, accelConstraint)); } public TrajectorySequenceBuilder splineToSplineHeading(Pose2d endPose, double endHeading) { return addPath(() -> currentTrajectoryBuilder.splineToSplineHeading(endPose, endHeading, currentVelConstraint, currentAccelConstraint)); } public TrajectorySequenceBuilder splineToSplineHeading( Pose2d endPose, double endHeading, TrajectoryVelocityConstraint velConstraint, TrajectoryAccelerationConstraint accelConstraint ) { return addPath(() -> currentTrajectoryBuilder.splineToSplineHeading(endPose, endHeading, velConstraint, accelConstraint)); } private TrajectorySequenceBuilder addPath(AddPathCallback callback) { if (currentTrajectoryBuilder == null) newPath(); try { callback.run(); } catch (PathContinuityViolationException e) { newPath(); callback.run(); } Trajectory builtTraj = currentTrajectoryBuilder.build(); double durationDifference = builtTraj.duration() - lastDurationTraj; double displacementDifference = builtTraj.getPath().length() - lastDisplacementTraj; lastPose = builtTraj.end(); currentDuration += durationDifference; currentDisplacement += displacementDifference; lastDurationTraj = builtTraj.duration(); lastDisplacementTraj = builtTraj.getPath().length(); return this; } public TrajectorySequenceBuilder setTangent(double tangent) { setAbsoluteTangent = true; absoluteTangent = tangent; pushPath(); return this; } private TrajectorySequenceBuilder setTangentOffset(double offset) { setAbsoluteTangent = false; this.tangentOffset = offset; this.pushPath(); return this; } public TrajectorySequenceBuilder setReversed(boolean reversed) { return reversed ? this.setTangentOffset(Math.toRadians(180.0)) : this.setTangentOffset(0.0); } public TrajectorySequenceBuilder setConstraints( TrajectoryVelocityConstraint velConstraint, TrajectoryAccelerationConstraint accelConstraint ) { this.currentVelConstraint = velConstraint; this.currentAccelConstraint = accelConstraint; return this; } public TrajectorySequenceBuilder resetConstraints() { this.currentVelConstraint = this.baseVelConstraint; this.currentAccelConstraint = this.baseAccelConstraint; return this; } public TrajectorySequenceBuilder setVelConstraint(TrajectoryVelocityConstraint velConstraint) { this.currentVelConstraint = velConstraint; return this; } public TrajectorySequenceBuilder resetVelConstraint() { this.currentVelConstraint = this.baseVelConstraint; return this; } public TrajectorySequenceBuilder setAccelConstraint(TrajectoryAccelerationConstraint accelConstraint) { this.currentAccelConstraint = accelConstraint; return this; } public TrajectorySequenceBuilder resetAccelConstraint() { this.currentAccelConstraint = this.baseAccelConstraint; return this; } public TrajectorySequenceBuilder setTurnConstraint(double maxAngVel, double maxAngAccel) { this.currentTurnConstraintMaxAngVel = maxAngVel; this.currentTurnConstraintMaxAngAccel = maxAngAccel; return this; } public TrajectorySequenceBuilder resetTurnConstraint() { this.currentTurnConstraintMaxAngVel = baseTurnConstraintMaxAngVel; this.currentTurnConstraintMaxAngAccel = baseTurnConstraintMaxAngAccel; return this; } public TrajectorySequenceBuilder addTemporalMarker(MarkerCallback callback) { return this.addTemporalMarker(currentDuration, callback); } public TrajectorySequenceBuilder UNSTABLE_addTemporalMarkerOffset(double offset, MarkerCallback callback) { return this.addTemporalMarker(currentDuration + offset, callback); } public TrajectorySequenceBuilder addTemporalMarker(double time, MarkerCallback callback) { return this.addTemporalMarker(0.0, time, callback); } public TrajectorySequenceBuilder addTemporalMarker(double scale, double offset, MarkerCallback callback) { return this.addTemporalMarker(time -> scale * time + offset, callback); } public TrajectorySequenceBuilder addTemporalMarker(TimeProducer time, MarkerCallback callback) { this.temporalMarkers.add(new TemporalMarker(time, callback)); return this; } public TrajectorySequenceBuilder addSpatialMarker(Vector2d point, MarkerCallback callback) { this.spatialMarkers.add(new SpatialMarker(point, callback)); return this; } public TrajectorySequenceBuilder addDisplacementMarker(MarkerCallback callback) { return this.addDisplacementMarker(currentDisplacement, callback); } public TrajectorySequenceBuilder UNSTABLE_addDisplacementMarkerOffset(double offset, MarkerCallback callback) { return this.addDisplacementMarker(currentDisplacement + offset, callback); } public TrajectorySequenceBuilder addDisplacementMarker(double displacement, MarkerCallback callback) { return this.addDisplacementMarker(0.0, displacement, callback); } public TrajectorySequenceBuilder addDisplacementMarker(double scale, double offset, MarkerCallback callback) { return addDisplacementMarker((displacement -> scale * displacement + offset), callback); } public TrajectorySequenceBuilder addDisplacementMarker(DisplacementProducer displacement, MarkerCallback callback) { displacementMarkers.add(new DisplacementMarker(displacement, callback)); return this; } public TrajectorySequenceBuilder turn(double angle) { return turn(angle, currentTurnConstraintMaxAngVel, currentTurnConstraintMaxAngAccel); } public TrajectorySequenceBuilder turn(double angle, double maxAngVel, double maxAngAccel) { pushPath(); MotionProfile turnProfile = MotionProfileGenerator.generateSimpleMotionProfile( new MotionState(lastPose.getHeading(), 0.0, 0.0, 0.0), new MotionState(lastPose.getHeading() + angle, 0.0, 0.0, 0.0), maxAngVel, maxAngAccel ); sequenceSegments.add(new TurnSegment(lastPose, angle, turnProfile, Collections.emptyList())); lastPose = new Pose2d( lastPose.getX(), lastPose.getY(), Angle.norm(lastPose.getHeading() + angle) ); currentDuration += turnProfile.duration(); return this; } public TrajectorySequenceBuilder waitSeconds(double seconds) { pushPath();
sequenceSegments.add(new WaitSegment(lastPose, seconds, Collections.emptyList()));
2
2023-10-31 16:06:46+00:00
4k
Fuzss/diagonalwalls
1.19/Common/src/main/java/fuzs/diagonalwindows/client/model/MultipartAppender.java
[ { "identifier": "DiagonalWindows", "path": "1.18/Common/src/main/java/fuzs/diagonalwindows/DiagonalWindows.java", "snippet": "public class DiagonalWindows implements ModConstructor {\n public static final String MOD_ID = \"diagonalwindows\";\n public static final String MOD_NAME = \"Diagonal Windo...
import com.google.common.base.Stopwatch; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import fuzs.diagonalwindows.DiagonalWindows; import fuzs.diagonalwindows.api.world.level.block.DiagonalBlock; import fuzs.diagonalwindows.api.world.level.block.EightWayDirection; import fuzs.diagonalwindows.client.core.ClientAbstractions; import fuzs.diagonalwindows.mixin.client.accessor.*; import net.minecraft.client.renderer.block.BlockModelShaper; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.renderer.block.model.MultiVariant; import net.minecraft.client.renderer.block.model.Variant; import net.minecraft.client.renderer.block.model.multipart.*; import net.minecraft.client.resources.model.BakedModel; import net.minecraft.client.resources.model.ModelBakery; import net.minecraft.client.resources.model.ModelResourceLocation; import net.minecraft.client.resources.model.UnbakedModel; import net.minecraft.core.Direction; import net.minecraft.core.Registry; import net.minecraft.resources.ResourceLocation; import net.minecraft.util.RandomSource; import net.minecraft.world.level.block.FenceBlock; import net.minecraft.world.level.block.IronBarsBlock; import net.minecraft.world.level.block.state.BlockState; import org.apache.commons.lang3.ArrayUtils; import org.apache.logging.log4j.util.BiConsumer; import org.jetbrains.annotations.Nullable; import java.util.*; import java.util.function.Predicate; import java.util.function.UnaryOperator;
2,229
package fuzs.diagonalwindows.client.model; public class MultipartAppender { public static void onPrepareModelBaking(ModelBakery modelBakery) { Stopwatch stopwatch = Stopwatch.createStarted(); Registry.BLOCK.stream() .filter(block -> (block instanceof FenceBlock || block instanceof IronBarsBlock) && block instanceof DiagonalBlock diagonalBlock && diagonalBlock.hasProperties()) .map(block -> block.getStateDefinition().any()) .forEach(state -> { if (modelBakery.getModel(BlockModelShaper.stateToModelLocation(state)) instanceof MultiPart multiPart) { appendDiagonalSelectors(((ModelBakeryAccessor) modelBakery)::diagonalfences$callCacheAndQueueDependencies, multiPart, state.getBlock() instanceof IronBarsBlock); } else {
package fuzs.diagonalwindows.client.model; public class MultipartAppender { public static void onPrepareModelBaking(ModelBakery modelBakery) { Stopwatch stopwatch = Stopwatch.createStarted(); Registry.BLOCK.stream() .filter(block -> (block instanceof FenceBlock || block instanceof IronBarsBlock) && block instanceof DiagonalBlock diagonalBlock && diagonalBlock.hasProperties()) .map(block -> block.getStateDefinition().any()) .forEach(state -> { if (modelBakery.getModel(BlockModelShaper.stateToModelLocation(state)) instanceof MultiPart multiPart) { appendDiagonalSelectors(((ModelBakeryAccessor) modelBakery)::diagonalfences$callCacheAndQueueDependencies, multiPart, state.getBlock() instanceof IronBarsBlock); } else {
DiagonalWindows.LOGGER.warn("Block '{}' is not using multipart models, diagonal connections will not be visible!", state.getBlock());
0
2023-10-27 09:06:16+00:00
4k
slatepowered/slate
slate-common/src/main/java/slatepowered/slate/model/ManagedNode.java
[ { "identifier": "Logger", "path": "slate-common/src/main/java/slatepowered/slate/logging/Logger.java", "snippet": "public interface Logger {\r\n\r\n /* Information */\r\n void info(Object... msg);\r\n default void info(Supplier<Object> msg) { info(msg.get()); }\r\n\r\n /* Warnings */\r\n ...
import slatepowered.slate.logging.Logger; import slatepowered.slate.logging.Logging; import slatepowered.slate.service.Service; import slatepowered.slate.service.ServiceKey; import slatepowered.slate.service.network.NodeHostBoundServiceKey; import slatepowered.veru.collection.Sequence; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.function.BiFunction; import java.util.function.Function;
3,051
package slatepowered.slate.model; /** * Represents a node you have management capabilities over. */ @SuppressWarnings("rawtypes") public abstract class ManagedNode extends Node { protected static final Logger LOGGER = Logging.getLogger("ManagedNode"); /** * The children of this node. */ protected final Map<String, ManagedNode> children = new HashMap<>(); /** * The parent node. */ protected final Node parent; /** * All components attached to this node. */ protected final List<NodeComponent> components; public ManagedNode(Node parent, String name, Network network, List<NodeComponent> components) { super(name, network); this.parent = parent; // ensure a thread-safe component list this.components = new Vector<>(); // invoke node attachments if (components != null) { for (NodeComponent component : components) { attach(component); } } } public ManagedNode(Node parent, String name, Network network) { super(name, network); this.parent = parent; this.components = new ArrayList<>(); } /** * Get the parent node of this node. * * The parent of a node is generally unimportant except for * organization or special behavior. * * @return The parent node. */ public Node getParent() { return parent; } /** * Get all components attached to this node. * * @return The components. */ public List<NodeComponent> getComponents() { return components; } /** * Find all components which are assignable to the given class. * * @param kl The class. * @param <T> The value type. * @return The list of components. */ @SuppressWarnings("unchecked") public <T extends NodeComponent> Sequence<T> findComponents(Class<? super T> kl) { Sequence<T> set = new Sequence<>(); for (NodeComponent component : components) { if (kl.isAssignableFrom(component.getClass())) { set.add((T) component); } } return set; } /** * Attach the given component to this node, this is the * only mutable part of the node. * * @param component The component. * @return This. */ public synchronized ManagedNode attach(NodeComponent component) { if (component == null) return this; if (component.attached(this)) { components.add(component); } return this; } public Map<String, ManagedNode> getChildren() { return children; } public ManagedNode getChild(String name) { return children.get(name); } /** * Assume this operation is valid under normal circumstances * and blindly adopt the given node as this node's child. * * @param node The node to adopt. * @return This. */ public ManagedNode adopt(ManagedNode node) { children.put(node.getName(), node); return this; } /** * Execute an action through all the components * * @param componentClass The component class to match the components against. * @param invoker The invoker function which runs the action and returns the result. * @param resultComposer The result composer which composes any errors into a result object. * @param <T> The result type. * @param <C> The component type. * @return The result future. */ @SuppressWarnings("unchecked") public <T, C extends NodeComponent> CompletableFuture<T> runVoidAction(Class<C> componentClass, BiFunction<C, ManagedNode, CompletableFuture<?>> invoker, Function<Throwable, T> resultComposer) { List<CompletableFuture<?>> futureList = new ArrayList<>(); for (C component : findComponents(componentClass)) { if (Logging.DEBUG) LOGGER.debug(" Action executed on component(" + component + ") of node(name: " + name + ")"); futureList.add(invoker.apply(component, this)); } if (resultComposer != null) { return CompletableFuture .allOf(futureList.toArray(new CompletableFuture[0])) .thenApply(__ -> resultComposer.apply(null)) .exceptionally(resultComposer); } else { return (CompletableFuture<T>) CompletableFuture.allOf(futureList.toArray(new CompletableFuture[0])); } } @Override
package slatepowered.slate.model; /** * Represents a node you have management capabilities over. */ @SuppressWarnings("rawtypes") public abstract class ManagedNode extends Node { protected static final Logger LOGGER = Logging.getLogger("ManagedNode"); /** * The children of this node. */ protected final Map<String, ManagedNode> children = new HashMap<>(); /** * The parent node. */ protected final Node parent; /** * All components attached to this node. */ protected final List<NodeComponent> components; public ManagedNode(Node parent, String name, Network network, List<NodeComponent> components) { super(name, network); this.parent = parent; // ensure a thread-safe component list this.components = new Vector<>(); // invoke node attachments if (components != null) { for (NodeComponent component : components) { attach(component); } } } public ManagedNode(Node parent, String name, Network network) { super(name, network); this.parent = parent; this.components = new ArrayList<>(); } /** * Get the parent node of this node. * * The parent of a node is generally unimportant except for * organization or special behavior. * * @return The parent node. */ public Node getParent() { return parent; } /** * Get all components attached to this node. * * @return The components. */ public List<NodeComponent> getComponents() { return components; } /** * Find all components which are assignable to the given class. * * @param kl The class. * @param <T> The value type. * @return The list of components. */ @SuppressWarnings("unchecked") public <T extends NodeComponent> Sequence<T> findComponents(Class<? super T> kl) { Sequence<T> set = new Sequence<>(); for (NodeComponent component : components) { if (kl.isAssignableFrom(component.getClass())) { set.add((T) component); } } return set; } /** * Attach the given component to this node, this is the * only mutable part of the node. * * @param component The component. * @return This. */ public synchronized ManagedNode attach(NodeComponent component) { if (component == null) return this; if (component.attached(this)) { components.add(component); } return this; } public Map<String, ManagedNode> getChildren() { return children; } public ManagedNode getChild(String name) { return children.get(name); } /** * Assume this operation is valid under normal circumstances * and blindly adopt the given node as this node's child. * * @param node The node to adopt. * @return This. */ public ManagedNode adopt(ManagedNode node) { children.put(node.getName(), node); return this; } /** * Execute an action through all the components * * @param componentClass The component class to match the components against. * @param invoker The invoker function which runs the action and returns the result. * @param resultComposer The result composer which composes any errors into a result object. * @param <T> The result type. * @param <C> The component type. * @return The result future. */ @SuppressWarnings("unchecked") public <T, C extends NodeComponent> CompletableFuture<T> runVoidAction(Class<C> componentClass, BiFunction<C, ManagedNode, CompletableFuture<?>> invoker, Function<Throwable, T> resultComposer) { List<CompletableFuture<?>> futureList = new ArrayList<>(); for (C component : findComponents(componentClass)) { if (Logging.DEBUG) LOGGER.debug(" Action executed on component(" + component + ") of node(name: " + name + ")"); futureList.add(invoker.apply(component, this)); } if (resultComposer != null) { return CompletableFuture .allOf(futureList.toArray(new CompletableFuture[0])) .thenApply(__ -> resultComposer.apply(null)) .exceptionally(resultComposer); } else { return (CompletableFuture<T>) CompletableFuture.allOf(futureList.toArray(new CompletableFuture[0])); } } @Override
public <T extends Service> ServiceKey<T> qualifyServiceKey(ServiceKey<T> key) throws UnsupportedOperationException {
2
2023-10-30 08:58:02+00:00
4k
The2019/NewBase-1.20.2
src/client/java/net/The2019/NewBase/utils/InitKeyBindings.java
[ { "identifier": "Test", "path": "src/client/java/net/The2019/NewBase/features/generic/Test.java", "snippet": "public class Test {\n\n public static void test(){\n }\n}" }, { "identifier": "YawSet", "path": "src/client/java/net/The2019/NewBase/features/generic/YawSet.java", "snippet...
import net.The2019.NewBase.features.generic.Test; import net.The2019.NewBase.features.generic.YawSet; import net.The2019.NewBase.screens.ChatCoordinatesScreen; import net.The2019.NewBase.screens.ConfigScreen; import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents; import net.fabricmc.fabric.api.client.keybinding.v1.KeyBindingHelper; import net.minecraft.client.MinecraftClient; import net.minecraft.client.option.KeyBinding; import net.minecraft.text.Text; import net.minecraft.util.hit.BlockHitResult; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Direction; import org.lwjgl.glfw.GLFW; import static net.The2019.NewBase.config.ModuleConfig.readModule; import static net.The2019.NewBase.config.ModuleConfig.saveModuleState; import static net.The2019.NewBase.config.ModuleStates.placer;
1,858
package net.The2019.NewBase.utils; public class InitKeyBindings { private static final MinecraftClient mc = MinecraftClient.getInstance(); public static void initKeys(){ KeyBinding configScreen = KeyBindingHelper.registerKeyBinding(new KeyBinding("newbase.keybinds.configscreen", GLFW.GLFW_KEY_O, "newbase.name")); KeyBinding chatCoordinates = KeyBindingHelper.registerKeyBinding(new KeyBinding("newbase.keybinds.sendcoordinates", GLFW.GLFW_KEY_P, "newbase.name")); KeyBinding togglePlacer = KeyBindingHelper.registerKeyBinding(new KeyBinding("newbase.keybinds.toggleplacer", GLFW.GLFW_KEY_K, "newbase.name")); KeyBinding toggleYawSet = KeyBindingHelper.registerKeyBinding(new KeyBinding("newbase.keybinds.toggletest", GLFW.GLFW_KEY_J, "newbase.name")); ClientTickEvents.END_CLIENT_TICK.register(client -> { if(configScreen.wasPressed()){ mc.setScreen(new ConfigScreen(mc.currentScreen, mc.options)); } if(chatCoordinates.wasPressed()){ mc.setScreen(new ChatCoordinatesScreen(mc.currentScreen, mc.options)); } if(togglePlacer.wasPressed()){
package net.The2019.NewBase.utils; public class InitKeyBindings { private static final MinecraftClient mc = MinecraftClient.getInstance(); public static void initKeys(){ KeyBinding configScreen = KeyBindingHelper.registerKeyBinding(new KeyBinding("newbase.keybinds.configscreen", GLFW.GLFW_KEY_O, "newbase.name")); KeyBinding chatCoordinates = KeyBindingHelper.registerKeyBinding(new KeyBinding("newbase.keybinds.sendcoordinates", GLFW.GLFW_KEY_P, "newbase.name")); KeyBinding togglePlacer = KeyBindingHelper.registerKeyBinding(new KeyBinding("newbase.keybinds.toggleplacer", GLFW.GLFW_KEY_K, "newbase.name")); KeyBinding toggleYawSet = KeyBindingHelper.registerKeyBinding(new KeyBinding("newbase.keybinds.toggletest", GLFW.GLFW_KEY_J, "newbase.name")); ClientTickEvents.END_CLIENT_TICK.register(client -> { if(configScreen.wasPressed()){ mc.setScreen(new ConfigScreen(mc.currentScreen, mc.options)); } if(chatCoordinates.wasPressed()){ mc.setScreen(new ChatCoordinatesScreen(mc.currentScreen, mc.options)); } if(togglePlacer.wasPressed()){
MinecraftClient.getInstance().options.forwardKey.setPressed(!readModule(placer));
6
2023-10-28 10:33:51+00:00
4k
Ax3dGaming/Sons-Of-Sins-Organs-Addition
src/main/java/com/axed/compat/OrganCreationCategory.java
[ { "identifier": "ModBlocks", "path": "src/main/java/com/axed/block/ModBlocks.java", "snippet": "public class ModBlocks {\n public static final DeferredRegister<Block> BLOCKS =\n DeferredRegister.create(ForgeRegistries.BLOCKS, sosorgans.MODID);\n\n public static final RegistryObject<Bloc...
import com.axed.block.ModBlocks; import com.axed.recipe.OrganCreatorRecipe; import com.axed.sosorgans; import mezz.jei.api.constants.VanillaTypes; import mezz.jei.api.gui.builder.IRecipeLayoutBuilder; import mezz.jei.api.gui.drawable.IDrawable; import mezz.jei.api.helpers.IGuiHelper; import mezz.jei.api.recipe.IFocusGroup; import mezz.jei.api.recipe.RecipeIngredientRole; import mezz.jei.api.recipe.RecipeType; import mezz.jei.api.recipe.category.IRecipeCategory; import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.ItemStack;
1,821
package com.axed.compat; public class OrganCreationCategory implements IRecipeCategory<OrganCreatorRecipe> { public static final ResourceLocation UID = new ResourceLocation(sosorgans.MODID, "organ_creation"); public static final ResourceLocation TEXTURE = new ResourceLocation(sosorgans.MODID, "textures/gui/organ_creator_gui_jei.png"); public static final RecipeType<OrganCreatorRecipe> ORGAN_CREATION_TYPE = new RecipeType<>(UID, OrganCreatorRecipe.class); private final IDrawable background; private final IDrawable icon; public OrganCreationCategory(IGuiHelper helper) { this.background = helper.createDrawable(TEXTURE, 0, 0, 176, 85);
package com.axed.compat; public class OrganCreationCategory implements IRecipeCategory<OrganCreatorRecipe> { public static final ResourceLocation UID = new ResourceLocation(sosorgans.MODID, "organ_creation"); public static final ResourceLocation TEXTURE = new ResourceLocation(sosorgans.MODID, "textures/gui/organ_creator_gui_jei.png"); public static final RecipeType<OrganCreatorRecipe> ORGAN_CREATION_TYPE = new RecipeType<>(UID, OrganCreatorRecipe.class); private final IDrawable background; private final IDrawable icon; public OrganCreationCategory(IGuiHelper helper) { this.background = helper.createDrawable(TEXTURE, 0, 0, 176, 85);
this.icon = helper.createDrawableIngredient(VanillaTypes.ITEM_STACK, new ItemStack(ModBlocks.ORGAN_CREATOR.get()));
0
2023-10-25 19:33:18+00:00
4k
DarlanNoetzold/anPerformaticEcommerce
src/main/java/tech/noetzold/anPerformaticEcommerce/security/controller/AuthenticationController.java
[ { "identifier": "CommerceItemController", "path": "src/main/java/tech/noetzold/anPerformaticEcommerce/controller/CommerceItemController.java", "snippet": "@CrossOrigin(origins = \"*\")\n@PreAuthorize(\"hasAnyRole('ADMIN', 'MANAGER', 'USER')\")\n@RestController\n@RequestMapping(\"/ecommerce/v1/commerceit...
import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import lombok.RequiredArgsConstructor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import tech.noetzold.anPerformaticEcommerce.controller.CommerceItemController; import tech.noetzold.anPerformaticEcommerce.security.user.AuthenticationRequest; import tech.noetzold.anPerformaticEcommerce.security.user.AuthenticationResponse; import tech.noetzold.anPerformaticEcommerce.security.user.RegisterRequest; import tech.noetzold.anPerformaticEcommerce.security.service.AuthenticationService; import java.io.IOException;
1,951
package tech.noetzold.anPerformaticEcommerce.security.controller; @RestController @RequestMapping("/ecommerce/v1/auth") @RequiredArgsConstructor public class AuthenticationController { private final AuthenticationService service; private static final Logger logger = LoggerFactory.getLogger(AuthenticationController.class); @PostMapping("/register")
package tech.noetzold.anPerformaticEcommerce.security.controller; @RestController @RequestMapping("/ecommerce/v1/auth") @RequiredArgsConstructor public class AuthenticationController { private final AuthenticationService service; private static final Logger logger = LoggerFactory.getLogger(AuthenticationController.class); @PostMapping("/register")
public ResponseEntity<AuthenticationResponse> register(
2
2023-10-28 12:30:24+00:00
4k
gianlucameloni/shelly-em
src/main/java/com/gmeloni/shelly/service/ScheduledService.java
[ { "identifier": "GetEMStatusResponse", "path": "src/main/java/com/gmeloni/shelly/dto/rest/GetEMStatusResponse.java", "snippet": "@Data\npublic class GetEMStatusResponse {\n @JsonProperty(\"unixtime\")\n private Long unixTime;\n @JsonProperty(\"emeters\")\n private List<RawEMSample> rawEMSamp...
import com.gmeloni.shelly.dto.rest.GetEMStatusResponse; import com.gmeloni.shelly.model.HourlyEMEnergy; import com.gmeloni.shelly.model.RawEMData; import com.gmeloni.shelly.repository.HourlyEMEnergyRepository; import com.gmeloni.shelly.repository.RawEMDataRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import java.time.Instant; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; import java.util.List; import java.util.TimeZone; import static com.gmeloni.shelly.Constants.DATE_AND_TIME_FORMAT;
3,167
package com.gmeloni.shelly.service; @Service public class ScheduledService { private final Logger log = LoggerFactory.getLogger(this.getClass()); private final DateTimeFormatter sampleFormatter = DateTimeFormatter.ofPattern(DATE_AND_TIME_FORMAT); private final DateTimeFormatter hourlyAggregationFormatter = DateTimeFormatter.ofPattern(DATE_AND_TIME_FORMAT); @Autowired private RawEMDataService rawEMDataService; @Autowired private RawEMDataRepository rawEmDataRepository; @Autowired private HourlyEMEnergyRepository hourlyEMEnergyRepository; @Value("${raw-em.sampling.period.milliseconds}") private String samplingPeriodInMilliseconds; @Value("${raw-em.sampling.threshold}") private Double samplingThreshold; @Scheduled(fixedRateString = "${raw-em.sampling.period.milliseconds}") public void processRawEMData() {
package com.gmeloni.shelly.service; @Service public class ScheduledService { private final Logger log = LoggerFactory.getLogger(this.getClass()); private final DateTimeFormatter sampleFormatter = DateTimeFormatter.ofPattern(DATE_AND_TIME_FORMAT); private final DateTimeFormatter hourlyAggregationFormatter = DateTimeFormatter.ofPattern(DATE_AND_TIME_FORMAT); @Autowired private RawEMDataService rawEMDataService; @Autowired private RawEMDataRepository rawEmDataRepository; @Autowired private HourlyEMEnergyRepository hourlyEMEnergyRepository; @Value("${raw-em.sampling.period.milliseconds}") private String samplingPeriodInMilliseconds; @Value("${raw-em.sampling.threshold}") private Double samplingThreshold; @Scheduled(fixedRateString = "${raw-em.sampling.period.milliseconds}") public void processRawEMData() {
GetEMStatusResponse getEMStatusResponse = rawEMDataService.getRawEMSamples();
0
2023-10-26 19:52:00+00:00
4k
DimitarDSimeonov/ShopApp
src/test/java/bg/softuni/shop_app/service/impl/ProductServiceImplTest.java
[ { "identifier": "MyTime", "path": "src/main/java/bg/softuni/shop_app/helper/MyTime.java", "snippet": "@Configuration\npublic class MyTime {\n @Bean\n public LocalDateTime getNow() {\n return LocalDateTime.now();\n }\n}" }, { "identifier": "AddProductDTO", "path": "src/main/ja...
import bg.softuni.shop_app.helper.MyTime; import bg.softuni.shop_app.model.dto.product.AddProductDTO; import bg.softuni.shop_app.model.dto.product.ProductOwnerViewDTO; import bg.softuni.shop_app.model.dto.product.ProductSearchDTO; import bg.softuni.shop_app.model.dto.product.ProductViewDTO; import bg.softuni.shop_app.model.entity.Product; import bg.softuni.shop_app.model.entity.User; import bg.softuni.shop_app.repository.ProductRepository; import bg.softuni.shop_app.service.ProductService; import bg.softuni.shop_app.service.UserService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.modelmapper.ModelMapper; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; import java.util.Optional; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.*;
1,800
package bg.softuni.shop_app.service.impl; @ExtendWith(MockitoExtension.class) class ProductServiceImplTest { private ProductService productServiceToTest; @Mock private UserService mockUserService; @Mock private ModelMapper mockModelMapper; @Mock private ProductRepository mockProductRepository; @Mock private MyTime mockMyTime; @BeforeEach void setUp() { productServiceToTest = new ProductServiceImpl(mockUserService, mockModelMapper, mockProductRepository, mockMyTime); } @Test void createProduct() { AddProductDTO addProductDTO = new AddProductDTO(); User user = new User();
package bg.softuni.shop_app.service.impl; @ExtendWith(MockitoExtension.class) class ProductServiceImplTest { private ProductService productServiceToTest; @Mock private UserService mockUserService; @Mock private ModelMapper mockModelMapper; @Mock private ProductRepository mockProductRepository; @Mock private MyTime mockMyTime; @BeforeEach void setUp() { productServiceToTest = new ProductServiceImpl(mockUserService, mockModelMapper, mockProductRepository, mockMyTime); } @Test void createProduct() { AddProductDTO addProductDTO = new AddProductDTO(); User user = new User();
Product product = new Product();
5
2023-10-27 13:33:23+00:00
4k
achrafaitibba/invoiceYou
src/main/java/com/onxshield/invoiceyou/invoicestatement/controller/invoiceController.java
[ { "identifier": "action", "path": "src/main/java/com/onxshield/invoiceyou/invoicestatement/model/action.java", "snippet": "public enum action {\n ADDED,\n DELETED,\n NOT_YET\n}" }, { "identifier": "invoice", "path": "src/main/java/com/onxshield/invoiceyou/invoicestatement/model/invo...
import com.onxshield.invoiceyou.invoicestatement.dto.request.invoiceRequest; import com.onxshield.invoiceyou.invoicestatement.dto.response.basicInvoiceResponse; import com.onxshield.invoiceyou.invoicestatement.dto.response.merchandiseResponse; import com.onxshield.invoiceyou.invoicestatement.model.action; import com.onxshield.invoiceyou.invoicestatement.model.invoice; import com.onxshield.invoiceyou.invoicestatement.model.paymentMethod; import com.onxshield.invoiceyou.invoicestatement.model.status; import com.onxshield.invoiceyou.invoicestatement.service.invoiceService; import lombok.RequiredArgsConstructor; import org.springframework.data.domain.Page; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List;
3,352
package com.onxshield.invoiceyou.invoicestatement.controller; @RestController @RequestMapping("/api/v1/invoices") @RequiredArgsConstructor public class invoiceController { private final invoiceService invoiceService; @GetMapping("/status") public ResponseEntity<status[]> allStatus() { return ResponseEntity.ok(status.values()); } @GetMapping("/payMethods")
package com.onxshield.invoiceyou.invoicestatement.controller; @RestController @RequestMapping("/api/v1/invoices") @RequiredArgsConstructor public class invoiceController { private final invoiceService invoiceService; @GetMapping("/status") public ResponseEntity<status[]> allStatus() { return ResponseEntity.ok(status.values()); } @GetMapping("/payMethods")
public ResponseEntity<paymentMethod[]> paymentMethods() {
2
2023-10-29 11:16:37+00:00
4k
Melledy/LunarCore
src/main/java/emu/lunarcore/data/excel/RelicExcel.java
[ { "identifier": "GameData", "path": "src/main/java/emu/lunarcore/data/GameData.java", "snippet": "@SuppressWarnings(\"unused\")\npublic class GameData {\n // Excels\n @Getter private static Int2ObjectMap<AvatarExcel> avatarExcelMap = new Int2ObjectOpenHashMap<>();\n @Getter private static Int2O...
import emu.lunarcore.data.GameData; import emu.lunarcore.data.GameResource; import emu.lunarcore.data.ResourceType; import emu.lunarcore.data.ResourceType.LoadPriority; import emu.lunarcore.game.enums.RelicType; import lombok.Getter;
3,352
package emu.lunarcore.data.excel; @Getter @ResourceType(name = {"RelicConfig.json"}, loadPriority = LoadPriority.LOW) public class RelicExcel extends GameResource { private int ID; private int SetID; private RelicType Type; private int MainAffixGroup; private int SubAffixGroup; private int MaxLevel; private int ExpType; private int ExpProvide; private int CoinCost; @Override public int getId() { return ID; } public int getSetId() { return SetID; } @Override public void onLoad() {
package emu.lunarcore.data.excel; @Getter @ResourceType(name = {"RelicConfig.json"}, loadPriority = LoadPriority.LOW) public class RelicExcel extends GameResource { private int ID; private int SetID; private RelicType Type; private int MainAffixGroup; private int SubAffixGroup; private int MaxLevel; private int ExpType; private int ExpProvide; private int CoinCost; @Override public int getId() { return ID; } public int getSetId() { return SetID; } @Override public void onLoad() {
ItemExcel excel = GameData.getItemExcelMap().get(this.getId());
0
2023-10-10 12:57:35+00:00
4k
jar-analyzer/jar-analyzer
src/test/java/me/n1ar4/jar/analyzer/test/ClassJDBCTest.java
[ { "identifier": "ConfigFile", "path": "src/main/java/me/n1ar4/jar/analyzer/config/ConfigFile.java", "snippet": "public class ConfigFile {\n private String jarPath;\n private String dbPath;\n private String tempPath;\n private String dbSize;\n private String totalJar;\n private String t...
import me.n1ar4.jar.analyzer.config.ConfigFile; import me.n1ar4.jar.analyzer.entity.ClassResult; import me.n1ar4.jar.analyzer.engine.CoreEngine; import me.n1ar4.jar.analyzer.starter.Const;
3,287
package me.n1ar4.jar.analyzer.test; public class ClassJDBCTest { public static void main(String[] args) {
package me.n1ar4.jar.analyzer.test; public class ClassJDBCTest { public static void main(String[] args) {
ConfigFile configFile = new ConfigFile();
0
2023-10-07 15:42:35+00:00
4k
EasyProgramming/easy-mqtt
server/src/main/java/com/ep/mqtt/server/processor/PubRelMqttProcessor.java
[ { "identifier": "MqttUtil", "path": "server/src/main/java/com/ep/mqtt/server/util/MqttUtil.java", "snippet": "public class MqttUtil {\n\n public static void sendPublish(ChannelHandlerContext channelHandlerContext, MessageVo messageVo) {\n MqttFixedHeader mqttFixedHeader = new MqttFixedHeader(M...
import com.ep.mqtt.server.util.MqttUtil; import com.ep.mqtt.server.util.NettyUtil; import com.ep.mqtt.server.util.WorkerThreadPool; import com.ep.mqtt.server.vo.MessageVo; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.mqtt.*; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component;
1,687
package com.ep.mqtt.server.processor; /** * 发布释放 * * @author zbz * @date 2023/7/31 9:47 */ @Slf4j @Component public class PubRelMqttProcessor extends AbstractMqttProcessor<MqttMessage> { @Override protected void process(ChannelHandlerContext channelHandlerContext, MqttMessage mqttMessage) { Integer messageId = getMessageId(mqttMessage);
package com.ep.mqtt.server.processor; /** * 发布释放 * * @author zbz * @date 2023/7/31 9:47 */ @Slf4j @Component public class PubRelMqttProcessor extends AbstractMqttProcessor<MqttMessage> { @Override protected void process(ChannelHandlerContext channelHandlerContext, MqttMessage mqttMessage) { Integer messageId = getMessageId(mqttMessage);
String clientId = NettyUtil.getClientId(channelHandlerContext);
1
2023-10-08 06:41:33+00:00
4k
jjenkov/parsers
src/test/java/com/jenkov/parsers/tokenizers/BasicTokenizerMethodizedTest.java
[ { "identifier": "Utf8Buffer", "path": "src/main/java/com/jenkov/parsers/unicode/Utf8Buffer.java", "snippet": "public class Utf8Buffer {\n\n public byte[] buffer;\n public int offset;\n public int length;\n public int endOffset;\n\n /** A field that can be used during parsing of the data i...
import com.jenkov.parsers.unicode.Utf8Buffer; import org.junit.jupiter.api.Test; import static com.jenkov.parsers.tokenizers.TokenizerTestUtil.assertToken; import static org.junit.jupiter.api.Assertions.assertEquals;
3,367
package com.jenkov.parsers.tokenizers; public class BasicTokenizerMethodizedTest { @Test public void testTokenize() { String data = " + - \"this is a quoted token \" * &abc()def349.87iuy:899/*abc*/"; System.out.println(data.length());
package com.jenkov.parsers.tokenizers; public class BasicTokenizerMethodizedTest { @Test public void testTokenize() { String data = " + - \"this is a quoted token \" * &abc()def349.87iuy:899/*abc*/"; System.out.println(data.length());
Utf8Buffer utf8Buffer = new Utf8Buffer(new byte[1024], 0, 1024);
0
2023-10-12 18:46:04+00:00
4k
egorolegovichyakovlev/DroidRec
app/src/main/java/com/yakovlevegor/DroidRec/MainActivity.java
[ { "identifier": "OnShakeEventHelper", "path": "app/src/main/java/com/yakovlevegor/DroidRec/shake/OnShakeEventHelper.java", "snippet": "public class OnShakeEventHelper {\n private SensorEventListener currentListener;\n private boolean hasListenerChanged;\n private Context context;\n private S...
import android.Manifest; import android.annotation.TargetApi; import android.app.AlertDialog; import android.content.ComponentName; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.ServiceConnection; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.content.res.Configuration; import android.graphics.Color; import android.graphics.ColorFilter; import android.graphics.PorterDuff; import android.graphics.PorterDuffColorFilter; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.graphics.drawable.StateListDrawable; import android.graphics.drawable.VectorDrawable; import android.graphics.drawable.LayerDrawable; import android.graphics.drawable.AnimationDrawable; import android.hardware.display.DisplayManager; import android.media.projection.MediaProjectionManager; import android.net.Uri; import android.os.Binder; import android.os.Build; import android.os.Bundle; import android.os.IBinder; import android.os.SystemClock; import android.provider.Settings; import android.util.DisplayMetrics; import android.view.Display; import android.view.Surface; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.view.MotionEvent; import android.widget.RelativeLayout; import android.widget.ImageView; import android.widget.ImageButton; import android.widget.Chronometer; import android.widget.RadioButton; import android.widget.TextView; import android.widget.Toast; import android.widget.RelativeLayout; import android.widget.LinearLayout; import android.animation.ObjectAnimator; import android.animation.ValueAnimator; import android.animation.AnimatorInflater; import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat; import androidx.vectordrawable.graphics.drawable.AnimatedVectorDrawableCompat; import androidx.vectordrawable.graphics.drawable.Animatable2Compat; import androidx.activity.result.ActivityResult; import androidx.activity.result.ActivityResultCallback; import androidx.activity.result.ActivityResultLauncher; import androidx.activity.result.contract.ActivityResultContracts; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.TooltipCompat; import com.yakovlevegor.DroidRec.shake.OnShakeEventHelper; import com.yakovlevegor.DroidRec.shake.event.ServiceConnectedEvent; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import java.util.ArrayList;
1,972
/* * This is free and unencumbered software released into the public domain. * * Anyone is free to copy, modify, publish, use, compile, sell, or * distribute this software, either in source code form or as a compiled * binary, for any purpose, commercial or non-commercial, and by any * means. * * In jurisdictions that recognize copyright laws, the author or authors * of this software dedicate any and all copyright interest in the * software to the public domain. We make this dedication for the benefit * of the public at large and to the detriment of our heirs and * successors. We intend this dedication to be an overt act of * relinquishment in perpetuity of all present and future rights to this * software under copyright law. * * 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 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. * * For more information, please refer to <http://unlicense.org/> */ package com.yakovlevegor.DroidRec; public class MainActivity extends AppCompatActivity { private static final int REQUEST_MICROPHONE = 56808; private static final int REQUEST_MICROPHONE_PLAYBACK = 59465; private static final int REQUEST_MICROPHONE_RECORD = 58467; private static final int REQUEST_STORAGE = 58593; private static final int REQUEST_STORAGE_AUDIO = 58563; private static final int REQUEST_MODE_CHANGE = 58857; private ScreenRecorder.RecordingBinder recordingBinder; boolean screenRecorderStarted = false; private MediaProjectionManager activityProjectionManager; private SharedPreferences appSettings; private SharedPreferences.Editor appSettingsEditor; Display display; ImageButton mainRecordingButton; ImageButton startRecordingButton; ImageButton recordScreenSetting; ImageButton recordMicrophoneSetting; ImageButton recordAudioSetting; ImageButton recordInfo; ImageButton recordSettings; ImageButton recordShare; ImageButton recordDelete; ImageButton recordOpen; ImageButton recordStop; LinearLayout timerPanel; LinearLayout modesPanel; LinearLayout finishedPanel; LinearLayout optionsPanel; Chronometer timeCounter; TextView audioPlaybackUnavailable; Intent serviceIntent; public static String appName = "com.yakovlevegor.DroidRec"; public static String ACTION_ACTIVITY_START_RECORDING = appName+".ACTIVITY_START_RECORDING"; private boolean stateActivated = false; private boolean serviceToRecording = false; private AlertDialog dialog; private boolean recordModeChosen;
/* * This is free and unencumbered software released into the public domain. * * Anyone is free to copy, modify, publish, use, compile, sell, or * distribute this software, either in source code form or as a compiled * binary, for any purpose, commercial or non-commercial, and by any * means. * * In jurisdictions that recognize copyright laws, the author or authors * of this software dedicate any and all copyright interest in the * software to the public domain. We make this dedication for the benefit * of the public at large and to the detriment of our heirs and * successors. We intend this dedication to be an overt act of * relinquishment in perpetuity of all present and future rights to this * software under copyright law. * * 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 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. * * For more information, please refer to <http://unlicense.org/> */ package com.yakovlevegor.DroidRec; public class MainActivity extends AppCompatActivity { private static final int REQUEST_MICROPHONE = 56808; private static final int REQUEST_MICROPHONE_PLAYBACK = 59465; private static final int REQUEST_MICROPHONE_RECORD = 58467; private static final int REQUEST_STORAGE = 58593; private static final int REQUEST_STORAGE_AUDIO = 58563; private static final int REQUEST_MODE_CHANGE = 58857; private ScreenRecorder.RecordingBinder recordingBinder; boolean screenRecorderStarted = false; private MediaProjectionManager activityProjectionManager; private SharedPreferences appSettings; private SharedPreferences.Editor appSettingsEditor; Display display; ImageButton mainRecordingButton; ImageButton startRecordingButton; ImageButton recordScreenSetting; ImageButton recordMicrophoneSetting; ImageButton recordAudioSetting; ImageButton recordInfo; ImageButton recordSettings; ImageButton recordShare; ImageButton recordDelete; ImageButton recordOpen; ImageButton recordStop; LinearLayout timerPanel; LinearLayout modesPanel; LinearLayout finishedPanel; LinearLayout optionsPanel; Chronometer timeCounter; TextView audioPlaybackUnavailable; Intent serviceIntent; public static String appName = "com.yakovlevegor.DroidRec"; public static String ACTION_ACTIVITY_START_RECORDING = appName+".ACTIVITY_START_RECORDING"; private boolean stateActivated = false; private boolean serviceToRecording = false; private AlertDialog dialog; private boolean recordModeChosen;
private OnShakeEventHelper onShakeEventHelper;
0
2023-10-09 00:04:13+00:00
4k
fuzhengwei/chatglm-sdk-java
src/main/java/cn/bugstack/chatglm/session/defaults/DefaultOpenAiSession.java
[ { "identifier": "IOpenAiApi", "path": "src/main/java/cn/bugstack/chatglm/IOpenAiApi.java", "snippet": "public interface IOpenAiApi {\n\n String v3_completions = \"api/paas/v3/model-api/{model}/sse-invoke\";\n String v3_completions_sync = \"api/paas/v3/model-api/{model}/invoke\";\n\n @POST(v3_co...
import cn.bugstack.chatglm.IOpenAiApi; import cn.bugstack.chatglm.model.ChatCompletionRequest; import cn.bugstack.chatglm.model.ChatCompletionResponse; import cn.bugstack.chatglm.model.ChatCompletionSyncResponse; import cn.bugstack.chatglm.model.EventType; import cn.bugstack.chatglm.session.Configuration; import cn.bugstack.chatglm.session.OpenAiSession; import com.alibaba.fastjson.JSON; import com.fasterxml.jackson.core.JsonProcessingException; import lombok.extern.slf4j.Slf4j; import okhttp3.*; import okhttp3.sse.EventSource; import okhttp3.sse.EventSourceListener; import org.jetbrains.annotations.Nullable; import java.io.IOException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch;
2,366
package cn.bugstack.chatglm.session.defaults; /** * @author 小傅哥,微信:fustack * @description 会话服务 * @github https://github.com/fuzhengwei * @Copyright 公众号:bugstack虫洞栈 | 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! */ @Slf4j public class DefaultOpenAiSession implements OpenAiSession { /** * OpenAi 接口 */ private final Configuration configuration; /** * 工厂事件 */ private final EventSource.Factory factory; public DefaultOpenAiSession(Configuration configuration) { this.configuration = configuration; this.factory = configuration.createRequestFactory(); } @Override public EventSource completions(ChatCompletionRequest chatCompletionRequest, EventSourceListener eventSourceListener) throws JsonProcessingException { // 构建请求信息 Request request = new Request.Builder() .url(configuration.getApiHost().concat(IOpenAiApi.v3_completions).replace("{model}", chatCompletionRequest.getModel().getCode())) .post(RequestBody.create(MediaType.parse("application/json"), chatCompletionRequest.toString())) .build(); // 返回事件结果 return factory.newEventSource(request, eventSourceListener); } @Override public CompletableFuture<String> completions(ChatCompletionRequest chatCompletionRequest) throws InterruptedException { // 用于执行异步任务并获取结果 CompletableFuture<String> future = new CompletableFuture<>(); StringBuffer dataBuffer = new StringBuffer(); // 构建请求信息 Request request = new Request.Builder() .url(configuration.getApiHost().concat(IOpenAiApi.v3_completions).replace("{model}", chatCompletionRequest.getModel().getCode())) .post(RequestBody.create(MediaType.parse("application/json"), chatCompletionRequest.toString())) .build(); // 异步响应请求 factory.newEventSource(request, new EventSourceListener() { @Override public void onEvent(EventSource eventSource, @Nullable String id, @Nullable String type, String data) {
package cn.bugstack.chatglm.session.defaults; /** * @author 小傅哥,微信:fustack * @description 会话服务 * @github https://github.com/fuzhengwei * @Copyright 公众号:bugstack虫洞栈 | 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! */ @Slf4j public class DefaultOpenAiSession implements OpenAiSession { /** * OpenAi 接口 */ private final Configuration configuration; /** * 工厂事件 */ private final EventSource.Factory factory; public DefaultOpenAiSession(Configuration configuration) { this.configuration = configuration; this.factory = configuration.createRequestFactory(); } @Override public EventSource completions(ChatCompletionRequest chatCompletionRequest, EventSourceListener eventSourceListener) throws JsonProcessingException { // 构建请求信息 Request request = new Request.Builder() .url(configuration.getApiHost().concat(IOpenAiApi.v3_completions).replace("{model}", chatCompletionRequest.getModel().getCode())) .post(RequestBody.create(MediaType.parse("application/json"), chatCompletionRequest.toString())) .build(); // 返回事件结果 return factory.newEventSource(request, eventSourceListener); } @Override public CompletableFuture<String> completions(ChatCompletionRequest chatCompletionRequest) throws InterruptedException { // 用于执行异步任务并获取结果 CompletableFuture<String> future = new CompletableFuture<>(); StringBuffer dataBuffer = new StringBuffer(); // 构建请求信息 Request request = new Request.Builder() .url(configuration.getApiHost().concat(IOpenAiApi.v3_completions).replace("{model}", chatCompletionRequest.getModel().getCode())) .post(RequestBody.create(MediaType.parse("application/json"), chatCompletionRequest.toString())) .build(); // 异步响应请求 factory.newEventSource(request, new EventSourceListener() { @Override public void onEvent(EventSource eventSource, @Nullable String id, @Nullable String type, String data) {
ChatCompletionResponse response = JSON.parseObject(data, ChatCompletionResponse.class);
2
2023-10-10 13:49:59+00:00
4k
lunasaw/gb28181-proxy
sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/SipProcessorObserver.java
[ { "identifier": "Event", "path": "sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/event/Event.java", "snippet": "public interface Event {\n /**\n * 回调\n * \n * @param eventResult\n */\n void response(EventResult eventResult);\n}" }, { "identifier": "EventResu...
import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import javax.sip.*; import javax.sip.header.CSeqHeader; import javax.sip.header.CallIdHeader; import javax.sip.message.Request; import javax.sip.message.Response; import org.apache.commons.collections4.CollectionUtils; import com.alibaba.fastjson.JSON; import io.github.lunasaw.sip.common.transmit.event.Event; import io.github.lunasaw.sip.common.transmit.event.EventResult; import io.github.lunasaw.sip.common.transmit.event.SipSubscribe; import io.github.lunasaw.sip.common.transmit.event.request.SipRequestProcessor; import io.github.lunasaw.sip.common.transmit.event.response.SipResponseProcessor; import io.github.lunasaw.sip.common.transmit.event.timeout.ITimeoutProcessor; import lombok.extern.slf4j.Slf4j; import org.apache.skywalking.apm.toolkit.trace.Trace; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component;
2,315
package io.github.lunasaw.sip.common.transmit; /** * SIP信令处理类观察者 * * @author luna */ @Slf4j @Component public class SipProcessorObserver implements SipListener { @Autowired private SipProcessorInject sipProcessorInject; /** * 对SIP事件进行处理 */
package io.github.lunasaw.sip.common.transmit; /** * SIP信令处理类观察者 * * @author luna */ @Slf4j @Component public class SipProcessorObserver implements SipListener { @Autowired private SipProcessorInject sipProcessorInject; /** * 对SIP事件进行处理 */
private static final Map<String, List<SipRequestProcessor>> REQUEST_PROCESSOR_MAP = new ConcurrentHashMap<>();
3
2023-10-11 06:56:28+00:00
4k
1415181920/yamis-admin
cocoyam-common/src/main/java/io/xiaoyu/common/req/CommonPageRequest.java
[ { "identifier": "PageResp", "path": "cocoyam-common/src/main/java/io/xiaoyu/common/resp/PageResp.java", "snippet": "@Getter\n@Setter\npublic class PageResp<T> extends Page<T>{\n\n /**\n * 当前页的列表\n */\n private List<T> items;\n /**\n * 当前页码\n */\n private long pageNum;\n /*...
import cn.hutool.core.convert.Convert; import cn.hutool.core.util.ObjectUtil; import com.baomidou.mybatisplus.core.metadata.OrderItem; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import io.xiaoyu.common.resp.PageResp; import io.xiaoyu.common.util.CommonServletUtil; import lombok.extern.slf4j.Slf4j; import java.util.List;
1,631
/* * Copyright [2022] [https://www.xiaonuo.vip] * * Snowy采用APACHE LICENSE 2.0开源协议,您在使用过程中,需要注意以下几点: * * 1.请不要删除和修改根目录下的LICENSE文件。 * 2.请不要删除和修改Snowy源码头部的版权声明。 * 3.本项目代码可免费商业使用,商业使用请保留源码和相关描述文件的项目出处,作者声明等。 * 4.分发源码时候,请注明软件出处 https://www.xiaonuo.vip * 5.不可二次分发开源参与同类竞品,如有想法可联系团队xiaonuobase@qq.com商议合作。 * 6.若您的项目无法满足以上几点,需要更多功能代码,获取Snowy商业授权许可,请在官网购买授权,地址为 https://www.xiaonuo.vip */ package io.xiaoyu.common.req; /** * 通用分页请求 * * @author xiaoyu * @date 2021/12/18 14:43 */ @Slf4j public class CommonPageRequest { private static final String PAGE_SIZE_PARAM_NAME = "perPage"; private static final String PAGE_PARAM_NAME = "page"; private static final Integer PAGE_SIZE_MAX_VALUE = 100; public static <T> PageResp<T> defaultPage() { return defaultPage(null); } public static <T> PageResp<T> defaultPage(List<OrderItem> orderItemList) { int perPage = 20; int page = 1; //每页条数
/* * Copyright [2022] [https://www.xiaonuo.vip] * * Snowy采用APACHE LICENSE 2.0开源协议,您在使用过程中,需要注意以下几点: * * 1.请不要删除和修改根目录下的LICENSE文件。 * 2.请不要删除和修改Snowy源码头部的版权声明。 * 3.本项目代码可免费商业使用,商业使用请保留源码和相关描述文件的项目出处,作者声明等。 * 4.分发源码时候,请注明软件出处 https://www.xiaonuo.vip * 5.不可二次分发开源参与同类竞品,如有想法可联系团队xiaonuobase@qq.com商议合作。 * 6.若您的项目无法满足以上几点,需要更多功能代码,获取Snowy商业授权许可,请在官网购买授权,地址为 https://www.xiaonuo.vip */ package io.xiaoyu.common.req; /** * 通用分页请求 * * @author xiaoyu * @date 2021/12/18 14:43 */ @Slf4j public class CommonPageRequest { private static final String PAGE_SIZE_PARAM_NAME = "perPage"; private static final String PAGE_PARAM_NAME = "page"; private static final Integer PAGE_SIZE_MAX_VALUE = 100; public static <T> PageResp<T> defaultPage() { return defaultPage(null); } public static <T> PageResp<T> defaultPage(List<OrderItem> orderItemList) { int perPage = 20; int page = 1; //每页条数
String pageSizeString = CommonServletUtil.getParamFromRequest(PAGE_SIZE_PARAM_NAME);
1
2023-10-09 06:04:30+00:00
4k
Swofty-Developments/Continued-Slime-World-Manager
swoftyworldmanager-plugin/src/main/java/net/swofty/swm/plugin/commands/subtypes/subCommand_reloadconfig.java
[ { "identifier": "CommandCooldown", "path": "swoftyworldmanager-plugin/src/main/java/net/swofty/swm/plugin/commands/CommandCooldown.java", "snippet": "public interface CommandCooldown {\n long cooldownSeconds();\n\n default long getCooldown() {\n return cooldownSeconds() * 1000;\n }\n}" ...
import net.swofty.swm.plugin.commands.CommandCooldown; import net.swofty.swm.plugin.commands.CommandParameters; import net.swofty.swm.plugin.commands.CommandSource; import net.swofty.swm.plugin.commands.SWMCommand; import net.swofty.swm.plugin.config.ConfigManager; import net.swofty.swm.plugin.log.Logging; import ninja.leaping.configurate.objectmapping.ObjectMappingException; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import org.bukkit.command.ConsoleCommandSender; import java.io.IOException; import java.util.List;
2,676
package net.swofty.swm.plugin.commands.subtypes; @CommandParameters(description = "Reloads the config files", inGameOnly = false, permission = "swm.reload") public class subCommand_reloadconfig extends SWMCommand implements CommandCooldown { @Override public long cooldownSeconds() { return 3; } @Override
package net.swofty.swm.plugin.commands.subtypes; @CommandParameters(description = "Reloads the config files", inGameOnly = false, permission = "swm.reload") public class subCommand_reloadconfig extends SWMCommand implements CommandCooldown { @Override public long cooldownSeconds() { return 3; } @Override
public void run(CommandSource sender, String[] args) {
1
2023-10-08 10:54:28+00:00
4k
calicosun258/5c-client-N
src/main/java/fifthcolumn/n/mixins/TextVisitFactoryMixin.java
[ { "identifier": "LarpModule", "path": "src/main/java/fifthcolumn/n/modules/LarpModule.java", "snippet": "public class LarpModule extends Module {\n private final SettingGroup sgGeneral = this.settings.getDefaultGroup();\n\n public final Setting<String> alias = this.sgGeneral.add(new StringSetting.Bu...
import fifthcolumn.n.modules.LarpModule; import fifthcolumn.n.modules.StreamerMode; import net.minecraft.text.TextVisitFactory; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.ModifyVariable;
1,881
package fifthcolumn.n.mixins; @Mixin({TextVisitFactory.class}) public class TextVisitFactoryMixin { @ModifyVariable( method = {"visitFormatted(Ljava/lang/String;ILnet/minecraft/text/Style;Lnet/minecraft/text/Style;Lnet/minecraft/text/CharacterVisitor;)Z"}, at = @At("HEAD"), ordinal = 0, index = 0, argsOnly = true ) private static String n$modifyAllPlayerNameInstances(String text) { text = LarpModule.modifyPlayerNameInstances(text);
package fifthcolumn.n.mixins; @Mixin({TextVisitFactory.class}) public class TextVisitFactoryMixin { @ModifyVariable( method = {"visitFormatted(Ljava/lang/String;ILnet/minecraft/text/Style;Lnet/minecraft/text/Style;Lnet/minecraft/text/CharacterVisitor;)Z"}, at = @At("HEAD"), ordinal = 0, index = 0, argsOnly = true ) private static String n$modifyAllPlayerNameInstances(String text) { text = LarpModule.modifyPlayerNameInstances(text);
text = StreamerMode.anonymizePlayerNameInstances(text);
1
2023-10-14 19:18:35+00:00
4k
shenmejianghu/bili-downloader
src/main/java/com/bilibili/downloader/controller/MainController.java
[ { "identifier": "LiveConfig", "path": "src/main/java/com/bilibili/downloader/pojo/LiveConfig.java", "snippet": "public class LiveConfig {\n //推流地址\n private String url;\n private String secret;\n //循环次数,-1表示无限循环\n private Integer loop;\n\n public String getUrl() {\n return url;\...
import cn.hutool.core.io.FileUtil; import cn.hutool.crypto.digest.MD5; import cn.hutool.http.HttpRequest; import cn.hutool.json.JSON; import cn.hutool.json.JSONArray; import cn.hutool.json.JSONObject; import cn.hutool.json.JSONUtil; import com.bilibili.downloader.pojo.LiveConfig; import com.bilibili.downloader.pojo.Result; import com.bilibili.downloader.util.HttpFile; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.exception.ExceptionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpMethod; import org.springframework.http.client.ClientHttpRequest; import org.springframework.http.client.ClientHttpResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.client.RequestCallback; import org.springframework.web.client.ResponseExtractor; import org.springframework.web.client.RestTemplate; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.net.Authenticator; import java.net.InetSocketAddress; import java.net.PasswordAuthentication; import java.net.Proxy; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern;
3,005
if (output != null){ output.close(); } } } }; Object result = restTemplate.execute(videoUrl, HttpMethod.GET,videoRequestCallback,videoResponseExtractor); if ((Boolean)result){ videoFile = finalFileName; break; } } } if (audioList != null){ for (Object audio:audioList){ JSONObject map = (JSONObject)audio; String audioUrl = map.get("baseUrl").toString(); String segmentInit = map.getByPath("SegmentBase.Initialization").toString(); RequestCallback requestCallback = new RequestCallback() { @Override public void doWithRequest(ClientHttpRequest clientHttpRequest) throws IOException { clientHttpRequest.getHeaders().add("Referer",url); clientHttpRequest.getHeaders().add("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36"); clientHttpRequest.getHeaders().add("Range","bytes="+segmentInit); } }; ResponseExtractor responseExtractor = new ResponseExtractor<String>() { @Override public String extractData(ClientHttpResponse clientHttpResponse) throws IOException { return clientHttpResponse.getHeaders().get("Content-Range").get(0).split("/")[1]; } }; Object audioSize = restTemplate.execute(audioUrl, HttpMethod.GET,requestCallback,responseExtractor); logger.info("音频地址:{}",audioUrl); logger.info("音频大小:{}",audioSize); RequestCallback audioRequestCallback = new RequestCallback() { @Override public void doWithRequest(ClientHttpRequest clientHttpRequest) throws IOException { clientHttpRequest.getHeaders().add("Referer",url); clientHttpRequest.getHeaders().add("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36"); clientHttpRequest.getHeaders().add("Range","bytes=0-"+audioSize); } }; String fileName = StringUtils.substringBefore(audioUrl,".m4s"); fileName = StringUtils.substringAfterLast(fileName,"/"); final String finalFileName = fileName +".mp3"; ResponseExtractor audioResponseExtractor = new ResponseExtractor<Boolean>() { @Override public Boolean extractData(ClientHttpResponse clientHttpResponse) throws IOException { OutputStream output = null; try { output = new FileOutputStream(dir+ finalFileName); logger.info("开始下载音频文件:{}", finalFileName); IOUtils.copy(clientHttpResponse.getBody(),output); logger.info("音频文件下载完成:{}", finalFileName); return Boolean.TRUE; }catch (Exception e){ e.printStackTrace(); return Boolean.FALSE; }finally { if (output != null){ output.close(); } } } }; Object result = restTemplate.execute(audioUrl, HttpMethod.GET,audioRequestCallback,audioResponseExtractor); if ((Boolean)result){ audioFile = finalFileName; break; } } } if (StringUtils.isEmpty(videoFile)&&StringUtils.isEmpty(audioFile)){ logger.warn("未找到视频:{}",url); return Result.fail(null,"未找到视频"); } if (StringUtils.isNotEmpty(videoFile) && StringUtils.isNotEmpty(audioFile)){ //ffmpeg -i 视频文件名.mp4 -i 音频文件名.mp3 -c:v copy -c:a copy 输出文件名.mp4 List<String> commands = new ArrayList<>(); commands.add(ffmpegPath); commands.add("-i"); commands.add(dir+videoFile); commands.add("-i"); commands.add(dir+audioFile); commands.add("-c:v"); commands.add("copy"); commands.add("-c:a"); commands.add("copy"); commands.add(dir+"final-file.mp4"); logger.info("开始合成视频音频"); ProcessBuilder builder = new ProcessBuilder(); builder.command(commands); try { builder.inheritIO().start().waitFor(); logger.info("视频合成完成"); } catch (InterruptedException | IOException e) { logger.info("视频合成失败:{}", ExceptionUtils.getStackTrace(e)); } return Result.success(uuid+"_"+"final-file.mp4"); } if (StringUtils.isNotEmpty(videoFile)){ return Result.success(uuid+"_"+videoFile); } if (StringUtils.isNotEmpty(audioFile)){ return Result.success(uuid+"_"+audioFile); } return Result.fail(null,"未找到视频"); }else { logger.warn("视频地址解析错误"); return Result.fail(null,"视频地址解析错误"); } }catch (Exception e){ logger.error(ExceptionUtils.getStackTrace(e)); return Result.fail(null,"视频地址解析错误"); } } @RequestMapping("/live") @ResponseBody
package com.bilibili.downloader.controller; @Controller public class MainController { private static Logger logger = LoggerFactory.getLogger(MainController.class); @Autowired private RestTemplate restTemplate; @Value("${server.tomcat.basedir}") private String baseDir; @Value("${application.ffmpeg-path}") private String ffmpegPath; @RequestMapping("/download") public void download(HttpServletResponse response, String file){ logger.info("下载视频文件:{}",file); if (StringUtils.isEmpty(file)){ return; } String[] arr = file.split("_"); if (arr.length != 2){ return; } String filePath = baseDir+File.separator+arr[0]+File.separator+arr[1]; if (!FileUtil.exist(filePath)){ return; } HttpFile.downloadFile(arr[1],filePath,response); FileUtil.del(baseDir+File.separator+arr[0]); } @RequestMapping("/parse") @ResponseBody public Result<String> parse(String url){ try { logger.info("开始解析视频地址:{}",url); String html = restTemplate.getForObject(url,String.class); String regex = "(?<=<script>window.__playinfo__=).*?(?=</script>)"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(html); if (matcher.find()) { String uuid = UUID.randomUUID().toString().replace("-",""); String dir = baseDir + File.separator + uuid +File.separator; if (!FileUtil.exist(dir)){ FileUtil.mkdir(dir); } String videoFile = ""; String audioFile = ""; String jsonStr = matcher.group(); JSON json = JSONUtil.parse(jsonStr); JSONArray videoList = (JSONArray)json.getByPath("data.dash.video"); JSONArray audioList = (JSONArray)json.getByPath("data.dash.audio"); if (videoList != null){ for (Object video:videoList){ JSONObject map = (JSONObject)video; String videoUrl = map.get("baseUrl").toString(); String segmentInit = map.getByPath("SegmentBase.Initialization").toString(); RequestCallback requestCallback = new RequestCallback() { @Override public void doWithRequest(ClientHttpRequest clientHttpRequest) throws IOException { clientHttpRequest.getHeaders().add("Referer",url); clientHttpRequest.getHeaders().add("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36"); clientHttpRequest.getHeaders().add("Range","bytes="+segmentInit); } }; ResponseExtractor responseExtractor = new ResponseExtractor<String>() { @Override public String extractData(ClientHttpResponse clientHttpResponse) throws IOException { return clientHttpResponse.getHeaders().get("Content-Range").get(0).split("/")[1]; } }; Object videoSize = restTemplate.execute(videoUrl, HttpMethod.GET,requestCallback,responseExtractor); logger.info("视频地址:{}",videoUrl); logger.info("视频大小:{}",videoSize); RequestCallback videoRequestCallback = new RequestCallback() { @Override public void doWithRequest(ClientHttpRequest clientHttpRequest) throws IOException { clientHttpRequest.getHeaders().add("Referer",url); clientHttpRequest.getHeaders().add("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36"); clientHttpRequest.getHeaders().add("Range","bytes=0-"+videoSize); } }; String fileName = StringUtils.substringBefore(videoUrl,".m4s"); fileName = StringUtils.substringAfterLast(fileName,"/"); final String finalFileName = fileName +".mp4"; ResponseExtractor videoResponseExtractor = new ResponseExtractor<Boolean>() { @Override public Boolean extractData(ClientHttpResponse clientHttpResponse) throws IOException { OutputStream output = null; try { output = new FileOutputStream(dir+ finalFileName); logger.info("开始下载视频文件:{}",finalFileName); IOUtils.copy(clientHttpResponse.getBody(),output); logger.info("视频文件下载完成:{}",finalFileName); return Boolean.TRUE; }catch (Exception e){ e.printStackTrace(); return Boolean.FALSE; }finally { if (output != null){ output.close(); } } } }; Object result = restTemplate.execute(videoUrl, HttpMethod.GET,videoRequestCallback,videoResponseExtractor); if ((Boolean)result){ videoFile = finalFileName; break; } } } if (audioList != null){ for (Object audio:audioList){ JSONObject map = (JSONObject)audio; String audioUrl = map.get("baseUrl").toString(); String segmentInit = map.getByPath("SegmentBase.Initialization").toString(); RequestCallback requestCallback = new RequestCallback() { @Override public void doWithRequest(ClientHttpRequest clientHttpRequest) throws IOException { clientHttpRequest.getHeaders().add("Referer",url); clientHttpRequest.getHeaders().add("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36"); clientHttpRequest.getHeaders().add("Range","bytes="+segmentInit); } }; ResponseExtractor responseExtractor = new ResponseExtractor<String>() { @Override public String extractData(ClientHttpResponse clientHttpResponse) throws IOException { return clientHttpResponse.getHeaders().get("Content-Range").get(0).split("/")[1]; } }; Object audioSize = restTemplate.execute(audioUrl, HttpMethod.GET,requestCallback,responseExtractor); logger.info("音频地址:{}",audioUrl); logger.info("音频大小:{}",audioSize); RequestCallback audioRequestCallback = new RequestCallback() { @Override public void doWithRequest(ClientHttpRequest clientHttpRequest) throws IOException { clientHttpRequest.getHeaders().add("Referer",url); clientHttpRequest.getHeaders().add("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36"); clientHttpRequest.getHeaders().add("Range","bytes=0-"+audioSize); } }; String fileName = StringUtils.substringBefore(audioUrl,".m4s"); fileName = StringUtils.substringAfterLast(fileName,"/"); final String finalFileName = fileName +".mp3"; ResponseExtractor audioResponseExtractor = new ResponseExtractor<Boolean>() { @Override public Boolean extractData(ClientHttpResponse clientHttpResponse) throws IOException { OutputStream output = null; try { output = new FileOutputStream(dir+ finalFileName); logger.info("开始下载音频文件:{}", finalFileName); IOUtils.copy(clientHttpResponse.getBody(),output); logger.info("音频文件下载完成:{}", finalFileName); return Boolean.TRUE; }catch (Exception e){ e.printStackTrace(); return Boolean.FALSE; }finally { if (output != null){ output.close(); } } } }; Object result = restTemplate.execute(audioUrl, HttpMethod.GET,audioRequestCallback,audioResponseExtractor); if ((Boolean)result){ audioFile = finalFileName; break; } } } if (StringUtils.isEmpty(videoFile)&&StringUtils.isEmpty(audioFile)){ logger.warn("未找到视频:{}",url); return Result.fail(null,"未找到视频"); } if (StringUtils.isNotEmpty(videoFile) && StringUtils.isNotEmpty(audioFile)){ //ffmpeg -i 视频文件名.mp4 -i 音频文件名.mp3 -c:v copy -c:a copy 输出文件名.mp4 List<String> commands = new ArrayList<>(); commands.add(ffmpegPath); commands.add("-i"); commands.add(dir+videoFile); commands.add("-i"); commands.add(dir+audioFile); commands.add("-c:v"); commands.add("copy"); commands.add("-c:a"); commands.add("copy"); commands.add(dir+"final-file.mp4"); logger.info("开始合成视频音频"); ProcessBuilder builder = new ProcessBuilder(); builder.command(commands); try { builder.inheritIO().start().waitFor(); logger.info("视频合成完成"); } catch (InterruptedException | IOException e) { logger.info("视频合成失败:{}", ExceptionUtils.getStackTrace(e)); } return Result.success(uuid+"_"+"final-file.mp4"); } if (StringUtils.isNotEmpty(videoFile)){ return Result.success(uuid+"_"+videoFile); } if (StringUtils.isNotEmpty(audioFile)){ return Result.success(uuid+"_"+audioFile); } return Result.fail(null,"未找到视频"); }else { logger.warn("视频地址解析错误"); return Result.fail(null,"视频地址解析错误"); } }catch (Exception e){ logger.error(ExceptionUtils.getStackTrace(e)); return Result.fail(null,"视频地址解析错误"); } } @RequestMapping("/live") @ResponseBody
public Result<String> live(@RequestBody LiveConfig live){
0
2023-10-08 01:32:06+00:00
4k
Robothy/sdwebui-java-sdk
src/main/java/io/github/robothy/sdwebui/sdk/services/DefaultTxt2ImageService.java
[ { "identifier": "SdWebuiBeanContainer", "path": "src/main/java/io/github/robothy/sdwebui/sdk/SdWebuiBeanContainer.java", "snippet": "public interface SdWebuiBeanContainer {\n\n static SdWebuiBeanContainer create(SdWebuiOptions options) {\n return new DefaultSdWebuiBeanContainer(options);\n }\n\n <...
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import io.github.robothy.sdwebui.sdk.SdWebuiBeanContainer; import io.github.robothy.sdwebui.sdk.Txt2Image; import io.github.robothy.sdwebui.sdk.models.SdWebuiOptions; import io.github.robothy.sdwebui.sdk.models.SystemInfo; import io.github.robothy.sdwebui.sdk.models.options.Txt2ImageOptions; import io.github.robothy.sdwebui.sdk.models.results.Txt2ImgResult; import io.github.robothy.sdwebui.sdk.utils.SdWebuiResponseUtils; import org.apache.hc.client5.http.classic.HttpClient; import org.apache.hc.client5.http.classic.methods.HttpPost; import org.apache.hc.core5.http.ClassicHttpRequest; import org.apache.hc.core5.http.ClassicHttpResponse; import org.apache.hc.core5.http.HttpEntity; import org.apache.hc.core5.http.io.entity.StringEntity; import java.io.IOException;
2,315
package io.github.robothy.sdwebui.sdk.services; public class DefaultTxt2ImageService implements Txt2Image { private static final String TXT2IMG_PATH = "/sdapi/v1/txt2img"; private final SdWebuiBeanContainer beanContainer; public DefaultTxt2ImageService(SdWebuiBeanContainer beanContainer) { this.beanContainer = beanContainer; } @Override
package io.github.robothy.sdwebui.sdk.services; public class DefaultTxt2ImageService implements Txt2Image { private static final String TXT2IMG_PATH = "/sdapi/v1/txt2img"; private final SdWebuiBeanContainer beanContainer; public DefaultTxt2ImageService(SdWebuiBeanContainer beanContainer) { this.beanContainer = beanContainer; } @Override
public Txt2ImgResult txt2Img(Txt2ImageOptions options) {
4
2023-10-10 14:55:42+00:00
4k
dadegrande99/HikeMap
app/src/main/java/com/usi/hikemap/ui/authentication/LoginFragment.java
[ { "identifier": "MainActivity", "path": "app/src/main/java/com/usi/hikemap/MainActivity.java", "snippet": "public class MainActivity extends AppCompatActivity {\n\n private ActivityMainBinding binding;\n\n private GoogleMap mMap;\n\n MeowBottomNavigation bottomNavigation;\n\n String userId;\...
import android.content.Intent; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.lifecycle.ViewModelProvider; import androidx.navigation.fragment.NavHostFragment; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import com.google.android.gms.auth.api.signin.GoogleSignIn; import com.google.android.gms.auth.api.signin.GoogleSignInAccount; import com.google.android.gms.auth.api.signin.GoogleSignInClient; import com.google.android.gms.auth.api.signin.GoogleSignInOptions; import com.google.android.gms.tasks.Task; import com.google.android.material.snackbar.Snackbar; import com.usi.hikemap.MainActivity; import com.usi.hikemap.R; import com.usi.hikemap.databinding.FragmentLoginBinding; import com.usi.hikemap.ui.viewmodel.AuthViewModel; import com.usi.hikemap.utils.Constants;
2,029
package com.usi.hikemap.ui.authentication; public class LoginFragment extends Fragment { EditText mEmailEditText; EditText mPasswordEditText; Button mLoginButton; ImageView mGoogleButton, mReturnStartPage; private GoogleSignInClient mGoogleSignInClient; AuthViewModel mAuthViewModel; private final String TAG = "LoginFragment"; private FragmentLoginBinding binding; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mAuthViewModel = new ViewModelProvider(requireActivity()).get(AuthViewModel.class); } @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { binding = FragmentLoginBinding.inflate(inflater, container, false); View root = binding.getRoot(); mEmailEditText = root.findViewById(R.id.email_log_editText); mPasswordEditText = root.findViewById(R.id.password_log_editText); mLoginButton = root.findViewById(R.id.access_button); //*********************** mReturnStartPage = root.findViewById(R.id.return_to_startPage_from_login); mReturnStartPage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { NavHostFragment.findNavController(LoginFragment.this).navigate(R.id.login_to_startpage); } }); //*********************** mLoginButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String email, password; email = mEmailEditText.getText().toString().trim(); password = mPasswordEditText.getText().toString().trim(); if (TextUtils.isEmpty(email)) { mEmailEditText.setError("Email is required"); return; } if (TextUtils.isEmpty(password) || password.length() < 8) { mEmailEditText.setError("Password is required"); return; } mAuthViewModel.loginWithEmail(email, password).observe(getViewLifecycleOwner(), authenticationResponse -> { if (authenticationResponse != null) { if (authenticationResponse.isSuccess()) { Log.d(TAG, "onClick: Access to main Activity");
package com.usi.hikemap.ui.authentication; public class LoginFragment extends Fragment { EditText mEmailEditText; EditText mPasswordEditText; Button mLoginButton; ImageView mGoogleButton, mReturnStartPage; private GoogleSignInClient mGoogleSignInClient; AuthViewModel mAuthViewModel; private final String TAG = "LoginFragment"; private FragmentLoginBinding binding; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mAuthViewModel = new ViewModelProvider(requireActivity()).get(AuthViewModel.class); } @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { binding = FragmentLoginBinding.inflate(inflater, container, false); View root = binding.getRoot(); mEmailEditText = root.findViewById(R.id.email_log_editText); mPasswordEditText = root.findViewById(R.id.password_log_editText); mLoginButton = root.findViewById(R.id.access_button); //*********************** mReturnStartPage = root.findViewById(R.id.return_to_startPage_from_login); mReturnStartPage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { NavHostFragment.findNavController(LoginFragment.this).navigate(R.id.login_to_startpage); } }); //*********************** mLoginButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String email, password; email = mEmailEditText.getText().toString().trim(); password = mPasswordEditText.getText().toString().trim(); if (TextUtils.isEmpty(email)) { mEmailEditText.setError("Email is required"); return; } if (TextUtils.isEmpty(password) || password.length() < 8) { mEmailEditText.setError("Password is required"); return; } mAuthViewModel.loginWithEmail(email, password).observe(getViewLifecycleOwner(), authenticationResponse -> { if (authenticationResponse != null) { if (authenticationResponse.isSuccess()) { Log.d(TAG, "onClick: Access to main Activity");
Intent intent = new Intent(getActivity(), MainActivity.class);
0
2023-10-09 14:23:22+00:00
4k
xiaoymin/LlmInAction
llm_chat_java_hello/src/main/java/com/github/xiaoymin/llm/command/AddTxtCommand.java
[ { "identifier": "TxtChunk", "path": "llm_chat_java_hello/src/main/java/com/github/xiaoymin/llm/compoents/TxtChunk.java", "snippet": "@Slf4j\n@Component\n@AllArgsConstructor\npublic class TxtChunk {\n\n public List<ChunkResult> chunk(String docId){\n String path=\"data/\"+docId+\".txt\";\n ...
import com.github.xiaoymin.llm.compoents.TxtChunk; import com.github.xiaoymin.llm.compoents.VectorStorage; import com.github.xiaoymin.llm.domain.llm.ChunkResult; import com.github.xiaoymin.llm.domain.llm.EmbeddingResult; import com.github.xiaoymin.llm.llm.ZhipuAI; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.shell.standard.ShellComponent; import org.springframework.shell.standard.ShellMethod; import java.util.List;
3,128
package com.github.xiaoymin.llm.command; /** * @author <a href="xiaoymin@foxmail.com">xiaoymin@foxmail.com</a> * 2023/10/06 12:50 * @since llm_chat_java_hello */ @Slf4j @AllArgsConstructor @ShellComponent public class AddTxtCommand { final TxtChunk txtChunk; final VectorStorage vectorStorage; final ZhipuAI zhipuAI; @ShellMethod(value = "add local txt data") public String add(String doc){ log.info("start add doc."); // 加载 List<ChunkResult> chunkResults= txtChunk.chunk(doc); // embedding
package com.github.xiaoymin.llm.command; /** * @author <a href="xiaoymin@foxmail.com">xiaoymin@foxmail.com</a> * 2023/10/06 12:50 * @since llm_chat_java_hello */ @Slf4j @AllArgsConstructor @ShellComponent public class AddTxtCommand { final TxtChunk txtChunk; final VectorStorage vectorStorage; final ZhipuAI zhipuAI; @ShellMethod(value = "add local txt data") public String add(String doc){ log.info("start add doc."); // 加载 List<ChunkResult> chunkResults= txtChunk.chunk(doc); // embedding
List<EmbeddingResult> embeddingResults=zhipuAI.embedding(chunkResults);
3
2023-10-10 23:25:33+00:00
4k
ZJU-ACES-ISE/chatunitest-core
src/main/java/zju/cst/aces/api/config/Config.java
[ { "identifier": "Project", "path": "src/main/java/zju/cst/aces/api/Project.java", "snippet": "public interface Project {\n Project getParent();\n File getBasedir();\n /**\n * Get the project packaging type.\n */\n String getPackaging();\n String getGroupId();\n String getArtifa...
import zju.cst.aces.api.Project; import com.github.javaparser.JavaParser; import com.github.javaparser.symbolsolver.javaparsermodel.JavaParserFacade; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import lombok.Getter; import lombok.Setter; import okhttp3.OkHttpClient; import zju.cst.aces.api.Validator; import zju.cst.aces.api.impl.LoggerImpl; import zju.cst.aces.api.Logger; import zju.cst.aces.api.impl.ValidatorImpl; import java.io.File; import java.net.InetSocketAddress; import java.net.Proxy; import java.nio.file.Path; import java.nio.file.Paths; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.List; import java.util.Map; import java.util.Random; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger;
1,828
package zju.cst.aces.api.config; @Getter @Setter public class Config { public String date; public Gson GSON; public Project project; public JavaParser parser; public JavaParserFacade parserFacade; public List<String> classPaths; public Path promptPath; public String url; public String[] apiKeys; public Logger log; public String OS; public boolean stopWhenSuccess; public boolean noExecution; public boolean enableMultithreading; public boolean enableRuleRepair; public boolean enableMerge; public boolean enableObfuscate; public String[] obfuscateGroupIds; public int maxThreads; public int classThreads; public int methodThreads; public int testNumber; public int maxRounds; public int maxPromptTokens; public int maxResponseTokens; public int minErrorTokens; public int sleepTime; public int dependencyDepth; public Model model; public Double temperature; public int topP; public int frequencyPenalty; public int presencePenalty; public Path testOutput; public Path tmpOutput; public Path compileOutputPath; public Path parseOutput; public Path errorOutput; public Path classNameMapPath; public Path historyPath; public Path examplePath; public Path symbolFramePath; public String proxy; public String hostname; public String port; public OkHttpClient client; public static AtomicInteger sharedInteger = new AtomicInteger(0); public static Map<String, Map<String, String>> classMapping; public Validator validator; public static class ConfigBuilder { public String date; public Project project; public JavaParser parser; public JavaParserFacade parserFacade; public List<String> classPaths; public Path promptPath; public String url; public String[] apiKeys; public Logger log; public String OS = System.getProperty("os.name").toLowerCase(); public boolean stopWhenSuccess = true; public boolean noExecution = false; public boolean enableMultithreading = true; public boolean enableRuleRepair = true; public boolean enableMerge = true; public boolean enableObfuscate = false; public String[] obfuscateGroupIds; public int maxThreads = Runtime.getRuntime().availableProcessors() * 5; public int classThreads = (int) Math.ceil((double) this.maxThreads / 10); public int methodThreads = (int) Math.ceil((double) this.maxThreads / this.classThreads); public int testNumber = 5; public int maxRounds = 5; public int maxPromptTokens = 2600; public int maxResponseTokens = 1024; public int minErrorTokens = 500; public int sleepTime = 0; public int dependencyDepth = 1; public Model model = Model.GPT_3_5_TURBO; public Double temperature = 0.5; public int topP = 1; public int frequencyPenalty = 0; public int presencePenalty = 0; public Path testOutput; public Path tmpOutput = Paths.get(System.getProperty("java.io.tmpdir"), "chatunitest-info"); public Path parseOutput; public Path compileOutputPath; public Path errorOutput; public Path classNameMapPath; public Path historyPath; public Path examplePath; public Path symbolFramePath; public String proxy = "null:-1"; public String hostname = "null"; public String port = "-1"; public OkHttpClient client = new OkHttpClient.Builder() .connectTimeout(5, TimeUnit.MINUTES) .writeTimeout(5, TimeUnit.MINUTES) .readTimeout(5, TimeUnit.MINUTES) .build(); public Validator validator; public ConfigBuilder(Project project) { this.date = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy_MM_dd_HH_mm_ss")).toString(); this.project = project;
package zju.cst.aces.api.config; @Getter @Setter public class Config { public String date; public Gson GSON; public Project project; public JavaParser parser; public JavaParserFacade parserFacade; public List<String> classPaths; public Path promptPath; public String url; public String[] apiKeys; public Logger log; public String OS; public boolean stopWhenSuccess; public boolean noExecution; public boolean enableMultithreading; public boolean enableRuleRepair; public boolean enableMerge; public boolean enableObfuscate; public String[] obfuscateGroupIds; public int maxThreads; public int classThreads; public int methodThreads; public int testNumber; public int maxRounds; public int maxPromptTokens; public int maxResponseTokens; public int minErrorTokens; public int sleepTime; public int dependencyDepth; public Model model; public Double temperature; public int topP; public int frequencyPenalty; public int presencePenalty; public Path testOutput; public Path tmpOutput; public Path compileOutputPath; public Path parseOutput; public Path errorOutput; public Path classNameMapPath; public Path historyPath; public Path examplePath; public Path symbolFramePath; public String proxy; public String hostname; public String port; public OkHttpClient client; public static AtomicInteger sharedInteger = new AtomicInteger(0); public static Map<String, Map<String, String>> classMapping; public Validator validator; public static class ConfigBuilder { public String date; public Project project; public JavaParser parser; public JavaParserFacade parserFacade; public List<String> classPaths; public Path promptPath; public String url; public String[] apiKeys; public Logger log; public String OS = System.getProperty("os.name").toLowerCase(); public boolean stopWhenSuccess = true; public boolean noExecution = false; public boolean enableMultithreading = true; public boolean enableRuleRepair = true; public boolean enableMerge = true; public boolean enableObfuscate = false; public String[] obfuscateGroupIds; public int maxThreads = Runtime.getRuntime().availableProcessors() * 5; public int classThreads = (int) Math.ceil((double) this.maxThreads / 10); public int methodThreads = (int) Math.ceil((double) this.maxThreads / this.classThreads); public int testNumber = 5; public int maxRounds = 5; public int maxPromptTokens = 2600; public int maxResponseTokens = 1024; public int minErrorTokens = 500; public int sleepTime = 0; public int dependencyDepth = 1; public Model model = Model.GPT_3_5_TURBO; public Double temperature = 0.5; public int topP = 1; public int frequencyPenalty = 0; public int presencePenalty = 0; public Path testOutput; public Path tmpOutput = Paths.get(System.getProperty("java.io.tmpdir"), "chatunitest-info"); public Path parseOutput; public Path compileOutputPath; public Path errorOutput; public Path classNameMapPath; public Path historyPath; public Path examplePath; public Path symbolFramePath; public String proxy = "null:-1"; public String hostname = "null"; public String port = "-1"; public OkHttpClient client = new OkHttpClient.Builder() .connectTimeout(5, TimeUnit.MINUTES) .writeTimeout(5, TimeUnit.MINUTES) .readTimeout(5, TimeUnit.MINUTES) .build(); public Validator validator; public ConfigBuilder(Project project) { this.date = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy_MM_dd_HH_mm_ss")).toString(); this.project = project;
this.log = new LoggerImpl();
2
2023-10-14 07:15:10+00:00
4k
Nyayurn/Yutori-QQ
src/main/java/io/github/nyayurn/yutori/qq/listener/guild/role/DispatcherGuildRoleListener.java
[ { "identifier": "Bot", "path": "src/main/java/io/github/nyayurn/yutori/qq/entity/event/Bot.java", "snippet": "@Data\npublic class Bot {\n /**\n * QQ 号\n */\n private String id;\n private ChannelApi channelApi;\n private GuildApi guildApi;\n private GuildMemberApi guildMemberApi;\n...
import io.github.nyayurn.yutori.ListenerContainer; import io.github.nyayurn.yutori.entity.EventEntity; import io.github.nyayurn.yutori.entity.PropertiesEntity; import io.github.nyayurn.yutori.event.GuildRoleEvents; import io.github.nyayurn.yutori.qq.entity.event.Bot; import io.github.nyayurn.yutori.qq.event.guild.GuildRoleEvent; import io.github.nyayurn.yutori.qq.listener.EventListenerContainer; import lombok.extern.slf4j.Slf4j;
3,298
/* Copyright (c) 2023 Yurn yutori-qq is licensed under Mulan PSL v2. You can use this software according to the terms and conditions of the Mulan PSL v2. You may obtain a copy of Mulan PSL v2 at: http://license.coscl.org.cn/MulanPSL2 THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. See the Mulan PSL v2 for more details. */ package io.github.nyayurn.yutori.qq.listener.guild.role; /** * @author Yurn */ @Slf4j public class DispatcherGuildRoleListener { private final PropertiesEntity properties;
/* Copyright (c) 2023 Yurn yutori-qq is licensed under Mulan PSL v2. You can use this software according to the terms and conditions of the Mulan PSL v2. You may obtain a copy of Mulan PSL v2 at: http://license.coscl.org.cn/MulanPSL2 THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. See the Mulan PSL v2 for more details. */ package io.github.nyayurn.yutori.qq.listener.guild.role; /** * @author Yurn */ @Slf4j public class DispatcherGuildRoleListener { private final PropertiesEntity properties;
private final EventListenerContainer listenerContainer;
2
2023-10-12 09:58:07+00:00
4k
villainwtf/weave
src/main/java/wtf/villain/weave/builder/WeaveInstanceBuilder.java
[ { "identifier": "Weave", "path": "src/main/java/wtf/villain/weave/Weave.java", "snippet": "public sealed interface Weave permits Weave.Impl {\n\n @NotNull\n static WeaveInstanceBuilder builder() {\n return new WeaveInstanceBuilder();\n }\n\n /**\n * Gets the underlying Retrofit cl...
import com.fasterxml.jackson.databind.ObjectMapper; import okhttp3.OkHttpClient; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import retrofit2.Retrofit; import retrofit2.converter.jackson.JacksonConverterFactory; import wtf.villain.weave.Weave; import wtf.villain.weave.client.TolgeeClient; import wtf.villain.weave.storage.Storage; import wtf.villain.weave.translation.process.PostProcessor; import wtf.villain.weave.util.Ensure; import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.CompletableFuture;
2,913
package wtf.villain.weave.builder; public final class WeaveInstanceBuilder { @Nullable private String apiKey; @Nullable private String endpoint; @NotNull private final List<Integer> projectIds = new ArrayList<>(); @NotNull private Duration connectTimeout = Duration.ofSeconds(30); @NotNull private Duration readTimeout = Duration.ofSeconds(30); @NotNull private Duration writeTimeout = Duration.ofSeconds(30); @NotNull
package wtf.villain.weave.builder; public final class WeaveInstanceBuilder { @Nullable private String apiKey; @Nullable private String endpoint; @NotNull private final List<Integer> projectIds = new ArrayList<>(); @NotNull private Duration connectTimeout = Duration.ofSeconds(30); @NotNull private Duration readTimeout = Duration.ofSeconds(30); @NotNull private Duration writeTimeout = Duration.ofSeconds(30); @NotNull
private final List<PostProcessor> processors = new ArrayList<>();
3
2023-10-09 13:46:52+00:00
4k
jmdevall/opencodeplan
src/main/java/jmdevall/opencodeplan/adapter/out/javaparser/relfinders/OverridesRelFinder.java
[ { "identifier": "Util", "path": "src/main/java/jmdevall/opencodeplan/adapter/out/javaparser/Util.java", "snippet": "public class Util {\n\n\tpublic static LineColPos toDomainPosition( com.github.javaparser.Position position) {\n\t\treturn LineColPos.builder()\n\t\t.line(position.line)\n\t\t.column(posit...
import java.util.Arrays; import java.util.List; import java.util.Optional; import com.github.javaparser.ast.Node; import com.github.javaparser.ast.body.CallableDeclaration.Signature; import com.github.javaparser.ast.body.MethodDeclaration; import com.github.javaparser.ast.expr.SimpleName; import com.github.javaparser.ast.visitor.VoidVisitorAdapter; import com.github.javaparser.resolution.SymbolResolver; import com.github.javaparser.resolution.UnsolvedSymbolException; import com.github.javaparser.resolution.declarations.ResolvedMethodDeclaration; import com.github.javaparser.resolution.types.ResolvedReferenceType; import com.github.javaparser.symbolsolver.javaparsermodel.JavaParserFacade; import jmdevall.opencodeplan.adapter.out.javaparser.Util; import jmdevall.opencodeplan.domain.dependencygraph.DependencyLabel; import jmdevall.opencodeplan.domain.dependencygraph.DependencyRelation; import lombok.extern.slf4j.Slf4j;
2,034
package jmdevall.opencodeplan.adapter.out.javaparser.relfinders; /** * Find field use relations (Uses and UsedBy) between a statement and the declaration of a field it uses. */ @Slf4j public class OverridesRelFinder extends VoidVisitorAdapter<List<DependencyRelation>>{ public OverridesRelFinder() { super(); } /* public SymbolResolver getSymbolResolver() { return findCompilationUnit().map(cu -> { if (cu.containsData(SYMBOL_RESOLVER_KEY)) { return cu.getData(SYMBOL_RESOLVER_KEY); } throw new IllegalStateException("Symbol resolution not configured: to configure consider setting a SymbolResolver in the ParserConfiguration"); }).orElseThrow(() -> new IllegalStateException("The node is not inserted in a CompilationUnit")); } */ private Optional<ResolvedMethodDeclaration> findMethod(ResolvedReferenceType type, String methodName,String descriptor){ List<ResolvedMethodDeclaration> methods=type.getAllMethodsVisibleToInheritors(); for(ResolvedMethodDeclaration method:methods) { try { System.out.println("qualified signature="+method.getQualifiedSignature()); System.out.println("signature="+method.getSignature()); System.out.println("methodName="+methodName); System.out.println("methodDescriptor="+descriptor); System.out.println("method.getName()"+method.getName()); System.out.println("method.toDescriptor()"+method.toDescriptor()); if(method.getName().equals(methodName) && method.toDescriptor().equals(descriptor)) { return Optional.of(method); } } catch (Exception e) { //TODO: en ciertos casos salta excepción no se por que return Optional.empty(); } } return Optional.empty(); } private Optional<ResolvedMethodDeclaration> findMethodByResolvedMethodDeclaration(ResolvedReferenceType type, ResolvedMethodDeclaration resolvedMethodImp){ List<ResolvedMethodDeclaration> methods=type.getAllMethodsVisibleToInheritors(); for(ResolvedMethodDeclaration method:methods) { if(method.getSignature().equals(resolvedMethodImp.getSignature())){ return Optional.of(method); } /*try { String signature2 = method.getSignature(); if(method.getName().equals(methodName) && signature2.equals(signature)) { return Optional.of(method); } } catch (Exception e) { //TODO: en ciertos casos salta excepción no se por que return Optional.empty(); }*/ } return Optional.empty(); } private Optional<Node> tryResolveMethodDeclaration(MethodDeclaration m){ try { ResolvedMethodDeclaration resolved=m.resolve(); log.debug("descriptor="+resolved.toDescriptor()); List<ResolvedReferenceType> ancestors=resolved.declaringType().getAllAncestors(); //resolved.declaringType().getA getAllAncestors(); for(ResolvedReferenceType ancestor:ancestors) { log.debug("searching method "+m.toDescriptor()+" in ancestestor "+ ancestor.getQualifiedName()); //Optional<ResolvedMethodDeclaration> metodoEnPadre=findMethod(ancestor,m.getName().toString(),m.toDescriptor()); Optional<ResolvedMethodDeclaration> metodoEnPadre=findMethodByResolvedMethodDeclaration(ancestor,resolved); if(metodoEnPadre.isPresent()) { return metodoEnPadre.get().toAst(); } } } catch (UnsolvedSymbolException e) { return Optional.empty(); } return Optional.empty(); } @Override public void visit(MethodDeclaration n, List<DependencyRelation> rels) { super.visit(n, rels); Optional<Node> methodDeclaration=tryResolveMethodDeclaration(n); if(methodDeclaration.isPresent()) { DependencyRelation childToParent=DependencyRelation.builder() .label(DependencyLabel.OVERRIDES)
package jmdevall.opencodeplan.adapter.out.javaparser.relfinders; /** * Find field use relations (Uses and UsedBy) between a statement and the declaration of a field it uses. */ @Slf4j public class OverridesRelFinder extends VoidVisitorAdapter<List<DependencyRelation>>{ public OverridesRelFinder() { super(); } /* public SymbolResolver getSymbolResolver() { return findCompilationUnit().map(cu -> { if (cu.containsData(SYMBOL_RESOLVER_KEY)) { return cu.getData(SYMBOL_RESOLVER_KEY); } throw new IllegalStateException("Symbol resolution not configured: to configure consider setting a SymbolResolver in the ParserConfiguration"); }).orElseThrow(() -> new IllegalStateException("The node is not inserted in a CompilationUnit")); } */ private Optional<ResolvedMethodDeclaration> findMethod(ResolvedReferenceType type, String methodName,String descriptor){ List<ResolvedMethodDeclaration> methods=type.getAllMethodsVisibleToInheritors(); for(ResolvedMethodDeclaration method:methods) { try { System.out.println("qualified signature="+method.getQualifiedSignature()); System.out.println("signature="+method.getSignature()); System.out.println("methodName="+methodName); System.out.println("methodDescriptor="+descriptor); System.out.println("method.getName()"+method.getName()); System.out.println("method.toDescriptor()"+method.toDescriptor()); if(method.getName().equals(methodName) && method.toDescriptor().equals(descriptor)) { return Optional.of(method); } } catch (Exception e) { //TODO: en ciertos casos salta excepción no se por que return Optional.empty(); } } return Optional.empty(); } private Optional<ResolvedMethodDeclaration> findMethodByResolvedMethodDeclaration(ResolvedReferenceType type, ResolvedMethodDeclaration resolvedMethodImp){ List<ResolvedMethodDeclaration> methods=type.getAllMethodsVisibleToInheritors(); for(ResolvedMethodDeclaration method:methods) { if(method.getSignature().equals(resolvedMethodImp.getSignature())){ return Optional.of(method); } /*try { String signature2 = method.getSignature(); if(method.getName().equals(methodName) && signature2.equals(signature)) { return Optional.of(method); } } catch (Exception e) { //TODO: en ciertos casos salta excepción no se por que return Optional.empty(); }*/ } return Optional.empty(); } private Optional<Node> tryResolveMethodDeclaration(MethodDeclaration m){ try { ResolvedMethodDeclaration resolved=m.resolve(); log.debug("descriptor="+resolved.toDescriptor()); List<ResolvedReferenceType> ancestors=resolved.declaringType().getAllAncestors(); //resolved.declaringType().getA getAllAncestors(); for(ResolvedReferenceType ancestor:ancestors) { log.debug("searching method "+m.toDescriptor()+" in ancestestor "+ ancestor.getQualifiedName()); //Optional<ResolvedMethodDeclaration> metodoEnPadre=findMethod(ancestor,m.getName().toString(),m.toDescriptor()); Optional<ResolvedMethodDeclaration> metodoEnPadre=findMethodByResolvedMethodDeclaration(ancestor,resolved); if(metodoEnPadre.isPresent()) { return metodoEnPadre.get().toAst(); } } } catch (UnsolvedSymbolException e) { return Optional.empty(); } return Optional.empty(); } @Override public void visit(MethodDeclaration n, List<DependencyRelation> rels) { super.visit(n, rels); Optional<Node> methodDeclaration=tryResolveMethodDeclaration(n); if(methodDeclaration.isPresent()) { DependencyRelation childToParent=DependencyRelation.builder() .label(DependencyLabel.OVERRIDES)
.origin(Util.toNodeId(n))
0
2023-10-14 18:27:18+00:00
4k
eahau/douyin-openapi
generator/src/main/java/com/github/eahau/openapi/douyin/generator/Main.java
[ { "identifier": "DouYinOpenDocApi", "path": "generator/src/main/java/com/github/eahau/openapi/douyin/generator/api/DouYinOpenDocApi.java", "snippet": "public interface DouYinOpenDocApi {\n\n @RequestLine(\"GET {path}?__loader=\" + Misc.DOC_LANGUAGE + \"/$\")\n DocResponse docs(@Param(\"path\") Str...
import com.github.eahau.openapi.douyin.generator.api.DouYinOpenDocApi; import com.github.eahau.openapi.douyin.generator.api.DouYinOpenDocApi.Children; import com.github.eahau.openapi.douyin.generator.api.DouYinOpenDocApi.Data; import com.github.eahau.openapi.douyin.generator.api.DouYinOpenDocApi.DocsResponse; import com.google.common.base.Stopwatch; import com.google.common.collect.Lists; import feign.Feign; import feign.Logger.Level; import feign.gson.GsonDecoder; import feign.slf4j.Slf4jLogger; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections4.CollectionUtils; import java.util.Collection; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference;
1,847
/* * Copyright 2023 eahau@foxmail.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.eahau.openapi.douyin.generator; @Slf4j public class Main { static final DouYinOpenDocApi douYinOpenDocApi = Feign.builder() .logLevel(Level.BASIC) .logger(new Slf4jLogger(DouYinOpenDocApi.class)) .decoder(new GsonDecoder(Misc.GSON)) .target(DouYinOpenDocApi.class, Misc.DOC_BASE_URL); static final ExecutorService executorService = new ThreadPoolExecutor( 30, Integer.MAX_VALUE, 60, TimeUnit.SECONDS, new SynchronousQueue<>(), new CallerRunsPolicy() ); @SneakyThrows public static void main(String[] args) { log.info("Hold on, generator started."); final Stopwatch stopwatch = Stopwatch.createStarted(); final DocsResponse docsResponse = douYinOpenDocApi.allDocs(); final List<Data> data = docsResponse.getData(); for (final Data datum : data) { final AtomicReference<GeneratorContents> contents = new AtomicReference<>(); final List<CompletableFuture<Void>> futures = Lists.newArrayList(); datum.getChildren() .stream() .filter(it -> it.getTitle().contains("开发"))
/* * Copyright 2023 eahau@foxmail.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.eahau.openapi.douyin.generator; @Slf4j public class Main { static final DouYinOpenDocApi douYinOpenDocApi = Feign.builder() .logLevel(Level.BASIC) .logger(new Slf4jLogger(DouYinOpenDocApi.class)) .decoder(new GsonDecoder(Misc.GSON)) .target(DouYinOpenDocApi.class, Misc.DOC_BASE_URL); static final ExecutorService executorService = new ThreadPoolExecutor( 30, Integer.MAX_VALUE, 60, TimeUnit.SECONDS, new SynchronousQueue<>(), new CallerRunsPolicy() ); @SneakyThrows public static void main(String[] args) { log.info("Hold on, generator started."); final Stopwatch stopwatch = Stopwatch.createStarted(); final DocsResponse docsResponse = douYinOpenDocApi.allDocs(); final List<Data> data = docsResponse.getData(); for (final Data datum : data) { final AtomicReference<GeneratorContents> contents = new AtomicReference<>(); final List<CompletableFuture<Void>> futures = Lists.newArrayList(); datum.getChildren() .stream() .filter(it -> it.getTitle().contains("开发"))
.map(Children::getChildren)
1
2023-10-07 09:09:15+00:00
4k
Aywen1/wispy
src/fr/nicolas/wispy/Frames/MainFrame.java
[ { "identifier": "GamePanel", "path": "src/fr/nicolas/wispy/Panels/GamePanel.java", "snippet": "public class GamePanel extends WPanel implements KeyListener, MouseListener, MouseMotionListener {\n\n\tpublic static final int BLOCK_SIZE = 25, INIT_PLAYER_X = 605, INIT_PLAYER_Y = 315;\n\tprivate int newBloc...
import java.awt.Dimension; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import javax.swing.JFrame; import fr.nicolas.wispy.Panels.GamePanel; import fr.nicolas.wispy.Panels.MenuPanel; import fr.nicolas.wispy.Panels.Components.Menu.WPanel;
3,378
package fr.nicolas.wispy.Frames; public class MainFrame extends JFrame { private WPanel panel; public static final int INIT_WIDTH = 1250, INIT_HEIGHT = 720; public MainFrame() { this.setTitle("Wispy"); this.setSize(INIT_WIDTH, INIT_HEIGHT); this.setMinimumSize(new Dimension(INIT_WIDTH, INIT_HEIGHT)); this.setLocationRelativeTo(null); this.setResizable(true); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); panel = new MenuPanel(this.getBounds(), this); this.addComponentListener(new ComponentListener() { public void componentResized(ComponentEvent e) { panel.setFrameBounds(getBounds()); } public void componentHidden(ComponentEvent e) { } public void componentMoved(ComponentEvent e) { } public void componentShown(ComponentEvent e) { } }); this.setContentPane(panel); this.setVisible(true); } public void newGame() {
package fr.nicolas.wispy.Frames; public class MainFrame extends JFrame { private WPanel panel; public static final int INIT_WIDTH = 1250, INIT_HEIGHT = 720; public MainFrame() { this.setTitle("Wispy"); this.setSize(INIT_WIDTH, INIT_HEIGHT); this.setMinimumSize(new Dimension(INIT_WIDTH, INIT_HEIGHT)); this.setLocationRelativeTo(null); this.setResizable(true); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); panel = new MenuPanel(this.getBounds(), this); this.addComponentListener(new ComponentListener() { public void componentResized(ComponentEvent e) { panel.setFrameBounds(getBounds()); } public void componentHidden(ComponentEvent e) { } public void componentMoved(ComponentEvent e) { } public void componentShown(ComponentEvent e) { } }); this.setContentPane(panel); this.setVisible(true); } public void newGame() {
panel = new GamePanel(this.getBounds(), true);
0
2023-10-13 13:10:56+00:00
4k
PfauMC/CyanWorld
cyanworld-cyan1dex/src/main/java/ru/cyanworld/cyan1dex/commands/CmdSethome.java
[ { "identifier": "Cyan1dex", "path": "cyanworld-cyan1dex/src/main/java/ru/cyanworld/cyan1dex/Cyan1dex.java", "snippet": "public class Cyan1dex extends JavaPlugin {\n public static Server server;\n public static Cyan1dex instance;\n public static File dataFolder;\n public static Random random;...
import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import ru.cyanworld.cyan1dex.Cyan1dex; import ru.cyanworld.cyan1dex.messages.Msg; import java.util.ArrayList;
1,957
package ru.cyanworld.cyan1dex.commands; public class CmdSethome extends Command { public CmdSethome() { super("sethome", "Телепортация на точку дома", "/sethome", new ArrayList()); Cyan1dex.server.getCommandMap().register(this.getName(), this); } public boolean execute(CommandSender sender, String commandLabel, String[] args) { if (sender instanceof Player) { Player player = (Player) sender;
package ru.cyanworld.cyan1dex.commands; public class CmdSethome extends Command { public CmdSethome() { super("sethome", "Телепортация на точку дома", "/sethome", new ArrayList()); Cyan1dex.server.getCommandMap().register(this.getName(), this); } public boolean execute(CommandSender sender, String commandLabel, String[] args) { if (sender instanceof Player) { Player player = (Player) sender;
player.sendMessage(Msg.sethome_needsleep);
1
2023-10-08 17:50:55+00:00
4k
vaaako/Vakraft
src/main/java/com/magenta/main/Engine.java
[ { "identifier": "IGameLogic", "path": "src/main/java/com/magenta/engine/IGameLogic.java", "snippet": "public interface IGameLogic {\n\tvoid init(Window window, MouseInput mouseInput) throws Exception;\n\tvoid input(Window window, KeyboardInput keyboardInput, MouseInput mouseInput);\n\tvoid update(double...
import com.magenta.engine.IGameLogic; import com.magenta.engine.KeyboardInput; import com.magenta.engine.Timer; import com.magenta.engine.Window; import com.magenta.engine.MouseInput;
2,663
package com.magenta.main; public class Engine implements Runnable { private final Window window; private final IGameLogic gameLogic; private final Timer timer; private final MouseInput mouseInput;
package com.magenta.main; public class Engine implements Runnable { private final Window window; private final IGameLogic gameLogic; private final Timer timer; private final MouseInput mouseInput;
private final KeyboardInput keyboardInput;
1
2023-10-08 04:08:22+00:00
4k
Aywen1/improvident
src/fr/nicolas/main/frames/EditFrame.java
[ { "identifier": "NBackground", "path": "src/fr/nicolas/main/components/NBackground.java", "snippet": "public class NBackground extends JPanel {\n\n\tprivate BufferedImage bg, bg2;\n\tprivate int type;\n\n\tpublic NBackground(int type) {\n\t\tthis.type = type;\n\t\tsetLayout(null);\n\n\t\tif (type == 0 |...
import java.awt.Point; import java.awt.Rectangle; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import javax.swing.ImageIcon; import javax.swing.JFrame; import fr.nicolas.main.components.NBackground; import fr.nicolas.main.components.NButtonImg; import fr.nicolas.main.components.NLabel; import fr.nicolas.main.panels.categories.NDefault;
3,509
package fr.nicolas.main.frames; public class EditFrame extends JFrame implements MouseListener, MouseMotionListener { private NBackground bg; private NButtonImg buttonAFaire, buttonARevoir, buttonArchives, buttonSupprimer; private NLabel labelText; private String path, category, url, name = "";
package fr.nicolas.main.frames; public class EditFrame extends JFrame implements MouseListener, MouseMotionListener { private NBackground bg; private NButtonImg buttonAFaire, buttonARevoir, buttonArchives, buttonSupprimer; private NLabel labelText; private String path, category, url, name = "";
private NDefault panel;
3
2023-10-13 10:30:31+00:00
4k
Mon-L/virtual-waiting-room
virtual-waiting-room-infrastructure/src/main/java/cn/zcn/virtual/waiting/room/infrastructure/repository/gateway/AccessTokenGatewayImpl.java
[ { "identifier": "AccessTokenGateway", "path": "virtual-waiting-room-domain/src/main/java/cn/zcn/virtual/waiting/room/domain/gateway/repository/AccessTokenGateway.java", "snippet": "public interface AccessTokenGateway {\n AccessToken add(AccessToken token);\n\n AccessToken getByQueueIdAndRequestId(...
import cn.zcn.virtual.waiting.room.domain.gateway.repository.AccessTokenGateway; import cn.zcn.virtual.waiting.room.domain.model.entity.AccessToken; import cn.zcn.virtual.waiting.room.domain.model.entity.AccessTokenStatus; import cn.zcn.virtual.waiting.room.infrastructure.repository.AccessTokenMapper; import cn.zcn.virtual.waiting.room.infrastructure.repository.converter.AccessTokenConverter; import cn.zcn.virtual.waiting.room.infrastructure.repository.po.AccessTokenPO; import javax.annotation.Resource; import org.springframework.stereotype.Component;
2,033
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package cn.zcn.virtual.waiting.room.infrastructure.repository.gateway; /** * @author zicung */ @Component public class AccessTokenGatewayImpl implements AccessTokenGateway { @Resource private AccessTokenMapper accessTokenMapper; @Override
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package cn.zcn.virtual.waiting.room.infrastructure.repository.gateway; /** * @author zicung */ @Component public class AccessTokenGatewayImpl implements AccessTokenGateway { @Resource private AccessTokenMapper accessTokenMapper; @Override
public AccessToken add(AccessToken token) {
1
2023-10-07 10:31:42+00:00
4k
ferderplays/ElypsaClient
src/main/java/net/elypsaclient/client/Main.java
[ { "identifier": "ClientRefers", "path": "src/main/java/net/ferderplays/elypsa/refers/ClientRefers.java", "snippet": "public class ClientRefers {\n public static final String MODID = \"elypsaclient\",\n NAME =\"Elypsa Client\",\n VERSION = \"0.0.1\";\n}" }, { "identifier"...
import net.ferderplays.elypsa.refers.ClientRefers; import net.elypsaclient.modules.Module; import net.elypsaclient.manager.ModuleManager; import net.elypsaclient.ui.HUD; import net.elypsaclient.ui.MainMenu; import net.ferderplays.elypsa.utils.ClientDirectoryUtil; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiMainMenu; import net.minecraftforge.client.event.GuiScreenEvent; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod.EventHandler; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.InputEvent; import org.apache.logging.log4j.Logger; import org.lwjgl.input.Keyboard;
2,546
package net.elypsaclient.client; @Mod(modid = ClientRefers.MODID, name = ClientRefers.NAME, version = ClientRefers.VERSION) public class Main { @Mod.Instance public Main instance;
package net.elypsaclient.client; @Mod(modid = ClientRefers.MODID, name = ClientRefers.NAME, version = ClientRefers.VERSION) public class Main { @Mod.Instance public Main instance;
public static ModuleManager moduleManager;
2
2023-10-10 18:11:26+00:00
4k
Kelwinkxps13/Projeto_POO_Swing
UrnaEletronica/src/br/edu/view/Login.java
[ { "identifier": "User", "path": "UrnaEletronica/src/br/edu/bancodedados/User.java", "snippet": "public class User {\r\n \r\n protected String nome;\r\n protected String senha;\r\n protected String email;\r\n\r\n public String getNome() {\r\n return nome;\r\n }\r\n\r\n public ...
import br.edu.bancodedados.User; import br.edu.bancodedados.UsuarioDAO; import javax.swing.JOptionPane; import java.sql.ResultSet; import java.sql.SQLException;
3,078
jButton1ActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(66, 66, 66) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(campoNome, javax.swing.GroupLayout.PREFERRED_SIZE, 356, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2) .addComponent(jLabel4) .addComponent(campoSenha, javax.swing.GroupLayout.PREFERRED_SIZE, 356, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(83, 83, 83) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(botaoEntrar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(botaoForgotPassword, javax.swing.GroupLayout.DEFAULT_SIZE, 320, Short.MAX_VALUE))) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(101, 101, 101) .addComponent(botaoCadastrar, javax.swing.GroupLayout.PREFERRED_SIZE, 282, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup() .addGap(196, 196, 196) .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton1)) .addComponent(jLabel5, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 489, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 289, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(18, 18, 18) .addComponent(jLabel1)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(1, 1, 1) .addComponent(jButton1))) .addGap(1, 1, 1) .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(campoNome, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel4) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(campoSenha, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(botaoEntrar, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(botaoCadastrar, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(botaoForgotPassword) .addContainerGap(14, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 490, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents String emailUser = null; private void campoSenhaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_campoSenhaActionPerformed // TODO add your handling code here: }//GEN-LAST:event_campoSenhaActionPerformed private void botaoCadastrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoCadastrarActionPerformed Cadastro cadastro = new Cadastro(); cadastro.setVisible(true); dispose(); }//GEN-LAST:event_botaoCadastrarActionPerformed private void botaoEntrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoEntrarActionPerformed /* 1- Coleta os dados de email e senha, por exemplo: email: example@gmail.com pass: 12345678 2- verificar no banco de dados se a combinaçao de email e senha existem na tabela da base de dados 3- se verdadeiro, deixe o usuario entrar na urna se falso, mostre: email ou senha incorretos */ String emailx, senhax; emailx = campoNome.getText(); senhax = campoSenha.getText(); if(emailx.equals("") || senhax.equals("")){ JOptionPane.showMessageDialog(null, "Preencha todos os campos!!"); }else{ try { String email = campoNome.getText(); String senha = campoSenha.getText(); Urna user = new Urna();
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/GUIForms/JFrame.java to edit this template */ package br.edu.view; /** * * @author Alunos */ public class Login extends javax.swing.JFrame { /** * Creates new form Login */ public Login() { initComponents(); setLocationRelativeTo(null); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); campoNome = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); campoSenha = new javax.swing.JPasswordField(); jLabel4 = new javax.swing.JLabel(); botaoCadastrar = new javax.swing.JButton(); botaoEntrar = new javax.swing.JButton(); botaoForgotPassword = new javax.swing.JButton(); jLabel5 = new javax.swing.JLabel(); jButton1 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Login"); setResizable(false); jPanel1.setBackground(new java.awt.Color(255, 255, 255)); jPanel1.setMaximumSize(new java.awt.Dimension(513, 645)); jPanel1.setMinimumSize(new java.awt.Dimension(513, 645)); jLabel1.setBackground(new java.awt.Color(0, 0, 0)); jLabel1.setFont(new java.awt.Font("Gill Sans MT", 1, 36)); // NOI18N jLabel1.setForeground(new java.awt.Color(0, 0, 0)); jLabel1.setText("Login"); campoNome.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { campoNomeActionPerformed(evt); } }); jLabel2.setFont(new java.awt.Font("Gadugi", 1, 18)); // NOI18N jLabel2.setForeground(new java.awt.Color(153, 153, 153)); jLabel2.setText("Email"); campoSenha.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { campoSenhaActionPerformed(evt); } }); jLabel4.setFont(new java.awt.Font("Gadugi", 1, 18)); // NOI18N jLabel4.setForeground(new java.awt.Color(153, 153, 153)); jLabel4.setText("Senha"); botaoCadastrar.setBackground(new java.awt.Color(0, 0, 0)); botaoCadastrar.setFont(new java.awt.Font("Leelawadee UI", 1, 18)); // NOI18N botaoCadastrar.setForeground(new java.awt.Color(255, 255, 255)); botaoCadastrar.setText("Cadastre-se "); botaoCadastrar.setBorder(new javax.swing.border.MatteBorder(null)); botaoCadastrar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { botaoCadastrarActionPerformed(evt); } }); botaoEntrar.setBackground(new java.awt.Color(0, 0, 0)); botaoEntrar.setFont(new java.awt.Font("Leelawadee UI", 1, 24)); // NOI18N botaoEntrar.setForeground(new java.awt.Color(255, 255, 255)); botaoEntrar.setText("Entrar"); botaoEntrar.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1)); botaoEntrar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { botaoEntrarActionPerformed(evt); } }); botaoForgotPassword.setBackground(new java.awt.Color(255, 255, 255)); botaoForgotPassword.setForeground(new java.awt.Color(102, 102, 102)); botaoForgotPassword.setText("Esqueceu sua Senha? Clique aqui"); botaoForgotPassword.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { botaoForgotPasswordActionPerformed(evt); } }); jLabel5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/edu/resourses/topo login.png"))); // NOI18N jLabel5.setText("jLabel5"); jButton1.setBackground(new java.awt.Color(255, 255, 255)); jButton1.setForeground(new java.awt.Color(0, 0, 0)); jButton1.setText("Ajuda?"); jButton1.setBorder(null); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(66, 66, 66) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(campoNome, javax.swing.GroupLayout.PREFERRED_SIZE, 356, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2) .addComponent(jLabel4) .addComponent(campoSenha, javax.swing.GroupLayout.PREFERRED_SIZE, 356, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(83, 83, 83) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(botaoEntrar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(botaoForgotPassword, javax.swing.GroupLayout.DEFAULT_SIZE, 320, Short.MAX_VALUE))) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(101, 101, 101) .addComponent(botaoCadastrar, javax.swing.GroupLayout.PREFERRED_SIZE, 282, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup() .addGap(196, 196, 196) .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton1)) .addComponent(jLabel5, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 489, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 289, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(18, 18, 18) .addComponent(jLabel1)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(1, 1, 1) .addComponent(jButton1))) .addGap(1, 1, 1) .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(campoNome, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel4) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(campoSenha, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(botaoEntrar, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(botaoCadastrar, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(botaoForgotPassword) .addContainerGap(14, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 490, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents String emailUser = null; private void campoSenhaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_campoSenhaActionPerformed // TODO add your handling code here: }//GEN-LAST:event_campoSenhaActionPerformed private void botaoCadastrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoCadastrarActionPerformed Cadastro cadastro = new Cadastro(); cadastro.setVisible(true); dispose(); }//GEN-LAST:event_botaoCadastrarActionPerformed private void botaoEntrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoEntrarActionPerformed /* 1- Coleta os dados de email e senha, por exemplo: email: example@gmail.com pass: 12345678 2- verificar no banco de dados se a combinaçao de email e senha existem na tabela da base de dados 3- se verdadeiro, deixe o usuario entrar na urna se falso, mostre: email ou senha incorretos */ String emailx, senhax; emailx = campoNome.getText(); senhax = campoSenha.getText(); if(emailx.equals("") || senhax.equals("")){ JOptionPane.showMessageDialog(null, "Preencha todos os campos!!"); }else{ try { String email = campoNome.getText(); String senha = campoSenha.getText(); Urna user = new Urna();
User objusuariodto = new User();
0
2023-10-10 18:25:35+00:00
4k
zlhy7/ldDecrypt
src/main/java/top/zlhy7/listener/FileListener.java
[ { "identifier": "MonitoredFileService", "path": "src/main/java/top/zlhy7/service/MonitoredFileService.java", "snippet": "@Slf4j\n@Service\npublic class MonitoredFileService {\n /**\n * 被监控的文件目录\n * 放置到此目录的所有文件会解密并放置到同级的 \"${monitoredFilePath}_解密\"目录中\n */\n @Value(\"${monitoredPath}\")...
import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.monitor.FileAlterationListenerAdaptor; import org.apache.commons.io.monitor.FileAlterationObserver; import org.springframework.stereotype.Component; import top.zlhy7.service.MonitoredFileService; import top.zlhy7.util.SpringUtils; import java.io.File;
2,387
package top.zlhy7.listener; /** * @author 任勇 * @date 2020/8/26 9:43 * @description 文件变化监听器 */ @Component @Slf4j public class FileListener extends FileAlterationListenerAdaptor { /** * 监控文件 */
package top.zlhy7.listener; /** * @author 任勇 * @date 2020/8/26 9:43 * @description 文件变化监听器 */ @Component @Slf4j public class FileListener extends FileAlterationListenerAdaptor { /** * 监控文件 */
private MonitoredFileService monitoredFileService = SpringUtils.getBean(MonitoredFileService.class);
1
2023-10-12 10:23:05+00:00
4k
openGemini/opengemini-client-java
opengemini-client-jdk/src/main/java/io/opengemini/client/jdk/OpenGeminiJdkClient.java
[ { "identifier": "Address", "path": "opengemini-client-api/src/main/java/io/opengemini/client/api/Address.java", "snippet": "@Getter\n@Setter\n@NoArgsConstructor\n@AllArgsConstructor\npublic class Address {\n /**\n * Host service ip or domain.\n */\n private String host;\n /**\n * Po...
import com.fasterxml.jackson.core.JsonProcessingException; import io.opengemini.client.api.Address; import io.opengemini.client.api.OpenGeminiException; import io.opengemini.client.api.Query; import io.opengemini.client.api.QueryResult; import io.opengemini.client.api.SslContextUtil; import io.opengemini.client.api.TlsConfig; import io.opengemini.client.jdk.common.OpenGeminiCommon; import java.net.URI; import java.net.URISyntaxException; import java.net.URLEncoder; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicInteger;
1,727
package io.opengemini.client.jdk; public class OpenGeminiJdkClient { private final Configuration conf; private final List<String> serverUrls = new ArrayList<>(); private final HttpClient client; private final AtomicInteger prevIndex = new AtomicInteger(0); public OpenGeminiJdkClient(Configuration conf) { this.conf = conf; HttpClient.Builder builder = HttpClient.newBuilder() .version(HttpClient.Version.HTTP_1_1); String httpPrefix; if (conf.isTlsEnabled()) { TlsConfig tlsConfig = conf.getTlsConfig(); builder = builder.sslContext(SslContextUtil.buildSSLContextFromJks( tlsConfig.getKeyStorePath(), tlsConfig.getKeyStorePassword(), tlsConfig.getTrustStorePath(), tlsConfig.getTrustStorePassword(), tlsConfig.isTlsVerificationDisabled())); httpPrefix = "https://"; } else { httpPrefix = "http://"; } for (Address address : conf.getAddresses()) { this.serverUrls.add(httpPrefix + address.getHost() + ":" + address.getPort()); } this.client = builder.build(); } public String encodeUtf8(String str) { return URLEncoder.encode(str, StandardCharsets.UTF_8); } private URI buildUri(String url, String command) throws URISyntaxException { // avoid multi-thread conflict, realize simple round-robin int idx = prevIndex.addAndGet(1); idx = idx % this.conf.getAddresses().size(); return buildUri(idx, url, command); } private URI buildUri(int index, String url, String command) throws URISyntaxException { StringBuilder sb = new StringBuilder(this.serverUrls.get(index)) .append(url) .append("?q=") .append(encodeUtf8(command)); return new URI(sb.toString()); }
package io.opengemini.client.jdk; public class OpenGeminiJdkClient { private final Configuration conf; private final List<String> serverUrls = new ArrayList<>(); private final HttpClient client; private final AtomicInteger prevIndex = new AtomicInteger(0); public OpenGeminiJdkClient(Configuration conf) { this.conf = conf; HttpClient.Builder builder = HttpClient.newBuilder() .version(HttpClient.Version.HTTP_1_1); String httpPrefix; if (conf.isTlsEnabled()) { TlsConfig tlsConfig = conf.getTlsConfig(); builder = builder.sslContext(SslContextUtil.buildSSLContextFromJks( tlsConfig.getKeyStorePath(), tlsConfig.getKeyStorePassword(), tlsConfig.getTrustStorePath(), tlsConfig.getTrustStorePassword(), tlsConfig.isTlsVerificationDisabled())); httpPrefix = "https://"; } else { httpPrefix = "http://"; } for (Address address : conf.getAddresses()) { this.serverUrls.add(httpPrefix + address.getHost() + ":" + address.getPort()); } this.client = builder.build(); } public String encodeUtf8(String str) { return URLEncoder.encode(str, StandardCharsets.UTF_8); } private URI buildUri(String url, String command) throws URISyntaxException { // avoid multi-thread conflict, realize simple round-robin int idx = prevIndex.addAndGet(1); idx = idx % this.conf.getAddresses().size(); return buildUri(idx, url, command); } private URI buildUri(int index, String url, String command) throws URISyntaxException { StringBuilder sb = new StringBuilder(this.serverUrls.get(index)) .append(url) .append("?q=") .append(encodeUtf8(command)); return new URI(sb.toString()); }
public CompletableFuture<QueryResult> query(Query query) throws URISyntaxException {
2
2023-10-12 09:08:55+00:00
4k
lilmayu/java-discord-oauth2-api
src/test/java/dev/mayuna/discord/oauth/DiscordOAuthTest.java
[ { "identifier": "DiscordAccessToken", "path": "src/main/java/dev/mayuna/discord/oauth/entities/DiscordAccessToken.java", "snippet": "@Getter\npublic class DiscordAccessToken extends DiscordApiResponse {\n\n /**\n * Gets the time when the access token was fetched, e.g., when the {@link DiscordAcce...
import dev.mayuna.discord.oauth.entities.DiscordAccessToken; import dev.mayuna.discord.oauth.server.DiscordOAuthServerMock; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.Random; import java.util.UUID; import static dev.mayuna.discord.Utils.AssertStringArraysEquals;
2,891
package dev.mayuna.discord.oauth; public class DiscordOAuthTest { private static final String clientId = new Random().nextLong() + ""; private static final String clientSecret = UUID.randomUUID().toString().replace("-", ""); private static final String redirectUrl = "https://localhost:8080"; private static final String code = UUID.randomUUID().toString().replace("-", ""); private static final String state = UUID.randomUUID().toString(); private static final String[] scopes = new String[]{"identify", "guilds"}; private static DiscordOAuthServerMock serverMock; private static DiscordOAuth discordOAuth; @BeforeAll public static void prepare() { serverMock = new DiscordOAuthServerMock(clientId, clientSecret, code, redirectUrl, String.join(" ", Arrays.asList(scopes))); serverMock.start(); DiscordApplication application = new DiscordApplication.Builder() .withApiUrl(serverMock.getUrl()) .withClientId(clientId) .withClientSecret(clientSecret) .withRedirectUrl(redirectUrl) .withScopes(scopes) .build(); discordOAuth = new DiscordOAuth(application); } @AfterAll public static void stop() { serverMock.stop(); } @Test public void testNullInConstructor() { Assertions.assertThrows(NullPointerException.class, () -> new DiscordOAuth(null)); } @Test public void testFetchingWithNulls() { Assertions.assertThrows(NullPointerException.class, () -> discordOAuth.fetchAccessToken(null).sendAsync().join()); Assertions.assertThrows(NullPointerException.class, () -> discordOAuth.refreshAccessToken(null).sendAsync().join()); Assertions.assertThrows(NullPointerException.class, () -> discordOAuth.revokeTokens(null).sendAsync().join()); } @Test public void fetchTokens() {
package dev.mayuna.discord.oauth; public class DiscordOAuthTest { private static final String clientId = new Random().nextLong() + ""; private static final String clientSecret = UUID.randomUUID().toString().replace("-", ""); private static final String redirectUrl = "https://localhost:8080"; private static final String code = UUID.randomUUID().toString().replace("-", ""); private static final String state = UUID.randomUUID().toString(); private static final String[] scopes = new String[]{"identify", "guilds"}; private static DiscordOAuthServerMock serverMock; private static DiscordOAuth discordOAuth; @BeforeAll public static void prepare() { serverMock = new DiscordOAuthServerMock(clientId, clientSecret, code, redirectUrl, String.join(" ", Arrays.asList(scopes))); serverMock.start(); DiscordApplication application = new DiscordApplication.Builder() .withApiUrl(serverMock.getUrl()) .withClientId(clientId) .withClientSecret(clientSecret) .withRedirectUrl(redirectUrl) .withScopes(scopes) .build(); discordOAuth = new DiscordOAuth(application); } @AfterAll public static void stop() { serverMock.stop(); } @Test public void testNullInConstructor() { Assertions.assertThrows(NullPointerException.class, () -> new DiscordOAuth(null)); } @Test public void testFetchingWithNulls() { Assertions.assertThrows(NullPointerException.class, () -> discordOAuth.fetchAccessToken(null).sendAsync().join()); Assertions.assertThrows(NullPointerException.class, () -> discordOAuth.refreshAccessToken(null).sendAsync().join()); Assertions.assertThrows(NullPointerException.class, () -> discordOAuth.revokeTokens(null).sendAsync().join()); } @Test public void fetchTokens() {
DiscordAccessToken token = discordOAuth.fetchAccessToken(code).sendAsync().join();
0
2023-10-10 15:10:53+00:00
4k
ljjy1/discord-mj-java
src/main/java/com/github/dmj/bot/DiscordBot.java
[ { "identifier": "DiscordAccountProperties", "path": "src/main/java/com/github/dmj/autoconfigure/DiscordAccountProperties.java", "snippet": "@Data\npublic class DiscordAccountProperties {\n\n /**\n * 用户key 自己定义不重复即可(用于切换用户调用接口)\n */\n private String userKey;\n /**\n * 用户token\n *...
import cn.hutool.core.collection.CollUtil; import cn.hutool.json.JSONUtil; import com.github.dmj.autoconfigure.DiscordAccountProperties; import com.github.dmj.autoconfigure.DiscordProxyProperties; import com.github.dmj.enums.MjMsgStatus; import com.github.dmj.model.MjMsg; import com.github.dmj.queue.MessageQueue; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.neovisionaries.ws.client.WebSocketFactory; import lombok.extern.slf4j.Slf4j; import net.dv8tion.jda.api.JDA; import net.dv8tion.jda.api.JDABuilder; import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.Message; import net.dv8tion.jda.api.entities.MessageChannel; import net.dv8tion.jda.api.events.message.MessageReceivedEvent; import net.dv8tion.jda.api.events.message.MessageUpdateEvent; import net.dv8tion.jda.api.hooks.ListenerAdapter; import net.dv8tion.jda.api.interactions.components.ActionRow; import net.dv8tion.jda.api.interactions.components.buttons.Button; import okhttp3.OkHttpClient; import org.jetbrains.annotations.NotNull; import org.springframework.util.DigestUtils; import java.net.InetSocketAddress; import java.net.Proxy; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern;
1,819
package com.github.dmj.bot; /** * @author ljjy1 * @classname DiscordBot * @description discord机器人 * @date 2023/10/11 13:38 */ @Slf4j public class DiscordBot extends ListenerAdapter { private final DiscordAccountProperties discordAccountProperties; private final Cache<String, String> cache; /** * 初始化机器人 */
package com.github.dmj.bot; /** * @author ljjy1 * @classname DiscordBot * @description discord机器人 * @date 2023/10/11 13:38 */ @Slf4j public class DiscordBot extends ListenerAdapter { private final DiscordAccountProperties discordAccountProperties; private final Cache<String, String> cache; /** * 初始化机器人 */
public DiscordBot(DiscordAccountProperties discordAccountProperties, DiscordProxyProperties discordProxyProperties) throws Exception {
1
2023-10-11 01:12:39+00:00
4k
weizen-w/Educational-Management-System-BE
src/test/java/de/ait/ems/services/ModulesServiceTest.java
[ { "identifier": "CoursesDtoTest", "path": "src/test/java/de/ait/ems/dto/CoursesDtoTest.java", "snippet": "@DisplayName(\"Courses DTO is works:\")\n@DisplayNameGeneration(value = DisplayNameGenerator.ReplaceUnderscores.class)\npublic class CoursesDtoTest {\n\n public static final Long ID = 1L;\n public...
import de.ait.ems.dto.CoursesDtoTest; import de.ait.ems.dto.ModuleDto; import de.ait.ems.dto.ModulesDtoTest; import de.ait.ems.dto.NewModuleDto; import de.ait.ems.dto.UpdateModuleDto; import java.util.List; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.DisplayNameGeneration; import org.junit.jupiter.api.DisplayNameGenerator; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.jdbc.Sql;
2,025
package de.ait.ems.services; /** * 01/11/2023 EducationalManagementSystemBE * * @author Wladimir Weizen */ @SpringBootTest @Nested @DisplayName("Module service is works:") @DisplayNameGeneration(value = DisplayNameGenerator.ReplaceUnderscores.class) @DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD) @ActiveProfiles("test") public class ModulesServiceTest { @Autowired private ModulesService modulesService; @Test @Sql(scripts = "/sql/data.sql") public void add_module() { NewModuleDto newModuleDto = new NewModuleDto(); newModuleDto.setName(ModulesDtoTest.NAME); ModuleDto moduleDto = modulesService.addModule(newModuleDto); Assertions.assertNotNull(moduleDto); Assertions.assertEquals(5, moduleDto.getId()); Assertions.assertEquals(newModuleDto.getName(), moduleDto.getName()); Assertions.assertEquals(false, moduleDto.getArchived()); } @Test @Sql(scripts = "/sql/data.sql") public void get_modules() { List<ModuleDto> modules = modulesService.getModules(); Assertions.assertNotNull(modules); Assertions.assertEquals(4, modules.size()); } @Test @Sql(scripts = "/sql/data.sql") public void update_module() {
package de.ait.ems.services; /** * 01/11/2023 EducationalManagementSystemBE * * @author Wladimir Weizen */ @SpringBootTest @Nested @DisplayName("Module service is works:") @DisplayNameGeneration(value = DisplayNameGenerator.ReplaceUnderscores.class) @DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD) @ActiveProfiles("test") public class ModulesServiceTest { @Autowired private ModulesService modulesService; @Test @Sql(scripts = "/sql/data.sql") public void add_module() { NewModuleDto newModuleDto = new NewModuleDto(); newModuleDto.setName(ModulesDtoTest.NAME); ModuleDto moduleDto = modulesService.addModule(newModuleDto); Assertions.assertNotNull(moduleDto); Assertions.assertEquals(5, moduleDto.getId()); Assertions.assertEquals(newModuleDto.getName(), moduleDto.getName()); Assertions.assertEquals(false, moduleDto.getArchived()); } @Test @Sql(scripts = "/sql/data.sql") public void get_modules() { List<ModuleDto> modules = modulesService.getModules(); Assertions.assertNotNull(modules); Assertions.assertEquals(4, modules.size()); } @Test @Sql(scripts = "/sql/data.sql") public void update_module() {
UpdateModuleDto updateModuleDto = new UpdateModuleDto(ModulesDtoTest.NAME,
4
2023-10-07 16:00:02+00:00
4k
wukong121/eights-reservation
src/main/java/com/bupt/eights/controller/LoginController.java
[ { "identifier": "LoginRequest", "path": "src/main/java/com/bupt/eights/dto/request/LoginRequest.java", "snippet": "@JsonInclude(JsonInclude.Include.NON_NULL)\n@JsonIgnoreProperties(ignoreUnknown = true)\n@NoArgsConstructor\n@AllArgsConstructor\n@Builder\n@Data\npublic class LoginRequest {\n \n @No...
import com.bupt.eights.dto.request.LoginRequest; import com.bupt.eights.dto.request.RegisterRequest; import com.bupt.eights.dto.response.LoginResponse; import com.bupt.eights.model.AuthorityRole; import com.bupt.eights.model.User; import com.bupt.eights.dto.response.HttpResponse; import com.bupt.eights.service.AuthenticateService; import com.bupt.eights.utils.JwtTokenUtils; import com.bupt.eights.utils.URLConstant; import jakarta.servlet.http.HttpServletRequest; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import javax.validation.Valid;
1,685
package com.bupt.eights.controller; @Slf4j @Controller @RequestMapping(URLConstant.LOGIN_URL) public class LoginController { @Autowired AuthenticateService loginService; private String redirectByRole(HttpServletRequest request) { if (request.isUserInRole(AuthorityRole.ROLE_ADMIN.toString())) { return "redirect:/admin"; } if (request.isUserInRole(AuthorityRole.ROLE_STUDENT.toString())) { return "redirect:/students/home"; } return ""; } @RequestMapping(value = "/login", method = RequestMethod.GET) public String showLogin(@ModelAttribute(value = "user") User user, HttpServletRequest request) { String path = redirectByRole(request); if (path.isEmpty()) { return "login"; } return path; } @RequestMapping(value = "/login-success", method = RequestMethod.GET) public String loginSuccess(HttpServletRequest request) { String path = redirectByRole(request); if (path.isEmpty()) { return "redirect:/home"; } return path; } @RequestMapping(value = "/login-failed", method = RequestMethod.GET) public String loginFailed(@ModelAttribute(value = "user") User user, Model model) { model.addAttribute("fail", true); return "login"; } @CrossOrigin @ResponseBody @RequestMapping(value = "/register", method = RequestMethod.POST) public HttpResponse<String> createUser(@RequestBody @Valid RegisterRequest request) { User user = loginService.createUser(request); HttpResponse<String> response = new HttpResponse<>(); response.setStatus("success"); response.setCode(HttpStatus.OK.value()); response.setMessage("注册成功"); response.setData(user.getUserId()); log.info("用户" + user.getUserName() + "注册成功"); return response; } @CrossOrigin @ResponseBody @RequestMapping(value = "/oauth/token", method = RequestMethod.POST) public HttpResponse<LoginResponse> login(@RequestBody @Valid LoginRequest loginRequest) { HttpResponse<LoginResponse> response = loginService.authenticate(loginRequest); if (response.getCode() != 200) { return response; }
package com.bupt.eights.controller; @Slf4j @Controller @RequestMapping(URLConstant.LOGIN_URL) public class LoginController { @Autowired AuthenticateService loginService; private String redirectByRole(HttpServletRequest request) { if (request.isUserInRole(AuthorityRole.ROLE_ADMIN.toString())) { return "redirect:/admin"; } if (request.isUserInRole(AuthorityRole.ROLE_STUDENT.toString())) { return "redirect:/students/home"; } return ""; } @RequestMapping(value = "/login", method = RequestMethod.GET) public String showLogin(@ModelAttribute(value = "user") User user, HttpServletRequest request) { String path = redirectByRole(request); if (path.isEmpty()) { return "login"; } return path; } @RequestMapping(value = "/login-success", method = RequestMethod.GET) public String loginSuccess(HttpServletRequest request) { String path = redirectByRole(request); if (path.isEmpty()) { return "redirect:/home"; } return path; } @RequestMapping(value = "/login-failed", method = RequestMethod.GET) public String loginFailed(@ModelAttribute(value = "user") User user, Model model) { model.addAttribute("fail", true); return "login"; } @CrossOrigin @ResponseBody @RequestMapping(value = "/register", method = RequestMethod.POST) public HttpResponse<String> createUser(@RequestBody @Valid RegisterRequest request) { User user = loginService.createUser(request); HttpResponse<String> response = new HttpResponse<>(); response.setStatus("success"); response.setCode(HttpStatus.OK.value()); response.setMessage("注册成功"); response.setData(user.getUserId()); log.info("用户" + user.getUserName() + "注册成功"); return response; } @CrossOrigin @ResponseBody @RequestMapping(value = "/oauth/token", method = RequestMethod.POST) public HttpResponse<LoginResponse> login(@RequestBody @Valid LoginRequest loginRequest) { HttpResponse<LoginResponse> response = loginService.authenticate(loginRequest); if (response.getCode() != 200) { return response; }
String jwtToken = JwtTokenUtils.createToken(loginRequest.getUserName(), AuthorityRole.ROLE_STUDENT,
7
2023-10-11 09:34:23+00:00
4k
aws-samples/amazon-vpc-lattice-secure-apis
lambda/src/main/java/cloud/heeki/DemoController.java
[ { "identifier": "Customer", "path": "lambda/src/main/java/cloud/heeki/lib/Customer.java", "snippet": "public class Customer {\n public UUID uuid;\n public String given_name;\n public String family_name;\n public String birthdate;\n public String email;\n public String phone_number;\n ...
import cloud.heeki.lib.Customer; import cloud.heeki.lib.DynamoAdapter; import cloud.heeki.lib.PropertiesLoader; 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 com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.Properties; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.ScanResponse; import software.amazon.awssdk.services.dynamodb.paginators.ScanIterable;
1,995
package cloud.heeki; @RestController public class DemoController { private Properties props = PropertiesLoader.loadProperties("application.properties");
package cloud.heeki; @RestController public class DemoController { private Properties props = PropertiesLoader.loadProperties("application.properties");
private ArrayList<Customer> customers = new ArrayList<Customer>();
0
2023-10-13 17:38:23+00:00
4k
ProjectgamesOOP/Adventure_to_the_Fallen_Kingdom
src/entities/Big_Bloated.java
[ { "identifier": "RIGHT", "path": "src/utilz/Constants.java", "snippet": "public static final int RIGHT = 2;" }, { "identifier": "EnemyConstants", "path": "src/utilz/Constants.java", "snippet": "public static class EnemyConstants {\n\tpublic static final int CARNIVOROUS = 0;\n\tpublic s...
import static utilz.Constants.Directions.RIGHT; import static utilz.Constants.EnemyConstants.*; import java.awt.geom.Rectangle2D; import main.Game;
2,109
package entities; public class Big_Bloated extends Enemy { private int attackBoxOffsetX; public Big_Bloated(float x, float y) { super(x, y, BIG_BLOATED_WIDTH, BIG_BLOATED_HEIGHT, BIG_BLOATED); initHitbox(22,30); initAttackBox(); } private void initAttackBox() {
package entities; public class Big_Bloated extends Enemy { private int attackBoxOffsetX; public Big_Bloated(float x, float y) { super(x, y, BIG_BLOATED_WIDTH, BIG_BLOATED_HEIGHT, BIG_BLOATED); initHitbox(22,30); initAttackBox(); } private void initAttackBox() {
attackBox = new Rectangle2D.Float(x,y,(int)(82 * Game.SCALE),(int)(30 * Game.SCALE));
2
2023-10-07 12:07:45+00:00
4k
yc-huang/bsdb
src/main/java/tech/bsdb/bench/UringAsyncFileBench.java
[ { "identifier": "NativeFileIO", "path": "src/main/java/tech/bsdb/io/NativeFileIO.java", "snippet": "public class NativeFileIO {\n public static final int PAGE_SIZE = 4096;\n public static int openForReadDirect(String file) throws IOException {\n return open(file, Native.O_DIRECT | Native.O_...
import tech.bsdb.io.NativeFileIO; import tech.bsdb.io.UringAsyncFileReader; import java.nio.ByteBuffer; import java.nio.channels.CompletionHandler; import java.nio.file.FileSystems; import java.nio.file.Path; import java.util.Random; import java.util.concurrent.atomic.AtomicLong;
2,245
package tech.bsdb.bench; public class UringAsyncFileBench { static AtomicLong readBytes = new AtomicLong(0); static AtomicLong ios = new AtomicLong(0); static AtomicLong failed = new AtomicLong(0); static AtomicLong submited = new AtomicLong(0); static boolean finished = false; static long iteration = 50000 * 1000 * 1000L; public static void main(String[] args) throws Exception { Path path = FileSystems.getDefault().getPath(args[0]); int parallel = Integer.parseInt(args[1]); int readLen = Integer.parseInt(args[2]); int submitThreads = Integer.parseInt(args[3]); //int callbackThreads = Integer.parseInt(args[4]); long fileLen = path.toFile().length(); new Thread(() -> { while (ios.get() < iteration) { long c = ios.get(); long start = System.currentTimeMillis(); try { Thread.sleep(1 * 1000); } catch (InterruptedException e) { throw new RuntimeException(e); } System.err.printf("submit:%d, complete %d failed %d read bytes %d, iops %d %n", submited.get(), ios.get(), failed.get(), readBytes.get(), (ios.get() - c) * 1000 / (System.currentTimeMillis() - start)); } finished = true; }).start(); for (int i = 0; i < parallel; i++) {
package tech.bsdb.bench; public class UringAsyncFileBench { static AtomicLong readBytes = new AtomicLong(0); static AtomicLong ios = new AtomicLong(0); static AtomicLong failed = new AtomicLong(0); static AtomicLong submited = new AtomicLong(0); static boolean finished = false; static long iteration = 50000 * 1000 * 1000L; public static void main(String[] args) throws Exception { Path path = FileSystems.getDefault().getPath(args[0]); int parallel = Integer.parseInt(args[1]); int readLen = Integer.parseInt(args[2]); int submitThreads = Integer.parseInt(args[3]); //int callbackThreads = Integer.parseInt(args[4]); long fileLen = path.toFile().length(); new Thread(() -> { while (ios.get() < iteration) { long c = ios.get(); long start = System.currentTimeMillis(); try { Thread.sleep(1 * 1000); } catch (InterruptedException e) { throw new RuntimeException(e); } System.err.printf("submit:%d, complete %d failed %d read bytes %d, iops %d %n", submited.get(), ios.get(), failed.get(), readBytes.get(), (ios.get() - c) * 1000 / (System.currentTimeMillis() - start)); } finished = true; }).start(); for (int i = 0; i < parallel; i++) {
UringAsyncFileReader reader = new UringAsyncFileReader(readLen, submitThreads, "");
1
2023-10-07 03:32:27+00:00
4k
reinershir/Shir-Boot
src/main/java/io/github/reinershir/boot/core/query/QueryHelper.java
[ { "identifier": "QueryRuleEnum", "path": "src/main/java/io/github/reinershir/boot/core/query/annotation/QueryRuleEnum.java", "snippet": "public enum QueryRuleEnum {\n\n\t/**查询规则 大于*/\n GT(\">\",\"gt\",\"大于\"),\n /**查询规则 大于等于*/\n GE(\">=\",\"ge\",\"大于等于\"),\n /**查询规则 小于*/\n LT(\"<\",\"lt\"...
import java.beans.PropertyDescriptor; import java.lang.reflect.Field; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import cn.hutool.core.bean.BeanUtil; import io.github.reinershir.boot.core.query.annotation.QueryRule; import io.github.reinershir.boot.core.query.annotation.QueryRuleEnum; import io.github.reinershir.boot.model.User; import io.github.reinershir.boot.utils.FieldUtils;
1,900
package io.github.reinershir.boot.core.query; /** * Copyright: Copyright (c) 2023 reiner * @ClassName: QueryHelper.java * @Description: * @version: v1.0.0 * @author: ReinerShir * @date: 2023年7月30日 下午10:50:57 * * Modification History: * Date Author Version Description *---------------------------------------------------------* * 2023年7月30日 ReinerShir v1.0.0 */ public class QueryHelper { public static <T> QueryWrapper<T> initQueryWrapper(T entity){ PropertyDescriptor[] properties = BeanUtil.getPropertyDescriptors(entity.getClass()); QueryWrapper<T> wrapper = new QueryWrapper<T>(); for (PropertyDescriptor property : properties) { String name = property.getName(); Object value=null; try { value = property.getReadMethod().invoke(entity); } catch (Exception e) { e.printStackTrace(); } if(value!=null&&!"".equals(value)) { Field filed=null; try { filed = entity.getClass().getDeclaredField(name); } catch (Exception e) { e.printStackTrace(); } if(filed!=null) { QueryRule queryRule = filed.getAnnotation(QueryRule.class);
package io.github.reinershir.boot.core.query; /** * Copyright: Copyright (c) 2023 reiner * @ClassName: QueryHelper.java * @Description: * @version: v1.0.0 * @author: ReinerShir * @date: 2023年7月30日 下午10:50:57 * * Modification History: * Date Author Version Description *---------------------------------------------------------* * 2023年7月30日 ReinerShir v1.0.0 */ public class QueryHelper { public static <T> QueryWrapper<T> initQueryWrapper(T entity){ PropertyDescriptor[] properties = BeanUtil.getPropertyDescriptors(entity.getClass()); QueryWrapper<T> wrapper = new QueryWrapper<T>(); for (PropertyDescriptor property : properties) { String name = property.getName(); Object value=null; try { value = property.getReadMethod().invoke(entity); } catch (Exception e) { e.printStackTrace(); } if(value!=null&&!"".equals(value)) { Field filed=null; try { filed = entity.getClass().getDeclaredField(name); } catch (Exception e) { e.printStackTrace(); } if(filed!=null) { QueryRule queryRule = filed.getAnnotation(QueryRule.class);
String columnName = FieldUtils.camelToUnderline(name);
2
2023-10-10 13:06:54+00:00
4k
wise-old-man/wiseoldman-runelite-plugin
src/main/java/net/wiseoldman/panel/BossingPanel.java
[ { "identifier": "Format", "path": "src/main/java/net/wiseoldman/util/Format.java", "snippet": "public class Format\n{\n public static String formatNumber(long num)\n {\n if ((num < 10000 && num > -10000))\n {\n return QuantityFormatter.formatNumber(num);\n }\n\n ...
import com.google.common.collect.ImmutableList; import net.wiseoldman.util.Format; import net.wiseoldman.beans.PlayerInfo; import net.wiseoldman.beans.Snapshot; import net.wiseoldman.beans.Computed; import net.runelite.client.ui.ColorScheme; import net.runelite.client.util.QuantityFormatter; import net.runelite.client.hiscore.HiscoreSkill; import net.runelite.client.hiscore.HiscoreSkillType; import javax.inject.Inject; import javax.swing.*; import java.awt.*; import java.util.ArrayList; import java.util.List; import java.util.Map; import static net.runelite.client.hiscore.HiscoreSkill.*;
1,813
package net.wiseoldman.panel; class BossingPanel extends JPanel { /** * Bosses, ordered in the way they should be displayed in the panel. */ private static final List<HiscoreSkill> BOSSES = ImmutableList.of( ABYSSAL_SIRE, ALCHEMICAL_HYDRA, ARTIO, BARROWS_CHESTS, BRYOPHYTA, CALLISTO, CALVARION, CERBERUS, CHAMBERS_OF_XERIC, CHAMBERS_OF_XERIC_CHALLENGE_MODE, CHAOS_ELEMENTAL, CHAOS_FANATIC, COMMANDER_ZILYANA, CORPOREAL_BEAST, DAGANNOTH_PRIME, DAGANNOTH_REX, DAGANNOTH_SUPREME, CRAZY_ARCHAEOLOGIST, DERANGED_ARCHAEOLOGIST, DUKE_SUCELLUS, GENERAL_GRAARDOR, GIANT_MOLE, GROTESQUE_GUARDIANS, HESPORI, KALPHITE_QUEEN, KING_BLACK_DRAGON, KRAKEN, KREEARRA, KRIL_TSUTSAROTH, MIMIC, NEX, NIGHTMARE, PHOSANIS_NIGHTMARE, OBOR, PHANTOM_MUSPAH, SARACHNIS, SCORPIA, SKOTIZO, SPINDEL, TEMPOROSS, THE_GAUNTLET, THE_CORRUPTED_GAUNTLET, THE_LEVIATHAN, THE_WHISPERER, THEATRE_OF_BLOOD, THEATRE_OF_BLOOD_HARD_MODE,THERMONUCLEAR_SMOKE_DEVIL, TOMBS_OF_AMASCUT, TOMBS_OF_AMASCUT_EXPERT, TZKAL_ZUK, TZTOK_JAD, VARDORVIS, VENENATIS, VETION, VORKATH, WINTERTODT, ZALCANO, ZULRAH ); static Color[] ROW_COLORS = {ColorScheme.DARKER_GRAY_COLOR, new Color(34, 34, 34)}; TableRow totalEhbRow; List<RowPair> tableRows = new ArrayList<>(); @Inject private BossingPanel() { setLayout(new GridLayout(0, 1)); StatsTableHeader tableHeader = new StatsTableHeader("bossing"); // Handle total ehb row separately because it's special totalEhbRow = new TableRow( "ehb", "EHB", HiscoreSkillType.BOSS, "kills", "rank", "ehb" ); totalEhbRow.setBackground(ROW_COLORS[1]); add(tableHeader); add(totalEhbRow); for (int i = 0; i < BOSSES.size(); i++) { HiscoreSkill boss = BOSSES.get(i); TableRow row = new TableRow( boss.name(), boss.getName(), HiscoreSkillType.BOSS, "kills", "rank", "ehb" ); row.setBackground(ROW_COLORS[i%2]); tableRows.add(new RowPair(boss, row)); add(row); } } public void update(PlayerInfo info) { if (info == null) { return; } Snapshot latestSnapshot = info.getLatestSnapshot(); for (RowPair rp : tableRows) { HiscoreSkill boss = rp.getSkill(); TableRow row = rp.getRow(); row.update(latestSnapshot.getData().getBosses().getBoss(boss), boss); } updateTotalEhb(latestSnapshot.getData().getComputed().getEhb()); }
package net.wiseoldman.panel; class BossingPanel extends JPanel { /** * Bosses, ordered in the way they should be displayed in the panel. */ private static final List<HiscoreSkill> BOSSES = ImmutableList.of( ABYSSAL_SIRE, ALCHEMICAL_HYDRA, ARTIO, BARROWS_CHESTS, BRYOPHYTA, CALLISTO, CALVARION, CERBERUS, CHAMBERS_OF_XERIC, CHAMBERS_OF_XERIC_CHALLENGE_MODE, CHAOS_ELEMENTAL, CHAOS_FANATIC, COMMANDER_ZILYANA, CORPOREAL_BEAST, DAGANNOTH_PRIME, DAGANNOTH_REX, DAGANNOTH_SUPREME, CRAZY_ARCHAEOLOGIST, DERANGED_ARCHAEOLOGIST, DUKE_SUCELLUS, GENERAL_GRAARDOR, GIANT_MOLE, GROTESQUE_GUARDIANS, HESPORI, KALPHITE_QUEEN, KING_BLACK_DRAGON, KRAKEN, KREEARRA, KRIL_TSUTSAROTH, MIMIC, NEX, NIGHTMARE, PHOSANIS_NIGHTMARE, OBOR, PHANTOM_MUSPAH, SARACHNIS, SCORPIA, SKOTIZO, SPINDEL, TEMPOROSS, THE_GAUNTLET, THE_CORRUPTED_GAUNTLET, THE_LEVIATHAN, THE_WHISPERER, THEATRE_OF_BLOOD, THEATRE_OF_BLOOD_HARD_MODE,THERMONUCLEAR_SMOKE_DEVIL, TOMBS_OF_AMASCUT, TOMBS_OF_AMASCUT_EXPERT, TZKAL_ZUK, TZTOK_JAD, VARDORVIS, VENENATIS, VETION, VORKATH, WINTERTODT, ZALCANO, ZULRAH ); static Color[] ROW_COLORS = {ColorScheme.DARKER_GRAY_COLOR, new Color(34, 34, 34)}; TableRow totalEhbRow; List<RowPair> tableRows = new ArrayList<>(); @Inject private BossingPanel() { setLayout(new GridLayout(0, 1)); StatsTableHeader tableHeader = new StatsTableHeader("bossing"); // Handle total ehb row separately because it's special totalEhbRow = new TableRow( "ehb", "EHB", HiscoreSkillType.BOSS, "kills", "rank", "ehb" ); totalEhbRow.setBackground(ROW_COLORS[1]); add(tableHeader); add(totalEhbRow); for (int i = 0; i < BOSSES.size(); i++) { HiscoreSkill boss = BOSSES.get(i); TableRow row = new TableRow( boss.name(), boss.getName(), HiscoreSkillType.BOSS, "kills", "rank", "ehb" ); row.setBackground(ROW_COLORS[i%2]); tableRows.add(new RowPair(boss, row)); add(row); } } public void update(PlayerInfo info) { if (info == null) { return; } Snapshot latestSnapshot = info.getLatestSnapshot(); for (RowPair rp : tableRows) { HiscoreSkill boss = rp.getSkill(); TableRow row = rp.getRow(); row.update(latestSnapshot.getData().getBosses().getBoss(boss), boss); } updateTotalEhb(latestSnapshot.getData().getComputed().getEhb()); }
private void updateTotalEhb(Computed ehb)
3
2023-10-09 14:23:06+00:00
4k
PinkGoosik/player-nametags
src/main/java/pinkgoosik/playernametags/command/PlayerNametagsCommands.java
[ { "identifier": "PlayerNametagsMod", "path": "src/main/java/pinkgoosik/playernametags/PlayerNametagsMod.java", "snippet": "public class PlayerNametagsMod implements ModInitializer {\n\tpublic static final String MOD_ID = \"player-nametags\";\n\tpublic static final Logger LOGGER = LoggerFactory.getLogger...
import com.mojang.brigadier.CommandDispatcher; import com.mojang.brigadier.arguments.BoolArgumentType; import com.mojang.brigadier.arguments.IntegerArgumentType; import com.mojang.brigadier.arguments.StringArgumentType; import com.mojang.brigadier.suggestion.SuggestionProvider; import net.fabricmc.fabric.api.command.v2.CommandRegistrationCallback; import net.minecraft.server.command.ServerCommandSource; import net.minecraft.text.Text; import pinkgoosik.playernametags.PlayerNametagsMod; import pinkgoosik.playernametags.config.PlayerNametagsConfig; import static net.minecraft.server.command.CommandManager.argument; import static net.minecraft.server.command.CommandManager.literal;
1,697
package pinkgoosik.playernametags.command; public class PlayerNametagsCommands { public static final SuggestionProvider<ServerCommandSource> SUGGEST_PERMISSION = (context, builder) -> { String remains = builder.getRemaining(); for(String permission : PlayerNametagsMod.config.formatPerPermission.keySet()) { if(permission.contains(remains)) { builder.suggest(permission); } } return builder.buildFuture(); }; static final String[] modes = new String[]{"gray-out", "hide", "none"}; public static final SuggestionProvider<ServerCommandSource> SUGGEST_SNEAKING_MODE = (context, builder) -> { String remains = builder.getRemaining(); for(String mode : modes) { if(mode.contains(remains)) { builder.suggest(mode); } } return builder.buildFuture(); }; public static void init() { CommandRegistrationCallback.EVENT.register((dispatcher, registryAccess, environment) -> register(dispatcher)); } private static void register(CommandDispatcher<ServerCommandSource> dispatcher) { dispatcher.register(literal("player-nametags").requires(source -> source.hasPermissionLevel(3)).then(literal("reload").executes(context -> {
package pinkgoosik.playernametags.command; public class PlayerNametagsCommands { public static final SuggestionProvider<ServerCommandSource> SUGGEST_PERMISSION = (context, builder) -> { String remains = builder.getRemaining(); for(String permission : PlayerNametagsMod.config.formatPerPermission.keySet()) { if(permission.contains(remains)) { builder.suggest(permission); } } return builder.buildFuture(); }; static final String[] modes = new String[]{"gray-out", "hide", "none"}; public static final SuggestionProvider<ServerCommandSource> SUGGEST_SNEAKING_MODE = (context, builder) -> { String remains = builder.getRemaining(); for(String mode : modes) { if(mode.contains(remains)) { builder.suggest(mode); } } return builder.buildFuture(); }; public static void init() { CommandRegistrationCallback.EVENT.register((dispatcher, registryAccess, environment) -> register(dispatcher)); } private static void register(CommandDispatcher<ServerCommandSource> dispatcher) { dispatcher.register(literal("player-nametags").requires(source -> source.hasPermissionLevel(3)).then(literal("reload").executes(context -> {
PlayerNametagsMod.config = PlayerNametagsConfig.read();
1
2023-10-10 10:12:09+00:00
4k
vaylor27/config
common/src/main/java/net/vakror/jamesconfig/config/example/ExampleConfigs.java
[ { "identifier": "CompoundRegistryObject", "path": "common/src/main/java/net/vakror/jamesconfig/config/config/object/default_objects/registry/CompoundRegistryObject.java", "snippet": "public class CompoundRegistryObject extends RegistryConfigObject {\n /**\n * a list of sub-objects to serialize an...
import net.vakror.jamesconfig.config.config.object.default_objects.registry.CompoundRegistryObject; import net.vakror.jamesconfig.config.example.configs.ExampleMultiObjectRegistryConfigImpl; import net.vakror.jamesconfig.config.example.configs.ExampleSettingConfig; import net.vakror.jamesconfig.config.example.configs.ExampleSingleObjectRegistryConfigImpl; import net.vakror.jamesconfig.config.manager.config.SimpleConfigManager; import net.vakror.jamesconfig.config.manager.object.SimpleConfigObjectManager;
1,707
package net.vakror.jamesconfig.config.example; public class ExampleConfigs { public static void addExampleConfig() {
package net.vakror.jamesconfig.config.example; public class ExampleConfigs { public static void addExampleConfig() {
SimpleConfigManager.INSTANCE.register(new ExampleMultiObjectRegistryConfigImpl());
1
2023-10-07 23:04:49+00:00
4k
ProfessorFichte/More-RPG-Classes
src/main/java/net/more_rpg_classes/effect/MRPGCEffects.java
[ { "identifier": "MRPGCMod", "path": "src/main/java/net/more_rpg_classes/MRPGCMod.java", "snippet": "public class MRPGCMod implements ModInitializer {\n\tpublic static final String MOD_ID = \"more_rpg_classes\";\n\tpublic static final Logger LOGGER = LoggerFactory.getLogger(\"more_rpg_classes\");\n\n\t@O...
import net.minecraft.entity.attribute.EntityAttributeModifier; import net.minecraft.entity.attribute.EntityAttributes; import net.minecraft.entity.effect.StatusEffect; import net.minecraft.entity.effect.StatusEffectCategory; import net.minecraft.registry.Registries; import net.minecraft.registry.Registry; import net.minecraft.util.Identifier; import net.more_rpg_classes.MRPGCMod; import net.more_rpg_classes.entity.attribute.MRPGCEntityAttributes; import net.spell_engine.api.effect.ActionImpairing; import net.spell_engine.api.effect.EntityActionsAllowed; import net.spell_engine.api.effect.RemoveOnHit; import net.spell_engine.api.effect.Synchronized; import net.spell_power.api.MagicSchool; import net.spell_power.api.SpellPower;
1,643
package net.more_rpg_classes.effect; public class MRPGCEffects { public static float rage_damage_increase = +0.5f; public static float rage_incoming_damage_increase = 0.5f; public static float rage_attack_speed_increase = +0.2f; public static float molten_armor_reduce_factor = -2.0f; public static float molten_toughness_reduce_factor = -1.0f; public static float stone_hand_attack = 1.0f; public static float stone_hand_attack_speed = -0.7f; public static float aerondight_attack = 0.1f; //RAGE public static StatusEffect RAGE = new RageStatusEffect(StatusEffectCategory.BENEFICIAL, 0xf70000) .addAttributeModifier(EntityAttributes.GENERIC_ATTACK_DAMAGE, "0b0701a4-4bdc-42a7-9b7e-06d0e397ae77", rage_damage_increase, EntityAttributeModifier.Operation.ADDITION) .addAttributeModifier(MRPGCEntityAttributes.INCOMING_DAMAGE_MODIFIER, "0bf30a36-798a-450d-bd74-959910e6778e", rage_incoming_damage_increase, EntityAttributeModifier.Operation.ADDITION) .addAttributeModifier(EntityAttributes.GENERIC_ATTACK_SPEED, "3098b421-2316-4b40-9fcf-71c84fd85fc3", rage_attack_speed_increase, EntityAttributeModifier.Operation.ADDITION); //MOLTEN_ARMOR public static final StatusEffect MOLTEN_ARMOR = new MoltenArmorEffect(StatusEffectCategory.HARMFUL,0xdd4e00) .addAttributeModifier(EntityAttributes.GENERIC_ARMOR, "d20cbd0d-4101-4dc8-9bbc-140494951dc8", molten_armor_reduce_factor, EntityAttributeModifier.Operation.ADDITION) .addAttributeModifier(EntityAttributes.GENERIC_ARMOR_TOUGHNESS, "0371dbb7-136a-471e-a7a8-512afa10389c", molten_toughness_reduce_factor, EntityAttributeModifier.Operation.ADDITION); //BARQ_ESNA public static StatusEffect BARQ_ESNA = new BarqEsnaEffect(StatusEffectCategory.HARMFUL, 0x8db4fe) .setVulnerability(MagicSchool.ARCANE, new SpellPower.Vulnerability(0.2F, 0.1F, 0F)); //MOONLIGHT public static StatusEffect MOONLIGHT = new MoonLightEffect(StatusEffectCategory.HARMFUL, 0xbce5fe); //STONE_HAND public static StatusEffect STONE_HAND = new StoneHandEffect(StatusEffectCategory.BENEFICIAL, 0xbce5fe) .addAttributeModifier(EntityAttributes.GENERIC_ATTACK_DAMAGE, "d1843e0f-8a63-4c96-a854-9c9444981042", stone_hand_attack, EntityAttributeModifier.Operation.ADDITION) .addAttributeModifier(EntityAttributes.GENERIC_ATTACK_SPEED, "9bf58fe9-4b58-4174-9f41-a492a3510271", stone_hand_attack_speed, EntityAttributeModifier.Operation.ADDITION); //STUNNED public static StatusEffect STUNNED = new StunEffect(StatusEffectCategory.HARMFUL, 0xfffeca); //FROZEN_SOLID public static StatusEffect FROZEN_SOLID= new FrozenSolidEffect(StatusEffectCategory.HARMFUL, 0x3beeff); //AERONDIGHT_CHARGE public static StatusEffect AERONDIGHT_CHARGE= new AerondightChargeEffect(StatusEffectCategory.BENEFICIAL, 0x6afecf) .addAttributeModifier(EntityAttributes.GENERIC_ATTACK_DAMAGE, "d1843e0f-8a63-4c96-a854-9c9444981042", aerondight_attack, EntityAttributeModifier.Operation.ADDITION); //QUEN SHIELD public static StatusEffect QUEN_SHIELD= new QuenEffect(StatusEffectCategory.BENEFICIAL, 0x3beeff); public static void register(){ Synchronized.configure(RAGE,true); Synchronized.configure(MOLTEN_ARMOR,true); Synchronized.configure(BARQ_ESNA,true); Synchronized.configure(MOONLIGHT,true); Synchronized.configure(STONE_HAND,true); Synchronized.configure(STUNNED,true); ActionImpairing.configure(STUNNED, EntityActionsAllowed.STUN); ActionImpairing.configure(FROZEN_SOLID, EntityActionsAllowed.STUN); RemoveOnHit.configure(FROZEN_SOLID, true); Synchronized.configure(FROZEN_SOLID,true); Synchronized.configure(AERONDIGHT_CHARGE,true); Synchronized.configure(QUEN_SHIELD,true); int mrpgc_spellid = 900;
package net.more_rpg_classes.effect; public class MRPGCEffects { public static float rage_damage_increase = +0.5f; public static float rage_incoming_damage_increase = 0.5f; public static float rage_attack_speed_increase = +0.2f; public static float molten_armor_reduce_factor = -2.0f; public static float molten_toughness_reduce_factor = -1.0f; public static float stone_hand_attack = 1.0f; public static float stone_hand_attack_speed = -0.7f; public static float aerondight_attack = 0.1f; //RAGE public static StatusEffect RAGE = new RageStatusEffect(StatusEffectCategory.BENEFICIAL, 0xf70000) .addAttributeModifier(EntityAttributes.GENERIC_ATTACK_DAMAGE, "0b0701a4-4bdc-42a7-9b7e-06d0e397ae77", rage_damage_increase, EntityAttributeModifier.Operation.ADDITION) .addAttributeModifier(MRPGCEntityAttributes.INCOMING_DAMAGE_MODIFIER, "0bf30a36-798a-450d-bd74-959910e6778e", rage_incoming_damage_increase, EntityAttributeModifier.Operation.ADDITION) .addAttributeModifier(EntityAttributes.GENERIC_ATTACK_SPEED, "3098b421-2316-4b40-9fcf-71c84fd85fc3", rage_attack_speed_increase, EntityAttributeModifier.Operation.ADDITION); //MOLTEN_ARMOR public static final StatusEffect MOLTEN_ARMOR = new MoltenArmorEffect(StatusEffectCategory.HARMFUL,0xdd4e00) .addAttributeModifier(EntityAttributes.GENERIC_ARMOR, "d20cbd0d-4101-4dc8-9bbc-140494951dc8", molten_armor_reduce_factor, EntityAttributeModifier.Operation.ADDITION) .addAttributeModifier(EntityAttributes.GENERIC_ARMOR_TOUGHNESS, "0371dbb7-136a-471e-a7a8-512afa10389c", molten_toughness_reduce_factor, EntityAttributeModifier.Operation.ADDITION); //BARQ_ESNA public static StatusEffect BARQ_ESNA = new BarqEsnaEffect(StatusEffectCategory.HARMFUL, 0x8db4fe) .setVulnerability(MagicSchool.ARCANE, new SpellPower.Vulnerability(0.2F, 0.1F, 0F)); //MOONLIGHT public static StatusEffect MOONLIGHT = new MoonLightEffect(StatusEffectCategory.HARMFUL, 0xbce5fe); //STONE_HAND public static StatusEffect STONE_HAND = new StoneHandEffect(StatusEffectCategory.BENEFICIAL, 0xbce5fe) .addAttributeModifier(EntityAttributes.GENERIC_ATTACK_DAMAGE, "d1843e0f-8a63-4c96-a854-9c9444981042", stone_hand_attack, EntityAttributeModifier.Operation.ADDITION) .addAttributeModifier(EntityAttributes.GENERIC_ATTACK_SPEED, "9bf58fe9-4b58-4174-9f41-a492a3510271", stone_hand_attack_speed, EntityAttributeModifier.Operation.ADDITION); //STUNNED public static StatusEffect STUNNED = new StunEffect(StatusEffectCategory.HARMFUL, 0xfffeca); //FROZEN_SOLID public static StatusEffect FROZEN_SOLID= new FrozenSolidEffect(StatusEffectCategory.HARMFUL, 0x3beeff); //AERONDIGHT_CHARGE public static StatusEffect AERONDIGHT_CHARGE= new AerondightChargeEffect(StatusEffectCategory.BENEFICIAL, 0x6afecf) .addAttributeModifier(EntityAttributes.GENERIC_ATTACK_DAMAGE, "d1843e0f-8a63-4c96-a854-9c9444981042", aerondight_attack, EntityAttributeModifier.Operation.ADDITION); //QUEN SHIELD public static StatusEffect QUEN_SHIELD= new QuenEffect(StatusEffectCategory.BENEFICIAL, 0x3beeff); public static void register(){ Synchronized.configure(RAGE,true); Synchronized.configure(MOLTEN_ARMOR,true); Synchronized.configure(BARQ_ESNA,true); Synchronized.configure(MOONLIGHT,true); Synchronized.configure(STONE_HAND,true); Synchronized.configure(STUNNED,true); ActionImpairing.configure(STUNNED, EntityActionsAllowed.STUN); ActionImpairing.configure(FROZEN_SOLID, EntityActionsAllowed.STUN); RemoveOnHit.configure(FROZEN_SOLID, true); Synchronized.configure(FROZEN_SOLID,true); Synchronized.configure(AERONDIGHT_CHARGE,true); Synchronized.configure(QUEN_SHIELD,true); int mrpgc_spellid = 900;
Registry.register(Registries.STATUS_EFFECT, mrpgc_spellid++, new Identifier(MRPGCMod.MOD_ID, "rage").toString(), RAGE);
0
2023-10-14 12:44:07+00:00
4k
PhoenixOrigin/websocket-client
src/main/java/net/phoenix/websocketclient/client/Websocket_clientClient.java
[ { "identifier": "SimpleConfig", "path": "src/main/java/net/phoenix/websocketclient/SimpleConfig.java", "snippet": "public class SimpleConfig {\n\n private static final Logger LOGGER = LogManager.getLogger(\"SimpleConfig\");\n private final HashMap<String, String> config = new HashMap<>();\n pri...
import com.google.gson.JsonObject; import com.mojang.brigadier.tree.LiteralCommandNode; import net.fabricmc.api.ClientModInitializer; import net.fabricmc.fabric.api.client.command.v2.ClientCommandManager; import net.fabricmc.fabric.api.client.command.v2.ClientCommandRegistrationCallback; import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; import net.fabricmc.fabric.api.client.message.v1.ClientReceiveMessageEvents; import net.minecraft.client.MinecraftClient; import net.minecraft.text.Text; import net.phoenix.websocketclient.SimpleConfig; import net.phoenix.websocketclient.WebsocketHandler; import net.phoenix.websocketclient.commands.WebsocketCommand; import java.net.URI; import java.net.URISyntaxException;
2,827
package net.phoenix.websocketclient.client; public class Websocket_clientClient implements ClientModInitializer { public static SimpleConfig config = null; public static WebsocketHandler websocket = null; /** * Runs the mod initializer on the client environment. */ @Override public void onInitializeClient() { ClientCommandRegistrationCallback.EVENT.register((dispatcher, registryAccess) -> {
package net.phoenix.websocketclient.client; public class Websocket_clientClient implements ClientModInitializer { public static SimpleConfig config = null; public static WebsocketHandler websocket = null; /** * Runs the mod initializer on the client environment. */ @Override public void onInitializeClient() { ClientCommandRegistrationCallback.EVENT.register((dispatcher, registryAccess) -> {
LiteralCommandNode<FabricClientCommandSource> node = dispatcher.register(new WebsocketCommand().build());
2
2023-10-11 16:32:13+00:00
4k
pasindusampath/Spring-Boot-Final
Guide Micro Service/src/main/java/lk/ijse/gdse63/springfinal/api/GuideAPI.java
[ { "identifier": "GuideDTO", "path": "Guide Micro Service/src/main/java/lk/ijse/gdse63/springfinal/dto/GuideDTO.java", "snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\npublic class GuideDTO {\n private int id;\n private String name;\n private String address;\n private String contac...
import lk.ijse.gdse63.springfinal.dto.GuideDTO; import lk.ijse.gdse63.springfinal.exception.SaveFailException; import lk.ijse.gdse63.springfinal.exception.SearchFailException; import lk.ijse.gdse63.springfinal.exception.UpdateFailException; import lk.ijse.gdse63.springfinal.service.GuidService; import lk.ijse.gdse63.springfinal.service.impl.GuideServiceIMPL; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.time.LocalDate;
2,932
package lk.ijse.gdse63.springfinal.api; @RestController @RequestMapping("/api/v1/guide") @CrossOrigin public class GuideAPI { GuidService service; public GuideAPI(GuidService service) { this.service = service; } @PostMapping public ResponseEntity saveGuide(@RequestParam("name")String name, @RequestParam("address")String address, @RequestParam("contact") String contact, @RequestParam("birthDate") LocalDate birthDate, @RequestParam("manDayValue") double manDayValue, @RequestParam("experience") String experience, @RequestPart("guideIdFront") byte[] guideIdFront, @RequestPart("guideIdRear") byte[] guideIdRear, @RequestPart("nicFront") byte[] nicFront, @RequestPart("nicRear") byte[] nicRear, @RequestPart("profilePic") byte[] profilePic) { GuideDTO guideDTO = new GuideDTO(); guideDTO.setName(name); guideDTO.setAddress(address); guideDTO.setContact(contact); guideDTO.setBirthDate(birthDate); guideDTO.setManDayValue(manDayValue); guideDTO.setExperience(experience); guideDTO.setGuideIdFront(guideIdFront); guideDTO.setGuideIdRear(guideIdRear); guideDTO.setNicFront(nicFront); guideDTO.setNicRear(nicRear); guideDTO.setProfilePic(profilePic); try { int i = service.saveGuide(guideDTO); return new ResponseEntity<>(i, HttpStatus.CREATED); } catch (SaveFailException e) { return new ResponseEntity<>(e.getMessage(), HttpStatus.CONFLICT); } } @DeleteMapping("/{id:\\d+}") public ResponseEntity deleteGuide(@PathVariable int id) { try { service.deleteGuide(id); return new ResponseEntity<>(HttpStatus.OK); } catch (Exception e) { return new ResponseEntity<>(e.getMessage(), HttpStatus.CONFLICT); } } @PutMapping("/{id:\\d+}") public ResponseEntity updateGuide(@PathVariable int id, @RequestParam("name")String name, @RequestParam("address")String address, @RequestParam("contact") String contact, @RequestParam("birthDate") LocalDate birthDate, @RequestParam("manDayValue") double manDayValue, @RequestParam("experience") String experience, @RequestPart("guideIdFront") byte[] guideIdFront, @RequestPart("guideIdRear") byte[] guideIdRear, @RequestPart("nicFront") byte[] nicFront, @RequestPart("nicRear") byte[] nicRear, @RequestPart("profilePic") byte[] profilePic) { GuideDTO guideDTO = new GuideDTO(); guideDTO.setId(id); guideDTO.setName(name); guideDTO.setAddress(address); guideDTO.setContact(contact); guideDTO.setBirthDate(birthDate); guideDTO.setManDayValue(manDayValue); guideDTO.setExperience(experience); guideDTO.setGuideIdFront(guideIdFront); guideDTO.setGuideIdRear(guideIdRear); guideDTO.setNicFront(nicFront); guideDTO.setNicRear(nicRear); guideDTO.setProfilePic(profilePic); try { service.updateGuide(guideDTO); return new ResponseEntity<>(HttpStatus.OK); } catch (UpdateFailException e) { return new ResponseEntity<>(e.getMessage(), HttpStatus.CONFLICT); } } @GetMapping("/{id:\\d+}") public ResponseEntity getGuide(@PathVariable int id) { try { GuideDTO guide = service.getGuide(id); return new ResponseEntity<>(guide, HttpStatus.OK);
package lk.ijse.gdse63.springfinal.api; @RestController @RequestMapping("/api/v1/guide") @CrossOrigin public class GuideAPI { GuidService service; public GuideAPI(GuidService service) { this.service = service; } @PostMapping public ResponseEntity saveGuide(@RequestParam("name")String name, @RequestParam("address")String address, @RequestParam("contact") String contact, @RequestParam("birthDate") LocalDate birthDate, @RequestParam("manDayValue") double manDayValue, @RequestParam("experience") String experience, @RequestPart("guideIdFront") byte[] guideIdFront, @RequestPart("guideIdRear") byte[] guideIdRear, @RequestPart("nicFront") byte[] nicFront, @RequestPart("nicRear") byte[] nicRear, @RequestPart("profilePic") byte[] profilePic) { GuideDTO guideDTO = new GuideDTO(); guideDTO.setName(name); guideDTO.setAddress(address); guideDTO.setContact(contact); guideDTO.setBirthDate(birthDate); guideDTO.setManDayValue(manDayValue); guideDTO.setExperience(experience); guideDTO.setGuideIdFront(guideIdFront); guideDTO.setGuideIdRear(guideIdRear); guideDTO.setNicFront(nicFront); guideDTO.setNicRear(nicRear); guideDTO.setProfilePic(profilePic); try { int i = service.saveGuide(guideDTO); return new ResponseEntity<>(i, HttpStatus.CREATED); } catch (SaveFailException e) { return new ResponseEntity<>(e.getMessage(), HttpStatus.CONFLICT); } } @DeleteMapping("/{id:\\d+}") public ResponseEntity deleteGuide(@PathVariable int id) { try { service.deleteGuide(id); return new ResponseEntity<>(HttpStatus.OK); } catch (Exception e) { return new ResponseEntity<>(e.getMessage(), HttpStatus.CONFLICT); } } @PutMapping("/{id:\\d+}") public ResponseEntity updateGuide(@PathVariable int id, @RequestParam("name")String name, @RequestParam("address")String address, @RequestParam("contact") String contact, @RequestParam("birthDate") LocalDate birthDate, @RequestParam("manDayValue") double manDayValue, @RequestParam("experience") String experience, @RequestPart("guideIdFront") byte[] guideIdFront, @RequestPart("guideIdRear") byte[] guideIdRear, @RequestPart("nicFront") byte[] nicFront, @RequestPart("nicRear") byte[] nicRear, @RequestPart("profilePic") byte[] profilePic) { GuideDTO guideDTO = new GuideDTO(); guideDTO.setId(id); guideDTO.setName(name); guideDTO.setAddress(address); guideDTO.setContact(contact); guideDTO.setBirthDate(birthDate); guideDTO.setManDayValue(manDayValue); guideDTO.setExperience(experience); guideDTO.setGuideIdFront(guideIdFront); guideDTO.setGuideIdRear(guideIdRear); guideDTO.setNicFront(nicFront); guideDTO.setNicRear(nicRear); guideDTO.setProfilePic(profilePic); try { service.updateGuide(guideDTO); return new ResponseEntity<>(HttpStatus.OK); } catch (UpdateFailException e) { return new ResponseEntity<>(e.getMessage(), HttpStatus.CONFLICT); } } @GetMapping("/{id:\\d+}") public ResponseEntity getGuide(@PathVariable int id) { try { GuideDTO guide = service.getGuide(id); return new ResponseEntity<>(guide, HttpStatus.OK);
} catch (SearchFailException e) {
2
2023-10-15 06:40:35+00:00
4k
juzi45/XianTech
src/main/java/com/qq/xiantech/block/BlockInit.java
[ { "identifier": "XianTech", "path": "src/main/java/com/qq/xiantech/XianTech.java", "snippet": "@Slf4j\n@Mod(XianTech.MOD_ID)\npublic class XianTech {\n\n /**\n * 模组ID,必须和 META-INF/mods.toml中保持一致\n */\n public static final String MOD_ID = \"xiantech\";\n\n public XianTech() {\n //...
import com.qq.xiantech.XianTech; import com.qq.xiantech.block.ore.DeepSlateStringCrystalOre; import com.qq.xiantech.block.ore.DeepSlateStringCrystalOreItem; import com.qq.xiantech.block.ore.StringCrystalOre; import com.qq.xiantech.block.ore.StringCrystalOreItem; import com.qq.xiantech.item.ItemInit; import net.minecraft.world.item.Item; import net.minecraft.world.level.block.Block; import net.minecraftforge.registries.DeferredRegister; import net.minecraftforge.registries.ForgeRegistries; import net.minecraftforge.registries.RegistryObject; import java.util.function.Function; import java.util.function.Supplier;
1,637
package com.qq.xiantech.block; /** * 方块初始化 * * @author Pig-Gua * @date 2023-10-18 */ public class BlockInit { /** * 延迟注册器(方块) */ public static final DeferredRegister<Block> BLOCKS = DeferredRegister.create(ForgeRegistries.BLOCKS, XianTech.MOD_ID); /** * 延迟注册器(物品) */ public static final DeferredRegister<Item> ITEMS = ItemInit.ITEMS; public static final RegistryObject<Block> STRING_CRYSTAL_ORE = register("string_crystal_ore", StringCrystalOre::new,
package com.qq.xiantech.block; /** * 方块初始化 * * @author Pig-Gua * @date 2023-10-18 */ public class BlockInit { /** * 延迟注册器(方块) */ public static final DeferredRegister<Block> BLOCKS = DeferredRegister.create(ForgeRegistries.BLOCKS, XianTech.MOD_ID); /** * 延迟注册器(物品) */ public static final DeferredRegister<Item> ITEMS = ItemInit.ITEMS; public static final RegistryObject<Block> STRING_CRYSTAL_ORE = register("string_crystal_ore", StringCrystalOre::new,
object -> () -> new StringCrystalOreItem(object.get()));
4
2023-10-13 12:32:28+00:00
4k
uku3lig/ukuwayplus
src/main/java/net/uku3lig/ukuway/ui/JukeboxScreen.java
[ { "identifier": "UkuwayPlus", "path": "src/main/java/net/uku3lig/ukuway/UkuwayPlus.java", "snippet": "@Environment(EnvType.CLIENT)\npublic class UkuwayPlus implements ClientModInitializer {\n @Getter\n private static final ConfigManager<UkuwayConfig> manager = ConfigManager.create(UkuwayConfig.cla...
import net.minecraft.client.MinecraftClient; import net.minecraft.client.gui.DrawContext; import net.minecraft.client.gui.screen.Screen; import net.minecraft.client.gui.widget.ButtonWidget; import net.minecraft.client.gui.widget.GridWidget; import net.minecraft.client.gui.widget.SimplePositioningWidget; import net.minecraft.screen.ScreenTexts; import net.minecraft.text.Text; import net.uku3lig.ukuway.UkuwayPlus; import net.uku3lig.ukuway.jukebox.JukeboxTrack;
1,827
package net.uku3lig.ukuway.ui; public class JukeboxScreen extends Screen { private final Screen parent; public JukeboxScreen(Screen parent) { super(Text.translatable("jukebox.title")); this.parent = parent; } @Override protected void init() { super.init(); GridWidget grid = new GridWidget(); GridWidget.Adder rowHelper = grid.setSpacing(4).createAdder(2);
package net.uku3lig.ukuway.ui; public class JukeboxScreen extends Screen { private final Screen parent; public JukeboxScreen(Screen parent) { super(Text.translatable("jukebox.title")); this.parent = parent; } @Override protected void init() { super.init(); GridWidget grid = new GridWidget(); GridWidget.Adder rowHelper = grid.setSpacing(4).createAdder(2);
for (JukeboxTrack track : JukeboxTrack.values()) {
1
2023-10-07 00:02:04+00:00
4k
YumiProject/yumi-gradle-licenser
src/main/java/dev/yumi/gradle/licenser/api/rule/HeaderRule.java
[ { "identifier": "RuleToken", "path": "src/main/java/dev/yumi/gradle/licenser/api/rule/token/RuleToken.java", "snippet": "public interface RuleToken {\n}" }, { "identifier": "VariableType", "path": "src/main/java/dev/yumi/gradle/licenser/api/rule/variable/VariableType.java", "snippet": "p...
import dev.yumi.gradle.licenser.api.rule.token.RuleToken; import dev.yumi.gradle.licenser.api.rule.token.TextToken; import dev.yumi.gradle.licenser.api.rule.token.VarToken; import dev.yumi.gradle.licenser.api.rule.variable.VariableType; import dev.yumi.gradle.licenser.util.Utils; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.UnmodifiableView; import java.util.*;
3,384
/* * Copyright 2023 Yumi Project * * 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 dev.yumi.gradle.licenser.api.rule; /** * Represents a header rule which describes how a header should look like. * * @author LambdAurora * @version 1.0.0 * @since 1.0.0 */ public class HeaderRule { private final String name; private final List<HeaderLine> lines; private final Map<String, VariableType<?>> variables; private final LicenseYearSelectionMode yearSelectionMode; public HeaderRule( @NotNull String name, @NotNull List<HeaderLine> lines, @NotNull Map<String, VariableType<?>> variables, @NotNull LicenseYearSelectionMode yearSelectionMode ) { this.name = name; this.lines = lines; this.variables = variables; this.yearSelectionMode = yearSelectionMode; } /** * {@return the name of this header rule} */ @Contract(pure = true) public @NotNull String getName() { return this.name; } /** * {@return a view of the lines of this header} */ @Contract(pure = true) public @UnmodifiableView @NotNull List<HeaderLine> getLines() { return Collections.unmodifiableList(this.lines); } /** * {@return the year selection mode} */ @Contract(pure = true) public @NotNull LicenseYearSelectionMode getYearSelectionMode() { return this.yearSelectionMode; } /** * Parses the given header according to the current rules, may throw an exception if the header is not valid. * * @param header the header to check * @return parsed data, contain the successfully parsed variables, and the error if parsing failed */ public @NotNull ParsedData parseHeader(@NotNull List<String> header) { var variableValues = new HashMap<String, Object>(); var presentOptionalLines = new HashSet<Integer>(); int headerLineIndex = 0, ruleLineIndex = 0; for (; headerLineIndex < header.size(); headerLineIndex++) { String headerLine = header.get(headerLineIndex); if (ruleLineIndex >= this.lines.size()) { return new ParsedData(variableValues, presentOptionalLines, new HeaderParseException(headerLineIndex, "There is unexpected extra header lines.")); } HeaderLine ruleLine = this.lines.get(ruleLineIndex); String error; while ((error = this.parseLine(headerLine, ruleLine, variableValues)) != null) { if (ruleLine.optional()) { // If the line is optional, attempts to check the next line. ruleLine = this.lines.get(++ruleLineIndex); } else { return new ParsedData(variableValues, presentOptionalLines, new HeaderParseException(headerLineIndex, error)); } } if (ruleLine.optional()) { presentOptionalLines.add(ruleLineIndex); } ruleLineIndex++; } return new ParsedData(variableValues, presentOptionalLines, null); } private @Nullable String parseLine( @NotNull String headerLine, @NotNull HeaderLine currentLine, @NotNull Map<String, Object> variablesMap ) { int currentIndex = 0; for (var token : currentLine.tokens()) { if (token instanceof TextToken textToken) { String text = textToken.content(); int theoreticalEnd = currentIndex + text.length(); if (theoreticalEnd > headerLine.length()) { return "Header is cut short, stopped at " + headerLine.length() + " instead of " + theoreticalEnd + "."; } String toCheck = headerLine.substring(currentIndex, theoreticalEnd); if (!text.equals(toCheck)) { return "Text differs at " + currentIndex + ", got \"" + toCheck + "\", expected \"" + text + "\"."; } currentIndex = currentIndex + text.length(); } else if (token instanceof VarToken varToken) { var type = this.variables.get(varToken.variable()); var result = type.parseVar(headerLine, currentIndex); if (result.isEmpty()) { return "Failed to parse variable \"" + varToken.variable() + "\" at " + currentIndex + "."; } var old = variablesMap.put(varToken.variable(), result.get().data()); if (old != null && !old.equals(result.get().data())) { return "Diverging variable values for \"" + varToken.variable() + "\"."; } currentIndex = result.get().end(); } } return null; } /** * Applies this header rule to the provided parsed data to create a valid up-to-date header comment. * * @param data the data parsed by attempting to read the header comment * @param context the context of the file to update * @return the updated header comment */ @SuppressWarnings({"rawtypes", "unchecked"}) public @NotNull List<String> apply(@NotNull ParsedData data, @NotNull HeaderFileContext context) { var result = new ArrayList<String>(); for (int i = 0; i < this.lines.size(); i++) { var line = this.lines.get(i); if (!line.optional() || data.presentOptionalLines.contains(i)) { var builder = new StringBuilder(); for (var token : line.tokens()) { if (token instanceof TextToken textToken) { builder.append(textToken.content()); } else if (token instanceof VarToken varToken) { var type = (VariableType) this.variables.get(varToken.variable()); var previous = data.variables.get(varToken.variable()); var newValue = type.getUpToDate(context, previous); builder.append(type.getAsString(newValue)); } } result.add(builder.toString()); } }
/* * Copyright 2023 Yumi Project * * 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 dev.yumi.gradle.licenser.api.rule; /** * Represents a header rule which describes how a header should look like. * * @author LambdAurora * @version 1.0.0 * @since 1.0.0 */ public class HeaderRule { private final String name; private final List<HeaderLine> lines; private final Map<String, VariableType<?>> variables; private final LicenseYearSelectionMode yearSelectionMode; public HeaderRule( @NotNull String name, @NotNull List<HeaderLine> lines, @NotNull Map<String, VariableType<?>> variables, @NotNull LicenseYearSelectionMode yearSelectionMode ) { this.name = name; this.lines = lines; this.variables = variables; this.yearSelectionMode = yearSelectionMode; } /** * {@return the name of this header rule} */ @Contract(pure = true) public @NotNull String getName() { return this.name; } /** * {@return a view of the lines of this header} */ @Contract(pure = true) public @UnmodifiableView @NotNull List<HeaderLine> getLines() { return Collections.unmodifiableList(this.lines); } /** * {@return the year selection mode} */ @Contract(pure = true) public @NotNull LicenseYearSelectionMode getYearSelectionMode() { return this.yearSelectionMode; } /** * Parses the given header according to the current rules, may throw an exception if the header is not valid. * * @param header the header to check * @return parsed data, contain the successfully parsed variables, and the error if parsing failed */ public @NotNull ParsedData parseHeader(@NotNull List<String> header) { var variableValues = new HashMap<String, Object>(); var presentOptionalLines = new HashSet<Integer>(); int headerLineIndex = 0, ruleLineIndex = 0; for (; headerLineIndex < header.size(); headerLineIndex++) { String headerLine = header.get(headerLineIndex); if (ruleLineIndex >= this.lines.size()) { return new ParsedData(variableValues, presentOptionalLines, new HeaderParseException(headerLineIndex, "There is unexpected extra header lines.")); } HeaderLine ruleLine = this.lines.get(ruleLineIndex); String error; while ((error = this.parseLine(headerLine, ruleLine, variableValues)) != null) { if (ruleLine.optional()) { // If the line is optional, attempts to check the next line. ruleLine = this.lines.get(++ruleLineIndex); } else { return new ParsedData(variableValues, presentOptionalLines, new HeaderParseException(headerLineIndex, error)); } } if (ruleLine.optional()) { presentOptionalLines.add(ruleLineIndex); } ruleLineIndex++; } return new ParsedData(variableValues, presentOptionalLines, null); } private @Nullable String parseLine( @NotNull String headerLine, @NotNull HeaderLine currentLine, @NotNull Map<String, Object> variablesMap ) { int currentIndex = 0; for (var token : currentLine.tokens()) { if (token instanceof TextToken textToken) { String text = textToken.content(); int theoreticalEnd = currentIndex + text.length(); if (theoreticalEnd > headerLine.length()) { return "Header is cut short, stopped at " + headerLine.length() + " instead of " + theoreticalEnd + "."; } String toCheck = headerLine.substring(currentIndex, theoreticalEnd); if (!text.equals(toCheck)) { return "Text differs at " + currentIndex + ", got \"" + toCheck + "\", expected \"" + text + "\"."; } currentIndex = currentIndex + text.length(); } else if (token instanceof VarToken varToken) { var type = this.variables.get(varToken.variable()); var result = type.parseVar(headerLine, currentIndex); if (result.isEmpty()) { return "Failed to parse variable \"" + varToken.variable() + "\" at " + currentIndex + "."; } var old = variablesMap.put(varToken.variable(), result.get().data()); if (old != null && !old.equals(result.get().data())) { return "Diverging variable values for \"" + varToken.variable() + "\"."; } currentIndex = result.get().end(); } } return null; } /** * Applies this header rule to the provided parsed data to create a valid up-to-date header comment. * * @param data the data parsed by attempting to read the header comment * @param context the context of the file to update * @return the updated header comment */ @SuppressWarnings({"rawtypes", "unchecked"}) public @NotNull List<String> apply(@NotNull ParsedData data, @NotNull HeaderFileContext context) { var result = new ArrayList<String>(); for (int i = 0; i < this.lines.size(); i++) { var line = this.lines.get(i); if (!line.optional() || data.presentOptionalLines.contains(i)) { var builder = new StringBuilder(); for (var token : line.tokens()) { if (token instanceof TextToken textToken) { builder.append(textToken.content()); } else if (token instanceof VarToken varToken) { var type = (VariableType) this.variables.get(varToken.variable()); var previous = data.variables.get(varToken.variable()); var newValue = type.getUpToDate(context, previous); builder.append(type.getAsString(newValue)); } } result.add(builder.toString()); } }
Utils.trimLines(result, String::isEmpty);
2
2023-10-08 20:51:43+00:00
4k
5152Alotobots/2024_Crescendo_Preseason
src/main/java/frc/robot/library/gyroscopes/pigeon2/SubSys_PigeonGyro.java
[ { "identifier": "Constants", "path": "src/main/java/frc/robot/Constants.java", "snippet": "public final class Constants {\n public static final class Robot {\n\n public static final class Calibrations {\n\n public static final class DriveTrain {\n public static final double PerfModeTrans...
import com.ctre.phoenix.sensors.Pigeon2; import edu.wpi.first.math.geometry.Rotation2d; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import edu.wpi.first.wpilibj2.command.SubsystemBase; import frc.robot.Constants; import frc.robot.library.gyroscopes.navx.SubSys_NavXGyro_Constants;
3,167
/*----------------------------------------------------------------------------*/ /* Copyright (c) 2019 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ package frc.robot.library.gyroscopes.pigeon2; public class SubSys_PigeonGyro extends SubsystemBase { /** Creates a new NavXGyro. */ private Pigeon2 pigeon2Gyro; private double gyroOffsetDegrees; public SubSys_PigeonGyro() { this.pigeon2Gyro = new Pigeon2(Constants.CAN_IDs.Pigeon2_ID); this.gyroOffsetDegrees = 0.0; // m_Pigeon2Gyro.setYaw(0); } @Override public void periodic() { // This method will be called once per scheduler run // Display SmartDashboard.putNumber("Pigeon_getRawYaw", getRawYaw()); SmartDashboard.putNumber("Pigeon_getYaw", getYaw()); SmartDashboard.putNumber("Pigeon_getYawRotation2d", getYawRotation2d().getDegrees()); // SmartDashboard.putNumber("GyroCompass", m_Pigeon2Gyro.getCompassHeading()); } public double getRawGyroPitch() { return this.pigeon2Gyro.getPitch(); } public double getRawGyroRoll() { return this.pigeon2Gyro.getRoll(); } /** * Return Raw Gyro Angle * * @return Raw Angle double raw Gyro Angle */ public double getRawYaw() { return this.pigeon2Gyro.getYaw(); } public double getYaw() { return getRawYaw() - this.gyroOffsetDegrees; } /** * Return Gyro Angle in Degrees * * @return Gyro Angle double Degrees */ public double getYawAngle() { return Math.IEEEremainder(getYaw(), 360)
/*----------------------------------------------------------------------------*/ /* Copyright (c) 2019 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ package frc.robot.library.gyroscopes.pigeon2; public class SubSys_PigeonGyro extends SubsystemBase { /** Creates a new NavXGyro. */ private Pigeon2 pigeon2Gyro; private double gyroOffsetDegrees; public SubSys_PigeonGyro() { this.pigeon2Gyro = new Pigeon2(Constants.CAN_IDs.Pigeon2_ID); this.gyroOffsetDegrees = 0.0; // m_Pigeon2Gyro.setYaw(0); } @Override public void periodic() { // This method will be called once per scheduler run // Display SmartDashboard.putNumber("Pigeon_getRawYaw", getRawYaw()); SmartDashboard.putNumber("Pigeon_getYaw", getYaw()); SmartDashboard.putNumber("Pigeon_getYawRotation2d", getYawRotation2d().getDegrees()); // SmartDashboard.putNumber("GyroCompass", m_Pigeon2Gyro.getCompassHeading()); } public double getRawGyroPitch() { return this.pigeon2Gyro.getPitch(); } public double getRawGyroRoll() { return this.pigeon2Gyro.getRoll(); } /** * Return Raw Gyro Angle * * @return Raw Angle double raw Gyro Angle */ public double getRawYaw() { return this.pigeon2Gyro.getYaw(); } public double getYaw() { return getRawYaw() - this.gyroOffsetDegrees; } /** * Return Gyro Angle in Degrees * * @return Gyro Angle double Degrees */ public double getYawAngle() { return Math.IEEEremainder(getYaw(), 360)
* (SubSys_NavXGyro_Constants.GyroReversed ? -1.0 : 1.0);
1
2023-10-09 00:27:11+00:00
4k
nexus3a/monitor-remote-agent
src/main/java/com/monitor/parser/LogParser.java
[ { "identifier": "FileState", "path": "src/main/java/com/monitor/agent/server/FileState.java", "snippet": "public class FileState {\n\n @JsonIgnore\n private File file;\n private String directory;\n private String fileName;\n @JsonIgnore\n private long lastModified;\n @JsonIgnore\n ...
import com.monitor.agent.server.FileState; import com.monitor.agent.server.filter.Filter; import com.monitor.parser.reader.ParserRecordsStorage; import java.io.IOException;
2,810
package com.monitor.parser; /* * Copyright 2021 Aleksei Andreev * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ public interface LogParser { public void parse(FileState state, String encoding, long fromPosition, int maxRecords, Filter filter, ParserParameters parameters) throws IOException, ParseException;
package com.monitor.parser; /* * Copyright 2021 Aleksei Andreev * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ public interface LogParser { public void parse(FileState state, String encoding, long fromPosition, int maxRecords, Filter filter, ParserParameters parameters) throws IOException, ParseException;
public void setRecordsStorage(ParserRecordsStorage storage);
2
2023-10-11 20:25:12+00:00
4k
mhaupt/basicode
src/test/java/de/haupz/basicode/DimTest.java
[ { "identifier": "ArrayType", "path": "src/main/java/de/haupz/basicode/array/ArrayType.java", "snippet": "public enum ArrayType {\n NUMBER,\n STRING;\n}" }, { "identifier": "BasicArray", "path": "src/main/java/de/haupz/basicode/array/BasicArray.java", "snippet": "public abstract cla...
import de.haupz.basicode.array.ArrayType; import de.haupz.basicode.array.BasicArray; import de.haupz.basicode.array.BasicArray1D; import de.haupz.basicode.array.BasicArray2D; import org.junit.jupiter.api.Test; import java.util.List; import java.util.Optional; import static org.junit.jupiter.api.Assertions.*;
2,311
package de.haupz.basicode; public class DimTest extends StatementTest { @Test public void test1DNonString() { run("DIM A(7)"); Optional<BasicArray> v = state.getArray("A"); assertTrue(v.isPresent());
package de.haupz.basicode; public class DimTest extends StatementTest { @Test public void test1DNonString() { run("DIM A(7)"); Optional<BasicArray> v = state.getArray("A"); assertTrue(v.isPresent());
assertEquals(BasicArray1D.class, v.get().getClass());
2
2023-10-14 12:20:59+00:00
4k
Thenuka22/BakerySalesnOrdering_System
BakeryPosSystem/src/bakerypossystem/View/PanelLoginAndRegister.java
[ { "identifier": "Button", "path": "BakeryPosSystem/src/CustomComponents/Button.java", "snippet": "public class Button extends JButton {\n\n public Color getEffectColor() {\n return effectColor;\n }\n\n public void setEffectColor(Color effectColor) {\n this.effectColor = effectColo...
import CustomComponents.Button; import CustomComponents.MyPasswordField; import CustomComponents.MyTextField; import java.awt.Color; import java.awt.Cursor; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; import bakerypossystem.Controller.CUserSignIn; import net.miginfocom.swing.MigLayout;
3,459
package bakerypossystem.View; public class PanelLoginAndRegister extends javax.swing.JLayeredPane { public PanelLoginAndRegister() { initComponents(); initRegister(); initLogin(); login.setVisible(false); register.setVisible(true); } private void initRegister() { register.setLayout(new MigLayout("wrap", "push[center]push", "push[]25[]10[]10[]25[]push")); JLabel label = new JLabel("Customer Login"); label.setFont(new Font("sansserif", 1, 30)); label.setForeground(new Color(7, 164, 121)); register.add(label); MyTextField txtUser = new MyTextField(); txtUser.setPrefixIcon(new ImageIcon(getClass().getResource("/icon/user_1.png"))); txtUser.setHint("Username"); register.add(txtUser, "w 60%"); MyPasswordField txtPass = new MyPasswordField(); txtPass.setPrefixIcon(new ImageIcon(getClass().getResource("/icon/pass.png"))); txtPass.setHint("Password"); register.add(txtPass, "w 60%"); Button cmd = new Button(); cmd.setBackground(new Color(7, 164, 121)); cmd.setForeground(new Color(250, 250, 250)); cmd.setText("Log in"); register.add(cmd, "w 40%, h 40"); JLabel label1 = new JLabel("Use Guest Account Instead"); label1.setFont(new Font("sansserif", 1, 20)); label1.setForeground(new Color(7, 164, 121)); register.add(label1); // Add an ActionListener to cmd1 button label1.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { openAnotherFrame(); JFrame frame = (JFrame) SwingUtilities.getWindowAncestor(PanelLoginAndRegister.this); frame.dispose(); } @Override public void mouseEntered(MouseEvent e){ label1.setCursor(new Cursor(Cursor.HAND_CURSOR)); } }); cmd.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String username = txtUser.getText(); String password = txtPass.getText(); CustomerView DashBoardCustomize = new CustomerView(); //CUserSignIn nn = new CUserSignIn(); if(username.equals("Thenuka" )&& password.equals("1234")) { DashBoardCustomize.show(); } else JOptionPane.showMessageDialog(null, "Sign In Unsuccessful.", "ERROR", JOptionPane.ERROR_MESSAGE); } }); } private void openAnotherFrame() { // Create and open another frame here CustomerView anotherFrame = new CustomerView(); // Add components, set properties, and customize the new frame as needed anotherFrame.setVisible(true); } private void initLogin() { login.setLayout(new MigLayout("wrap", "push[center]push", "push[]25[]10[]10[]25[]push")); JLabel label = new JLabel("Bakery Staff Login"); label.setFont(new Font("sansserif", 1, 30)); label.setForeground(new Color(7, 164, 121)); login.add(label); MyTextField txtEmail = new MyTextField(); txtEmail.setPrefixIcon(new ImageIcon(getClass().getResource("/icon/mail.png"))); txtEmail.setHint("Email"); login.add(txtEmail, "w 60%"); MyPasswordField txtPass = new MyPasswordField(); txtPass.setPrefixIcon(new ImageIcon(getClass().getResource("/icon/pass.png"))); txtPass.setHint("Password"); login.add(txtPass, "w 60%"); JButton cmdForget = new JButton("Forgot your password ?"); cmdForget.setForeground(new Color(100, 100, 100)); cmdForget.setFont(new Font("sansserif", 1, 12)); cmdForget.setContentAreaFilled(false); cmdForget.setCursor(new Cursor(Cursor.HAND_CURSOR)); login.add(cmdForget); Button cmd = new Button(); cmd.setBackground(new Color(7, 164, 121)); cmd.setForeground(new Color(250, 250, 250)); cmd.setText("Login"); login.add(cmd, "w 40%, h 40"); cmd.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String username = txtEmail.getText(); String password = txtPass.getText(); DashBoardCustomize DashBoardCustomize = new DashBoardCustomize();
package bakerypossystem.View; public class PanelLoginAndRegister extends javax.swing.JLayeredPane { public PanelLoginAndRegister() { initComponents(); initRegister(); initLogin(); login.setVisible(false); register.setVisible(true); } private void initRegister() { register.setLayout(new MigLayout("wrap", "push[center]push", "push[]25[]10[]10[]25[]push")); JLabel label = new JLabel("Customer Login"); label.setFont(new Font("sansserif", 1, 30)); label.setForeground(new Color(7, 164, 121)); register.add(label); MyTextField txtUser = new MyTextField(); txtUser.setPrefixIcon(new ImageIcon(getClass().getResource("/icon/user_1.png"))); txtUser.setHint("Username"); register.add(txtUser, "w 60%"); MyPasswordField txtPass = new MyPasswordField(); txtPass.setPrefixIcon(new ImageIcon(getClass().getResource("/icon/pass.png"))); txtPass.setHint("Password"); register.add(txtPass, "w 60%"); Button cmd = new Button(); cmd.setBackground(new Color(7, 164, 121)); cmd.setForeground(new Color(250, 250, 250)); cmd.setText("Log in"); register.add(cmd, "w 40%, h 40"); JLabel label1 = new JLabel("Use Guest Account Instead"); label1.setFont(new Font("sansserif", 1, 20)); label1.setForeground(new Color(7, 164, 121)); register.add(label1); // Add an ActionListener to cmd1 button label1.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { openAnotherFrame(); JFrame frame = (JFrame) SwingUtilities.getWindowAncestor(PanelLoginAndRegister.this); frame.dispose(); } @Override public void mouseEntered(MouseEvent e){ label1.setCursor(new Cursor(Cursor.HAND_CURSOR)); } }); cmd.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String username = txtUser.getText(); String password = txtPass.getText(); CustomerView DashBoardCustomize = new CustomerView(); //CUserSignIn nn = new CUserSignIn(); if(username.equals("Thenuka" )&& password.equals("1234")) { DashBoardCustomize.show(); } else JOptionPane.showMessageDialog(null, "Sign In Unsuccessful.", "ERROR", JOptionPane.ERROR_MESSAGE); } }); } private void openAnotherFrame() { // Create and open another frame here CustomerView anotherFrame = new CustomerView(); // Add components, set properties, and customize the new frame as needed anotherFrame.setVisible(true); } private void initLogin() { login.setLayout(new MigLayout("wrap", "push[center]push", "push[]25[]10[]10[]25[]push")); JLabel label = new JLabel("Bakery Staff Login"); label.setFont(new Font("sansserif", 1, 30)); label.setForeground(new Color(7, 164, 121)); login.add(label); MyTextField txtEmail = new MyTextField(); txtEmail.setPrefixIcon(new ImageIcon(getClass().getResource("/icon/mail.png"))); txtEmail.setHint("Email"); login.add(txtEmail, "w 60%"); MyPasswordField txtPass = new MyPasswordField(); txtPass.setPrefixIcon(new ImageIcon(getClass().getResource("/icon/pass.png"))); txtPass.setHint("Password"); login.add(txtPass, "w 60%"); JButton cmdForget = new JButton("Forgot your password ?"); cmdForget.setForeground(new Color(100, 100, 100)); cmdForget.setFont(new Font("sansserif", 1, 12)); cmdForget.setContentAreaFilled(false); cmdForget.setCursor(new Cursor(Cursor.HAND_CURSOR)); login.add(cmdForget); Button cmd = new Button(); cmd.setBackground(new Color(7, 164, 121)); cmd.setForeground(new Color(250, 250, 250)); cmd.setText("Login"); login.add(cmd, "w 40%, h 40"); cmd.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String username = txtEmail.getText(); String password = txtPass.getText(); DashBoardCustomize DashBoardCustomize = new DashBoardCustomize();
CUserSignIn nn = new CUserSignIn();
3
2023-10-11 16:55:32+00:00
4k
giteecode/bookmanage2-public
nhXJH-system/src/main/java/com/nhXJH/system/service/ISysRoleService.java
[ { "identifier": "SysRole", "path": "nhXJH-common/src/main/java/com/nhXJH/common/core/domain/entity/SysRole.java", "snippet": "public class SysRole extends BaseEntity {\n private static final long serialVersionUID = 1L;\n\n /** 角色ID */\n @Excel(name = \"角色序号\", cellType = ColumnType.NUMERIC)\n ...
import java.util.List; import java.util.Set; import com.nhXJH.common.core.domain.entity.SysRole; import com.nhXJH.system.domain.SysUserRole;
2,586
package com.nhXJH.system.service; /** * 角色业务层 * * @author nhXJH */ public interface ISysRoleService { /** * 根据条件分页查询角色数据 * * @param role 角色信息 * @return 角色数据集合信息 */ public List<SysRole> selectRoleList(SysRole role); /** * 根据用户ID查询角色列表 * * @param userId 用户ID * @return 角色列表 */ public List<SysRole> selectRolesByUserId(Long userId); /** * 根据用户ID查询角色权限 * * @param userId 用户ID * @return 权限列表 */ public Set<String> selectRolePermissionByUserId(Long userId); /** * 查询所有角色 * * @return 角色列表 */ public List<SysRole> selectRoleAll(); /** * 根据用户ID获取角色选择框列表 * * @param userId 用户ID * @return 选中角色ID列表 */ public List<Long> selectRoleListByUserId(Long userId); /** * 通过角色ID查询角色 * * @param roleId 角色ID * @return 角色对象信息 */ public SysRole selectRoleById(Long roleId); /** * 校验角色名称是否唯一 * * @param role 角色信息 * @return 结果 */ public String checkRoleNameUnique(SysRole role); /** * 校验角色权限是否唯一 * * @param role 角色信息 * @return 结果 */ public String checkRoleKeyUnique(SysRole role); /** * 校验角色是否允许操作 * * @param role 角色信息 */ public void checkRoleAllowed(SysRole role); /** * 校验角色是否有数据权限 * * @param roleId 角色id */ public void checkRoleDataScope(Long roleId); /** * 通过角色ID查询角色使用数量 * * @param roleId 角色ID * @return 结果 */ public int countUserRoleByRoleId(Long roleId); /** * 新增保存角色信息 * * @param role 角色信息 * @return 结果 */ public int insertRole(SysRole role); /** * 修改保存角色信息 * * @param role 角色信息 * @return 结果 */ public int updateRole(SysRole role); /** * 修改角色状态 * * @param role 角色信息 * @return 结果 */ public int updateRoleStatus(SysRole role); /** * 修改数据权限信息 * * @param role 角色信息 * @return 结果 */ public int authDataScope(SysRole role); /** * 通过角色ID删除角色 * * @param roleId 角色ID * @return 结果 */ public int deleteRoleById(Long roleId); /** * 批量删除角色信息 * * @param roleIds 需要删除的角色ID * @return 结果 */ public int deleteRoleByIds(Long[] roleIds); /** * 取消授权用户角色 * * @param userRole 用户和角色关联信息 * @return 结果 */
package com.nhXJH.system.service; /** * 角色业务层 * * @author nhXJH */ public interface ISysRoleService { /** * 根据条件分页查询角色数据 * * @param role 角色信息 * @return 角色数据集合信息 */ public List<SysRole> selectRoleList(SysRole role); /** * 根据用户ID查询角色列表 * * @param userId 用户ID * @return 角色列表 */ public List<SysRole> selectRolesByUserId(Long userId); /** * 根据用户ID查询角色权限 * * @param userId 用户ID * @return 权限列表 */ public Set<String> selectRolePermissionByUserId(Long userId); /** * 查询所有角色 * * @return 角色列表 */ public List<SysRole> selectRoleAll(); /** * 根据用户ID获取角色选择框列表 * * @param userId 用户ID * @return 选中角色ID列表 */ public List<Long> selectRoleListByUserId(Long userId); /** * 通过角色ID查询角色 * * @param roleId 角色ID * @return 角色对象信息 */ public SysRole selectRoleById(Long roleId); /** * 校验角色名称是否唯一 * * @param role 角色信息 * @return 结果 */ public String checkRoleNameUnique(SysRole role); /** * 校验角色权限是否唯一 * * @param role 角色信息 * @return 结果 */ public String checkRoleKeyUnique(SysRole role); /** * 校验角色是否允许操作 * * @param role 角色信息 */ public void checkRoleAllowed(SysRole role); /** * 校验角色是否有数据权限 * * @param roleId 角色id */ public void checkRoleDataScope(Long roleId); /** * 通过角色ID查询角色使用数量 * * @param roleId 角色ID * @return 结果 */ public int countUserRoleByRoleId(Long roleId); /** * 新增保存角色信息 * * @param role 角色信息 * @return 结果 */ public int insertRole(SysRole role); /** * 修改保存角色信息 * * @param role 角色信息 * @return 结果 */ public int updateRole(SysRole role); /** * 修改角色状态 * * @param role 角色信息 * @return 结果 */ public int updateRoleStatus(SysRole role); /** * 修改数据权限信息 * * @param role 角色信息 * @return 结果 */ public int authDataScope(SysRole role); /** * 通过角色ID删除角色 * * @param roleId 角色ID * @return 结果 */ public int deleteRoleById(Long roleId); /** * 批量删除角色信息 * * @param roleIds 需要删除的角色ID * @return 结果 */ public int deleteRoleByIds(Long[] roleIds); /** * 取消授权用户角色 * * @param userRole 用户和角色关联信息 * @return 结果 */
public int deleteAuthUser(SysUserRole userRole);
1
2023-10-13 07:19:20+00:00
4k
M-D-Team/ait-fabric-1.20.1
src/main/java/mdteam/ait/tardis/console/BorealisConsole.java
[ { "identifier": "AITMod", "path": "src/main/java/mdteam/ait/AITMod.java", "snippet": "public class AITMod implements ModInitializer {\n public static final String MOD_ID = \"ait\";\n public static final Logger LOGGER = LoggerFactory.getLogger(\"ait\");\n public static final Boolean DEBUG = true...
import mdteam.ait.AITMod; import mdteam.ait.tardis.control.ControlTypes; import mdteam.ait.tardis.control.impl.*; import mdteam.ait.tardis.control.impl.pos.IncrementControl; import mdteam.ait.tardis.control.impl.pos.XControl; import mdteam.ait.tardis.control.impl.pos.YControl; import mdteam.ait.tardis.control.impl.pos.ZControl; import net.minecraft.entity.EntityDimensions; import net.minecraft.util.Identifier; import org.joml.Vector3f;
2,881
package mdteam.ait.tardis.console; public class BorealisConsole extends ConsoleSchema { public static final Identifier REFERENCE = new Identifier(AITMod.MOD_ID, "console/borealis");
package mdteam.ait.tardis.console; public class BorealisConsole extends ConsoleSchema { public static final Identifier REFERENCE = new Identifier(AITMod.MOD_ID, "console/borealis");
private static final ControlTypes[] TYPES = new ControlTypes[] {
1
2023-10-08 00:38:53+00:00
4k
jianjian3219/044_bookmanage2-public
nhXJH-framework/src/main/java/com/nhXJH/framework/config/DruidConfig.java
[ { "identifier": "DataSourceType", "path": "nhXJH-common/src/main/java/com/nhXJH/common/enums/DataSourceType.java", "snippet": "public enum DataSourceType {\n /**\n * 主库\n */\n MASTER,\n\n /**\n * 从库\n */\n SLAVE\n}" }, { "identifier": "SpringUtils", "path": "nhXJH...
import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.sql.DataSource; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import com.alibaba.druid.pool.DruidDataSource; import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder; import com.alibaba.druid.spring.boot.autoconfigure.properties.DruidStatProperties; import com.alibaba.druid.util.Utils; import com.nhXJH.common.enums.DataSourceType; import com.nhXJH.common.utils.spring.SpringUtils; import com.nhXJH.framework.config.properties.DruidProperties; import com.nhXJH.framework.datasource.DynamicDataSource;
2,312
package com.nhXJH.framework.config; /** * druid 配置多数据源 * * @author nhXJH */ @Configuration public class DruidConfig { @Bean @ConfigurationProperties("spring.datasource.druid.master") public DataSource masterDataSource(DruidProperties druidProperties) { DruidDataSource dataSource = DruidDataSourceBuilder.create().build(); return druidProperties.dataSource(dataSource); } @Bean @ConfigurationProperties("spring.datasource.druid.slave") @ConditionalOnProperty(prefix = "spring.datasource.druid.slave", name = "enabled", havingValue = "true") public DataSource slaveDataSource(DruidProperties druidProperties) { DruidDataSource dataSource = DruidDataSourceBuilder.create().build(); return druidProperties.dataSource(dataSource); } @Bean(name = "dynamicDataSource") @Primary public DynamicDataSource dataSource(DataSource masterDataSource) { Map<Object, Object> targetDataSources = new HashMap<>();
package com.nhXJH.framework.config; /** * druid 配置多数据源 * * @author nhXJH */ @Configuration public class DruidConfig { @Bean @ConfigurationProperties("spring.datasource.druid.master") public DataSource masterDataSource(DruidProperties druidProperties) { DruidDataSource dataSource = DruidDataSourceBuilder.create().build(); return druidProperties.dataSource(dataSource); } @Bean @ConfigurationProperties("spring.datasource.druid.slave") @ConditionalOnProperty(prefix = "spring.datasource.druid.slave", name = "enabled", havingValue = "true") public DataSource slaveDataSource(DruidProperties druidProperties) { DruidDataSource dataSource = DruidDataSourceBuilder.create().build(); return druidProperties.dataSource(dataSource); } @Bean(name = "dynamicDataSource") @Primary public DynamicDataSource dataSource(DataSource masterDataSource) { Map<Object, Object> targetDataSources = new HashMap<>();
targetDataSources.put(DataSourceType.MASTER.name(), masterDataSource);
0
2023-10-14 04:57:42+00:00
4k
aleksandarsusnjar/paniql
commandline/src/test/java/net/susnjar/paniql/commandline/PaniqlMainTest.java
[ { "identifier": "CoreResourceDrivenTest", "path": "core/src/test/java/net/susnjar/paniql/CoreResourceDrivenTest.java", "snippet": "public abstract class CoreResourceDrivenTest extends ResourceDrivenTest {\n @Override\n public String getResourcePath() {\n return ResourceDrivenTest.getResourc...
import com.google.common.io.CharStreams; import graphql.schema.idl.TypeDefinitionRegistry; import io.github.classgraph.Resource; import net.susnjar.paniql.CoreResourceDrivenTest; import net.susnjar.paniql.Environment; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.DynamicTest; import org.junit.jupiter.api.TestFactory; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.Collection;
2,199
package net.susnjar.paniql.commandline; public class PaniqlMainTest extends CoreResourceDrivenTest { private TypeDefinitionRegistry typeReg;
package net.susnjar.paniql.commandline; public class PaniqlMainTest extends CoreResourceDrivenTest { private TypeDefinitionRegistry typeReg;
private Environment environment;
1
2023-10-10 01:58:56+00:00
4k
quan100/quan
quan-app/quan-app-core/src/main/java/cn/javaquan/app/core/base/controller/BaseConfigController.java
[ { "identifier": "PageResult", "path": "quan-common-utils/quan-base-common/src/main/java/cn/javaquan/common/base/message/PageResult.java", "snippet": "@Data\npublic class PageResult<T> implements Serializable {\n private static final long serialVersionUID = -6090269741449990770L;\n\n // 分页参数\n /...
import cn.javaquan.common.base.message.PageResult; import cn.javaquan.app.common.module.base.BaseConfigAddCommand; import cn.javaquan.app.common.module.base.BaseConfigQuery; import cn.javaquan.app.common.module.base.BaseConfigUpdateCommand; import cn.javaquan.common.base.message.Result; import cn.javaquan.app.core.base.convert.BaseConfigAssembler; import cn.javaquan.app.core.base.entity.BaseConfigPO; import cn.javaquan.app.core.base.repository.BaseConfigRepository; import lombok.RequiredArgsConstructor; import org.springframework.web.bind.annotation.*; import java.util.List;
2,571
package cn.javaquan.app.core.base.controller; /** * 系统通用配置 * * @author JavaQuan * @version 1.0.0 * @date 2023-04-04 10:38:39 */ @RequiredArgsConstructor @RestController @RequestMapping("/core/base/config/") public class BaseConfigController { private final BaseConfigRepository baseConfigRepository; /** * 查询列表 * * @param query * @return */ @GetMapping("page") public Result<PageResult> page(BaseConfigQuery query) {
package cn.javaquan.app.core.base.controller; /** * 系统通用配置 * * @author JavaQuan * @version 1.0.0 * @date 2023-04-04 10:38:39 */ @RequiredArgsConstructor @RestController @RequestMapping("/core/base/config/") public class BaseConfigController { private final BaseConfigRepository baseConfigRepository; /** * 查询列表 * * @param query * @return */ @GetMapping("page") public Result<PageResult> page(BaseConfigQuery query) {
BaseConfigPO po = BaseConfigAssembler.INSTANCE.toQueryPO(query);
5
2023-10-08 06:48:41+00:00
4k
Ghost-chu/DoDoSRV
src/main/java/com/ghostchu/plugins/dodosrv/command/bukkit/subcommand/SubCommand_Help.java
[ { "identifier": "DoDoSRV", "path": "src/main/java/com/ghostchu/plugins/dodosrv/DoDoSRV.java", "snippet": "public final class DoDoSRV extends JavaPlugin {\n\n private DodoBot bot;\n private DatabaseManager databaseManager;\n private UserBindManager userBindManager;\n private TextManager textM...
import com.ghostchu.plugins.dodosrv.DoDoSRV; import com.ghostchu.plugins.dodosrv.command.bukkit.CommandContainer; import com.ghostchu.plugins.dodosrv.command.bukkit.CommandHandler; import lombok.AllArgsConstructor; import org.bukkit.command.CommandSender; import org.jetbrains.annotations.NotNull; import java.util.List;
2,167
package com.ghostchu.plugins.dodosrv.command.bukkit.subcommand; @AllArgsConstructor public class SubCommand_Help implements CommandHandler<CommandSender> {
package com.ghostchu.plugins.dodosrv.command.bukkit.subcommand; @AllArgsConstructor public class SubCommand_Help implements CommandHandler<CommandSender> {
private final DoDoSRV plugin;
0
2023-10-11 16:16:54+00:00
4k
Hartie95/AnimeGamesLua
GILua/src/main/java/org/anime_game_servers/gi_lua/models/scene/SceneMeta.java
[ { "identifier": "SceneBlock", "path": "GILua/src/main/java/org/anime_game_servers/gi_lua/models/scene/block/SceneBlock.java", "snippet": "@ToString\n@Getter\npublic class SceneBlock {\n private static KLogger logger = KotlinLogging.INSTANCE.logger(SceneBlock.class.getName());\n\n private PositionI...
import io.github.oshai.kotlinlogging.KLogger; import io.github.oshai.kotlinlogging.KotlinLogging; import lombok.Getter; import lombok.ToString; import lombok.val; import org.anime_game_servers.gi_lua.models.loader.SceneDummyPointScriptLoadParams; import org.anime_game_servers.gi_lua.models.loader.SceneMetaScriptLoadParams; import org.anime_game_servers.gi_lua.models.scene.block.SceneBlock; import org.anime_game_servers.gi_lua.models.scene.block.SceneGroupInfo; import org.anime_game_servers.gi_lua.models.scene.group.SceneGroup; import org.anime_game_servers.gi_lua.models.loader.GIScriptLoader; import org.anime_game_servers.lua.engine.LuaScript; import javax.annotation.Nullable; import java.util.HashMap; import java.util.List; import java.util.Map;
3,382
package org.anime_game_servers.gi_lua.models.scene; @ToString @Getter public class SceneMeta { private static KLogger logger = KotlinLogging.INSTANCE.logger(SceneMeta.class.getName()); private int sceneId; private SceneConfig config; private List<Integer> blockIds; private Map<Integer, ActivityMeta> activities = new HashMap<>();
package org.anime_game_servers.gi_lua.models.scene; @ToString @Getter public class SceneMeta { private static KLogger logger = KotlinLogging.INSTANCE.logger(SceneMeta.class.getName()); private int sceneId; private SceneConfig config; private List<Integer> blockIds; private Map<Integer, ActivityMeta> activities = new HashMap<>();
private Map<Integer, SceneBlock> blocks;
0
2023-10-07 16:45:54+00:00
4k
PDC2023/project
src/main/java/pdc/project/entity/Ghost.java
[ { "identifier": "Universe", "path": "src/main/java/pdc/project/Universe.java", "snippet": "public final class Universe {\r\n\r\n public Player player = new Player(this, 0, 0);\r\n private int score = 0;\r\n public final Main main;\r\n\r\n public Set<Entity> entities = new HashSet<>();\r\n ...
import pdc.project.Universe; import pdc.project.Utils;
2,574
package pdc.project.entity; public class Ghost extends AbstractMovingEntity implements Enemy { private final static double SIZE_RATIO = 1.0; private final static double SPEED = 1; private final int xEnd; private final int xStart;
package pdc.project.entity; public class Ghost extends AbstractMovingEntity implements Enemy { private final static double SIZE_RATIO = 1.0; private final static double SPEED = 1; private final int xEnd; private final int xStart;
public Ghost(int xStart, int xEnd, Universe universe, int y) {
0
2023-10-09 03:01:39+00:00
4k
jmaes12345/lhasa-kata
examples/java1/src/main/java/org/katas/Assess.java
[ { "identifier": "catToOutputDir", "path": "examples/java1/src/main/java/org/katas/AssessUtils.java", "snippet": "public static String catToOutputDir(String category) {\n\tswitch (category) {\n\t\tcase \"I\":\n\t\t\treturn CAT1_DIR;\n\t\tcase \"II\":\n\t\t\treturn CAT2_DIR;\n\t\tcase \"III\":\n\t\t\tretu...
import static org.katas.AssessUtils.catToOutputDir; import static org.katas.AssessUtils.countFiles; import static org.katas.AssessUtils.foundInFiles; import static org.katas.AssessUtils.getTestCases; import static org.katas.SvgLocations.OUTPUT_DIRS_ALL; import static org.katas.SvgLocations.CAT1_DIR; import static org.katas.SvgLocations.CAT2_DIR; import static org.katas.SvgLocations.CAT3_DIR; import static org.katas.SvgLocations.INPUT_DIR; import static org.katas.SvgLocations.ROOT_DIR; import static org.katas.SvgLocations.UNCLASSIFIED_DIR; import java.io.File;
1,797
package org.katas; public class Assess { public static void main(String[] args) { String rootDir = args.length > 0 ? args[0] : null; if ("help".equals(rootDir) || "h".equals(rootDir) || "--help".equals(rootDir)) { System.out.println(""" Run using Java 17 To run summary test using default folders (C:/kata-svg), pass no arguments. To run summary test using custom folder, pass absolute path as first argument: java -jar svg-1.0-SNAPSHOT.jar C:/Test/svgClassificationFiles To run detailed test using default folders (C:/kata-svg): java -jar svg-1.0-SNAPSHOT.jar " " detail To run detailed test using custom folders: java -jar svg-1.0-SNAPSHOT.jar "C:/Test/kata files" detail """); rootDir = null; } var workingDir = rootDir != null && !rootDir.isBlank() ? rootDir : ROOT_DIR; System.out.println("Using 'input' and 'output' folders in parent directory: " + workingDir); String detailLevel = args.length > 1 ? args[1] : null; var summaryOnly = "summary".equalsIgnoreCase(detailLevel) || "s".equalsIgnoreCase(detailLevel); var detailMessage = summaryOnly ? "Running summary test..." : "Running summary and detailed test..."; System.out.println(detailMessage); var inputLocation = INPUT_DIR; if (rootDir != null && !rootDir.isBlank()) { inputLocation = rootDir + "/" + inputLocation.substring(inputLocation.indexOf("input")); } System.out.println("Reading from 'input' directory: " + inputLocation); var testCases = getTestCases(inputLocation); int expectedCat1 = testCases.stream().filter(tc -> "I".equals(tc.get(1))).toList().size(); int expectedCat2 = testCases.stream().filter(tc -> "II".equals(tc.get(1))).toList().size(); int expectedCat3 = testCases.stream().filter(tc -> "III".equals(tc.get(1))).toList().size(); int expectedUnclassified = testCases.stream().filter(tc -> "unclassified".equals(tc.get(1))).toList().size(); int foundCat1 = countFiles(CAT1_DIR, rootDir); int foundCat2 = countFiles(CAT2_DIR, rootDir); int foundCat3 = countFiles(CAT3_DIR, rootDir); int foundUnclassified = countFiles(UNCLASSIFIED_DIR, rootDir); boolean allCorrect = expectedCat1 == foundCat1 && expectedCat2 == foundCat2 && expectedCat3 == foundCat3 && expectedUnclassified == foundUnclassified; String message = allCorrect ? "/*** Great news, you have the correct number of files in each bucket! ***/" : "/*** Close but no carcinogenic dried leaf roll... ***/"; System.out.printf(""" %s Cat1 expected %d, found %d Cat2 expected %d, found %d Cat3 expected %d, found %d Unclassified expected %d, found %d """, message, expectedCat1, foundCat1, expectedCat2, foundCat2, expectedCat3, foundCat3, expectedUnclassified, foundUnclassified); System.out.println("\nRunning detailed tests..."); testCases.forEach(tc -> detailTest(tc.get(0), tc.get(1))); } private static void detailTest(String svgFileName, String expectedCategory) { var outputDir = catToOutputDir(expectedCategory); var contents = new File(outputDir).listFiles((dir, name) -> name.toLowerCase().endsWith(".svg")); if (foundInFiles(contents, svgFileName)) { System.out.printf("SUCCESS: '%s' found in correct category: %s, dir: '%s'%n", svgFileName, expectedCategory, outputDir); } else { System.out.printf("FAILURE: '%s' not found in correct category: %s, dir: '%s'%n", svgFileName, expectedCategory, outputDir); }
package org.katas; public class Assess { public static void main(String[] args) { String rootDir = args.length > 0 ? args[0] : null; if ("help".equals(rootDir) || "h".equals(rootDir) || "--help".equals(rootDir)) { System.out.println(""" Run using Java 17 To run summary test using default folders (C:/kata-svg), pass no arguments. To run summary test using custom folder, pass absolute path as first argument: java -jar svg-1.0-SNAPSHOT.jar C:/Test/svgClassificationFiles To run detailed test using default folders (C:/kata-svg): java -jar svg-1.0-SNAPSHOT.jar " " detail To run detailed test using custom folders: java -jar svg-1.0-SNAPSHOT.jar "C:/Test/kata files" detail """); rootDir = null; } var workingDir = rootDir != null && !rootDir.isBlank() ? rootDir : ROOT_DIR; System.out.println("Using 'input' and 'output' folders in parent directory: " + workingDir); String detailLevel = args.length > 1 ? args[1] : null; var summaryOnly = "summary".equalsIgnoreCase(detailLevel) || "s".equalsIgnoreCase(detailLevel); var detailMessage = summaryOnly ? "Running summary test..." : "Running summary and detailed test..."; System.out.println(detailMessage); var inputLocation = INPUT_DIR; if (rootDir != null && !rootDir.isBlank()) { inputLocation = rootDir + "/" + inputLocation.substring(inputLocation.indexOf("input")); } System.out.println("Reading from 'input' directory: " + inputLocation); var testCases = getTestCases(inputLocation); int expectedCat1 = testCases.stream().filter(tc -> "I".equals(tc.get(1))).toList().size(); int expectedCat2 = testCases.stream().filter(tc -> "II".equals(tc.get(1))).toList().size(); int expectedCat3 = testCases.stream().filter(tc -> "III".equals(tc.get(1))).toList().size(); int expectedUnclassified = testCases.stream().filter(tc -> "unclassified".equals(tc.get(1))).toList().size(); int foundCat1 = countFiles(CAT1_DIR, rootDir); int foundCat2 = countFiles(CAT2_DIR, rootDir); int foundCat3 = countFiles(CAT3_DIR, rootDir); int foundUnclassified = countFiles(UNCLASSIFIED_DIR, rootDir); boolean allCorrect = expectedCat1 == foundCat1 && expectedCat2 == foundCat2 && expectedCat3 == foundCat3 && expectedUnclassified == foundUnclassified; String message = allCorrect ? "/*** Great news, you have the correct number of files in each bucket! ***/" : "/*** Close but no carcinogenic dried leaf roll... ***/"; System.out.printf(""" %s Cat1 expected %d, found %d Cat2 expected %d, found %d Cat3 expected %d, found %d Unclassified expected %d, found %d """, message, expectedCat1, foundCat1, expectedCat2, foundCat2, expectedCat3, foundCat3, expectedUnclassified, foundUnclassified); System.out.println("\nRunning detailed tests..."); testCases.forEach(tc -> detailTest(tc.get(0), tc.get(1))); } private static void detailTest(String svgFileName, String expectedCategory) { var outputDir = catToOutputDir(expectedCategory); var contents = new File(outputDir).listFiles((dir, name) -> name.toLowerCase().endsWith(".svg")); if (foundInFiles(contents, svgFileName)) { System.out.printf("SUCCESS: '%s' found in correct category: %s, dir: '%s'%n", svgFileName, expectedCategory, outputDir); } else { System.out.printf("FAILURE: '%s' not found in correct category: %s, dir: '%s'%n", svgFileName, expectedCategory, outputDir); }
var wrongDirsFileFoundIn = OUTPUT_DIRS_ALL.stream()
4
2023-10-07 21:45:39+00:00
4k
qmjy/mapbox-offline-server
src/main/java/io/github/qmjy/mapbox/controller/MapServerFontsController.java
[ { "identifier": "AppConfig", "path": "src/main/java/io/github/qmjy/mapbox/config/AppConfig.java", "snippet": "@Component\n@ConfigurationProperties\npublic class AppConfig {\n\n public static final String FILE_EXTENSION_NAME_MBTILES = \".mbtiles\";\n public static final String FILE_EXTENSION_NAME_T...
import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.util.Optional; import io.github.qmjy.mapbox.config.AppConfig; import io.github.qmjy.mapbox.model.FontsFileModel; import io.github.qmjy.mapbox.MapServerDataCenter; import io.swagger.v3.oas.annotations.tags.Tag; import org.apache.tomcat.util.http.fileupload.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.ByteArrayResource; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.util.FileCopyUtils; import org.springframework.web.bind.annotation.*;
2,808
/* * Copyright (c) 2023 QMJY. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.qmjy.mapbox.controller; /** * 支持的字体访问API。 */ @RestController @RequestMapping("/api/fonts") @Tag(name = "Mapbox字体服务管理", description = "Mapbox离线服务接口能力") public class MapServerFontsController { private final Logger logger = LoggerFactory.getLogger(MapServerFontsController.class); @Autowired private MapServerDataCenter mapServerDataCenter; @Autowired
/* * Copyright (c) 2023 QMJY. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.qmjy.mapbox.controller; /** * 支持的字体访问API。 */ @RestController @RequestMapping("/api/fonts") @Tag(name = "Mapbox字体服务管理", description = "Mapbox离线服务接口能力") public class MapServerFontsController { private final Logger logger = LoggerFactory.getLogger(MapServerFontsController.class); @Autowired private MapServerDataCenter mapServerDataCenter; @Autowired
private AppConfig appConfig;
0
2023-10-09 03:18:52+00:00
4k
codegrits/CodeGRITS
src/main/java/trackers/EyeTracker.java
[ { "identifier": "RelativePathGetter", "path": "src/main/java/utils/RelativePathGetter.java", "snippet": "public class RelativePathGetter {\n /**\n * Get the relative path of a file compared to the project path. If the project path is not a prefix of the file path, the absolute path of the file is...
import com.intellij.openapi.Disposable; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.LogicalPosition; import com.intellij.openapi.editor.event.VisibleAreaListener; import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.fileEditor.FileEditorManagerEvent; import com.intellij.openapi.fileEditor.FileEditorManagerListener; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import org.jetbrains.annotations.NotNull; import org.w3c.dom.Document; import org.w3c.dom.Element; import utils.RelativePathGetter; import utils.XMLWriter; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import java.awt.*; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.function.Consumer;
2,298
} /** * The listener for the visible area used for filtering the eye tracking data. */ VisibleAreaListener visibleAreaListener = e -> visibleArea = e.getNewRectangle(); /** * This method starts the eye tracking. * * @param project The project. * @throws IOException The exception. */ public void startTracking(Project project) throws IOException { isTracking = true; psiDocumentManager = PsiDocumentManager.getInstance(project); editor = FileEditorManager.getInstance(project).getSelectedTextEditor(); if (editor != null) { editor.getScrollingModel().addVisibleAreaListener(visibleAreaListener); visibleArea = editor.getScrollingModel().getVisibleArea(); } VirtualFile[] virtualFiles = FileEditorManager.getInstance(project).getSelectedFiles(); if (virtualFiles.length > 0) { filePath = virtualFiles[0].getPath(); } if (deviceIndex == 0) { setting.setAttribute("eye_tracker", "Mouse"); } else { setting.setAttribute("eye_tracker", "Tobii Pro Fusion"); } setting.setAttribute("sample_frequency", String.valueOf(sampleFrequency)); track(); } /** * This method stops the eye tracking. * * @throws TransformerException The exception. */ public void stopTracking() throws TransformerException { isTracking = false; pythonOutputThread.interrupt(); pythonProcess.destroy(); XMLWriter.writeToXML(eyeTracking, dataOutputPath + "/eye_tracking.xml"); } /** * This method pauses the eye tracking. The {@code isTracking} variable will be set to {@code false}. */ public void pauseTracking() { isTracking = false; } /** * This method resumes the eye tracking. The {@code isTracking} variable will be set to {@code true}. */ public void resumeTracking() { isTracking = true; } /** * This method processes the raw data message from the eye tracker. It will filter the data, map the data to the specific source code element, and perform the upward traversal in the AST. * * @param message The raw data. */ public void processRawData(String message) { if (!isTracking) return; Element gaze = getRawGazeElement(message); gazes.appendChild(gaze); String leftInfo = message.split("; ")[1]; String leftGazePointX = leftInfo.split(", ")[0]; String leftGazePointY = leftInfo.split(", ")[1]; String rightInfo = message.split("; ")[2]; String rightGazePointX = rightInfo.split(", ")[0]; String rightGazePointY = rightInfo.split(", ")[1]; if (leftGazePointX.equals("nan") || leftGazePointY.equals("nan") || rightGazePointX.equals("nan") || rightGazePointY.equals("nan")) { gaze.setAttribute("remark", "Fail | Invalid Gaze Point"); return; } if (editor == null) { gaze.setAttribute("remark", "Fail | No Editor"); return; } int eyeX = (int) ((Double.parseDouble(leftGazePointX) + Double.parseDouble(rightGazePointX)) / 2 * screenWidth); int eyeY = (int) ((Double.parseDouble(leftGazePointY) + Double.parseDouble(rightGazePointY)) / 2 * screenHeight); int editorX, editorY; try { editorX = editor.getContentComponent().getLocationOnScreen().x; editorY = editor.getContentComponent().getLocationOnScreen().y; } catch (IllegalComponentStateException e) { gaze.setAttribute("remark", "Fail | No Editor"); return; } int relativeX = eyeX - editorX; int relativeY = eyeY - editorY; if ((relativeX - visibleArea.x) < 0 || (relativeY - visibleArea.y) < 0 || (relativeX - visibleArea.x) > visibleArea.width || (relativeY - visibleArea.y) > visibleArea.height) { gaze.setAttribute("remark", "Fail | Out of Text Editor"); return; } Point relativePoint = new Point(relativeX, relativeY); EventQueue.invokeLater(new Thread(() -> { PsiFile psiFile = psiDocumentManager.getPsiFile(editor.getDocument()); LogicalPosition logicalPosition = editor.xyToLogicalPosition(relativePoint); if (psiFile != null) { int offset = editor.logicalPositionToOffset(logicalPosition); PsiElement psiElement = psiFile.findElementAt(offset); Element location = eyeTracking.createElement("location"); location.setAttribute("x", String.valueOf(eyeX)); location.setAttribute("y", String.valueOf(eyeY)); location.setAttribute("line", String.valueOf(logicalPosition.line)); location.setAttribute("column", String.valueOf(logicalPosition.column));
package trackers; /** * This class is the eye tracker. */ public class EyeTracker implements Disposable { String dataOutputPath = ""; /** * This variable indicates the sample frequency of the eye tracker. */ double sampleFrequency; PsiDocumentManager psiDocumentManager; public Editor editor; /** * This variable is the XML document for storing the eye tracking data. */ Document eyeTracking = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); Element root = eyeTracking.createElement("eye_tracking"); Element setting = eyeTracking.createElement("setting"); Element gazes = eyeTracking.createElement("gazes"); /** * This variable indicates whether the tracking is started. */ boolean isTracking = false; double screenWidth, screenHeight; String projectPath = "", filePath = ""; PsiElement lastElement = null; Rectangle visibleArea = null; Process pythonProcess; Thread pythonOutputThread; String pythonInterpreter = ""; String pythonScriptTobii; String pythonScriptMouse; int deviceIndex = 0; /** * This variable indicates whether the real-time data is transmitting. */ private static boolean isRealTimeDataTransmitting = false; /** * This variable is the handler for eye tracking data. */ private Consumer<Element> eyeTrackerDataHandler; /** * This is the default constructor. */ public EyeTracker() throws ParserConfigurationException { eyeTracking.appendChild(root); root.appendChild(setting); root.appendChild(gazes); Dimension size = Toolkit.getDefaultToolkit().getScreenSize(); screenWidth = size.getWidth(); screenHeight = size.getHeight(); ApplicationManager.getApplication().getMessageBus().connect(this).subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, new FileEditorManagerListener() { @Override public void fileOpened(@NotNull FileEditorManager source, @NotNull VirtualFile file) { editor = source.getSelectedTextEditor(); if (editor != null) { editor.getScrollingModel().addVisibleAreaListener(visibleAreaListener); } filePath = file.getPath(); visibleArea = editor.getScrollingModel().getVisibleArea(); } @Override public void selectionChanged(@NotNull FileEditorManagerEvent event) { editor = event.getManager().getSelectedTextEditor() != null ? event.getManager().getSelectedTextEditor() : editor; if (event.getNewFile() != null) { if (editor != null) { editor.getScrollingModel().addVisibleAreaListener(visibleAreaListener); } filePath = event.getNewFile().getPath(); visibleArea = editor.getScrollingModel().getVisibleArea(); } } }); } /** * This is the constructor for the eye tracker. * * @param pythonInterpreter The path of the Python interpreter. * @param sampleFrequency The sample frequency of the eye tracker. * @param isUsingMouse Whether the mouse is used as the eye tracker. */ public EyeTracker(String pythonInterpreter, double sampleFrequency, boolean isUsingMouse) throws ParserConfigurationException { // designed specifically for the real-time data API this(); // call default constructor if (isUsingMouse) { deviceIndex = 0; } else { deviceIndex = 1; } this.pythonInterpreter = pythonInterpreter; this.sampleFrequency = sampleFrequency; setPythonScriptMouse(); setPythonScriptTobii(); } /** * The listener for the visible area used for filtering the eye tracking data. */ VisibleAreaListener visibleAreaListener = e -> visibleArea = e.getNewRectangle(); /** * This method starts the eye tracking. * * @param project The project. * @throws IOException The exception. */ public void startTracking(Project project) throws IOException { isTracking = true; psiDocumentManager = PsiDocumentManager.getInstance(project); editor = FileEditorManager.getInstance(project).getSelectedTextEditor(); if (editor != null) { editor.getScrollingModel().addVisibleAreaListener(visibleAreaListener); visibleArea = editor.getScrollingModel().getVisibleArea(); } VirtualFile[] virtualFiles = FileEditorManager.getInstance(project).getSelectedFiles(); if (virtualFiles.length > 0) { filePath = virtualFiles[0].getPath(); } if (deviceIndex == 0) { setting.setAttribute("eye_tracker", "Mouse"); } else { setting.setAttribute("eye_tracker", "Tobii Pro Fusion"); } setting.setAttribute("sample_frequency", String.valueOf(sampleFrequency)); track(); } /** * This method stops the eye tracking. * * @throws TransformerException The exception. */ public void stopTracking() throws TransformerException { isTracking = false; pythonOutputThread.interrupt(); pythonProcess.destroy(); XMLWriter.writeToXML(eyeTracking, dataOutputPath + "/eye_tracking.xml"); } /** * This method pauses the eye tracking. The {@code isTracking} variable will be set to {@code false}. */ public void pauseTracking() { isTracking = false; } /** * This method resumes the eye tracking. The {@code isTracking} variable will be set to {@code true}. */ public void resumeTracking() { isTracking = true; } /** * This method processes the raw data message from the eye tracker. It will filter the data, map the data to the specific source code element, and perform the upward traversal in the AST. * * @param message The raw data. */ public void processRawData(String message) { if (!isTracking) return; Element gaze = getRawGazeElement(message); gazes.appendChild(gaze); String leftInfo = message.split("; ")[1]; String leftGazePointX = leftInfo.split(", ")[0]; String leftGazePointY = leftInfo.split(", ")[1]; String rightInfo = message.split("; ")[2]; String rightGazePointX = rightInfo.split(", ")[0]; String rightGazePointY = rightInfo.split(", ")[1]; if (leftGazePointX.equals("nan") || leftGazePointY.equals("nan") || rightGazePointX.equals("nan") || rightGazePointY.equals("nan")) { gaze.setAttribute("remark", "Fail | Invalid Gaze Point"); return; } if (editor == null) { gaze.setAttribute("remark", "Fail | No Editor"); return; } int eyeX = (int) ((Double.parseDouble(leftGazePointX) + Double.parseDouble(rightGazePointX)) / 2 * screenWidth); int eyeY = (int) ((Double.parseDouble(leftGazePointY) + Double.parseDouble(rightGazePointY)) / 2 * screenHeight); int editorX, editorY; try { editorX = editor.getContentComponent().getLocationOnScreen().x; editorY = editor.getContentComponent().getLocationOnScreen().y; } catch (IllegalComponentStateException e) { gaze.setAttribute("remark", "Fail | No Editor"); return; } int relativeX = eyeX - editorX; int relativeY = eyeY - editorY; if ((relativeX - visibleArea.x) < 0 || (relativeY - visibleArea.y) < 0 || (relativeX - visibleArea.x) > visibleArea.width || (relativeY - visibleArea.y) > visibleArea.height) { gaze.setAttribute("remark", "Fail | Out of Text Editor"); return; } Point relativePoint = new Point(relativeX, relativeY); EventQueue.invokeLater(new Thread(() -> { PsiFile psiFile = psiDocumentManager.getPsiFile(editor.getDocument()); LogicalPosition logicalPosition = editor.xyToLogicalPosition(relativePoint); if (psiFile != null) { int offset = editor.logicalPositionToOffset(logicalPosition); PsiElement psiElement = psiFile.findElementAt(offset); Element location = eyeTracking.createElement("location"); location.setAttribute("x", String.valueOf(eyeX)); location.setAttribute("y", String.valueOf(eyeY)); location.setAttribute("line", String.valueOf(logicalPosition.line)); location.setAttribute("column", String.valueOf(logicalPosition.column));
location.setAttribute("path", RelativePathGetter.getRelativePath(filePath, projectPath));
0
2023-10-12 15:40:39+00:00
4k
soya-miyoshi/amazon-s3-encryption-client-cli
src/test/java/com/github/soyamiyoshi/FileTransferTest.java
[ { "identifier": "CKmsKeyBasedClient", "path": "src/main/java/com/github/soyamiyoshi/client/kmskeybased/CKmsKeyBasedClient.java", "snippet": "public class CKmsKeyBasedClient extends AAutoClosableClient {\n\n protected String mKmsKeyID;\n\n public CKmsKeyBasedClient(final String kmsKeyId) {\n ...
import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import com.github.soyamiyoshi.client.kmskeybased.CKmsKeyBasedClient; import com.github.soyamiyoshi.client.rawkeybased.download.CDelayedAuthenticationDownloader; import com.github.soyamiyoshi.client.rawkeybased.upload.CBlockingUploader; import com.github.soyamiyoshi.util.keyprovider.CPrivateKeyProvider; import com.github.soyamiyoshi.util.keyprovider.CPublicKeyProvider; import static com.github.soyamiyoshi.testutils.EnvLoader.getEnvOrExit; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey;
2,006
package com.github.soyamiyoshi; public class FileTransferTest { private static String TEST_BUCKET_NAME; private static String TEST_OBJECT_KEY; private static Path TEST_LOCAL_FILE_PATH; private static KeyPair keyPair; @BeforeAll static void setUp() { TEST_BUCKET_NAME = getEnvOrExit("BUCKET_NAME"); TEST_OBJECT_KEY = getEnvOrExit("OBJECT_KEY"); TEST_LOCAL_FILE_PATH = Paths.get(getEnvOrExit("LOCAL_FILE_PATH")); try { keyPair = KeyPairGenerator.getInstance("RSA").generateKeyPair(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); // signal that test failed to initialize assert false; } } class CMockPublicKeyProvider extends CPublicKeyProvider { public CMockPublicKeyProvider() { super(null); } @Override public PublicKey getKey() { return FileTransferTest.keyPair.getPublic(); } } class CMockPrivateKeyProvider extends CPrivateKeyProvider { public CMockPrivateKeyProvider() { super(null); } @Override public PrivateKey getKey() { return FileTransferTest.keyPair.getPrivate(); } } @Test public void testFileTransfer() throws Exception { // Initialize the clients try (CBlockingUploader uploader = new CBlockingUploader((CPublicKeyProvider) new CMockPublicKeyProvider())) { uploader.upload(TEST_BUCKET_NAME, TEST_OBJECT_KEY, TEST_LOCAL_FILE_PATH); } catch (Exception e) { e.printStackTrace(); } ; try (CDelayedAuthenticationDownloader downloader = new CDelayedAuthenticationDownloader(new CMockPrivateKeyProvider())) { downloader.download(TEST_BUCKET_NAME, TEST_OBJECT_KEY); } catch (Exception e) { e.printStackTrace(); } ; // Compare the contents byte[] originalContent = Files.readAllBytes(TEST_LOCAL_FILE_PATH); byte[] downloadedContent = Files.readAllBytes(Paths.get(TEST_OBJECT_KEY)); assertArrayEquals(originalContent, downloadedContent, "The contents of the uploaded and downloaded files should be the same."); } @Test public void testFileTransferKms() throws Exception {
package com.github.soyamiyoshi; public class FileTransferTest { private static String TEST_BUCKET_NAME; private static String TEST_OBJECT_KEY; private static Path TEST_LOCAL_FILE_PATH; private static KeyPair keyPair; @BeforeAll static void setUp() { TEST_BUCKET_NAME = getEnvOrExit("BUCKET_NAME"); TEST_OBJECT_KEY = getEnvOrExit("OBJECT_KEY"); TEST_LOCAL_FILE_PATH = Paths.get(getEnvOrExit("LOCAL_FILE_PATH")); try { keyPair = KeyPairGenerator.getInstance("RSA").generateKeyPair(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); // signal that test failed to initialize assert false; } } class CMockPublicKeyProvider extends CPublicKeyProvider { public CMockPublicKeyProvider() { super(null); } @Override public PublicKey getKey() { return FileTransferTest.keyPair.getPublic(); } } class CMockPrivateKeyProvider extends CPrivateKeyProvider { public CMockPrivateKeyProvider() { super(null); } @Override public PrivateKey getKey() { return FileTransferTest.keyPair.getPrivate(); } } @Test public void testFileTransfer() throws Exception { // Initialize the clients try (CBlockingUploader uploader = new CBlockingUploader((CPublicKeyProvider) new CMockPublicKeyProvider())) { uploader.upload(TEST_BUCKET_NAME, TEST_OBJECT_KEY, TEST_LOCAL_FILE_PATH); } catch (Exception e) { e.printStackTrace(); } ; try (CDelayedAuthenticationDownloader downloader = new CDelayedAuthenticationDownloader(new CMockPrivateKeyProvider())) { downloader.download(TEST_BUCKET_NAME, TEST_OBJECT_KEY); } catch (Exception e) { e.printStackTrace(); } ; // Compare the contents byte[] originalContent = Files.readAllBytes(TEST_LOCAL_FILE_PATH); byte[] downloadedContent = Files.readAllBytes(Paths.get(TEST_OBJECT_KEY)); assertArrayEquals(originalContent, downloadedContent, "The contents of the uploaded and downloaded files should be the same."); } @Test public void testFileTransferKms() throws Exception {
try (CKmsKeyBasedClient client = new CKmsKeyBasedClient(getEnvOrExit("KMS_KEY_ID"))) {
0
2023-10-11 06:30:54+00:00
4k
Aywen1/reciteeasily
src/fr/nicolas/main/frames/AFrameEnd.java
[ { "identifier": "ATools", "path": "src/fr/nicolas/main/ATools.java", "snippet": "public class ATools {\n\n\tpublic static String[] matiereList = { \"Histoire\", \"Géographie\", \"Emc\", \"Phys-Chim\", \"Svt\", \"Maths\",\n\t\t\t\"Anglais\", \"Espagnol\" };\n\tpublic static ArrayList<String> elements;\n\...
import java.awt.BorderLayout; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JPanel; import fr.nicolas.main.ATools; import fr.nicolas.main.components.ABackground; import fr.nicolas.main.components.AButtonImg; import fr.nicolas.main.components.ALabel; import fr.nicolas.main.components.ABackground.ABgType; import fr.nicolas.main.panel.APanelTop;
2,374
package fr.nicolas.main.frames; public class AFrameEnd extends JFrame { private JPanel base = new JPanel();
package fr.nicolas.main.frames; public class AFrameEnd extends JFrame { private JPanel base = new JPanel();
private APanelTop panelTop;
5
2023-10-13 13:17:51+00:00
4k
rgrosa/comes-e-bebes
src/main/java/br/com/project/domain/service/imp/AcquisitionServiceImpl.java
[ { "identifier": "AcquisitionEntity", "path": "src/main/java/br/com/project/domain/entity/AcquisitionEntity.java", "snippet": "@Entity\n@Table(name = \"ACQUISITION\")\npublic class AcquisitionEntity {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n @Column(name = \"ID\")\n pr...
import br.com.project.domain.dto.*; import br.com.project.domain.entity.AcquisitionEntity; import br.com.project.domain.entity.AdditionalItemRelEntity; import br.com.project.domain.entity.ItemAcquisitionRelEntity; import br.com.project.domain.entity.ItemEntity; import br.com.project.domain.repository.*; import br.com.project.domain.service.AcquisitionService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List;
2,293
package br.com.project.domain.service.imp; @Service public class AcquisitionServiceImpl implements AcquisitionService { @Autowired ItemRepository itemRepository; @Autowired AdditionalItemRepository additionalItemRepository; @Autowired AcquisitionRepository acquisitionRepository; @Autowired ItemAcquisitionRelRepository itemAcquisitionRelRepository; @Autowired AdditionalItemRelRepository additionalItemRelRepository; @Override public ItemAcquisitionReturnDTO postAcquisition(AcquisitionDTO acquisition) { Double totalPrice = 0.0;
package br.com.project.domain.service.imp; @Service public class AcquisitionServiceImpl implements AcquisitionService { @Autowired ItemRepository itemRepository; @Autowired AdditionalItemRepository additionalItemRepository; @Autowired AcquisitionRepository acquisitionRepository; @Autowired ItemAcquisitionRelRepository itemAcquisitionRelRepository; @Autowired AdditionalItemRelRepository additionalItemRelRepository; @Override public ItemAcquisitionReturnDTO postAcquisition(AcquisitionDTO acquisition) { Double totalPrice = 0.0;
AcquisitionEntity acquisitionEntity = new AcquisitionEntity();
0
2023-10-10 23:22:15+00:00
4k
Stachelbeere1248/zombies-utils
src/main/java/com/github/stachelbeere1248/zombiesutils/handlers/ChatHandler.java
[ { "identifier": "Difficulty", "path": "src/main/java/com/github/stachelbeere1248/zombiesutils/game/Difficulty.java", "snippet": "public enum Difficulty {\n NORMAL, HARD, RIP\n}" }, { "identifier": "GameMode", "path": "src/main/java/com/github/stachelbeere1248/zombiesutils/game/GameMode.ja...
import com.github.stachelbeere1248.zombiesutils.game.Difficulty; import com.github.stachelbeere1248.zombiesutils.game.GameMode; import com.github.stachelbeere1248.zombiesutils.timer.Timer; import com.github.stachelbeere1248.zombiesutils.utils.LanguageSupport; import net.minecraftforge.client.event.ClientChatReceivedEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import org.jetbrains.annotations.NotNull; import java.util.regex.Pattern;
2,342
package com.github.stachelbeere1248.zombiesutils.handlers; public class ChatHandler { private static final Pattern STRIP_COLOR_PATTERN = Pattern.compile("§[0-9A-FK-ORZ]", Pattern.CASE_INSENSITIVE); public ChatHandler() { } @SubscribeEvent public void difficultyChange(@NotNull ClientChatReceivedEvent event) { if (!Timer.getInstance().isPresent()) return; String message = STRIP_COLOR_PATTERN.matcher(event.message.getUnformattedText()).replaceAll("").trim(); GameMode gameMode = Timer.getInstance().get().getGameMode(); if (message.contains(":")) return;
package com.github.stachelbeere1248.zombiesutils.handlers; public class ChatHandler { private static final Pattern STRIP_COLOR_PATTERN = Pattern.compile("§[0-9A-FK-ORZ]", Pattern.CASE_INSENSITIVE); public ChatHandler() { } @SubscribeEvent public void difficultyChange(@NotNull ClientChatReceivedEvent event) { if (!Timer.getInstance().isPresent()) return; String message = STRIP_COLOR_PATTERN.matcher(event.message.getUnformattedText()).replaceAll("").trim(); GameMode gameMode = Timer.getInstance().get().getGameMode(); if (message.contains(":")) return;
if (LanguageSupport.containsHard(message)) {
3
2023-10-11 01:30:28+00:00
4k
gustavofg1pontes/Tickets-API
application/src/main/java/br/com/ifsp/tickets/api/app/guest/create/DefaultCreateGuestUseCase.java
[ { "identifier": "Event", "path": "domain/src/main/java/br/com/ifsp/tickets/api/domain/event/entity/Event.java", "snippet": "@Getter\n@Setter\npublic class Event extends AggregateRoot<EventID> {\n private String name;\n private LocalDateTime dateTime;\n private Integer maxTickets;\n private I...
import br.com.ifsp.tickets.api.domain.event.entity.Event; import br.com.ifsp.tickets.api.domain.event.entity.EventID; import br.com.ifsp.tickets.api.domain.event.gateway.EventGateway; import br.com.ifsp.tickets.api.domain.guest.entity.Guest; import br.com.ifsp.tickets.api.domain.guest.entity.GuestID; import br.com.ifsp.tickets.api.domain.guest.entity.profile.Profile; import br.com.ifsp.tickets.api.domain.guest.gateway.GuestGateway; import br.com.ifsp.tickets.api.domain.shared.exceptions.InternalErrorException; import br.com.ifsp.tickets.api.domain.shared.exceptions.NotFoundException; import br.com.ifsp.tickets.api.domain.shared.exceptions.NotificationException; import br.com.ifsp.tickets.api.domain.shared.validation.handler.Notification; import java.util.function.Supplier;
2,577
package br.com.ifsp.tickets.api.app.guest.create; public class DefaultCreateGuestUseCase extends CreateGuestUseCase { private final GuestGateway guestGateway;
package br.com.ifsp.tickets.api.app.guest.create; public class DefaultCreateGuestUseCase extends CreateGuestUseCase { private final GuestGateway guestGateway;
private final EventGateway eventGateway;
2
2023-10-11 00:05:05+00:00
4k
DrMango14/Create-Design-n-Decor
src/main/java/com/mangomilk/design_decor/base/DecorBuilderTransformer.java
[ { "identifier": "CreateMMBuilding", "path": "src/main/java/com/mangomilk/design_decor/CreateMMBuilding.java", "snippet": "@Mod(CreateMMBuilding.MOD_ID)\npublic class CreateMMBuilding\n{\n\n public static final String MOD_ID = \"design_decor\";\n public static final String NAME = \"Create: Design n...
import com.mangomilk.design_decor.CreateMMBuilding; import com.mangomilk.design_decor.blocks.OrnateGrateBlock; import com.mangomilk.design_decor.blocks.glass.ConnectedTintedGlassBlock; import com.simibubi.create.content.decoration.encasing.EncasedCTBehaviour; import com.simibubi.create.foundation.block.connected.CTSpriteShiftEntry; import com.simibubi.create.foundation.block.connected.ConnectedTextureBehaviour; import com.simibubi.create.foundation.block.connected.HorizontalCTBehaviour; import com.simibubi.create.foundation.data.AssetLookup; import com.simibubi.create.foundation.data.BlockStateGen; import com.simibubi.create.foundation.data.CreateRegistrate; import com.simibubi.create.foundation.data.SharedProperties; import com.tterrag.registrate.builders.BlockBuilder; import com.tterrag.registrate.util.DataIngredient; import com.tterrag.registrate.util.entry.BlockEntry; import com.tterrag.registrate.util.nullness.NonNullUnaryOperator; import net.minecraft.client.renderer.RenderType; import net.minecraft.core.BlockPos; import net.minecraft.tags.BlockTags; import net.minecraft.world.entity.EntityType; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.block.*; import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.material.MaterialColor; import net.minecraftforge.common.Tags; import java.util.function.Supplier; import static com.mangomilk.design_decor.registry.MmbBlocks.DecoTags.*; import static com.mangomilk.design_decor.registry.MmbBlocks.DecoTags.CreateItemTag; import static com.simibubi.create.foundation.data.CreateRegistrate.casingConnectivity; import static com.simibubi.create.foundation.data.CreateRegistrate.connectedTextures; import static com.simibubi.create.foundation.data.TagGen.pickaxeOnly;
2,988
package com.mangomilk.design_decor.base; public class DecorBuilderTransformer { public static <B extends Block> NonNullUnaryOperator<BlockBuilder<B, CreateRegistrate>> connected( Supplier<CTSpriteShiftEntry> ct) { return b -> b.initialProperties(SharedProperties::stone) .blockstate((c, p) -> p.simpleBlock(c.get())) .onRegister(connectedTextures(() -> new EncasedCTBehaviour(ct.get()))) .onRegister(casingConnectivity((block, cc) -> cc.makeCasing(block, ct.get()))); } public static <B extends Block> NonNullUnaryOperator<BlockBuilder<B, CreateRegistrate>> layeredConnected( Supplier<CTSpriteShiftEntry> ct, Supplier<CTSpriteShiftEntry> ct2) { return b -> b.initialProperties(SharedProperties::stone) .blockstate((c, p) -> p.simpleBlock(c.get(), p.models() .cubeColumn(c.getName(), ct.get() .getOriginalResourceLocation(), ct2.get() .getOriginalResourceLocation()))) .onRegister(connectedTextures(() -> new HorizontalCTBehaviour(ct.get(), ct2.get()))) .onRegister(casingConnectivity((block, cc) -> cc.makeCasing(block, ct.get()))); } public static <B extends OrnateGrateBlock> NonNullUnaryOperator<BlockBuilder<B, CreateRegistrate>> ornateconnected( Supplier<CTSpriteShiftEntry> ct) { return b -> b.initialProperties(SharedProperties::stone) .blockstate((c, p) -> p.simpleBlock(c.get(), AssetLookup.standardModel(c, p))) .onRegister(connectedTextures(() -> new EncasedCTBehaviour(ct.get()))) .onRegister(casingConnectivity((block, cc) -> cc.makeCasing(block, ct.get()))); } private static BlockBehaviour.Properties glassProperties(BlockBehaviour.Properties p) { return p.isValidSpawn(DecorBuilderTransformer::never) .isRedstoneConductor(DecorBuilderTransformer::never) .isSuffocating(DecorBuilderTransformer::never) .isViewBlocking(DecorBuilderTransformer::never) .noOcclusion(); } public static BlockEntry<ConnectedTintedGlassBlock> tintedframedGlass(Supplier<ConnectedTextureBehaviour> behaviour) { return CreateMMBuilding.REGISTRATE.block("tinted_framed_glass", ConnectedTintedGlassBlock::new) .onRegister(connectedTextures(behaviour)) .addLayer(() -> RenderType::translucent) .initialProperties(() -> Blocks.TINTED_GLASS) .properties(DecorBuilderTransformer::glassProperties) .recipe((c, p) -> p.stonecutting(DataIngredient.tag(Tags.Items.GLASS_TINTED), c::get)) .blockstate((c, p) -> BlockStateGen.cubeAll(c, p, "palettes/", "tinted_framed_glass")) .tag(Tags.Blocks.GLASS_TINTED, Tags.Blocks.GLASS, BlockTags.IMPERMEABLE) .lang("Tinted Framed Glass") .item() .tag(Tags.Items.GLASS_TINTED, Tags.Items.GLASS) .model((c, p) -> p.cubeColumn(c.getName(), p.modLoc(palettesDir() + c.getName()), p.modLoc("block/palettes/tinted_framed_glass"))) .build() .register(); } public static BlockEntry<ConnectedTintedGlassBlock> tintedframedGlass(String type,String name, Supplier<ConnectedTextureBehaviour> behaviour) { return CreateMMBuilding.REGISTRATE.block(type + "_tinted_framed_glass", ConnectedTintedGlassBlock::new) .onRegister(connectedTextures(behaviour)) .addLayer(() -> RenderType::translucent) .initialProperties(() -> Blocks.TINTED_GLASS) .properties(DecorBuilderTransformer::glassProperties) .recipe((c, p) -> p.stonecutting(DataIngredient.tag(Tags.Items.GLASS_TINTED), c::get)) .blockstate((c, p) -> BlockStateGen.cubeAll(c, p, "palettes/", type + "_tinted_framed_glass")) .tag(Tags.Blocks.GLASS_TINTED, Tags.Blocks.GLASS, BlockTags.IMPERMEABLE) .lang(name + " Tinted Framed Glass") .item() .tag(Tags.Items.GLASS_TINTED, Tags.Items.GLASS) .model((c, p) -> p.cubeColumn(c.getName(), p.modLoc(palettesDir() + c.getName()), p.modLoc("block/palettes/" + type + "_tinted_framed_glass"))) .build() .register(); } public static BlockEntry<Block> CastelBricks(String id, String lang, MaterialColor color, Block block) { CreateMMBuilding.REGISTRATE.block(id + "_castel_brick_stairs", p -> new StairBlock(block.defaultBlockState(), p)) .initialProperties(() -> block) .properties(p -> p.color(color)) .properties(p -> p.destroyTime(1.25f)) .transform(pickaxeOnly()) .tag(MCBlockTag("stairs"))
package com.mangomilk.design_decor.base; public class DecorBuilderTransformer { public static <B extends Block> NonNullUnaryOperator<BlockBuilder<B, CreateRegistrate>> connected( Supplier<CTSpriteShiftEntry> ct) { return b -> b.initialProperties(SharedProperties::stone) .blockstate((c, p) -> p.simpleBlock(c.get())) .onRegister(connectedTextures(() -> new EncasedCTBehaviour(ct.get()))) .onRegister(casingConnectivity((block, cc) -> cc.makeCasing(block, ct.get()))); } public static <B extends Block> NonNullUnaryOperator<BlockBuilder<B, CreateRegistrate>> layeredConnected( Supplier<CTSpriteShiftEntry> ct, Supplier<CTSpriteShiftEntry> ct2) { return b -> b.initialProperties(SharedProperties::stone) .blockstate((c, p) -> p.simpleBlock(c.get(), p.models() .cubeColumn(c.getName(), ct.get() .getOriginalResourceLocation(), ct2.get() .getOriginalResourceLocation()))) .onRegister(connectedTextures(() -> new HorizontalCTBehaviour(ct.get(), ct2.get()))) .onRegister(casingConnectivity((block, cc) -> cc.makeCasing(block, ct.get()))); } public static <B extends OrnateGrateBlock> NonNullUnaryOperator<BlockBuilder<B, CreateRegistrate>> ornateconnected( Supplier<CTSpriteShiftEntry> ct) { return b -> b.initialProperties(SharedProperties::stone) .blockstate((c, p) -> p.simpleBlock(c.get(), AssetLookup.standardModel(c, p))) .onRegister(connectedTextures(() -> new EncasedCTBehaviour(ct.get()))) .onRegister(casingConnectivity((block, cc) -> cc.makeCasing(block, ct.get()))); } private static BlockBehaviour.Properties glassProperties(BlockBehaviour.Properties p) { return p.isValidSpawn(DecorBuilderTransformer::never) .isRedstoneConductor(DecorBuilderTransformer::never) .isSuffocating(DecorBuilderTransformer::never) .isViewBlocking(DecorBuilderTransformer::never) .noOcclusion(); } public static BlockEntry<ConnectedTintedGlassBlock> tintedframedGlass(Supplier<ConnectedTextureBehaviour> behaviour) { return CreateMMBuilding.REGISTRATE.block("tinted_framed_glass", ConnectedTintedGlassBlock::new) .onRegister(connectedTextures(behaviour)) .addLayer(() -> RenderType::translucent) .initialProperties(() -> Blocks.TINTED_GLASS) .properties(DecorBuilderTransformer::glassProperties) .recipe((c, p) -> p.stonecutting(DataIngredient.tag(Tags.Items.GLASS_TINTED), c::get)) .blockstate((c, p) -> BlockStateGen.cubeAll(c, p, "palettes/", "tinted_framed_glass")) .tag(Tags.Blocks.GLASS_TINTED, Tags.Blocks.GLASS, BlockTags.IMPERMEABLE) .lang("Tinted Framed Glass") .item() .tag(Tags.Items.GLASS_TINTED, Tags.Items.GLASS) .model((c, p) -> p.cubeColumn(c.getName(), p.modLoc(palettesDir() + c.getName()), p.modLoc("block/palettes/tinted_framed_glass"))) .build() .register(); } public static BlockEntry<ConnectedTintedGlassBlock> tintedframedGlass(String type,String name, Supplier<ConnectedTextureBehaviour> behaviour) { return CreateMMBuilding.REGISTRATE.block(type + "_tinted_framed_glass", ConnectedTintedGlassBlock::new) .onRegister(connectedTextures(behaviour)) .addLayer(() -> RenderType::translucent) .initialProperties(() -> Blocks.TINTED_GLASS) .properties(DecorBuilderTransformer::glassProperties) .recipe((c, p) -> p.stonecutting(DataIngredient.tag(Tags.Items.GLASS_TINTED), c::get)) .blockstate((c, p) -> BlockStateGen.cubeAll(c, p, "palettes/", type + "_tinted_framed_glass")) .tag(Tags.Blocks.GLASS_TINTED, Tags.Blocks.GLASS, BlockTags.IMPERMEABLE) .lang(name + " Tinted Framed Glass") .item() .tag(Tags.Items.GLASS_TINTED, Tags.Items.GLASS) .model((c, p) -> p.cubeColumn(c.getName(), p.modLoc(palettesDir() + c.getName()), p.modLoc("block/palettes/" + type + "_tinted_framed_glass"))) .build() .register(); } public static BlockEntry<Block> CastelBricks(String id, String lang, MaterialColor color, Block block) { CreateMMBuilding.REGISTRATE.block(id + "_castel_brick_stairs", p -> new StairBlock(block.defaultBlockState(), p)) .initialProperties(() -> block) .properties(p -> p.color(color)) .properties(p -> p.destroyTime(1.25f)) .transform(pickaxeOnly()) .tag(MCBlockTag("stairs"))
.recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag("stone_types/" + id)), c::get, 1))
4
2023-10-14 21:51:49+00:00
4k
Konloch/InjectedCalculator
src/main/java/com/konloch/ic/InjectedCalculator.java
[ { "identifier": "Calculator", "path": "src/main/java/com/konloch/ic/calculator/Calculator.java", "snippet": "public abstract class Calculator\n{\n\tpublic abstract long add(long a, long b);\n\tpublic abstract long sub(long a, long b);\n\tpublic abstract long mul(long a, long b);\n\tpublic abstract long ...
import com.konloch.ic.calculator.Calculator; import com.konloch.ic.calculator.injector.CalculatorInjector; import com.konloch.ic.calculator.expression.ExpressionEvaluator;
1,619
package com.konloch.ic; /** * "But its also missing code, so it injects what its missing" * * @author Konloch * @since 10/15/2023 */ public class InjectedCalculator { private final ExpressionEvaluator evaluator; public InjectedCalculator(Calculator calculator) { this.evaluator = new ExpressionEvaluator(calculator); } public static void main(String[] args) {
package com.konloch.ic; /** * "But its also missing code, so it injects what its missing" * * @author Konloch * @since 10/15/2023 */ public class InjectedCalculator { private final ExpressionEvaluator evaluator; public InjectedCalculator(Calculator calculator) { this.evaluator = new ExpressionEvaluator(calculator); } public static void main(String[] args) {
InjectedCalculator calculator = new InjectedCalculator(new CalculatorInjector().inject());
1
2023-10-15 08:38:08+00:00
4k
DeeChael/dcg
src/main/java/net/deechael/dcg/source/structure/DyParameter.java
[ { "identifier": "DyType", "path": "src/main/java/net/deechael/dcg/source/type/DyType.java", "snippet": "public interface DyType extends DyExportable, Invoker {\n\n // Default provided JTypes\n DyType VOID = classType(void.class);\n DyType INT = classType(int.class);\n DyType BOOLEAN = classT...
import net.deechael.dcg.source.type.DyType; import net.deechael.dcg.source.variable.JvmVariable; import net.deechael.dcg.source.variable.internal.ReferringVariable; import net.deechael.dcg.util.StringCompiler; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.HashMap; import java.util.Map;
2,072
package net.deechael.dcg.source.structure; public class DyParameter extends ReferringVariable implements DyAnnotatable { protected final Map<DyType, Map<String, JvmVariable>> annotations = new HashMap<>(); public DyParameter(DyStructure structure, DyType type, String name) { super(structure, type, name); } @Override public void annotate(@NotNull DyType annotationType, @Nullable Map<String, JvmVariable> values) { this.annotations.put(annotationType, values != null ? values : new HashMap<>()); } @Override public @NotNull Map<DyType, Map<String, JvmVariable>> listAnnotations() { return this.annotations; } @Override public String toCompilableString() { StringBuilder builder = new StringBuilder(); if (!this.annotations.isEmpty())
package net.deechael.dcg.source.structure; public class DyParameter extends ReferringVariable implements DyAnnotatable { protected final Map<DyType, Map<String, JvmVariable>> annotations = new HashMap<>(); public DyParameter(DyStructure structure, DyType type, String name) { super(structure, type, name); } @Override public void annotate(@NotNull DyType annotationType, @Nullable Map<String, JvmVariable> values) { this.annotations.put(annotationType, values != null ? values : new HashMap<>()); } @Override public @NotNull Map<DyType, Map<String, JvmVariable>> listAnnotations() { return this.annotations; } @Override public String toCompilableString() { StringBuilder builder = new StringBuilder(); if (!this.annotations.isEmpty())
builder.append(StringCompiler.compileAnnotations(this.annotations))
3
2023-10-15 13:45:11+00:00
4k
giteecode/supermarket2Public
src/main/java/com/ruoyi/project/monitor/cache/CacheController.java
[ { "identifier": "BaseController", "path": "src/main/java/com/ruoyi/framework/web/controller/BaseController.java", "snippet": "public class BaseController\n{\n protected final Logger logger = LoggerFactory.getLogger(this.getClass());\n \n /**\n * 将前台传递过来的日期格式的字符串,自动转化为Date类型\n */\n @I...
import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.ruoyi.framework.web.controller.BaseController; import com.ruoyi.framework.web.domain.AjaxResult; import com.ruoyi.framework.web.service.CacheService;
2,718
package com.ruoyi.project.monitor.cache; /** * 缓存监控 * * @author ruoyi */ @Controller @RequestMapping("/monitor/cache")
package com.ruoyi.project.monitor.cache; /** * 缓存监控 * * @author ruoyi */ @Controller @RequestMapping("/monitor/cache")
public class CacheController extends BaseController
0
2023-10-14 02:27:47+00:00
4k
Yunzez/SubDependency_CodeLine_Analysis
java/Calculator-master/src/main/java/com/houarizegai/calculator/ui/CalculatorUI.java
[ { "identifier": "Theme", "path": "java/Calculator-master/src/main/java/com/houarizegai/calculator/theme/properties/Theme.java", "snippet": "public class Theme {\n\n private String name;\n private String applicationBackground;\n private String textColor;\n private String btnEqualTextColor;\n ...
import com.houarizegai.calculator.theme.properties.Theme; import com.houarizegai.calculator.theme.ThemeLoader; import java.awt.Cursor; import java.awt.Font; import java.awt.event.ItemEvent; import java.util.Map; import java.util.regex.Pattern; import java.awt.Color; import javax.swing.*; import static com.houarizegai.calculator.util.ColorUtil.hex2Color;
2,859
inputScreen.setText("0."); addToDisplay = true; } go = true; }); btn0 = createButton("0", columns[1], rows[5]); btn0.addActionListener(event -> { if (addToDisplay) { if (Pattern.matches("[0]*", inputScreen.getText())) { inputScreen.setText("0"); } else { inputScreen.setText(inputScreen.getText() + "0"); } } else { inputScreen.setText("0"); addToDisplay = true; } go = true; }); btnEqual = createButton("=", columns[2], rows[5]); btnEqual.addActionListener(event -> { if (!Pattern.matches(DOUBLE_OR_NUMBER_REGEX, inputScreen.getText())) return; if (go) { typedValue = calculate(typedValue, Double.parseDouble(inputScreen.getText()), selectedOperator); if (Pattern.matches("[-]?[\\d]+[.][0]*", String.valueOf(typedValue))) { inputScreen.setText(String.valueOf((int) typedValue)); } else { inputScreen.setText(String.valueOf(typedValue)); } selectedOperator = '='; addToDisplay = false; } }); btnEqual.setSize(2 * BUTTON_WIDTH + 10, BUTTON_HEIGHT); btnRoot = createButton("√", columns[4], rows[1]); btnRoot.addActionListener(event -> { if (!Pattern.matches(DOUBLE_OR_NUMBER_REGEX, inputScreen.getText())) return; if (go) { typedValue = Math.sqrt(Double.parseDouble(inputScreen.getText())); if (Pattern.matches("[-]?[\\d]+[.][0]*", String.valueOf(typedValue))) { inputScreen.setText(String.valueOf((int) typedValue)); } else { inputScreen.setText(String.valueOf(typedValue)); } selectedOperator = '√'; addToDisplay = false; } }); btnRoot.setVisible(false); btnPower = createButton("pow", columns[4], rows[2]); btnPower.addActionListener(event -> { if (!Pattern.matches(DOUBLE_OR_NUMBER_REGEX, inputScreen.getText())) return; if (go) { typedValue = calculate(typedValue, Double.parseDouble(inputScreen.getText()), selectedOperator); if (Pattern.matches("[-]?[\\d]+[.][0]*", String.valueOf(typedValue))) { inputScreen.setText(String.valueOf((int) typedValue)); } else { inputScreen.setText(String.valueOf(typedValue)); } selectedOperator = '^'; go = false; addToDisplay = false; } else { selectedOperator = '^'; } }); btnPower.setFont(new Font("Comic Sans MS", Font.PLAIN, 24)); btnPower.setVisible(false); btnLog = createButton("ln", columns[4], rows[3]); btnLog.addActionListener(event -> { if (!Pattern.matches(DOUBLE_OR_NUMBER_REGEX, inputScreen.getText())) return; if (go) { typedValue = Math.log(Double.parseDouble(inputScreen.getText())); if (Pattern.matches("[-]?[\\d]+[.][0]*", String.valueOf(typedValue))) { inputScreen.setText(String.valueOf((int) typedValue)); } else { inputScreen.setText(String.valueOf(typedValue)); } selectedOperator = 'l'; addToDisplay = false; } }); btnLog.setVisible(false); } private JComboBox<String> createComboBox(String[] items, int x, int y, String toolTip) { JComboBox<String> combo = new JComboBox<>(items); combo.setBounds(x, y, 140, 25); combo.setToolTipText(toolTip); combo.setCursor(new Cursor(Cursor.HAND_CURSOR)); window.add(combo); return combo; } private JButton createButton(String label, int x, int y) { JButton btn = new JButton(label); btn.setBounds(x, y, BUTTON_WIDTH, BUTTON_HEIGHT); btn.setFont(new Font("Comic Sans MS", Font.PLAIN, 28)); btn.setCursor(new Cursor(Cursor.HAND_CURSOR)); btn.setFocusable(false); window.add(btn); return btn; } private void applyTheme(Theme theme) {
package com.houarizegai.calculator.ui; public class CalculatorUI { private static final String FONT_NAME = "Comic Sans MS"; private static final String DOUBLE_OR_NUMBER_REGEX = "([-]?\\d+[.]\\d*)|(\\d+)|(-\\d+)"; private static final String APPLICATION_TITLE = "Calculator"; private static final int WINDOW_WIDTH = 410; private static final int WINDOW_HEIGHT = 600; private static final int BUTTON_WIDTH = 80; private static final int BUTTON_HEIGHT = 70; private static final int MARGIN_X = 20; private static final int MARGIN_Y = 60; private final JFrame window; private JComboBox<String> comboCalculatorType; private JComboBox<String> comboTheme; private JTextField inputScreen; private JButton btnC; private JButton btnBack; private JButton btnMod; private JButton btnDiv; private JButton btnMul; private JButton btnSub; private JButton btnAdd; private JButton btn0; private JButton btn1; private JButton btn2; private JButton btn3; private JButton btn4; private JButton btn5; private JButton btn6; private JButton btn7; private JButton btn8; private JButton btn9; private JButton btnPoint; private JButton btnEqual; private JButton btnRoot; private JButton btnPower; private JButton btnLog; private char selectedOperator = ' '; private boolean go = true; // For calculate with Opt != (=) private boolean addToDisplay = true; // Connect numbers in display private double typedValue = 0; private final Map<String, Theme> themesMap; public CalculatorUI() { themesMap = ThemeLoader.loadThemes(); window = new JFrame(APPLICATION_TITLE); window.setSize(WINDOW_WIDTH, WINDOW_HEIGHT); window.setLocationRelativeTo(null); int[] columns = {MARGIN_X, MARGIN_X + 90, MARGIN_X + 90 * 2, MARGIN_X + 90 * 3, MARGIN_X + 90 * 4}; int[] rows = {MARGIN_Y, MARGIN_Y + 100, MARGIN_Y + 100 + 80, MARGIN_Y + 100 + 80 * 2, MARGIN_Y + 100 + 80 * 3, MARGIN_Y + 100 + 80 * 4}; initInputScreen(columns, rows); initButtons(columns, rows); initCalculatorTypeSelector(); initThemeSelector(); window.setLayout(null); window.setResizable(false); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); window.setVisible(true); } public double calculate(double firstNumber, double secondNumber, char operator) { switch (operator) { case '+': return firstNumber + secondNumber; case '-': return firstNumber - secondNumber; case '*': return firstNumber * secondNumber; case '/': return firstNumber / secondNumber; case '%': return firstNumber % secondNumber; case '^': return Math.pow(firstNumber, secondNumber); default: return secondNumber; } } private void initThemeSelector() { comboTheme = createComboBox(themesMap.keySet().toArray(new String[0]), 230, 30, "Theme"); comboTheme.addItemListener(event -> { if (event.getStateChange() != ItemEvent.SELECTED) return; String selectedTheme = (String) event.getItem(); applyTheme(themesMap.get(selectedTheme)); }); if (themesMap.entrySet().iterator().hasNext()) { applyTheme(themesMap.entrySet().iterator().next().getValue()); } } private void initInputScreen(int[] columns, int[] rows) { inputScreen = new JTextField("0"); inputScreen.setBounds(columns[0], rows[0], 350, 70); inputScreen.setEditable(false); inputScreen.setBackground(Color.WHITE); inputScreen.setFont(new Font(FONT_NAME, Font.PLAIN, 33)); window.add(inputScreen); } private void initCalculatorTypeSelector() { comboCalculatorType = createComboBox(new String[]{"Standard", "Scientific"}, 20, 30, "Calculator type"); comboCalculatorType.addItemListener(event -> { if (event.getStateChange() != ItemEvent.SELECTED) return; String selectedItem = (String) event.getItem(); switch (selectedItem) { case "Standard": window.setSize(WINDOW_WIDTH, WINDOW_HEIGHT); btnRoot.setVisible(false); btnPower.setVisible(false); btnLog.setVisible(false); break; case "Scientific": window.setSize(WINDOW_WIDTH + 80, WINDOW_HEIGHT); btnRoot.setVisible(true); btnPower.setVisible(true); btnLog.setVisible(true); break; } }); } private void initButtons(int[] columns, int[] rows) { btnC = createButton("C", columns[0], rows[1]); btnC.addActionListener(event -> { inputScreen.setText("0"); selectedOperator = ' '; typedValue = 0; }); btnBack = createButton("<-", columns[1], rows[1]); btnBack.addActionListener(event -> { String str = inputScreen.getText(); StringBuilder str2 = new StringBuilder(); for (int i = 0; i < (str.length() - 1); i++) { str2.append(str.charAt(i)); } if (str2.toString().equals("")) { inputScreen.setText("0"); } else { inputScreen.setText(str2.toString()); } }); btnMod = createButton("%", columns[2], rows[1]); btnMod.addActionListener(event -> { if (!Pattern.matches(DOUBLE_OR_NUMBER_REGEX, inputScreen.getText()) || !go) return; typedValue = calculate(typedValue, Double.parseDouble(inputScreen.getText()), selectedOperator); if (Pattern.matches("[-]?[\\d]+[.][0]*", String.valueOf(typedValue))) { inputScreen.setText(String.valueOf((int) typedValue)); } else { inputScreen.setText(String.valueOf(typedValue)); } selectedOperator = '%'; go = false; addToDisplay = false; }); btnDiv = createButton("/", columns[3], rows[1]); btnDiv.addActionListener(event -> { if (!Pattern.matches(DOUBLE_OR_NUMBER_REGEX, inputScreen.getText())) return; if (go) { typedValue = calculate(typedValue, Double.parseDouble(inputScreen.getText()), selectedOperator); if (Pattern.matches("[-]?[\\d]+[.][0]*", String.valueOf(typedValue))) { inputScreen.setText(String.valueOf((int) typedValue)); } else { inputScreen.setText(String.valueOf(typedValue)); } selectedOperator = '/'; go = false; addToDisplay = false; } else { selectedOperator = '/'; } }); btn7 = createButton("7", columns[0], rows[2]); btn7.addActionListener(event -> { if (addToDisplay) { if (Pattern.matches("[0]*", inputScreen.getText())) { inputScreen.setText("7"); } else { inputScreen.setText(inputScreen.getText() + "7"); } } else { inputScreen.setText("7"); addToDisplay = true; } go = true; }); btn8 = createButton("8", columns[1], rows[2]); btn8.addActionListener(event -> { if (addToDisplay) { if (Pattern.matches("[0]*", inputScreen.getText())) { inputScreen.setText("8"); } else { inputScreen.setText(inputScreen.getText() + "8"); } } else { inputScreen.setText("8"); addToDisplay = true; } go = true; }); btn9 = createButton("9", columns[2], rows[2]); btn9.addActionListener(event -> { if (addToDisplay) { if (Pattern.matches("[0]*", inputScreen.getText())) { inputScreen.setText("9"); } else { inputScreen.setText(inputScreen.getText() + "9"); } } else { inputScreen.setText("9"); addToDisplay = true; } go = true; }); btnMul = createButton("*", columns[3], rows[2]); btnMul.addActionListener(event -> { if (!Pattern.matches(DOUBLE_OR_NUMBER_REGEX, inputScreen.getText())) return; if (go) { typedValue = calculate(typedValue, Double.parseDouble(inputScreen.getText()), selectedOperator); if (Pattern.matches("[-]?[\\d]+[.][0]*", String.valueOf(typedValue))) { inputScreen.setText(String.valueOf((int) typedValue)); } else { inputScreen.setText(String.valueOf(typedValue)); } selectedOperator = '*'; go = false; addToDisplay = false; } else { selectedOperator = '*'; } }); btn4 = createButton("4", columns[0], rows[3]); btn4.addActionListener(event -> { if (addToDisplay) { if (Pattern.matches("[0]*", inputScreen.getText())) { inputScreen.setText("4"); } else { inputScreen.setText(inputScreen.getText() + "4"); } } else { inputScreen.setText("4"); addToDisplay = true; } go = true; }); btn5 = createButton("5", columns[1], rows[3]); btn5.addActionListener(event -> { if (addToDisplay) { if (Pattern.matches("[0]*", inputScreen.getText())) { inputScreen.setText("5"); } else { inputScreen.setText(inputScreen.getText() + "5"); } } else { inputScreen.setText("5"); addToDisplay = true; } go = true; }); btn6 = createButton("6", columns[2], rows[3]); btn6.addActionListener(event -> { if (addToDisplay) { if (Pattern.matches("[0]*", inputScreen.getText())) { inputScreen.setText("6"); } else { inputScreen.setText(inputScreen.getText() + "6"); } } else { inputScreen.setText("6"); addToDisplay = true; } go = true; }); btnSub = createButton("-", columns[3], rows[3]); btnSub.addActionListener(event -> { if (!Pattern.matches(DOUBLE_OR_NUMBER_REGEX, inputScreen.getText())) return; if (go) { typedValue = calculate(typedValue, Double.parseDouble(inputScreen.getText()), selectedOperator); if (Pattern.matches("[-]?[\\d]+[.][0]*", String.valueOf(typedValue))) { inputScreen.setText(String.valueOf((int) typedValue)); } else { inputScreen.setText(String.valueOf(typedValue)); } selectedOperator = '-'; go = false; addToDisplay = false; } else { selectedOperator = '-'; } }); btn1 = createButton("1", columns[0], rows[4]); btn1.addActionListener(event -> { if (addToDisplay) { if (Pattern.matches("[0]*", inputScreen.getText())) { inputScreen.setText("1"); } else { inputScreen.setText(inputScreen.getText() + "1"); } } else { inputScreen.setText("1"); addToDisplay = true; } go = true; }); btn2 = createButton("2", columns[1], rows[4]); btn2.addActionListener(event -> { if (addToDisplay) { if (Pattern.matches("[0]*", inputScreen.getText())) { inputScreen.setText("2"); } else { inputScreen.setText(inputScreen.getText() + "2"); } } else { inputScreen.setText("2"); addToDisplay = true; } go = true; }); btn3 = createButton("3", columns[2], rows[4]); btn3.addActionListener(event -> { if (addToDisplay) { if (Pattern.matches("[0]*", inputScreen.getText())) { inputScreen.setText("3"); } else { inputScreen.setText(inputScreen.getText() + "3"); } } else { inputScreen.setText("3"); addToDisplay = true; } go = true; }); btnAdd = createButton("+", columns[3], rows[4]); btnAdd.addActionListener(event -> { if (!Pattern.matches(DOUBLE_OR_NUMBER_REGEX, inputScreen.getText())) return; if (go) { typedValue = calculate(typedValue, Double.parseDouble(inputScreen.getText()), selectedOperator); if (Pattern.matches("[-]?[\\d]+[.][0]*", String.valueOf(typedValue))) { inputScreen.setText(String.valueOf((int) typedValue)); } else { inputScreen.setText(String.valueOf(typedValue)); } selectedOperator = '+'; go = false; addToDisplay = false; } else { selectedOperator = '+'; } }); btnPoint = createButton(".", columns[0], rows[5]); btnPoint.addActionListener(event -> { if (addToDisplay) { if (!inputScreen.getText().contains(".")) { inputScreen.setText(inputScreen.getText() + "."); } } else { inputScreen.setText("0."); addToDisplay = true; } go = true; }); btn0 = createButton("0", columns[1], rows[5]); btn0.addActionListener(event -> { if (addToDisplay) { if (Pattern.matches("[0]*", inputScreen.getText())) { inputScreen.setText("0"); } else { inputScreen.setText(inputScreen.getText() + "0"); } } else { inputScreen.setText("0"); addToDisplay = true; } go = true; }); btnEqual = createButton("=", columns[2], rows[5]); btnEqual.addActionListener(event -> { if (!Pattern.matches(DOUBLE_OR_NUMBER_REGEX, inputScreen.getText())) return; if (go) { typedValue = calculate(typedValue, Double.parseDouble(inputScreen.getText()), selectedOperator); if (Pattern.matches("[-]?[\\d]+[.][0]*", String.valueOf(typedValue))) { inputScreen.setText(String.valueOf((int) typedValue)); } else { inputScreen.setText(String.valueOf(typedValue)); } selectedOperator = '='; addToDisplay = false; } }); btnEqual.setSize(2 * BUTTON_WIDTH + 10, BUTTON_HEIGHT); btnRoot = createButton("√", columns[4], rows[1]); btnRoot.addActionListener(event -> { if (!Pattern.matches(DOUBLE_OR_NUMBER_REGEX, inputScreen.getText())) return; if (go) { typedValue = Math.sqrt(Double.parseDouble(inputScreen.getText())); if (Pattern.matches("[-]?[\\d]+[.][0]*", String.valueOf(typedValue))) { inputScreen.setText(String.valueOf((int) typedValue)); } else { inputScreen.setText(String.valueOf(typedValue)); } selectedOperator = '√'; addToDisplay = false; } }); btnRoot.setVisible(false); btnPower = createButton("pow", columns[4], rows[2]); btnPower.addActionListener(event -> { if (!Pattern.matches(DOUBLE_OR_NUMBER_REGEX, inputScreen.getText())) return; if (go) { typedValue = calculate(typedValue, Double.parseDouble(inputScreen.getText()), selectedOperator); if (Pattern.matches("[-]?[\\d]+[.][0]*", String.valueOf(typedValue))) { inputScreen.setText(String.valueOf((int) typedValue)); } else { inputScreen.setText(String.valueOf(typedValue)); } selectedOperator = '^'; go = false; addToDisplay = false; } else { selectedOperator = '^'; } }); btnPower.setFont(new Font("Comic Sans MS", Font.PLAIN, 24)); btnPower.setVisible(false); btnLog = createButton("ln", columns[4], rows[3]); btnLog.addActionListener(event -> { if (!Pattern.matches(DOUBLE_OR_NUMBER_REGEX, inputScreen.getText())) return; if (go) { typedValue = Math.log(Double.parseDouble(inputScreen.getText())); if (Pattern.matches("[-]?[\\d]+[.][0]*", String.valueOf(typedValue))) { inputScreen.setText(String.valueOf((int) typedValue)); } else { inputScreen.setText(String.valueOf(typedValue)); } selectedOperator = 'l'; addToDisplay = false; } }); btnLog.setVisible(false); } private JComboBox<String> createComboBox(String[] items, int x, int y, String toolTip) { JComboBox<String> combo = new JComboBox<>(items); combo.setBounds(x, y, 140, 25); combo.setToolTipText(toolTip); combo.setCursor(new Cursor(Cursor.HAND_CURSOR)); window.add(combo); return combo; } private JButton createButton(String label, int x, int y) { JButton btn = new JButton(label); btn.setBounds(x, y, BUTTON_WIDTH, BUTTON_HEIGHT); btn.setFont(new Font("Comic Sans MS", Font.PLAIN, 28)); btn.setCursor(new Cursor(Cursor.HAND_CURSOR)); btn.setFocusable(false); window.add(btn); return btn; } private void applyTheme(Theme theme) {
window.getContentPane().setBackground(hex2Color(theme.getApplicationBackground()));
2
2023-10-14 20:31:35+00:00
4k
notoriux/xshellmenu
xshellmenu-gui/src/main/java/it/xargon/xshellmenu/misc/XSGuiPlatform.java
[ { "identifier": "XShellMenuMainClass", "path": "xshellmenu-gui/src/main/java/it/xargon/xshellmenu/XShellMenuMainClass.java", "snippet": "public class XShellMenuMainClass {\n\tprivate static Object exitLock = new Object();\n\tprivate static volatile AtomicInteger exitCodeRef = null;\n\t\n\tprivate TrayIc...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.StringWriter; import java.lang.reflect.InvocationTargetException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; import it.xargon.xshellmenu.XShellMenuMainClass; import it.xargon.xshellmenu.api.XSPlatform; import it.xargon.xshellmenu.api.XSPlatformResource; import it.xargon.xshellmenu.res.Resources;
2,270
package it.xargon.xshellmenu.misc; public class XSGuiPlatform implements XSPlatform { private static final String REGQUERY_UTIL = "reg query "; private static final String REGDWORD_TOKEN = "REG_DWORD"; private static final String DARK_THEME_CMD = REGQUERY_UTIL + "\"HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize\"" + " /v SystemUsesLightTheme"; private static class StreamReader extends Thread { private InputStream is; private StringWriter sw; StreamReader(InputStream is) { this.is = is; sw = new StringWriter(); } public void run() { try { int c; while ((c = is.read()) != -1) sw.write(c); } catch (IOException e) { ; } } String getResult() { return sw.toString(); } } private ScheduledExecutorService internalTaskScheduler; private ExecutorService iconFetcherScheduler; public XSGuiPlatform() { internalTaskScheduler = Executors.newSingleThreadScheduledExecutor(); iconFetcherScheduler = Executors.newWorkStealingPool(); } @Override public OperatingSystem getOperatingSystem() { String os = System.getProperty("os.name").toLowerCase(); if (os.indexOf("win") >= 0) { return OperatingSystem.WINDOWS; } else if (os.indexOf("mac") >= 0) { return OperatingSystem.MACOS; } else if (os.indexOf("nix") >= 0 || os.indexOf("nux") >= 0) { return OperatingSystem.LINUX; } else if (os.indexOf("sunos") >= 0) { return OperatingSystem.SOLARIS; } else { return OperatingSystem.NONE; } } @Override public void abortApplication(String errorMessage, Exception ex) { ex.printStackTrace(); String abortMessage = errorMessage + "\n\n" + ex.getClass().getName() + ": " + ex.getMessage(); showErrorMessage(abortMessage, true); XShellMenuMainClass.exitApplication(255); } @Override public void showErrorMessage(String errorMessage, boolean wait) { Runnable showTask = () -> { JOptionPane.showMessageDialog( null, errorMessage, "XShellMenu", JOptionPane.ERROR_MESSAGE); }; if (wait) { if (SwingUtilities.isEventDispatchThread()) { showTask.run(); } else { try { SwingUtilities.invokeAndWait(showTask); } catch (InvocationTargetException | InterruptedException ex) { ex.printStackTrace(); } } } else SwingUtilities.invokeLater(showTask); } @Override public boolean isDarkModeSystemTheme() { switch(getOperatingSystem()) { case WINDOWS: return isWindowsDarkMode(); case MACOS: return isMacOsDarkMode(); default: return false; } } private boolean isMacOsDarkMode() { try { boolean isDarkMode = false; Runtime runtime = Runtime.getRuntime(); Process process = runtime.exec("defaults read -g AppleInterfaceStyle"); InputStreamReader is = new InputStreamReader(process.getInputStream()); BufferedReader rd = new BufferedReader(is); String line; while((line = rd.readLine()) != null) { if (line.equals("Dark")) { isDarkMode = true; } } int rc = process.waitFor(); return 0 == rc && isDarkMode; } catch (IOException | InterruptedException e) { return false; } } private boolean isWindowsDarkMode() { try { Process process = Runtime.getRuntime().exec(DARK_THEME_CMD); StreamReader reader = new StreamReader(process.getInputStream()); reader.start(); process.waitFor(); reader.join(); String result = reader.getResult(); int p = result.indexOf(REGDWORD_TOKEN); if (p == -1) { return false; } // 1 == Light Mode, 0 == Dark Mode String temp = result.substring(p + REGDWORD_TOKEN.length()).trim(); return ((Integer.parseInt(temp.substring("0x".length()), 16))) == 0; } catch (Exception e) { e.printStackTrace(); showErrorMessage("Exception while invoking \"reg\" utility: " + e.getMessage(), true); return false; } } @Override
package it.xargon.xshellmenu.misc; public class XSGuiPlatform implements XSPlatform { private static final String REGQUERY_UTIL = "reg query "; private static final String REGDWORD_TOKEN = "REG_DWORD"; private static final String DARK_THEME_CMD = REGQUERY_UTIL + "\"HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize\"" + " /v SystemUsesLightTheme"; private static class StreamReader extends Thread { private InputStream is; private StringWriter sw; StreamReader(InputStream is) { this.is = is; sw = new StringWriter(); } public void run() { try { int c; while ((c = is.read()) != -1) sw.write(c); } catch (IOException e) { ; } } String getResult() { return sw.toString(); } } private ScheduledExecutorService internalTaskScheduler; private ExecutorService iconFetcherScheduler; public XSGuiPlatform() { internalTaskScheduler = Executors.newSingleThreadScheduledExecutor(); iconFetcherScheduler = Executors.newWorkStealingPool(); } @Override public OperatingSystem getOperatingSystem() { String os = System.getProperty("os.name").toLowerCase(); if (os.indexOf("win") >= 0) { return OperatingSystem.WINDOWS; } else if (os.indexOf("mac") >= 0) { return OperatingSystem.MACOS; } else if (os.indexOf("nix") >= 0 || os.indexOf("nux") >= 0) { return OperatingSystem.LINUX; } else if (os.indexOf("sunos") >= 0) { return OperatingSystem.SOLARIS; } else { return OperatingSystem.NONE; } } @Override public void abortApplication(String errorMessage, Exception ex) { ex.printStackTrace(); String abortMessage = errorMessage + "\n\n" + ex.getClass().getName() + ": " + ex.getMessage(); showErrorMessage(abortMessage, true); XShellMenuMainClass.exitApplication(255); } @Override public void showErrorMessage(String errorMessage, boolean wait) { Runnable showTask = () -> { JOptionPane.showMessageDialog( null, errorMessage, "XShellMenu", JOptionPane.ERROR_MESSAGE); }; if (wait) { if (SwingUtilities.isEventDispatchThread()) { showTask.run(); } else { try { SwingUtilities.invokeAndWait(showTask); } catch (InvocationTargetException | InterruptedException ex) { ex.printStackTrace(); } } } else SwingUtilities.invokeLater(showTask); } @Override public boolean isDarkModeSystemTheme() { switch(getOperatingSystem()) { case WINDOWS: return isWindowsDarkMode(); case MACOS: return isMacOsDarkMode(); default: return false; } } private boolean isMacOsDarkMode() { try { boolean isDarkMode = false; Runtime runtime = Runtime.getRuntime(); Process process = runtime.exec("defaults read -g AppleInterfaceStyle"); InputStreamReader is = new InputStreamReader(process.getInputStream()); BufferedReader rd = new BufferedReader(is); String line; while((line = rd.readLine()) != null) { if (line.equals("Dark")) { isDarkMode = true; } } int rc = process.waitFor(); return 0 == rc && isDarkMode; } catch (IOException | InterruptedException e) { return false; } } private boolean isWindowsDarkMode() { try { Process process = Runtime.getRuntime().exec(DARK_THEME_CMD); StreamReader reader = new StreamReader(process.getInputStream()); reader.start(); process.waitFor(); reader.join(); String result = reader.getResult(); int p = result.indexOf(REGDWORD_TOKEN); if (p == -1) { return false; } // 1 == Light Mode, 0 == Dark Mode String temp = result.substring(p + REGDWORD_TOKEN.length()).trim(); return ((Integer.parseInt(temp.substring("0x".length()), 16))) == 0; } catch (Exception e) { e.printStackTrace(); showErrorMessage("Exception while invoking \"reg\" utility: " + e.getMessage(), true); return false; } } @Override
public <T> T getPlatformResource(XSPlatformResource<T> resourceIdentifier) {
2
2023-10-14 16:43:45+00:00
4k
FOBshippingpoint/ncu-punch-clock
src/main/java/com/sdovan1/ncupunchclock/Initializer.java
[ { "identifier": "Passcode", "path": "src/main/java/com/sdovan1/ncupunchclock/passcode/Passcode.java", "snippet": "@Entity\n@Data\n@NoArgsConstructor\n@Table\npublic class Passcode {\n @Id\n @GeneratedValue(strategy = GenerationType.AUTO)\n private Long id;\n\n @Column(nullable = false, uniqu...
import com.sdovan1.ncupunchclock.passcode.Passcode; import com.sdovan1.ncupunchclock.passcode.PasscodeRepository; import com.sdovan1.ncupunchclock.schedule.Punch; import com.sdovan1.ncupunchclock.schedule.PunchRepository; import com.sdovan1.ncupunchclock.schedule.PunchScheduler; import com.sdovan1.ncupunchclock.user.User; import com.sdovan1.ncupunchclock.user.UserRepository; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.CommandLineRunner; import org.springframework.context.annotation.Bean; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Component;
2,711
package com.sdovan1.ncupunchclock; @Component @Slf4j public class Initializer { @Autowired private UserRepository userRepository; @Autowired private PasswordEncoder passwordEncoder; @Autowired private PunchRepository punchRepository; @Autowired private PasscodeRepository passcodeRepository; @Autowired
package com.sdovan1.ncupunchclock; @Component @Slf4j public class Initializer { @Autowired private UserRepository userRepository; @Autowired private PasswordEncoder passwordEncoder; @Autowired private PunchRepository punchRepository; @Autowired private PasscodeRepository passcodeRepository; @Autowired
private PunchScheduler punchScheduler;
4
2023-10-12 15:41:58+00:00
4k
davidsaltacc/shadowclient
src/main/java/net/shadowclient/main/module/modules/combat/KillAura.java
[ { "identifier": "Event", "path": "src/main/java/net/shadowclient/main/event/Event.java", "snippet": "public abstract class Event {\n public boolean cancelled = false;\n public void cancel() {\n this.cancelled = true;\n }\n public void uncancel() {\n this.cancelled = false;\n ...
import net.minecraft.client.gui.screen.ingame.HandledScreen; import net.minecraft.entity.LivingEntity; import net.minecraft.util.Hand; import net.shadowclient.main.annotations.EventListener; import net.shadowclient.main.annotations.SearchTags; import net.shadowclient.main.event.Event; import net.shadowclient.main.event.events.PreTickEvent; import net.shadowclient.main.module.Module; import net.shadowclient.main.module.ModuleCategory; import net.shadowclient.main.setting.settings.BooleanSetting; import net.shadowclient.main.util.RotationUtils; import net.shadowclient.main.util.WorldUtils;
1,763
package net.shadowclient.main.module.modules.combat; @EventListener({PreTickEvent.class}) @SearchTags({"killaura", "kill aura", "auto kill", "auto hit"})
package net.shadowclient.main.module.modules.combat; @EventListener({PreTickEvent.class}) @SearchTags({"killaura", "kill aura", "auto kill", "auto hit"})
public class KillAura extends Module {
2
2023-10-07 06:55:12+00:00
4k
MRkto/MappetVoice
src/main/java/mrkto/mvoice/proxy/ServerProxy.java
[ { "identifier": "MappetVoice", "path": "src/main/java/mrkto/mvoice/MappetVoice.java", "snippet": "@Mod.EventBusSubscriber\n@Mod(\n modid = MappetVoice.MOD_ID,\n name = MappetVoice.NAME,\n version = MappetVoice.VERSION\n)\npublic class MappetVoice {\n\n public static final String ...
import mrkto.mvoice.MappetVoice; import mrkto.mvoice.client.AudioUtils; import mrkto.mvoice.utils.other.OpusNotLoadedException; import net.labymod.opus.OpusCodec; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import javax.annotation.Nullable;
3,095
package mrkto.mvoice.proxy; public class ServerProxy{ public void preInit(FMLPreInitializationEvent event) throws OpusNotLoadedException { MappetVoice.logger.info("server pre-init complete"); } public void init(FMLInitializationEvent event) { MappetVoice.logger.info("server init complete"); } public void postInit(FMLPostInitializationEvent event) { if(MappetVoice.opus.get()){
package mrkto.mvoice.proxy; public class ServerProxy{ public void preInit(FMLPreInitializationEvent event) throws OpusNotLoadedException { MappetVoice.logger.info("server pre-init complete"); } public void init(FMLInitializationEvent event) { MappetVoice.logger.info("server init complete"); } public void postInit(FMLPostInitializationEvent event) { if(MappetVoice.opus.get()){
AudioUtils.loadOpus();
1
2023-10-14 19:20:12+00:00
4k
batmatt/cli-rpg-java
src/com/clirpg/game/Quest.java
[ { "identifier": "Civillian", "path": "src/com/clirpg/characters/Civillian.java", "snippet": "public class Civillian extends Entity implements Talk{\n final static boolean friendly = true;\n String job;\n\n public Civillian(String name, String job)\n {\n super(name);\n this.job ...
import src.com.clirpg.characters.Civillian; import src.com.clirpg.characters.Player; import src.com.utils.ConsoleColors;
2,075
package src.com.clirpg.game; public class Quest { private Player player; public void setPlayer(Player player) { this.player = player; if(healthQuest < 60 ){ healthQuest = player.health + 20; } if(strengthQuest < 10){ strengthQuest = player.attackStrength + 10; } } private int levelArenaQuest; private int healthQuest; private int strengthQuest; private Civillian mayor; public Quest() { levelArenaQuest = 5; healthQuest = 0; strengthQuest = 0; mayor = new Civillian("Thomas", "Mayor"); } public void showQuests(){ checkQuests(); printQuests();
package src.com.clirpg.game; public class Quest { private Player player; public void setPlayer(Player player) { this.player = player; if(healthQuest < 60 ){ healthQuest = player.health + 20; } if(strengthQuest < 10){ strengthQuest = player.attackStrength + 10; } } private int levelArenaQuest; private int healthQuest; private int strengthQuest; private Civillian mayor; public Quest() { levelArenaQuest = 5; healthQuest = 0; strengthQuest = 0; mayor = new Civillian("Thomas", "Mayor"); } public void showQuests(){ checkQuests(); printQuests();
System.out.println(ConsoleColors.GREEN + "\n" + mayor.toString() + ": Come back the next time you have finished one of those quests\n" + ConsoleColors.RESET);
2
2023-10-14 15:38:50+00:00
4k
lukas-mb/ABAP-SQL-Beautifier
ABAP SQL Beautifier/src/com/abap/sql/beautifier/settings/CommasAdder.java
[ { "identifier": "Abap", "path": "ABAP SQL Beautifier/src/com/abap/sql/beautifier/Abap.java", "snippet": "public final class Abap {\n\n\t// class to store keywords and stuff\n\t// --> easier to find use with 'where used list'\n\n\tpublic static final List<String> JOINS = Arrays.asList(\"INNER JOIN\", \"J...
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import com.abap.sql.beautifier.Abap; import com.abap.sql.beautifier.Activator; import com.abap.sql.beautifier.preferences.PreferenceConstants; import com.abap.sql.beautifier.statement.AbapSqlPart; import com.abap.sql.beautifier.statement.Factory; import com.abap.sql.beautifier.utility.Utility;
3,445
package com.abap.sql.beautifier.settings; public class CommasAdder extends AbstractSqlSetting { public CommasAdder() { // TODO Auto-generated constructor stub } @Override public void apply() { if (Activator.getDefault().getPreferenceStore().getBoolean(PreferenceConstants.COMMAS)) {
package com.abap.sql.beautifier.settings; public class CommasAdder extends AbstractSqlSetting { public CommasAdder() { // TODO Auto-generated constructor stub } @Override public void apply() { if (Activator.getDefault().getPreferenceStore().getBoolean(PreferenceConstants.COMMAS)) {
String select = Utility.cleanString(abapSql.getPart(Abap.SELECT).getLines().toString());
0
2023-10-10 18:56:27+00:00
4k
Milosz08/screen-sharing-system
host/src/main/java/pl/polsl/screensharing/host/view/tabbed/TabbedScreenFramePanel.java
[ { "identifier": "HostWindow", "path": "host/src/main/java/pl/polsl/screensharing/host/view/HostWindow.java", "snippet": "@Getter\npublic class HostWindow extends AbstractRootFrame {\n private final HostState hostState;\n private final Optional<Image> streamingImageIconOptional;\n\n private fina...
import lombok.Getter; import pl.polsl.screensharing.host.view.HostWindow; import pl.polsl.screensharing.host.view.fragment.DisableScreenPanel; import pl.polsl.screensharing.host.view.fragment.VideoCanvas; import pl.polsl.screensharing.host.view.fragment.VideoParametersPanel; import pl.polsl.screensharing.lib.gui.AbstractTabbedPanel; import javax.swing.*; import java.awt.*;
2,655
/* * Copyright (c) 2023 by MULTIPLE AUTHORS * Part of the CS study course project. */ package pl.polsl.screensharing.host.view.tabbed; @Getter public class TabbedScreenFramePanel extends AbstractTabbedPanel { private final JPanel videoFrameHolder; private final VideoCanvas videoCanvas; private final DisableScreenPanel disableScreenPanel;
/* * Copyright (c) 2023 by MULTIPLE AUTHORS * Part of the CS study course project. */ package pl.polsl.screensharing.host.view.tabbed; @Getter public class TabbedScreenFramePanel extends AbstractTabbedPanel { private final JPanel videoFrameHolder; private final VideoCanvas videoCanvas; private final DisableScreenPanel disableScreenPanel;
private final VideoParametersPanel videoParametersPanel;
3
2023-10-11 16:12:02+00:00
4k
cbfacademy-admin/java-rest-api-assessment-jenieb3
src/test/java/com/cbfacademy/apiassessment/repository/InvestmentRepositoryTest.java
[ { "identifier": "InvestmentValidationException", "path": "src/main/java/com/cbfacademy/apiassessment/exceptions/InvestmentValidationException.java", "snippet": "public class InvestmentValidationException extends RuntimeException{\n public InvestmentValidationException(String message) {\n super...
import com.cbfacademy.apiassessment.exceptions.InvestmentValidationException; import com.cbfacademy.apiassessment.model.Bond; import com.cbfacademy.apiassessment.model.Investment; import com.cbfacademy.apiassessment.model.Stock; import com.cbfacademy.apiassessment.utility.JsonUtil; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Optional; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.*;
2,119
package com.cbfacademy.apiassessment.repository; /** * Unit tests for the InvestmentRepository class. * This class verifies the functionality of data access operations, including the ability to correctly * perform CRUD operations on investment data. * Special focus is given to the correct handling of edge cases and exceptions. */ @ExtendWith(MockitoExtension.class) public class InvestmentRepositoryTest { @Mock private JsonUtil jsonUtil; @InjectMocks private InvestmentRepository investmentRepository; // Concrete implementation of Investments private Bond sampleBond; private Stock sampleStock; @BeforeEach void setup() throws IOException { sampleBond = new Bond(); sampleBond.setId(1L); sampleBond.setName("Sample Bond"); sampleBond.setQuantity(15); sampleStock = new Stock(); sampleStock.setId(2L); sampleStock.setName("Sample Stock"); sampleStock.setQuantity(20); // Mocking the JsonUtil response lenient().when(jsonUtil.readInvestmentsFromJson()).thenReturn(Arrays.asList(sampleBond, sampleStock)); investmentRepository.init(); } @Test // Initialize the repository and verify contents void initTest() { List<Investment> investments = investmentRepository.findAll(); assertTrue(investments.contains(sampleBond)); assertTrue(investments.contains(sampleStock)); assertEquals(2, investments.size()); } @Test void findAllTest() { // Test to retrieve all Investments List<Investment> investments = investmentRepository.findAll(); assertFalse(investments.isEmpty()); assertTrue(investments.contains(sampleBond)); assertTrue(investments.contains(sampleStock)); assertEquals(2, investments.size()); } @Test void findByIdTest() { // Test for finding investments by ID investmentRepository.init(); // Make sure the repository is initialized Optional<Investment> foundBond = investmentRepository.findById(sampleBond.getId()); assertTrue(foundBond.isPresent()); assertEquals(sampleBond, foundBond.get()); Optional<Investment> foundStock = investmentRepository.findById(sampleStock.getId()); assertTrue(foundStock.isPresent()); assertEquals(sampleStock, foundStock.get()); } @Test void saveTest() throws IOException { // Test saving a new investment Stock newStock = new Stock(); newStock.setId(2L); newStock.setName("New Investment"); investmentRepository.save(newStock); verify(jsonUtil).writeInvestmentsToJson(any(List.class), eq(false)); assertEquals(newStock, investmentRepository.findById(2L).orElse(null)); } @Test void saveWithInvalidIdTest () { Bond invalidBond = new Bond(); invalidBond.setId(0L); invalidBond.setName("Invalid Bond");
package com.cbfacademy.apiassessment.repository; /** * Unit tests for the InvestmentRepository class. * This class verifies the functionality of data access operations, including the ability to correctly * perform CRUD operations on investment data. * Special focus is given to the correct handling of edge cases and exceptions. */ @ExtendWith(MockitoExtension.class) public class InvestmentRepositoryTest { @Mock private JsonUtil jsonUtil; @InjectMocks private InvestmentRepository investmentRepository; // Concrete implementation of Investments private Bond sampleBond; private Stock sampleStock; @BeforeEach void setup() throws IOException { sampleBond = new Bond(); sampleBond.setId(1L); sampleBond.setName("Sample Bond"); sampleBond.setQuantity(15); sampleStock = new Stock(); sampleStock.setId(2L); sampleStock.setName("Sample Stock"); sampleStock.setQuantity(20); // Mocking the JsonUtil response lenient().when(jsonUtil.readInvestmentsFromJson()).thenReturn(Arrays.asList(sampleBond, sampleStock)); investmentRepository.init(); } @Test // Initialize the repository and verify contents void initTest() { List<Investment> investments = investmentRepository.findAll(); assertTrue(investments.contains(sampleBond)); assertTrue(investments.contains(sampleStock)); assertEquals(2, investments.size()); } @Test void findAllTest() { // Test to retrieve all Investments List<Investment> investments = investmentRepository.findAll(); assertFalse(investments.isEmpty()); assertTrue(investments.contains(sampleBond)); assertTrue(investments.contains(sampleStock)); assertEquals(2, investments.size()); } @Test void findByIdTest() { // Test for finding investments by ID investmentRepository.init(); // Make sure the repository is initialized Optional<Investment> foundBond = investmentRepository.findById(sampleBond.getId()); assertTrue(foundBond.isPresent()); assertEquals(sampleBond, foundBond.get()); Optional<Investment> foundStock = investmentRepository.findById(sampleStock.getId()); assertTrue(foundStock.isPresent()); assertEquals(sampleStock, foundStock.get()); } @Test void saveTest() throws IOException { // Test saving a new investment Stock newStock = new Stock(); newStock.setId(2L); newStock.setName("New Investment"); investmentRepository.save(newStock); verify(jsonUtil).writeInvestmentsToJson(any(List.class), eq(false)); assertEquals(newStock, investmentRepository.findById(2L).orElse(null)); } @Test void saveWithInvalidIdTest () { Bond invalidBond = new Bond(); invalidBond.setId(0L); invalidBond.setName("Invalid Bond");
Exception exception = assertThrows(InvestmentValidationException.class, () -> {
0
2023-10-10 18:57:19+00:00
4k
sh0inx/Dragon-Cancel
src/main/java/io/github/sh0inx/dragoncancellite/commands/HelpCommand.java
[ { "identifier": "DragonCancelLite", "path": "src/main/java/io/github/sh0inx/dragoncancellite/DragonCancelLite.java", "snippet": "public class DragonCancelLite extends JavaPlugin {\n\n private static DragonCancelLite instance;\n public static FileConfiguration config;\n public static List<String...
import com.iridium.iridiumcolorapi.IridiumColorAPI; import io.github.sh0inx.dragoncancellite.DragonCancelLite; import io.github.sh0inx.dragoncancellite.Substring; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender;
2,147
package io.github.sh0inx.dragoncancellite.commands; public class HelpCommand implements CommandExecutor { @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { sender.sendMessage(IridiumColorAPI.process(
package io.github.sh0inx.dragoncancellite.commands; public class HelpCommand implements CommandExecutor { @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { sender.sendMessage(IridiumColorAPI.process(
DragonCancelLite.getInstance().getSubString(Substring.DRAGONCANCELTITLE)));
0
2023-10-09 05:32:02+00:00
4k
Bawnorton/Potters
src/main/java/com/bawnorton/potters/block/entity/BottomlessDecoratedPotBlockEntity.java
[ { "identifier": "BottomlessDecoratedPotBlock", "path": "src/main/java/com/bawnorton/potters/block/BottomlessDecoratedPotBlock.java", "snippet": "public class BottomlessDecoratedPotBlock extends PottersDecoratedPotBlockBase {\n public static final Identifier WITH_CONTENT = Potters.id(\"with_content\")...
import com.bawnorton.potters.block.BottomlessDecoratedPotBlock; import com.bawnorton.potters.block.entity.base.PottersDecoratedPotBlockEntityBase; import com.bawnorton.potters.registry.PottersBlockEntityType; import com.bawnorton.potters.storage.BottomlessDecoratedPotStorage; import com.bawnorton.potters.storage.PottersDecoratedPotStorageBase; import net.minecraft.block.Block; import net.minecraft.block.BlockState; import net.minecraft.nbt.NbtCompound; import net.minecraft.network.packet.s2c.play.BlockEntityUpdateS2CPacket; import net.minecraft.util.math.BlockPos;
3,568
package com.bawnorton.potters.block.entity; public class BottomlessDecoratedPotBlockEntity extends PottersDecoratedPotBlockEntityBase { private final BottomlessDecoratedPotStorage storage; public BottomlessDecoratedPotBlockEntity(BlockPos pos, BlockState state) { super(PottersBlockEntityType.BOTTOMLESS_DECORATED_POT, pos, state); storage = new BottomlessDecoratedPotStorage(); storage.addListener(storageView -> { if (world == null) return; if (world.isClient) return; if (storageView.isResourceBlank()) { world.setBlockState(pos, state.with(BottomlessDecoratedPotBlock.EMTPY, true), Block.NO_REDRAW); } else { world.setBlockState(pos, state.with(BottomlessDecoratedPotBlock.EMTPY, false), Block.NO_REDRAW); } }); } @Override
package com.bawnorton.potters.block.entity; public class BottomlessDecoratedPotBlockEntity extends PottersDecoratedPotBlockEntityBase { private final BottomlessDecoratedPotStorage storage; public BottomlessDecoratedPotBlockEntity(BlockPos pos, BlockState state) { super(PottersBlockEntityType.BOTTOMLESS_DECORATED_POT, pos, state); storage = new BottomlessDecoratedPotStorage(); storage.addListener(storageView -> { if (world == null) return; if (world.isClient) return; if (storageView.isResourceBlank()) { world.setBlockState(pos, state.with(BottomlessDecoratedPotBlock.EMTPY, true), Block.NO_REDRAW); } else { world.setBlockState(pos, state.with(BottomlessDecoratedPotBlock.EMTPY, false), Block.NO_REDRAW); } }); } @Override
public PottersDecoratedPotStorageBase getStorage() {
4
2023-10-13 19:14:56+00:00
4k
YinQin257/mqs-adapter
mqs-starter/src/main/java/org/yinqin/mqs/kafka/consumer/factory/CreateKafkaConsumer.java
[ { "identifier": "Constants", "path": "mqs-starter/src/main/java/org/yinqin/mqs/common/Constants.java", "snippet": "public interface Constants {\n int SUCCESS = 1;\n int ERROR = 0;\n String TRAN = \"TRAN\";\n String BATCH = \"BATCH\";\n String BROADCAST = \"BROADCAST\";\n String TRUE = ...
import org.apache.kafka.clients.CommonClientConfigs; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.clients.consumer.KafkaConsumer; import org.apache.kafka.common.serialization.ByteArrayDeserializer; import org.apache.kafka.common.serialization.StringDeserializer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.yinqin.mqs.common.Constants; import org.yinqin.mqs.common.config.MqsProperties; import org.yinqin.mqs.common.handler.MessageHandler; import org.yinqin.mqs.common.util.ConvertUtil; import java.util.Map; import java.util.Properties; import java.util.UUID;
2,859
package org.yinqin.mqs.kafka.consumer.factory; /** * 创建kafka消费者公共方法 * * @author YinQin * @version 1.0.6 * @createDate 2023年11月30日 * @since 1.0.6 */ public interface CreateKafkaConsumer { Logger logger = LoggerFactory.getLogger(CreateKafkaConsumer.class); /** * 初始化kafka配置 * * @param kafkaProperties kafka配置 * @param properties mqs配置 */ default void init(Properties kafkaProperties, MqsProperties.AdapterProperties properties) { kafkaProperties.putAll(properties.getKafka().getClientConfig()); kafkaProperties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); kafkaProperties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, ByteArrayDeserializer.class.getName()); kafkaProperties.put(ConsumerConfig.CLIENT_ID_CONFIG, UUID.randomUUID().toString().replace(Constants.HYPHEN, Constants.EMPTY).substring(0, 8)); kafkaProperties.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, Constants.TRUE); } /** * 订阅topic * * @param kafkaConsumer kafka消费者 * @param instanceId 实例ID * @param groupName 消费组名称 * @param messageHandlers 消息处理器 */ default void subscribe(KafkaConsumer<String, byte[]> kafkaConsumer, String instanceId, String groupName, Map<String, MessageHandler> messageHandlers) { kafkaConsumer.subscribe(messageHandlers.keySet()); for (String topic : messageHandlers.keySet()) { logger.info("实例:{} 消费者启动中,消费组:{},订阅Topic:{}", instanceId, groupName, topic); } } /** * 创建kafka原生消费者 * * @param groupName 消费组名称 * @param properties mqs配置 * @param kafkaProperties kafka配置 * @return kafka原生消费者 */ default KafkaConsumer<String, byte[]> createKafkaConsumer(String groupName, MqsProperties.AdapterProperties properties, Properties kafkaProperties) {
package org.yinqin.mqs.kafka.consumer.factory; /** * 创建kafka消费者公共方法 * * @author YinQin * @version 1.0.6 * @createDate 2023年11月30日 * @since 1.0.6 */ public interface CreateKafkaConsumer { Logger logger = LoggerFactory.getLogger(CreateKafkaConsumer.class); /** * 初始化kafka配置 * * @param kafkaProperties kafka配置 * @param properties mqs配置 */ default void init(Properties kafkaProperties, MqsProperties.AdapterProperties properties) { kafkaProperties.putAll(properties.getKafka().getClientConfig()); kafkaProperties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); kafkaProperties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, ByteArrayDeserializer.class.getName()); kafkaProperties.put(ConsumerConfig.CLIENT_ID_CONFIG, UUID.randomUUID().toString().replace(Constants.HYPHEN, Constants.EMPTY).substring(0, 8)); kafkaProperties.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, Constants.TRUE); } /** * 订阅topic * * @param kafkaConsumer kafka消费者 * @param instanceId 实例ID * @param groupName 消费组名称 * @param messageHandlers 消息处理器 */ default void subscribe(KafkaConsumer<String, byte[]> kafkaConsumer, String instanceId, String groupName, Map<String, MessageHandler> messageHandlers) { kafkaConsumer.subscribe(messageHandlers.keySet()); for (String topic : messageHandlers.keySet()) { logger.info("实例:{} 消费者启动中,消费组:{},订阅Topic:{}", instanceId, groupName, topic); } } /** * 创建kafka原生消费者 * * @param groupName 消费组名称 * @param properties mqs配置 * @param kafkaProperties kafka配置 * @return kafka原生消费者 */ default KafkaConsumer<String, byte[]> createKafkaConsumer(String groupName, MqsProperties.AdapterProperties properties, Properties kafkaProperties) {
groupName = ConvertUtil.convertName(groupName, properties.getGroup());
3
2023-10-11 03:23:43+00:00
4k
openpilot-hub/devpilot-intellij
src/main/java/com/zhongan/devpilot/settings/DevPilotConfigForm.java
[ { "identifier": "ModelServiceEnum", "path": "src/main/java/com/zhongan/devpilot/enums/ModelServiceEnum.java", "snippet": "public enum ModelServiceEnum {\n OPENAI(\"OpenAI\", \"OpenAI Service\"),\n LLAMA(\"LLaMA\", \"Code LLaMA (Locally)\"),\n AIGATEWAY(\"AIGateway\", \"AI Gateway\");\n\n // ...
import com.intellij.openapi.ui.ComboBox; import com.intellij.ui.components.JBTextField; import com.intellij.util.ui.FormBuilder; import com.intellij.util.ui.JBUI; import com.intellij.util.ui.UI; import com.zhongan.devpilot.enums.ModelServiceEnum; import com.zhongan.devpilot.enums.ModelTypeEnum; import com.zhongan.devpilot.enums.OpenAIModelNameEnum; import com.zhongan.devpilot.settings.state.AIGatewaySettingsState; import com.zhongan.devpilot.settings.state.CodeLlamaSettingsState; import com.zhongan.devpilot.settings.state.DevPilotLlmSettingsState; import com.zhongan.devpilot.settings.state.LanguageSettingsState; import com.zhongan.devpilot.settings.state.OpenAISettingsState; import com.zhongan.devpilot.util.DevPilotMessageBundle; import javax.swing.JComponent; import javax.swing.JPanel;
3,391
package com.zhongan.devpilot.settings; public class DevPilotConfigForm { private final JPanel comboBoxPanel; private final ComboBox<ModelServiceEnum> modelComboBox; private final JPanel openAIServicePanel; private final JBTextField openAIBaseHostField; private final JBTextField openAIKeyField; private final ComboBox<OpenAIModelNameEnum> openAIModelNameComboBox; private final JBTextField openAICustomModelNameField; private final JPanel aiGatewayServicePanel; private final JBTextField aiGatewayBaseHostField; private final ComboBox<ModelTypeEnum> aiGatewayModelComboBox; private final JPanel codeLlamaServicePanel; private final JBTextField codeLlamaBaseHostField; private final JBTextField codeLlamaModelNameField; private Integer index; public DevPilotConfigForm() {
package com.zhongan.devpilot.settings; public class DevPilotConfigForm { private final JPanel comboBoxPanel; private final ComboBox<ModelServiceEnum> modelComboBox; private final JPanel openAIServicePanel; private final JBTextField openAIBaseHostField; private final JBTextField openAIKeyField; private final ComboBox<OpenAIModelNameEnum> openAIModelNameComboBox; private final JBTextField openAICustomModelNameField; private final JPanel aiGatewayServicePanel; private final JBTextField aiGatewayBaseHostField; private final ComboBox<ModelTypeEnum> aiGatewayModelComboBox; private final JPanel codeLlamaServicePanel; private final JBTextField codeLlamaBaseHostField; private final JBTextField codeLlamaModelNameField; private Integer index; public DevPilotConfigForm() {
var devPilotSettings = DevPilotLlmSettingsState.getInstance();
5
2023-11-29 06:37:51+00:00
4k
Gaia3D/mago-3d-tiler
tiler/src/main/java/com/gaia3d/process/ProcessFlowThread.java
[ { "identifier": "FileLoader", "path": "tiler/src/main/java/com/gaia3d/converter/FileLoader.java", "snippet": "public interface FileLoader {\n public List<TileInfo> loadTileInfo(File file);\n public List<File> loadFiles();\n}" }, { "identifier": "PostProcess", "path": "tiler/src/main/ja...
import com.gaia3d.converter.FileLoader; import com.gaia3d.process.postprocess.PostProcess; import com.gaia3d.process.postprocess.thread.ProcessThreadPool; import com.gaia3d.process.preprocess.PreProcess; import com.gaia3d.process.tileprocess.Process; import com.gaia3d.process.tileprocess.TileProcess; import com.gaia3d.process.tileprocess.Tiler; import com.gaia3d.process.tileprocess.tile.ContentInfo; import com.gaia3d.process.tileprocess.tile.TileInfo; import com.gaia3d.process.tileprocess.tile.tileset.Tileset; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List;
2,341
package com.gaia3d.process; @Slf4j @AllArgsConstructor public class ProcessFlowThread implements Process { private List<PreProcess> preProcesses;
package com.gaia3d.process; @Slf4j @AllArgsConstructor public class ProcessFlowThread implements Process { private List<PreProcess> preProcesses;
private TileProcess tileProcess;
5
2023-11-30 01:59:44+00:00
4k
xuemingqi/x-cloud
x-config/src/main/java/com/x/config/filter/BaseFilter.java
[ { "identifier": "CommonConstant", "path": "x-common/src/main/java/com/x/common/constants/CommonConstant.java", "snippet": "public class CommonConstant {\n\n /**\n * traceId\n */\n public static final String TRACE_ID = \"traceId\";\n\n /**\n * ip\n */\n public static final Str...
import com.x.common.constants.CommonConstant; import com.x.common.utils.ServletUtil; import org.slf4j.MDC; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import java.io.IOException;
1,636
package com.x.config.filter; /** * @author xuemingqi */ @Configuration public class BaseFilter { @Bean public Filter filter() { return new Filter() { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { try { HttpServletRequest req = (HttpServletRequest) servletRequest; String traceId = req.getHeader(CommonConstant.TRACE_ID); MDC.put(CommonConstant.TRACE_ID, traceId);
package com.x.config.filter; /** * @author xuemingqi */ @Configuration public class BaseFilter { @Bean public Filter filter() { return new Filter() { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { try { HttpServletRequest req = (HttpServletRequest) servletRequest; String traceId = req.getHeader(CommonConstant.TRACE_ID); MDC.put(CommonConstant.TRACE_ID, traceId);
MDC.put(CommonConstant.IP, ServletUtil.getRemoteIP());
1
2023-11-27 08:23:38+00:00
4k
okx/OKBund
aa-task/src/main/java/com/okcoin/dapp/bundler/task/logevent/LogEventService.java
[ { "identifier": "ChainUtil", "path": "aa-infra/src/main/java/com/okcoin/dapp/bundler/infra/chain/ChainUtil.java", "snippet": "public class ChainUtil {\n\n //region getBlockNumber getNonce getGasPrice getNetVersion getChainId\n\n @SneakyThrows\n public static BigInteger getBlockNumber(IChain cha...
import com.google.common.collect.Lists; import com.okcoin.dapp.bundler.infra.chain.ChainUtil; import com.okcoin.dapp.bundler.infra.chain.ReceiptUtil; import com.okcoin.dapp.bundler.infra.storage.DTO.BlockHeightSignEntity; import com.okcoin.dapp.bundler.infra.storage.dao.BlockHeightSignDAO; import com.okcoin.dapp.bundler.pool.config.ChainConfig; import com.okcoin.dapp.bundler.pool.config.PoolConfig; import com.okcoin.dapp.bundler.pool.domain.event.AccountDeployedEvent; import com.okcoin.dapp.bundler.pool.domain.event.UserOperationEvent; import com.okcoin.dapp.bundler.pool.result.OnChainResultService; import com.okcoin.dapp.bundler.task.constant.LogEventConstant; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.util.CollectionUtils; import org.web3j.protocol.core.methods.response.Log; import javax.annotation.PostConstruct; import javax.annotation.Resource; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.Callable; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit;
3,528
package com.okcoin.dapp.bundler.task.logevent; /** * @Author fanweiqiang * @create 2023/10/24 17:54 */ @Slf4j @Component public class LogEventService { private Long lastProcessBlockHeight; @Resource
package com.okcoin.dapp.bundler.task.logevent; /** * @Author fanweiqiang * @create 2023/10/24 17:54 */ @Slf4j @Component public class LogEventService { private Long lastProcessBlockHeight; @Resource
private OnChainResultService onChainResultService;
8
2023-11-27 10:54:49+00:00
4k
lidaofu-hub/j_media_server
src/main/java/com/ldf/media/api/service/impl/ApiServiceImpl.java
[ { "identifier": "MediaInfoResult", "path": "src/main/java/com/ldf/media/api/model/result/MediaInfoResult.java", "snippet": "@Data\n@ApiModel(value = \"GetMediaListParam对象\", description = \"流信息\")\npublic class MediaInfoResult implements Serializable {\n\n private static final long serialVersionUID =...
import cn.hutool.core.lang.Assert; import com.ldf.media.api.model.param.*; import com.ldf.media.api.model.result.MediaInfoResult; import com.ldf.media.api.model.result.Track; import com.ldf.media.api.service.IApiService; import com.ldf.media.callback.MKSourceFindCallBack; import com.ldf.media.constants.MediaServerConstants; import com.ldf.media.context.MediaServerContext; import com.ldf.media.sdk.callback.IMKProxyPlayCloseCallBack; import com.ldf.media.sdk.structure.MK_MEDIA_SOURCE; import com.ldf.media.sdk.structure.MK_PROXY_PLAYER; import com.ldf.media.sdk.structure.MK_TRACK; import com.sun.jna.Pointer; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicReference;
2,999
package com.ldf.media.api.service.impl; /** * 接口服务 * * @author lidaofu * @since 2023/11/29 **/ @Service public class ApiServiceImpl implements IApiService { @Override public void addStreamProxy(StreamProxyParam param) { //查询流是是否存在
package com.ldf.media.api.service.impl; /** * 接口服务 * * @author lidaofu * @since 2023/11/29 **/ @Service public class ApiServiceImpl implements IApiService { @Override public void addStreamProxy(StreamProxyParam param) { //查询流是是否存在
MK_MEDIA_SOURCE mkMediaSource = MediaServerContext.ZLM_API.mk_media_source_find2(param.getEnableRtmp() == 1 ? "rtmp" : "rtsp", MediaServerConstants.DEFAULT_VHOST, param.getApp(), param.getStream(), 0);
5
2023-11-29 07:47:56+00:00
4k
qdrant/java-client
src/test/java/io/qdrant/client/PointsTest.java
[ { "identifier": "QdrantContainer", "path": "src/test/java/io/qdrant/client/container/QdrantContainer.java", "snippet": "public class QdrantContainer extends GenericContainer<QdrantContainer> {\n\n private static final DockerImageName DEFAULT_IMAGE_NAME = DockerImageName.parse(\"qdrant/qdrant\");\n ...
import io.grpc.Grpc; import io.grpc.InsecureChannelCredentials; import io.grpc.ManagedChannel; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInfo; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; import org.testcontainers.shaded.com.google.common.collect.ImmutableList; import org.testcontainers.shaded.com.google.common.collect.ImmutableMap; import org.testcontainers.shaded.com.google.common.collect.ImmutableSet; import io.qdrant.client.container.QdrantContainer; import io.qdrant.client.grpc.Points.DiscoverPoints; import io.qdrant.client.grpc.Points.PointVectors; import io.qdrant.client.grpc.Points.PointsIdsList; import io.qdrant.client.grpc.Points.PointsSelector; import io.qdrant.client.grpc.Points.PointsUpdateOperation; import io.qdrant.client.grpc.Points.UpdateBatchResponse; import io.qdrant.client.grpc.Points.PointsUpdateOperation.ClearPayload; import io.qdrant.client.grpc.Points.PointsUpdateOperation.UpdateVectors; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import static io.qdrant.client.grpc.Collections.CollectionInfo; import static io.qdrant.client.grpc.Collections.CreateCollection; import static io.qdrant.client.grpc.Collections.Distance; import static io.qdrant.client.grpc.Collections.PayloadSchemaType; import static io.qdrant.client.grpc.Collections.VectorParams; import static io.qdrant.client.grpc.Collections.VectorsConfig; import static io.qdrant.client.grpc.Points.BatchResult; import static io.qdrant.client.grpc.Points.Filter; import static io.qdrant.client.grpc.Points.PointGroup; import static io.qdrant.client.grpc.Points.PointStruct; import static io.qdrant.client.grpc.Points.RecommendPointGroups; import static io.qdrant.client.grpc.Points.RecommendPoints; import static io.qdrant.client.grpc.Points.RetrievedPoint; import static io.qdrant.client.grpc.Points.ScoredPoint; import static io.qdrant.client.grpc.Points.ScrollPoints; import static io.qdrant.client.grpc.Points.ScrollResponse; import static io.qdrant.client.grpc.Points.SearchPointGroups; import static io.qdrant.client.grpc.Points.SearchPoints; import static io.qdrant.client.grpc.Points.UpdateResult; import static io.qdrant.client.grpc.Points.UpdateStatus; import static io.qdrant.client.grpc.Points.Vectors; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static io.qdrant.client.ConditionFactory.hasId; import static io.qdrant.client.ConditionFactory.matchKeyword; import static io.qdrant.client.PointIdFactory.id; import static io.qdrant.client.TargetVectorFactory.targetVector; import static io.qdrant.client.ValueFactory.value; import static io.qdrant.client.VectorFactory.vector; import static io.qdrant.client.VectorsFactory.vectors;
3,152
List<RetrievedPoint> points = client.retrieveAsync(testName, id(9), null).get(); assertEquals(1, points.size()); RetrievedPoint point = points.get(0); assertEquals(id(9), point.getId()); assertTrue(point.getPayloadMap().isEmpty()); } @Test public void createFieldIndex() throws ExecutionException, InterruptedException { createAndSeedCollection(testName); UpdateResult result = client.createPayloadIndexAsync( testName, "foo", PayloadSchemaType.Keyword, null, null, null, null).get(); assertEquals(UpdateStatus.Completed, result.getStatus()); result = client.createPayloadIndexAsync( testName, "bar", PayloadSchemaType.Integer, null, null, null, null).get(); assertEquals(UpdateStatus.Completed, result.getStatus()); CollectionInfo collectionInfo = client.getCollectionInfoAsync(testName).get(); assertEquals(ImmutableSet.of("foo", "bar"), collectionInfo.getPayloadSchemaMap().keySet()); assertEquals(PayloadSchemaType.Keyword, collectionInfo.getPayloadSchemaMap().get("foo").getDataType()); assertEquals(PayloadSchemaType.Integer, collectionInfo.getPayloadSchemaMap().get("bar").getDataType()); } @Test public void deleteFieldIndex() throws ExecutionException, InterruptedException { createAndSeedCollection(testName); UpdateResult result = client.createPayloadIndexAsync( testName, "foo", PayloadSchemaType.Keyword, null, null, null, null).get(); assertEquals(UpdateStatus.Completed, result.getStatus()); result = client.deletePayloadIndexAsync( testName, "foo", null, null, null).get(); assertEquals(UpdateStatus.Completed, result.getStatus()); } @Test public void search() throws ExecutionException, InterruptedException { createAndSeedCollection(testName); List<ScoredPoint> points = client.searchAsync( SearchPoints.newBuilder() .setCollectionName(testName) .setWithPayload(WithPayloadSelectorFactory.enable(true)) .addAllVector(ImmutableList.of(10.4f, 11.4f)) .setLimit(1) .build()).get(); assertEquals(1, points.size()); ScoredPoint point = points.get(0); assertEquals(id(9), point.getId()); assertEquals(ImmutableSet.of("foo", "bar"), point.getPayloadMap().keySet()); assertEquals(value("goodbye"), point.getPayloadMap().get("foo")); assertEquals(value(2), point.getPayloadMap().get("bar")); assertFalse(point.getVectors().hasVector()); } @Test public void searchBatch() throws ExecutionException, InterruptedException { createAndSeedCollection(testName); List<BatchResult> batchResults = client.searchBatchAsync(testName, ImmutableList.of( SearchPoints.newBuilder() .addAllVector(ImmutableList.of(10.4f, 11.4f)) .setLimit(1) .build(), SearchPoints.newBuilder() .addAllVector(ImmutableList.of(3.4f, 4.4f)) .setLimit(1) .build() ), null).get(); assertEquals(2, batchResults.size()); BatchResult result = batchResults.get(0); assertEquals(1, result.getResultCount()); assertEquals(id(9), result.getResult(0).getId()); result = batchResults.get(1); assertEquals(1, result.getResultCount()); assertEquals(id(8), result.getResult(0).getId()); } @Test public void searchGroups() throws ExecutionException, InterruptedException { createAndSeedCollection(testName); client.upsertAsync( testName, ImmutableList.of( PointStruct.newBuilder() .setId(id(10))
package io.qdrant.client; @Testcontainers class PointsTest { @Container private static final QdrantContainer QDRANT_CONTAINER = new QdrantContainer(); private QdrantClient client; private ManagedChannel channel; private String testName; @BeforeEach public void setup(TestInfo testInfo) { testName = testInfo.getDisplayName().replace("()", ""); channel = Grpc.newChannelBuilder( QDRANT_CONTAINER.getGrpcHostAddress(), InsecureChannelCredentials.create()) .build(); QdrantGrpcClient grpcClient = QdrantGrpcClient.newBuilder(channel).build(); client = new QdrantClient(grpcClient); } @AfterEach public void teardown() throws Exception { List<String> collectionNames = client.listCollectionsAsync().get(); for (String collectionName : collectionNames) { client.deleteCollectionAsync(collectionName).get(); } client.close(); channel.shutdownNow().awaitTermination(5, TimeUnit.SECONDS); } @Test public void retrieve() throws ExecutionException, InterruptedException { createAndSeedCollection(testName); List<RetrievedPoint> points = client.retrieveAsync( testName, id(9), null).get(); assertEquals(1, points.size()); RetrievedPoint point = points.get(0); assertEquals(id(9), point.getId()); assertEquals(ImmutableSet.of("foo", "bar"), point.getPayloadMap().keySet()); assertEquals(value("goodbye"), point.getPayloadMap().get("foo")); assertEquals(value(2), point.getPayloadMap().get("bar")); assertEquals(Vectors.getDefaultInstance(), point.getVectors()); } @Test public void retrieve_with_vector_without_payload() throws ExecutionException, InterruptedException { createAndSeedCollection(testName); List<RetrievedPoint> points = client.retrieveAsync( testName, id(8), false, true, null).get(); assertEquals(1, points.size()); RetrievedPoint point = points.get(0); assertEquals(id(8), point.getId()); assertTrue(point.getPayloadMap().isEmpty()); assertEquals(Vectors.VectorsOptionsCase.VECTOR, point.getVectors().getVectorsOptionsCase()); } @Test public void setPayload() throws ExecutionException, InterruptedException { createAndSeedCollection(testName); client.setPayloadAsync( testName, ImmutableMap.of("bar", value("some bar")), id(9), null, null, null).get(); List<RetrievedPoint> points = client.retrieveAsync(testName, id(9), null).get(); assertEquals(1, points.size()); RetrievedPoint point = points.get(0); assertEquals(id(9), point.getId()); assertEquals(ImmutableSet.of("foo", "bar"), point.getPayloadMap().keySet()); assertEquals(value("some bar"), point.getPayloadMap().get("bar")); assertEquals(value("goodbye"), point.getPayloadMap().get("foo")); } @Test public void overwritePayload() throws ExecutionException, InterruptedException { createAndSeedCollection(testName); client.overwritePayloadAsync( testName, ImmutableMap.of("bar", value("some bar")), id(9), null, null, null).get(); List<RetrievedPoint> points = client.retrieveAsync(testName, id(9), null).get(); assertEquals(1, points.size()); RetrievedPoint point = points.get(0); assertEquals(id(9), point.getId()); assertEquals(ImmutableSet.of("bar"), point.getPayloadMap().keySet()); assertEquals(value("some bar"), point.getPayloadMap().get("bar")); } @Test public void deletePayload() throws ExecutionException, InterruptedException { createAndSeedCollection(testName); client.setPayloadAsync( testName, ImmutableMap.of("bar", value("some bar")), id(9), null, null, null).get(); client.deletePayloadAsync(testName, ImmutableList.of("foo"), id(9), null, null, null).get(); List<RetrievedPoint> points = client.retrieveAsync(testName, id(9), null).get(); assertEquals(1, points.size()); RetrievedPoint point = points.get(0); assertEquals(id(9), point.getId()); assertEquals(ImmutableSet.of("bar"), point.getPayloadMap().keySet()); assertEquals(value("some bar"), point.getPayloadMap().get("bar")); } @Test public void clearPayload() throws ExecutionException, InterruptedException { createAndSeedCollection(testName); client.clearPayloadAsync(testName, id(9), true, null, null).get(); List<RetrievedPoint> points = client.retrieveAsync(testName, id(9), null).get(); assertEquals(1, points.size()); RetrievedPoint point = points.get(0); assertEquals(id(9), point.getId()); assertTrue(point.getPayloadMap().isEmpty()); } @Test public void createFieldIndex() throws ExecutionException, InterruptedException { createAndSeedCollection(testName); UpdateResult result = client.createPayloadIndexAsync( testName, "foo", PayloadSchemaType.Keyword, null, null, null, null).get(); assertEquals(UpdateStatus.Completed, result.getStatus()); result = client.createPayloadIndexAsync( testName, "bar", PayloadSchemaType.Integer, null, null, null, null).get(); assertEquals(UpdateStatus.Completed, result.getStatus()); CollectionInfo collectionInfo = client.getCollectionInfoAsync(testName).get(); assertEquals(ImmutableSet.of("foo", "bar"), collectionInfo.getPayloadSchemaMap().keySet()); assertEquals(PayloadSchemaType.Keyword, collectionInfo.getPayloadSchemaMap().get("foo").getDataType()); assertEquals(PayloadSchemaType.Integer, collectionInfo.getPayloadSchemaMap().get("bar").getDataType()); } @Test public void deleteFieldIndex() throws ExecutionException, InterruptedException { createAndSeedCollection(testName); UpdateResult result = client.createPayloadIndexAsync( testName, "foo", PayloadSchemaType.Keyword, null, null, null, null).get(); assertEquals(UpdateStatus.Completed, result.getStatus()); result = client.deletePayloadIndexAsync( testName, "foo", null, null, null).get(); assertEquals(UpdateStatus.Completed, result.getStatus()); } @Test public void search() throws ExecutionException, InterruptedException { createAndSeedCollection(testName); List<ScoredPoint> points = client.searchAsync( SearchPoints.newBuilder() .setCollectionName(testName) .setWithPayload(WithPayloadSelectorFactory.enable(true)) .addAllVector(ImmutableList.of(10.4f, 11.4f)) .setLimit(1) .build()).get(); assertEquals(1, points.size()); ScoredPoint point = points.get(0); assertEquals(id(9), point.getId()); assertEquals(ImmutableSet.of("foo", "bar"), point.getPayloadMap().keySet()); assertEquals(value("goodbye"), point.getPayloadMap().get("foo")); assertEquals(value(2), point.getPayloadMap().get("bar")); assertFalse(point.getVectors().hasVector()); } @Test public void searchBatch() throws ExecutionException, InterruptedException { createAndSeedCollection(testName); List<BatchResult> batchResults = client.searchBatchAsync(testName, ImmutableList.of( SearchPoints.newBuilder() .addAllVector(ImmutableList.of(10.4f, 11.4f)) .setLimit(1) .build(), SearchPoints.newBuilder() .addAllVector(ImmutableList.of(3.4f, 4.4f)) .setLimit(1) .build() ), null).get(); assertEquals(2, batchResults.size()); BatchResult result = batchResults.get(0); assertEquals(1, result.getResultCount()); assertEquals(id(9), result.getResult(0).getId()); result = batchResults.get(1); assertEquals(1, result.getResultCount()); assertEquals(id(8), result.getResult(0).getId()); } @Test public void searchGroups() throws ExecutionException, InterruptedException { createAndSeedCollection(testName); client.upsertAsync( testName, ImmutableList.of( PointStruct.newBuilder() .setId(id(10))
.setVectors(VectorsFactory.vectors(30f, 31f))
7
2023-11-30 10:21:23+00:00
4k
seraxis/lr2oraja-endlessdream
core/src/bms/player/beatoraja/skin/SkinHeader.java
[ { "identifier": "Resolution", "path": "core/src/bms/player/beatoraja/Resolution.java", "snippet": "public enum Resolution {\n\tSD(640, 480),\n\tSVGA(800, 600),\n\tXGA(1024, 768),\n\tHD(1280, 720),\n\tQUADVGA(1280, 960),\n\tFWXGA(1366, 768),\n\tSXGAPLUS(1400, 1050),\n\tHDPLUS(1600, 900),\n\tUXGA(1600, 12...
import bms.player.beatoraja.Resolution; import bms.player.beatoraja.SkinConfig; import static bms.player.beatoraja.skin.SkinProperty.OPTION_RANDOM_VALUE; import java.io.File; import java.nio.file.Path; import java.util.*;
2,498
package bms.player.beatoraja.skin; /** * スキンのヘッダ情報 * * @author exch */ public class SkinHeader { /** * スキンの種類 */ private int type; /** * スキン:LR2 */ public static final int TYPE_LR2SKIN = 0; /** * スキン:beatoraja */ public static final int TYPE_BEATORJASKIN = 1; /** * スキンファイルのパス */ private Path path; /** * スキンタイプ */ private SkinType mode; /** * スキン名 */ private String name; /** * スキン製作者名 */ private String author; /** * カスタムオプション */ private CustomOption[] options = CustomOption.EMPTY_ARRAY; /** * カスタムファイル */ private CustomFile[] files = CustomFile.EMPTY_ARRAY; /** * カスタムオフセット */ private CustomOffset[] offsets = CustomOffset.EMPTY_ARRAY; /** * カスタムカテゴリー */ private CustomCategory[] categories = CustomCategory.EMPTY_ARRAY; /** * スキン解像度 */ private Resolution resolution = Resolution.SD; private Resolution sourceResolution; private Resolution destinationResolution; public SkinType getSkinType() { return mode; } public void setSkinType(SkinType mode) { this.mode = mode; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public CustomOption[] getCustomOptions() { return options; } public void setCustomOptions(CustomOption[] options) { this.options = options; } public CustomFile[] getCustomFiles() { return files; } public void setCustomFiles(CustomFile[] files) { this.files = files; } public Path getPath() { return path; } public void setPath(Path path) { this.path = path; } public Resolution getResolution() { return resolution; } public void setResolution(Resolution resolution) { this.resolution = resolution; } public int getType() { return type; } public void setType(int type) { this.type = type; } public CustomOffset[] getCustomOffsets() { return offsets; } public void setCustomOffsets(CustomOffset[] offsets) { this.offsets = offsets; } public CustomCategory[] getCustomCategories() { return categories; } public void setCustomCategories(CustomCategory[] categories) { this.categories = categories; }
package bms.player.beatoraja.skin; /** * スキンのヘッダ情報 * * @author exch */ public class SkinHeader { /** * スキンの種類 */ private int type; /** * スキン:LR2 */ public static final int TYPE_LR2SKIN = 0; /** * スキン:beatoraja */ public static final int TYPE_BEATORJASKIN = 1; /** * スキンファイルのパス */ private Path path; /** * スキンタイプ */ private SkinType mode; /** * スキン名 */ private String name; /** * スキン製作者名 */ private String author; /** * カスタムオプション */ private CustomOption[] options = CustomOption.EMPTY_ARRAY; /** * カスタムファイル */ private CustomFile[] files = CustomFile.EMPTY_ARRAY; /** * カスタムオフセット */ private CustomOffset[] offsets = CustomOffset.EMPTY_ARRAY; /** * カスタムカテゴリー */ private CustomCategory[] categories = CustomCategory.EMPTY_ARRAY; /** * スキン解像度 */ private Resolution resolution = Resolution.SD; private Resolution sourceResolution; private Resolution destinationResolution; public SkinType getSkinType() { return mode; } public void setSkinType(SkinType mode) { this.mode = mode; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public CustomOption[] getCustomOptions() { return options; } public void setCustomOptions(CustomOption[] options) { this.options = options; } public CustomFile[] getCustomFiles() { return files; } public void setCustomFiles(CustomFile[] files) { this.files = files; } public Path getPath() { return path; } public void setPath(Path path) { this.path = path; } public Resolution getResolution() { return resolution; } public void setResolution(Resolution resolution) { this.resolution = resolution; } public int getType() { return type; } public void setType(int type) { this.type = type; } public CustomOffset[] getCustomOffsets() { return offsets; } public void setCustomOffsets(CustomOffset[] offsets) { this.offsets = offsets; } public CustomCategory[] getCustomCategories() { return categories; } public void setCustomCategories(CustomCategory[] categories) { this.categories = categories; }
public void setSkinConfigProperty(SkinConfig.Property property) {
1
2023-12-02 23:41:17+00:00
4k