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 |
|---|---|---|---|---|---|---|---|---|---|---|
GoogleCloudPlatform/dataflow-ordered-processing | beam-ordered-processing/src/main/java/org/apache/beam/sdk/extensions/ordered/OrderedEventProcessor.java | [
{
"identifier": "Builder",
"path": "beam-ordered-processing/src/main/java/org/apache/beam/sdk/extensions/ordered/OrderedProcessingDiagnosticEvent.java",
"snippet": "@AutoValue.Builder\npublic abstract static class Builder {\n\n public abstract Builder setSequenceNumber(long value);\n\n public abstract... | import com.google.auto.value.AutoValue;
import java.util.Arrays;
import java.util.Iterator;
import javax.annotation.Nullable;
import org.apache.beam.sdk.Pipeline;
import org.apache.beam.sdk.coders.BooleanCoder;
import org.apache.beam.sdk.coders.Coder;
import org.apache.beam.sdk.coders.KvCoder;
import org.apache.beam.sdk.coders.VarLongCoder;
import org.apache.beam.sdk.extensions.ordered.OrderedProcessingDiagnosticEvent.Builder;
import org.apache.beam.sdk.extensions.ordered.OrderedProcessingDiagnosticEvent.ClearedBufferedEvents;
import org.apache.beam.sdk.extensions.ordered.OrderedProcessingDiagnosticEvent.QueriedBufferedEvents;
import org.apache.beam.sdk.extensions.ordered.ProcessingState.ProcessingStateCoder;
import org.apache.beam.sdk.extensions.ordered.UnprocessedEvent.Reason;
import org.apache.beam.sdk.extensions.ordered.UnprocessedEvent.UnprocessedEventCoder;
import org.apache.beam.sdk.schemas.NoSuchSchemaException;
import org.apache.beam.sdk.schemas.SchemaCoder;
import org.apache.beam.sdk.schemas.SchemaRegistry;
import org.apache.beam.sdk.state.OrderedListState;
import org.apache.beam.sdk.state.StateSpec;
import org.apache.beam.sdk.state.StateSpecs;
import org.apache.beam.sdk.state.TimeDomain;
import org.apache.beam.sdk.state.Timer;
import org.apache.beam.sdk.state.TimerSpec;
import org.apache.beam.sdk.state.TimerSpecs;
import org.apache.beam.sdk.state.ValueState;
import org.apache.beam.sdk.transforms.DoFn;
import org.apache.beam.sdk.transforms.PTransform;
import org.apache.beam.sdk.transforms.ParDo;
import org.apache.beam.sdk.transforms.windowing.BoundedWindow;
import org.apache.beam.sdk.values.KV;
import org.apache.beam.sdk.values.PCollection;
import org.apache.beam.sdk.values.PCollection.IsBounded;
import org.apache.beam.sdk.values.PCollectionTuple;
import org.apache.beam.sdk.values.TimestampedValue;
import org.apache.beam.sdk.values.TupleTag;
import org.apache.beam.sdk.values.TupleTagList;
import org.apache.beam.sdk.values.TypeDescriptor;
import org.joda.time.Duration;
import org.joda.time.Instant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | 4,622 | }
if (processingState.isNextEvent(currentSequence)) {
// Event matches expected sequence
state = currentStateState.read();
state.mutate(currentEvent);
Result result = state.produceResult();
if (result != null) {
outputReceiver.get(mainOutputTupleTag).output(KV.of(processingState.getKey(), result));
processingState.resultProduced();
}
processingState.eventAccepted(currentSequence, thisIsTheLastEvent);
return state;
}
// Event is not ready to be processed yet
Instant eventTimestamp = Instant.ofEpochMilli(currentSequence);
bufferedEventsState.add(TimestampedValue.of(currentEvent, eventTimestamp));
processingState.eventBuffered(currentSequence, thisIsTheLastEvent);
diagnostics.setEventBufferedTime(eventTimestamp);
// This will signal that the state hasn't been mutated and we don't need to save it.
return null;
}
/**
* Process buffered events
*
* @param processingState
* @param state
* @param bufferedEventsState
* @param outputReceiver
* @param largeBatchEmissionTimer
* @param diagnostics
*/
private void processBufferedEvents(ProcessingState<EventKey> processingState,
State state, OrderedListState<Event> bufferedEventsState,
MultiOutputReceiver outputReceiver,
Timer largeBatchEmissionTimer, Builder diagnostics) {
if (state == null) {
// Only when the current event caused a state mutation and the state is passed to this
// method should we attempt to process buffered events
return;
}
if (!processingState.readyToProcessBufferedEvents()) {
return;
}
if (exceededMaxResultCountForBundle(processingState, largeBatchEmissionTimer)) {
// No point in trying to process buffered events
return;
}
int recordCount = 0;
Instant firstEventRead = null;
Instant startRange = Instant.ofEpochMilli(processingState.getEarliestBufferedSequence());
Instant endRange = Instant.ofEpochMilli(processingState.getLatestBufferedSequence() + 1);
Instant endClearRange = null;
// readRange is efficiently implemented and will bring records in batches
Iterable<TimestampedValue<Event>> events = bufferedEventsState.readRange(startRange,
endRange);
Iterator<TimestampedValue<Event>> bufferedEventsIterator = events.iterator();
while (bufferedEventsIterator.hasNext()) {
TimestampedValue<Event> timestampedEvent = bufferedEventsIterator.next();
Instant eventTimestamp = timestampedEvent.getTimestamp();
long eventSequence = eventTimestamp.getMillis();
if (recordCount++ == 0) {
firstEventRead = eventTimestamp;
}
Event bufferedEvent = timestampedEvent.getValue();
if (processingState.checkForDuplicateBatchedEvent(eventSequence)) {
outputReceiver.get(unprocessedEventsTupleTag).output(KV.of(processingState.getKey(),
KV.of(eventSequence, UnprocessedEvent.create(bufferedEvent, Reason.duplicate))));
continue;
}
if (eventSequence > processingState.getLastOutputSequence() + 1) {
processingState.foundSequenceGap(eventSequence);
// Records will be cleared up to this element
endClearRange = Instant.ofEpochMilli(eventSequence);
break;
}
// This check needs to be done after we checked for sequence gap and before we
// attempt to process the next element which can result in a new result.
if (exceededMaxResultCountForBundle(processingState, largeBatchEmissionTimer)) {
endClearRange = Instant.ofEpochMilli(eventSequence);
break;
}
state.mutate(bufferedEvent);
Result result = state.produceResult();
if (result != null) {
outputReceiver.get(mainOutputTupleTag).output(KV.of(processingState.getKey(), result));
processingState.resultProduced();
}
processingState.processedBufferedEvent(eventSequence);
// Remove this record also
endClearRange = Instant.ofEpochMilli(eventSequence + 1);
}
// Temporarily disabled due to https://github.com/apache/beam/pull/28171
// bufferedEventsState.clearRange(startRange, endClearRange);
// TODO: Draining events is a temporary workaround related to https://github.com/apache/beam/issues/28370
// It can be removed once https://github.com/apache/beam/pull/28371 is available in a regular release
while (bufferedEventsIterator.hasNext()) {
// Read and discard all events
bufferedEventsIterator.next();
}
diagnostics.setQueriedBufferedEvents(
QueriedBufferedEvents.create(startRange, endRange, firstEventRead)); | /*
* Copyright 2023 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.beam.sdk.extensions.ordered;
/**
* Transform for processing ordered events. Events are grouped by the key and within each key they
* are applied according to the provided sequence. Events which arrive out of sequence are buffered
* and reprocessed when new events for a given key arrived.
*
* @param <Event>
* @param <EventKey>
* @param <State>
*/
@AutoValue
@SuppressWarnings({"nullness", "TypeNameShadowing"})
public abstract class OrderedEventProcessor<Event, EventKey, Result, State extends MutableState<Event, Result>> extends
PTransform<PCollection<KV<EventKey, KV<Long, Event>>>, OrderedEventProcessorResult<EventKey, Result, Event>> {
public static final int DEFAULT_STATUS_UPDATE_FREQUENCY_SECONDS = 5;
public static final boolean DEFAULT_PRODUCE_DIAGNOSTIC_EVENTS = false;
private static final boolean DEFAULT_PRODUCE_STATUS_UPDATE_ON_EVERY_EVENT = false;
public static final int DEFAULT_MAX_ELEMENTS_TO_OUTPUT = 10_000;
public static <EventType, KeyType, ResultType, StateType extends MutableState<EventType, ResultType>> OrderedEventProcessor<EventType, KeyType, ResultType, StateType> create(
EventExaminer<EventType, StateType> eventExaminer, Coder<KeyType> keyCoder,
Coder<StateType> stateCoder, Coder<ResultType> resultTypeCoder) {
return new AutoValue_OrderedEventProcessor<>(eventExaminer, null /* no event coder */,
stateCoder, keyCoder, resultTypeCoder,
DEFAULT_STATUS_UPDATE_FREQUENCY_SECONDS, DEFAULT_PRODUCE_STATUS_UPDATE_ON_EVERY_EVENT,
DEFAULT_PRODUCE_DIAGNOSTIC_EVENTS, DEFAULT_MAX_ELEMENTS_TO_OUTPUT);
}
/**
* Default constructor method
*
* @param <EventType>
* @param <KeyType>
* @param <StateType>
* @param eventCoder coder for the Event class
* @param keyCoder coder for the Key class
* @param stateCoder coder for the State class
* @param resultCoder
* @return
*/
public static <EventType, KeyType, ResultType, StateType extends MutableState<EventType, ResultType>> OrderedEventProcessor<EventType, KeyType, ResultType, StateType> create(
EventExaminer<EventType, StateType> eventExaminer, Coder<EventType> eventCoder,
Coder<KeyType> keyCoder, Coder<StateType> stateCoder, Coder<ResultType> resultCoder) {
// TODO: none of the values are marked as @Nullable and the transform will fail if nulls are provided. But need a better error messaging.
return new AutoValue_OrderedEventProcessor<>(eventExaminer, eventCoder,
stateCoder, keyCoder, resultCoder,
DEFAULT_STATUS_UPDATE_FREQUENCY_SECONDS, DEFAULT_PRODUCE_STATUS_UPDATE_ON_EVERY_EVENT,
DEFAULT_PRODUCE_DIAGNOSTIC_EVENTS, DEFAULT_MAX_ELEMENTS_TO_OUTPUT);
}
/**
* Provide a custom status update frequency
*
* @param seconds
* @return
*/
public OrderedEventProcessor<Event, EventKey, Result, State> withStatusUpdateFrequencySeconds(
int seconds) {
return new AutoValue_OrderedEventProcessor<>(
this.getEventExaminer(), this.getEventCoder(), this.getStateCoder(), this.getKeyCoder(),
this.getResultCoder(), seconds,
this.isProduceStatusUpdateOnEveryEvent(), this.isProduceDiagnosticEvents(),
this.getMaxNumberOfResultsPerOutput());
}
public OrderedEventProcessor<Event, EventKey, Result, State> produceDiagnosticEvents(
boolean produceDiagnosticEvents) {
return new AutoValue_OrderedEventProcessor<>(
this.getEventExaminer(), this.getEventCoder(), this.getStateCoder(), this.getKeyCoder(),
this.getResultCoder(),
this.getStatusUpdateFrequencySeconds(), this.isProduceStatusUpdateOnEveryEvent(),
produceDiagnosticEvents, this.getMaxNumberOfResultsPerOutput());
}
/**
* Notice that unless the status frequency update is set to 0 or negative number the status will
* be produced on every event and with the specified frequency.
*/
public OrderedEventProcessor<Event, EventKey, Result, State> produceStatusUpdatesOnEveryEvent(
boolean value) {
return new AutoValue_OrderedEventProcessor<>(
this.getEventExaminer(), this.getEventCoder(), this.getStateCoder(), this.getKeyCoder(),
this.getResultCoder(),
this.getStatusUpdateFrequencySeconds(), value, this.isProduceDiagnosticEvents(),
this.getMaxNumberOfResultsPerOutput());
}
public OrderedEventProcessor<Event, EventKey, Result, State> withMaxResultsPerOutput(
long maxResultsPerOutput) {
return new AutoValue_OrderedEventProcessor<>(
this.getEventExaminer(), this.getEventCoder(), this.getStateCoder(), this.getKeyCoder(),
this.getResultCoder(),
this.getStatusUpdateFrequencySeconds(), this.isProduceStatusUpdateOnEveryEvent(),
this.isProduceDiagnosticEvents(), maxResultsPerOutput);
}
abstract EventExaminer<Event, State> getEventExaminer();
@Nullable
abstract Coder<Event> getEventCoder();
abstract Coder<State> getStateCoder();
@Nullable
abstract Coder<EventKey> getKeyCoder();
abstract Coder<Result> getResultCoder();
abstract int getStatusUpdateFrequencySeconds();
abstract boolean isProduceStatusUpdateOnEveryEvent();
abstract boolean isProduceDiagnosticEvents();
abstract long getMaxNumberOfResultsPerOutput();
@Override
public OrderedEventProcessorResult<EventKey, Result, Event> expand(
PCollection<KV<EventKey, KV<Long, Event>>> input) {
final TupleTag<KV<EventKey, Result>> mainOutput = new TupleTag<>("mainOutput") {
};
final TupleTag<KV<EventKey, OrderedProcessingStatus>> statusOutput = new TupleTag<>("status") {
};
final TupleTag<KV<EventKey, OrderedProcessingDiagnosticEvent>> diagnosticOutput = new TupleTag<>(
"diagnostics") {
};
final TupleTag<KV<EventKey, KV<Long, UnprocessedEvent<Event>>>> unprocessedEventOutput = new TupleTag<>(
"unprocessed-events") {
};
Coder<EventKey> keyCoder = getKeyCoder();
if (keyCoder == null) {
// Assume that the default key coder is used and use the key coder from it.
keyCoder = ((KvCoder<EventKey, KV<Long, Event>>) input.getCoder()).getKeyCoder();
}
Coder<Event> eventCoder = getEventCoder();
if (eventCoder == null) {
// Assume that the default key coder is used and use the event coder from it.
eventCoder = ((KvCoder<Long, Event>) ((KvCoder<EventKey, KV<Long, Event>>) input.getCoder()).getValueCoder()).getValueCoder();
}
PCollectionTuple processingResult = input.apply(ParDo.of(
new OrderedProcessorDoFn<>(getEventExaminer(), eventCoder,
getStateCoder(),
keyCoder, mainOutput, statusOutput,
getStatusUpdateFrequencySeconds() <= 0 ? null
: Duration.standardSeconds(getStatusUpdateFrequencySeconds()), diagnosticOutput,
unprocessedEventOutput,
isProduceDiagnosticEvents(), isProduceStatusUpdateOnEveryEvent(),
input.isBounded() == IsBounded.BOUNDED ? Integer.MAX_VALUE
: getMaxNumberOfResultsPerOutput())).withOutputTags(mainOutput,
TupleTagList.of(Arrays.asList(statusOutput, diagnosticOutput, unprocessedEventOutput))));
KvCoder<EventKey, Result> mainOutputCoder = KvCoder.of(keyCoder, getResultCoder());
KvCoder<EventKey, OrderedProcessingStatus> processingStatusCoder = KvCoder.of(keyCoder,
getOrderedProcessingStatusCoder(input.getPipeline()));
KvCoder<EventKey, OrderedProcessingDiagnosticEvent> diagnosticOutputCoder = KvCoder.of(keyCoder,
getOrderedProcessingDiagnosticsCoder(input.getPipeline()));
KvCoder<EventKey, KV<Long, UnprocessedEvent<Event>>> unprocessedEventsCoder = KvCoder.of(
keyCoder,
KvCoder.of(VarLongCoder.of(), new UnprocessedEventCoder<>(eventCoder)));
return new OrderedEventProcessorResult<>(
input.getPipeline(),
processingResult.get(mainOutput).setCoder(mainOutputCoder),
mainOutput,
processingResult.get(statusOutput).setCoder(processingStatusCoder),
statusOutput,
processingResult.get(diagnosticOutput).setCoder(diagnosticOutputCoder),
diagnosticOutput,
processingResult.get(unprocessedEventOutput).setCoder(unprocessedEventsCoder),
unprocessedEventOutput);
}
private static Coder<OrderedProcessingStatus> getOrderedProcessingStatusCoder(Pipeline pipeline) {
SchemaRegistry schemaRegistry = pipeline.getSchemaRegistry();
Coder<OrderedProcessingStatus> result;
try {
result = SchemaCoder.of(schemaRegistry.getSchema(OrderedProcessingStatus.class),
TypeDescriptor.of(OrderedProcessingStatus.class),
schemaRegistry.getToRowFunction(OrderedProcessingStatus.class),
schemaRegistry.getFromRowFunction(OrderedProcessingStatus.class));
} catch (NoSuchSchemaException e) {
throw new RuntimeException(e);
}
return result;
}
private static Coder<OrderedProcessingDiagnosticEvent> getOrderedProcessingDiagnosticsCoder(
Pipeline pipeline) {
SchemaRegistry schemaRegistry = pipeline.getSchemaRegistry();
Coder<OrderedProcessingDiagnosticEvent> result;
try {
result = SchemaCoder.of(schemaRegistry.getSchema(OrderedProcessingDiagnosticEvent.class),
TypeDescriptor.of(OrderedProcessingDiagnosticEvent.class),
schemaRegistry.getToRowFunction(OrderedProcessingDiagnosticEvent.class),
schemaRegistry.getFromRowFunction(OrderedProcessingDiagnosticEvent.class));
} catch (NoSuchSchemaException e) {
throw new RuntimeException(e);
}
return result;
}
/**
* Main DoFn for processing ordered events
*
* @param <Event>
* @param <EventKey>
* @param <State>
*/
static class OrderedProcessorDoFn<Event, EventKey, Result, State extends MutableState<Event, Result>> extends
DoFn<KV<EventKey, KV<Long, Event>>, KV<EventKey, Result>> {
private static final Logger LOG = LoggerFactory.getLogger(OrderedProcessorDoFn.class);
private static final String PROCESSING_STATE = "processingState";
private static final String MUTABLE_STATE = "mutableState";
private static final String BUFFERED_EVENTS = "bufferedEvents";
private static final String STATUS_EMISSION_TIMER = "statusTimer";
private static final String LARGE_BATCH_EMISSION_TIMER = "largeBatchTimer";
private static final String WINDOW_CLOSED = "windowClosed";
private final EventExaminer<Event, State> eventExaminer;
@StateId(BUFFERED_EVENTS)
@SuppressWarnings("unused")
private final StateSpec<OrderedListState<Event>> bufferedEventsSpec;
@StateId(PROCESSING_STATE)
@SuppressWarnings("unused")
private final StateSpec<ValueState<ProcessingState<EventKey>>> processingStateSpec;
@SuppressWarnings("unused")
@StateId(MUTABLE_STATE)
private final StateSpec<ValueState<State>> mutableStateSpec;
@StateId(WINDOW_CLOSED)
@SuppressWarnings("unused")
private final StateSpec<ValueState<Boolean>> windowClosedSpec;
@TimerId(STATUS_EMISSION_TIMER)
@SuppressWarnings("unused")
private final TimerSpec statusEmissionTimer = TimerSpecs.timer(TimeDomain.PROCESSING_TIME);
@TimerId(LARGE_BATCH_EMISSION_TIMER)
@SuppressWarnings("unused")
private final TimerSpec largeBatchEmissionTimer = TimerSpecs.timer(TimeDomain.EVENT_TIME);
private final TupleTag<KV<EventKey, OrderedProcessingStatus>> statusTupleTag;
private final Duration statusUpdateFrequency;
private final TupleTag<KV<EventKey, Result>> mainOutputTupleTag;
private final TupleTag<KV<EventKey, OrderedProcessingDiagnosticEvent>> diagnosticEventsTupleTag;
private final TupleTag<KV<EventKey, KV<Long, UnprocessedEvent<Event>>>> unprocessedEventsTupleTag;
private final boolean produceDiagnosticEvents;
private final boolean produceStatusUpdateOnEveryEvent;
private final long maxNumberOfResultsToProduce;
private Long numberOfResultsBeforeBundleStart;
/**
* Stateful DoFn to do the bulk of processing
*
* @param eventExaminer
* @param eventCoder
* @param stateCoder
* @param keyCoder
* @param mainOutputTupleTag
* @param statusTupleTag
* @param statusUpdateFrequency
* @param diagnosticEventsTupleTag
* @param unprocessedEventTupleTag
* @param produceDiagnosticEvents
* @param produceStatusUpdateOnEveryEvent
* @param maxNumberOfResultsToProduce
*/
OrderedProcessorDoFn(
EventExaminer<Event, State> eventExaminer, Coder<Event> eventCoder,
Coder<State> stateCoder, Coder<EventKey> keyCoder,
TupleTag<KV<EventKey, Result>> mainOutputTupleTag,
TupleTag<KV<EventKey, OrderedProcessingStatus>> statusTupleTag,
Duration statusUpdateFrequency,
TupleTag<KV<EventKey, OrderedProcessingDiagnosticEvent>> diagnosticEventsTupleTag,
TupleTag<KV<EventKey, KV<Long, UnprocessedEvent<Event>>>> unprocessedEventTupleTag,
boolean produceDiagnosticEvents, boolean produceStatusUpdateOnEveryEvent,
long maxNumberOfResultsToProduce) {
this.eventExaminer = eventExaminer;
this.bufferedEventsSpec = StateSpecs.orderedList(eventCoder);
this.mutableStateSpec = StateSpecs.value(stateCoder);
this.processingStateSpec = StateSpecs.value(ProcessingStateCoder.of(keyCoder));
this.windowClosedSpec = StateSpecs.value(BooleanCoder.of());
this.mainOutputTupleTag = mainOutputTupleTag;
this.statusTupleTag = statusTupleTag;
this.unprocessedEventsTupleTag = unprocessedEventTupleTag;
this.statusUpdateFrequency = statusUpdateFrequency;
this.diagnosticEventsTupleTag = diagnosticEventsTupleTag;
this.produceDiagnosticEvents = produceDiagnosticEvents;
this.produceStatusUpdateOnEveryEvent = produceStatusUpdateOnEveryEvent;
this.maxNumberOfResultsToProduce = maxNumberOfResultsToProduce;
}
@StartBundle
public void onBundleStart() {
numberOfResultsBeforeBundleStart = null;
}
@FinishBundle
public void onBundleFinish() {
// This might be necessary because this field is also used in a Timer
numberOfResultsBeforeBundleStart = null;
}
@ProcessElement
public void processElement(
@StateId(BUFFERED_EVENTS) OrderedListState<Event> bufferedEventsState,
@AlwaysFetched @StateId(PROCESSING_STATE) ValueState<ProcessingState<EventKey>> processingStateState,
@StateId(MUTABLE_STATE) ValueState<State> mutableStateState,
@TimerId(STATUS_EMISSION_TIMER) Timer statusEmissionTimer,
@TimerId(LARGE_BATCH_EMISSION_TIMER) Timer largeBatchEmissionTimer,
@Element KV<EventKey, KV<Long, Event>> eventAndSequence,
MultiOutputReceiver outputReceiver,
BoundedWindow window) {
// TODO: should we make diagnostics generation optional?
OrderedProcessingDiagnosticEvent.Builder diagnostics = OrderedProcessingDiagnosticEvent.builder();
diagnostics.setProcessingTime(Instant.now());
EventKey key = eventAndSequence.getKey();
long sequence = eventAndSequence.getValue().getKey();
Event event = eventAndSequence.getValue().getValue();
diagnostics.setSequenceNumber(sequence);
ProcessingState<EventKey> processingState = processingStateState.read();
if (processingState == null) {
// This is the first time we see this key/window pair
processingState = new ProcessingState<>(key);
if (statusUpdateFrequency != null) {
// Set up the timer to produce the status of the processing on a regular basis
statusEmissionTimer.offset(statusUpdateFrequency).setRelative();
}
}
if (numberOfResultsBeforeBundleStart == null) {
// Per key processing is synchronized by Beam. There is no need to have it here.
numberOfResultsBeforeBundleStart = processingState.getResultCount();
}
processingState.recordReceived();
diagnostics.setReceivedOrder(processingState.getRecordsReceived());
State state = processNewEvent(sequence, event, processingState, mutableStateState,
bufferedEventsState, outputReceiver, diagnostics);
processBufferedEvents(processingState, state, bufferedEventsState,
outputReceiver, largeBatchEmissionTimer, diagnostics);
saveStatesAndOutputDiagnostics(processingStateState, processingState, mutableStateState,
state, outputReceiver, diagnostics, key, window.maxTimestamp());
checkIfProcessingIsCompleted(processingState);
}
private boolean checkIfProcessingIsCompleted(ProcessingState<EventKey> processingState) {
boolean result = processingState.isProcessingCompleted();
if (result) {
LOG.info("Processing for key '" + processingState.getKey() + "' is completed.");
}
return result;
}
private void saveStatesAndOutputDiagnostics(
ValueState<ProcessingState<EventKey>> processingStatusState,
ProcessingState<EventKey> processingStatus, ValueState<State> currentStateState,
State state,
MultiOutputReceiver outputReceiver, Builder diagnostics, EventKey key,
Instant windowTimestamp) {
// There is always a change to the processing status
processingStatusState.write(processingStatus);
// Stored state may not have changes if the element was out of sequence.
if (state != null) {
currentStateState.write(state);
}
if (produceDiagnosticEvents) {
outputReceiver.get(diagnosticEventsTupleTag).output(KV.of(key, diagnostics.build()));
}
if (produceStatusUpdateOnEveryEvent) {
// During pipeline draining the window timestamp is set to a large value in the future.
// Producing an event before that results in error, that's why this logic exist.
Instant statusTimestamp = Instant.now();
statusTimestamp =
statusTimestamp.isAfter(windowTimestamp) ? statusTimestamp : windowTimestamp;
emitProcessingStatus(processingStatus, outputReceiver, statusTimestamp);
}
}
private void emitProcessingStatus(ProcessingState<EventKey> processingState,
MultiOutputReceiver outputReceiver, Instant statusTimestamp) {
outputReceiver.get(statusTupleTag).outputWithTimestamp(KV.of(processingState.getKey(),
OrderedProcessingStatus.create(processingState.getLastOutputSequence(),
processingState.getBufferedRecordCount(),
processingState.getEarliestBufferedSequence(),
processingState.getLatestBufferedSequence(),
processingState.getRecordsReceived(),
processingState.getResultCount(),
processingState.getDuplicates(),
processingState.isLastEventReceived())), statusTimestamp);
}
/**
* Process the just received event
*
* @param currentSequence
* @param currentEvent
* @param processingState
* @param currentStateState
* @param bufferedEventsState
* @param outputReceiver
* @param diagnostics
* @return
*/
private State processNewEvent(long currentSequence, Event currentEvent,
ProcessingState<EventKey> processingState, ValueState<State> currentStateState,
OrderedListState<Event> bufferedEventsState,
MultiOutputReceiver outputReceiver, Builder diagnostics) {
if (currentSequence == Long.MAX_VALUE) {
LOG.error("Received an event with " + currentSequence + " as the sequence number. "
+ "It will be dropped because it needs to be less than Long.MAX_VALUE.");
return null;
}
if (processingState.hasAlreadyBeenProcessed(currentSequence)) {
outputReceiver.get(unprocessedEventsTupleTag).output(KV.of(processingState.getKey(),
KV.of(currentSequence, UnprocessedEvent.create(currentEvent, Reason.duplicate))));
return null;
}
State state;
boolean thisIsTheLastEvent = eventExaminer.isLastEvent(currentSequence, currentEvent);
if (eventExaminer.isInitialEvent(currentSequence, currentEvent)) {
// First event of the key/window
// What if it's a duplicate event - it will reset everything. Shall we drop/DLQ anything that's before
// the processingState.lastOutputSequence?
try {
state = eventExaminer.createStateOnInitialEvent(currentEvent);
} catch (Exception e) {
// TODO: Handle exception in a better way - DLQ.
// Initial state creator can be pretty heavy - remote calls, etc..
throw new RuntimeException(e);
}
processingState.eventAccepted(currentSequence, thisIsTheLastEvent);
Result result = state.produceResult();
if (result != null) {
outputReceiver.get(mainOutputTupleTag).output(KV.of(processingState.getKey(), result));
processingState.resultProduced();
}
// Nothing else to do. We will attempt to process buffered events later.
return state;
}
if (processingState.isNextEvent(currentSequence)) {
// Event matches expected sequence
state = currentStateState.read();
state.mutate(currentEvent);
Result result = state.produceResult();
if (result != null) {
outputReceiver.get(mainOutputTupleTag).output(KV.of(processingState.getKey(), result));
processingState.resultProduced();
}
processingState.eventAccepted(currentSequence, thisIsTheLastEvent);
return state;
}
// Event is not ready to be processed yet
Instant eventTimestamp = Instant.ofEpochMilli(currentSequence);
bufferedEventsState.add(TimestampedValue.of(currentEvent, eventTimestamp));
processingState.eventBuffered(currentSequence, thisIsTheLastEvent);
diagnostics.setEventBufferedTime(eventTimestamp);
// This will signal that the state hasn't been mutated and we don't need to save it.
return null;
}
/**
* Process buffered events
*
* @param processingState
* @param state
* @param bufferedEventsState
* @param outputReceiver
* @param largeBatchEmissionTimer
* @param diagnostics
*/
private void processBufferedEvents(ProcessingState<EventKey> processingState,
State state, OrderedListState<Event> bufferedEventsState,
MultiOutputReceiver outputReceiver,
Timer largeBatchEmissionTimer, Builder diagnostics) {
if (state == null) {
// Only when the current event caused a state mutation and the state is passed to this
// method should we attempt to process buffered events
return;
}
if (!processingState.readyToProcessBufferedEvents()) {
return;
}
if (exceededMaxResultCountForBundle(processingState, largeBatchEmissionTimer)) {
// No point in trying to process buffered events
return;
}
int recordCount = 0;
Instant firstEventRead = null;
Instant startRange = Instant.ofEpochMilli(processingState.getEarliestBufferedSequence());
Instant endRange = Instant.ofEpochMilli(processingState.getLatestBufferedSequence() + 1);
Instant endClearRange = null;
// readRange is efficiently implemented and will bring records in batches
Iterable<TimestampedValue<Event>> events = bufferedEventsState.readRange(startRange,
endRange);
Iterator<TimestampedValue<Event>> bufferedEventsIterator = events.iterator();
while (bufferedEventsIterator.hasNext()) {
TimestampedValue<Event> timestampedEvent = bufferedEventsIterator.next();
Instant eventTimestamp = timestampedEvent.getTimestamp();
long eventSequence = eventTimestamp.getMillis();
if (recordCount++ == 0) {
firstEventRead = eventTimestamp;
}
Event bufferedEvent = timestampedEvent.getValue();
if (processingState.checkForDuplicateBatchedEvent(eventSequence)) {
outputReceiver.get(unprocessedEventsTupleTag).output(KV.of(processingState.getKey(),
KV.of(eventSequence, UnprocessedEvent.create(bufferedEvent, Reason.duplicate))));
continue;
}
if (eventSequence > processingState.getLastOutputSequence() + 1) {
processingState.foundSequenceGap(eventSequence);
// Records will be cleared up to this element
endClearRange = Instant.ofEpochMilli(eventSequence);
break;
}
// This check needs to be done after we checked for sequence gap and before we
// attempt to process the next element which can result in a new result.
if (exceededMaxResultCountForBundle(processingState, largeBatchEmissionTimer)) {
endClearRange = Instant.ofEpochMilli(eventSequence);
break;
}
state.mutate(bufferedEvent);
Result result = state.produceResult();
if (result != null) {
outputReceiver.get(mainOutputTupleTag).output(KV.of(processingState.getKey(), result));
processingState.resultProduced();
}
processingState.processedBufferedEvent(eventSequence);
// Remove this record also
endClearRange = Instant.ofEpochMilli(eventSequence + 1);
}
// Temporarily disabled due to https://github.com/apache/beam/pull/28171
// bufferedEventsState.clearRange(startRange, endClearRange);
// TODO: Draining events is a temporary workaround related to https://github.com/apache/beam/issues/28370
// It can be removed once https://github.com/apache/beam/pull/28371 is available in a regular release
while (bufferedEventsIterator.hasNext()) {
// Read and discard all events
bufferedEventsIterator.next();
}
diagnostics.setQueriedBufferedEvents(
QueriedBufferedEvents.create(startRange, endRange, firstEventRead)); | diagnostics.setClearedBufferedEvents(ClearedBufferedEvents.create(startRange, endClearRange)); | 1 | 2023-11-15 21:26:06+00:00 | 8k |
Hikaito/Fox-Engine | src/system/project/treeElements/ProjectFile.java | [
{
"identifier": "Program",
"path": "src/system/Program.java",
"snippet": "public class Program {\n\n //region initialization------------------------------------------\n\n // \"global\" variables\n private static UserSetting userSetting;\n private static MainWindow window;\n private static... | import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import system.Program;
import system.backbone.FileOperations;
import system.gui.WarningWindow;
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage; | 5,969 | package system.project.treeElements;
//====================================================================================================
// Authors: Hikaito
// Project: Fox Engine
//====================================================================================================
public class ProjectFile extends ProjectCore implements Comparable<ProjectFile> {
// constructor
public ProjectFile(String title, long id){
super("file", id); //super
this.title = title;
}
// longer constructor
public ProjectFile(String path, String title, long id){
super("file", id); //super
this.path = path;
this.title = title;
}
//path for file
@Expose
@SerializedName(value = "filepath")
protected String path = "";
public String getPath(){return path;}
public void setPath(String path){this.path = path;}
public void setNewPath(String directory, String path){
// reject if directory doesn't match
if(!(directory.equals(path.substring(0, directory.length())))){ | package system.project.treeElements;
//====================================================================================================
// Authors: Hikaito
// Project: Fox Engine
//====================================================================================================
public class ProjectFile extends ProjectCore implements Comparable<ProjectFile> {
// constructor
public ProjectFile(String title, long id){
super("file", id); //super
this.title = title;
}
// longer constructor
public ProjectFile(String path, String title, long id){
super("file", id); //super
this.path = path;
this.title = title;
}
//path for file
@Expose
@SerializedName(value = "filepath")
protected String path = "";
public String getPath(){return path;}
public void setPath(String path){this.path = path;}
public void setNewPath(String directory, String path){
// reject if directory doesn't match
if(!(directory.equals(path.substring(0, directory.length())))){ | WarningWindow.warningWindow("File rejected; must be in root folder."); | 2 | 2023-11-12 21:12:21+00:00 | 8k |
KomnisEvangelos/GeoApp | app/src/main/java/gr/ihu/geoapp/ui/dashboard/DashboardFragment.java | [
{
"identifier": "Repository",
"path": "app/src/main/java/gr/ihu/geoapp/managers/Repository.java",
"snippet": "public class Repository {\n private static final String BASE_URL = \"http://192.168.1.6/geoapp/\";\n private static Repository instance;\n\n private Repository() {\n }\n\n public ... | import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Base64;
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 android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.lifecycle.ViewModelProvider;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.google.android.material.chip.Chip;
import com.google.android.material.chip.ChipGroup;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import gr.ihu.geoapp.R;
import gr.ihu.geoapp.databinding.FragmentDashboardBinding;
import gr.ihu.geoapp.databinding.DataLayoutBinding;
import gr.ihu.geoapp.managers.Repository;
import gr.ihu.geoapp.models.users.RegularUser;
import gr.ihu.geoapp.ui.dashboard.PhotoBinActivity.PhotoBinActivity;
import gr.ihu.geoapp.ui.signup.RegisterActivity; | 6,701 | package gr.ihu.geoapp.ui.dashboard;
/**
* This class represents the Dashboard Fragment in the application.
* It provides functionalities for uploading photos, adding tags, and editing descriptions.
* It also sends the uploaded photo along with its metadata to an API server.
*/
public class DashboardFragment extends Fragment {
private FragmentDashboardBinding binding;
private DataLayoutBinding dataLayoutBinding;
public static final int GALLERY_REQUEST_CODE = 1000;
public static final int CAMERA_REQUEST_CODE = 2000;
private DashboardViewModel dashboardViewModel;
private ChipGroup chipGroup;
private String currentDescription = "";
private String currentTitle = "";
private FloatingActionButton fab;
private static final int PICK_PHOTO_REQUEST = 1;
private Bitmap imageBitmap;
private EditText tagEditText;
private EditText descrEditText;
private List<String> tag_csv = null;
private EditText titleEditText;
/**
* Initializes the view of the fragment.
* Sets up the click listeners for the buttons and observes changes in the image path and image bitmap.
*
* @param inflater the LayoutInflater to inflate the view
* @param container the container for the view
* @param savedInstanceState the saved instance state
* @return the view of the fragment
*/
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
dashboardViewModel =
new ViewModelProvider(this).get(DashboardViewModel.class);
binding = FragmentDashboardBinding.inflate(inflater,container, false);
dataLayoutBinding = binding.include;
View root = binding.getRoot();
final ImageView imageView = binding.image;
tag_csv = new ArrayList<>();
chipGroup = binding.chipGroup;
// chipGroup.setOnCheckedChangeListener(new ChipGroup.OnCheckedChangeListener() {
// @Override
// public void onCheckedChanged(ChipGroup group, int checkedId) {
//
// Chip selectedChip = findViewById(checkedId);
// if (selectedChip != null) {
// String category = selectedChip.getText().toString();
// }
// }
// });
Button addButton= binding.addButton;
tagEditText= binding.tagEditText;
descrEditText = dataLayoutBinding.descrEditText;
titleEditText = dataLayoutBinding.titleEditText;
Button addDescrBtn = dataLayoutBinding.addDescrBtn;
Button saveDescrBtn = dataLayoutBinding.saveDescrBtn;
Button editDescrBtn = dataLayoutBinding.editDescrBtn;
Button addTitleBtn = dataLayoutBinding.addTitleBtn;
Button saveTitleBtn = dataLayoutBinding.saveTitleBtn;
Button editTitleBtn = dataLayoutBinding.editTitleBtn;
Button sendPhotoBtn = binding.sendPhotoBtn;
fab = binding.fab;
addTitleBtn.setVisibility(View.GONE);
addDescrBtn.setVisibility(View.GONE);
saveDescrBtn.setVisibility(View.GONE);
editDescrBtn.setVisibility(View.GONE);
saveTitleBtn.setVisibility(View.GONE);
editTitleBtn.setVisibility(View.GONE);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(), PhotoBinActivity.class);
startActivityForResult(intent, PICK_PHOTO_REQUEST);
}
});
addButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String newTag = tagEditText.getText().toString().trim();
if (!newTag.isEmpty()) {
Chip newChip = new Chip(getContext());
newChip.setText(newTag);
chipGroup.addView(newChip);
tag_csv.add(newTag);
tagEditText.setText("");
}
}
});
dashboardViewModel.getImagePath().observe(getViewLifecycleOwner(), imagePath -> {
if (imagePath != null && !imagePath.isEmpty()) {
Glide.with(requireContext()).load(imagePath).into(imageView);
}
});
dashboardViewModel.getImageBitmap().observe(getViewLifecycleOwner(), imageBitmap -> {
if (imageBitmap != null) {
imageView.setImageBitmap(imageBitmap);
}
});
sendPhotoBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ByteArrayOutputStream byteArrayOutputStream;
byteArrayOutputStream = new ByteArrayOutputStream();
if (imageBitmap != null) {
imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
byte[] bytes = byteArrayOutputStream.toByteArray();
final String base64Image = Base64.encodeToString(bytes, Base64.DEFAULT);
String url = "http://192.168.1.2/geoapp/img/photo_profile.php";
RequestQueue queue = Volley.newRequestQueue(getContext());
// request method to post the data to API
StringRequest request = new StringRequest(Request.Method.POST, url, new com.android.volley.Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
Log.d("response",response);
JSONObject jsonResponse = new JSONObject(response);
String status = jsonResponse.getString("status");
if (status.equals("success")) {
String targetPath = jsonResponse.getString("targetPath");
//user.setPhoto(targetPath);
//SharedPrefManager.getInstance(getContext()).setPhoto(targetPath);
Toast.makeText(getContext(), "Data added to API", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getContext(), "Failed", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new com.android.volley.Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// method to handle errors.
Toast.makeText(getContext(), "Fail to get response = " + error.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
}
}) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("image", base64Image); | package gr.ihu.geoapp.ui.dashboard;
/**
* This class represents the Dashboard Fragment in the application.
* It provides functionalities for uploading photos, adding tags, and editing descriptions.
* It also sends the uploaded photo along with its metadata to an API server.
*/
public class DashboardFragment extends Fragment {
private FragmentDashboardBinding binding;
private DataLayoutBinding dataLayoutBinding;
public static final int GALLERY_REQUEST_CODE = 1000;
public static final int CAMERA_REQUEST_CODE = 2000;
private DashboardViewModel dashboardViewModel;
private ChipGroup chipGroup;
private String currentDescription = "";
private String currentTitle = "";
private FloatingActionButton fab;
private static final int PICK_PHOTO_REQUEST = 1;
private Bitmap imageBitmap;
private EditText tagEditText;
private EditText descrEditText;
private List<String> tag_csv = null;
private EditText titleEditText;
/**
* Initializes the view of the fragment.
* Sets up the click listeners for the buttons and observes changes in the image path and image bitmap.
*
* @param inflater the LayoutInflater to inflate the view
* @param container the container for the view
* @param savedInstanceState the saved instance state
* @return the view of the fragment
*/
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
dashboardViewModel =
new ViewModelProvider(this).get(DashboardViewModel.class);
binding = FragmentDashboardBinding.inflate(inflater,container, false);
dataLayoutBinding = binding.include;
View root = binding.getRoot();
final ImageView imageView = binding.image;
tag_csv = new ArrayList<>();
chipGroup = binding.chipGroup;
// chipGroup.setOnCheckedChangeListener(new ChipGroup.OnCheckedChangeListener() {
// @Override
// public void onCheckedChanged(ChipGroup group, int checkedId) {
//
// Chip selectedChip = findViewById(checkedId);
// if (selectedChip != null) {
// String category = selectedChip.getText().toString();
// }
// }
// });
Button addButton= binding.addButton;
tagEditText= binding.tagEditText;
descrEditText = dataLayoutBinding.descrEditText;
titleEditText = dataLayoutBinding.titleEditText;
Button addDescrBtn = dataLayoutBinding.addDescrBtn;
Button saveDescrBtn = dataLayoutBinding.saveDescrBtn;
Button editDescrBtn = dataLayoutBinding.editDescrBtn;
Button addTitleBtn = dataLayoutBinding.addTitleBtn;
Button saveTitleBtn = dataLayoutBinding.saveTitleBtn;
Button editTitleBtn = dataLayoutBinding.editTitleBtn;
Button sendPhotoBtn = binding.sendPhotoBtn;
fab = binding.fab;
addTitleBtn.setVisibility(View.GONE);
addDescrBtn.setVisibility(View.GONE);
saveDescrBtn.setVisibility(View.GONE);
editDescrBtn.setVisibility(View.GONE);
saveTitleBtn.setVisibility(View.GONE);
editTitleBtn.setVisibility(View.GONE);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(), PhotoBinActivity.class);
startActivityForResult(intent, PICK_PHOTO_REQUEST);
}
});
addButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String newTag = tagEditText.getText().toString().trim();
if (!newTag.isEmpty()) {
Chip newChip = new Chip(getContext());
newChip.setText(newTag);
chipGroup.addView(newChip);
tag_csv.add(newTag);
tagEditText.setText("");
}
}
});
dashboardViewModel.getImagePath().observe(getViewLifecycleOwner(), imagePath -> {
if (imagePath != null && !imagePath.isEmpty()) {
Glide.with(requireContext()).load(imagePath).into(imageView);
}
});
dashboardViewModel.getImageBitmap().observe(getViewLifecycleOwner(), imageBitmap -> {
if (imageBitmap != null) {
imageView.setImageBitmap(imageBitmap);
}
});
sendPhotoBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ByteArrayOutputStream byteArrayOutputStream;
byteArrayOutputStream = new ByteArrayOutputStream();
if (imageBitmap != null) {
imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
byte[] bytes = byteArrayOutputStream.toByteArray();
final String base64Image = Base64.encodeToString(bytes, Base64.DEFAULT);
String url = "http://192.168.1.2/geoapp/img/photo_profile.php";
RequestQueue queue = Volley.newRequestQueue(getContext());
// request method to post the data to API
StringRequest request = new StringRequest(Request.Method.POST, url, new com.android.volley.Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
Log.d("response",response);
JSONObject jsonResponse = new JSONObject(response);
String status = jsonResponse.getString("status");
if (status.equals("success")) {
String targetPath = jsonResponse.getString("targetPath");
//user.setPhoto(targetPath);
//SharedPrefManager.getInstance(getContext()).setPhoto(targetPath);
Toast.makeText(getContext(), "Data added to API", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getContext(), "Failed", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new com.android.volley.Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// method to handle errors.
Toast.makeText(getContext(), "Fail to get response = " + error.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
}
}) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("image", base64Image); | params.put("user_id", RegularUser.getInstance().getUserId()); | 1 | 2023-11-10 17:43:18+00:00 | 8k |
Nel1yMinecraft/Grim | src/main/java/ac/grim/grimac/predictionengine/predictions/rideable/PredictionEngineRideableLava.java | [
{
"identifier": "GrimPlayer",
"path": "src/main/java/ac/grim/grimac/player/GrimPlayer.java",
"snippet": "public class GrimPlayer {\n public final UUID playerUUID;\n public final int entityID;\n public final Player bukkitPlayer;\n // Determining player ping\n // The difference between keep... | import ac.grim.grimac.player.GrimPlayer;
import ac.grim.grimac.predictionengine.predictions.PredictionEngineLava;
import ac.grim.grimac.utils.data.VectorData;
import org.bukkit.util.Vector;
import java.util.List;
import java.util.Set; | 6,071 | package ac.grim.grimac.predictionengine.predictions.rideable;
public class PredictionEngineRideableLava extends PredictionEngineLava {
Vector movementVector;
public PredictionEngineRideableLava(Vector movementVector) {
this.movementVector = movementVector;
}
@Override | package ac.grim.grimac.predictionengine.predictions.rideable;
public class PredictionEngineRideableLava extends PredictionEngineLava {
Vector movementVector;
public PredictionEngineRideableLava(Vector movementVector) {
this.movementVector = movementVector;
}
@Override | public void addJumpsToPossibilities(GrimPlayer player, Set<VectorData> existingVelocities) { | 2 | 2023-11-11 05:14:12+00:00 | 8k |
kawainime/IOT-Smart_Farming | IOT_Farm_V.2/src/Core/Background/boot_Up.java | [
{
"identifier": "Connector",
"path": "IOT_Farm_V.2/src/Core/MySql/Connector.java",
"snippet": "public class Connector\n{\n public static Connection connection()\n {\n Connection conn = null;\n \n String host = Load_Settings.load_data(\"HOST\");\n \n String port =... | import Core.MySql.Connector;
import UI.home;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement; | 4,515 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Core.Background;
/**
*
* @author Jayashanka Deshan
*/
public class boot_Up implements Runnable
{
private final Thread thread;
public boot_Up()
{
thread = new Thread(this);
}
@Override
public void run()
{ | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Core.Background;
/**
*
* @author Jayashanka Deshan
*/
public class boot_Up implements Runnable
{
private final Thread thread;
public boot_Up()
{
thread = new Thread(this);
}
@Override
public void run()
{ | Connection connection = Connector.connection(); | 0 | 2023-11-11 08:23:10+00:00 | 8k |
Outer-Fields/item-server | src/main/java/io/mindspice/itemserver/configuration/ServiceConfig.java | [
{
"identifier": "PackType",
"path": "src/main/java/io/mindspice/itemserver/schema/PackType.java",
"snippet": "public enum PackType {\n BOOSTER(12),\n STARTER(39);\n\n public int cardAmount;\n\n PackType(int cardAmount) {\n this.cardAmount = cardAmount;\n }\n\n}"
},
{
"ident... | import io.mindspice.databaseservice.client.api.OkraChiaAPI;
import io.mindspice.databaseservice.client.api.OkraGameAPI;
import io.mindspice.databaseservice.client.api.OkraNFTAPI;
import io.mindspice.databaseservice.client.schema.Card;
import io.mindspice.itemserver.schema.PackType;
import io.mindspice.itemserver.Settings;
import io.mindspice.itemserver.monitor.BlockchainMonitor;
import io.mindspice.itemserver.services.*;
import io.mindspice.itemserver.util.CustomLogger;
import io.mindspice.itemserver.util.TransactLogger;
import io.mindspice.jxch.rpc.http.FullNodeAPI;
import io.mindspice.jxch.rpc.http.WalletAPI;
import io.mindspice.jxch.rpc.schemas.wallet.nft.MetaData;
import io.mindspice.jxch.transact.settings.JobConfig;
import io.mindspice.mindlib.data.tuples.Pair;
import io.mindspice.mindlib.http.UnsafeHttpJsonClient;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.io.IOException;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit; | 5,194 | package io.mindspice.itemserver.configuration;
@Configuration
public class ServiceConfig {
@Bean(destroyMethod = "shutdown")
public ScheduledExecutorService executor() {
return Executors.newScheduledThreadPool(6);
}
@Bean
public UnsafeHttpJsonClient authResponseClient() {
return new UnsafeHttpJsonClient();
}
@Bean
public BlockchainMonitor blockchainMonitor(
@Qualifier("mainNodeAPI") FullNodeAPI monNodeApi,
@Qualifier("monWalletAPI") WalletAPI monWalletApi,
@Qualifier("okraChiaAPI") OkraChiaAPI okraChiaAPI,
@Qualifier("okraNFTAPI") OkraNFTAPI okraNFTAPI,
@Qualifier("mintService") CardMintService mintService,
@Qualifier("cardList") List<Card> cardList, | package io.mindspice.itemserver.configuration;
@Configuration
public class ServiceConfig {
@Bean(destroyMethod = "shutdown")
public ScheduledExecutorService executor() {
return Executors.newScheduledThreadPool(6);
}
@Bean
public UnsafeHttpJsonClient authResponseClient() {
return new UnsafeHttpJsonClient();
}
@Bean
public BlockchainMonitor blockchainMonitor(
@Qualifier("mainNodeAPI") FullNodeAPI monNodeApi,
@Qualifier("monWalletAPI") WalletAPI monWalletApi,
@Qualifier("okraChiaAPI") OkraChiaAPI okraChiaAPI,
@Qualifier("okraNFTAPI") OkraNFTAPI okraNFTAPI,
@Qualifier("mintService") CardMintService mintService,
@Qualifier("cardList") List<Card> cardList, | @Qualifier("assetTable") Map<String, Pair<String, PackType>> assetTable, | 0 | 2023-11-14 14:56:37+00:00 | 8k |
CodecNomad/CodecClient | src/main/java/com/github/codecnomad/codecclient/modules/FishingMacro.java | [
{
"identifier": "Client",
"path": "src/main/java/com/github/codecnomad/codecclient/Client.java",
"snippet": "@Mod(modid = \"codecclient\", useMetadata = true)\npublic class Client {\n public static Map<String, Module> modules = new HashMap<>();\n public static Minecraft mc = Minecraft.getMinecraft... | import com.github.codecnomad.codecclient.Client;
import com.github.codecnomad.codecclient.events.PacketEvent;
import com.github.codecnomad.codecclient.mixins.S19PacketAccessor;
import com.github.codecnomad.codecclient.ui.Config;
import com.github.codecnomad.codecclient.utils.Math;
import com.github.codecnomad.codecclient.utils.*;
import net.minecraft.client.Minecraft;
import net.minecraft.client.settings.KeyBinding;
import net.minecraft.entity.Entity;
import net.minecraft.entity.item.EntityArmorStand;
import net.minecraft.entity.passive.EntitySquid;
import net.minecraft.entity.projectile.EntityFishHook;
import net.minecraft.item.*;
import net.minecraft.network.play.server.*;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.BlockPos;
import net.minecraftforge.client.event.ClientChatReceivedEvent;
import net.minecraftforge.client.event.RenderWorldLastEvent;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.entity.EntityJoinWorldEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.TickEvent;
import java.util.List;
import java.util.regex.Matcher; | 4,215 | double expandedMaxY = aabb.maxY + 1;
double expandedMaxZ = aabb.maxZ + 1;
lastAABB = new AxisAlignedBB(expandedMinX, expandedMinY, expandedMinZ, expandedMaxX, expandedMaxY, expandedMaxZ);
double randomX = expandedMinX + java.lang.Math.random() * (expandedMaxX - expandedMinX);
double randomY = expandedMinY + java.lang.Math.random() * (expandedMaxY - expandedMinY);
double randomZ = expandedMinZ + java.lang.Math.random() * (expandedMaxZ - expandedMinZ);
Client.rotation.setYaw(Math.getYaw(new BlockPos(randomX, randomY, randomZ)), 5);
Client.rotation.setPitch(Math.getPitch(new BlockPos(randomX, randomY, randomZ)), 5);
}
for (Entity entity : Client.mc.theWorld.loadedEntityList) {
if (entity instanceof EntityFishHook && ((EntityFishHook) entity).angler == Client.mc.thePlayer) {
fishingHook = entity;
}
}
if (fishingHook == null) {
currentStep = FishingSteps.FIND_ROD;
return;
}
if (fishingMarker != null && fishingMarker.isEntityAlive() && fishingMarker.getName().contains("!!!")) {
currentStep = FishingSteps.CATCH;
fishingMarker = null;
return;
}
return;
}
case CATCH: {
KeyBinding.onTick(Client.mc.gameSettings.keyBindUseItem.getKeyCode());
if (Config.AutoKill) {
currentStep = FishingSteps.KILL_DELAY;
} else {
currentStep = FishingSteps.FIND_ROD;
}
catches++;
}
case KILL_DELAY: {
if (MainCounter.countUntil(Config.KillDelay)) {
return;
}
currentStep = FishingSteps.KILL_MONSTER;
}
case KILL_MONSTER: {
if (fishingMonster == null || !fishingMonster.isEntityAlive() || !Client.mc.thePlayer.canEntityBeSeen(fishingMonster)) {
currentStep = FishingSteps.FIND_ROD;
fishingMonster = null;
return;
}
Client.mc.thePlayer.inventory.currentItem = Config.WeaponSlot - 1;
AxisAlignedBB boundingBox = fishingMonster.getEntityBoundingBox();
double deltaX = boundingBox.maxX - boundingBox.minX;
double deltaY = boundingBox.maxY - boundingBox.minY;
double deltaZ = boundingBox.maxZ - boundingBox.minZ;
BlockPos randomPositionOnBoundingBox = new BlockPos(boundingBox.minX + deltaX, boundingBox.minY + deltaY, boundingBox.minZ + deltaZ);
Client.rotation.setYaw(Math.getYaw(randomPositionOnBoundingBox), Config.RotationSmoothing);
Client.rotation.setPitch(Math.getPitch(randomPositionOnBoundingBox), Config.RotationSmoothing);
if (!MainCounter.countUntil(20 / Config.AttackCps)) {
MainCounter.add(java.lang.Math.random() * 100 > 70 ? 1 : 0);
if (Config.RightClick) {
KeyBinding.onTick(Client.mc.gameSettings.keyBindUseItem.getKeyCode());
return;
}
KeyBinding.onTick(Client.mc.gameSettings.keyBindAttack.getKeyCode());
}
}
}
}
@SubscribeEvent
public void renderWorld(RenderWorldLastEvent event) {
if (lastAABB != null) {
Render.drawOutlinedFilledBoundingBox(lastAABB, Config.VisualColor.toJavaColor(), event.partialTicks);
}
}
@SubscribeEvent
public void entitySpawn(EntityJoinWorldEvent event) {
if (fishingHook == null || event.entity instanceof EntitySquid || event.entity.getName().equals("item.tile.stone.stone")) {
return;
}
if (event.entity instanceof EntityArmorStand && event.entity.getDistanceToEntity(fishingHook) <= 0.1) {
fishingMarker = event.entity;
return;
}
if (fishingMonster == null &&
event.entity.getDistanceToEntity(fishingHook) <= 1.5
) {
fishingMonster = event.entity;
}
}
@SubscribeEvent
public void chatReceive(ClientChatReceivedEvent event) {
if (event.type != 2) {
return;
}
Matcher matcher = Regex.FishingSkillPattern.matcher(event.message.getFormattedText());
if (matcher.find()) {
xpGain += Float.parseFloat(matcher.group(1));
}
}
@SubscribeEvent | package com.github.codecnomad.codecclient.modules;
@SuppressWarnings("DuplicatedCode")
public class FishingMacro extends Module {
public static final String[] FAILSAFE_TEXT = new String[]{"?", "you good?", "HI IM HERE", "can you not bro", "can you dont", "j g growl wtf", "can i get friend request??", "hello i'm here",};
public static int startTime = 0;
public static int catches = 0;
public static float xpGain = 0;
public static FishingSteps currentStep = FishingSteps.FIND_ROD;
public static Counter MainCounter = new Counter();
public static Counter AlternativeCounter = new Counter();
public static Counter FailsafeCounter = new Counter();
public static boolean failSafe = false;
Entity fishingHook = null;
Entity fishingMarker = null;
Entity fishingMonster = null;
public static float lastYaw = 0;
public static float lastPitch = 0;
public static AxisAlignedBB lastAABB = null;
public BlockPos startPos = null;
public static Pathfinding pathfinding = new Pathfinding();
@Override
public void register() {
MinecraftForge.EVENT_BUS.register(this);
this.state = true;
lastYaw = Client.mc.thePlayer.rotationYaw;
lastPitch = Client.mc.thePlayer.rotationPitch;
Sound.disableSounds();
startTime = (int) java.lang.Math.floor((double) System.currentTimeMillis() / 1000);
startPos = Client.mc.thePlayer.getPosition();
}
@Override
public void unregister() {
MinecraftForge.EVENT_BUS.unregister(this);
this.state = false;
Client.rotation.updatePitch = false;
Client.rotation.updateYaw = false;
lastPitch = 0;
lastYaw = 0;
Sound.enableSounds();
startTime = 0;
catches = 0;
xpGain = 0;
currentStep = FishingSteps.FIND_ROD;
MainCounter.reset();
FailsafeCounter.reset();
failSafe = false;
fishingHook = null;
fishingMarker = null;
fishingMonster = null;
lastAABB = null;
startPos = null;
}
@SubscribeEvent
public void onTick(TickEvent.ClientTickEvent event) {
if (failSafe) {
return;
}
switch (currentStep) {
case GO_BACK_TO_ORIGINAL: {
currentStep = FishingSteps.EMPTY;
List<BlockPos> path = pathfinding.createPath(Client.mc.thePlayer.getPosition().add(0, -1 , 0), startPos.add(0, -1, 0));
new Walker(path, () -> {
currentStep = FishingSteps.FIND_ROD;
}).start();
return;
}
case FIND_ROD: {
if (startPos != null && Client.mc.thePlayer.getPosition().distanceSq(startPos) > 1.5) {
currentStep = FishingSteps.GO_BACK_TO_ORIGINAL;
return;
}
for (int slotIndex = 0; slotIndex < 9; slotIndex++) {
ItemStack stack = Client.mc.thePlayer.inventory.getStackInSlot(slotIndex);
if (stack != null && stack.getItem() instanceof ItemFishingRod) {
Client.rotation.setYaw(lastYaw, Config.RotationSmoothing);
Client.rotation.setPitch(lastPitch, Config.RotationSmoothing);
Client.mc.thePlayer.inventory.currentItem = slotIndex;
currentStep = FishingSteps.CAST_HOOK;
return;
}
}
Chat.sendMessage("Disabled macro -> couldn't find rod.");
this.unregister();
return;
}
case CAST_HOOK: {
if (Client.rotation.updateYaw || Client.rotation.updatePitch) {
return;
}
KeyBinding.onTick(Client.mc.gameSettings.keyBindUseItem.getKeyCode());
currentStep = FishingSteps.WAIT_FOR_CATCH;
return;
}
case WAIT_FOR_CATCH: {
if (MainCounter.countUntil(Config.FishingDelay)) {
return;
}
if (!AlternativeCounter.countUntil(Config.MovementFrequency)) {
if (fishingHook == null) {
currentStep = FishingSteps.FIND_ROD;
return;
}
AxisAlignedBB aabb = fishingHook.getEntityBoundingBox();
double expandedMinX = aabb.minX - 1;
double expandedMinY = aabb.minY - 1;
double expandedMinZ = aabb.minZ - 1;
double expandedMaxX = aabb.maxX + 1;
double expandedMaxY = aabb.maxY + 1;
double expandedMaxZ = aabb.maxZ + 1;
lastAABB = new AxisAlignedBB(expandedMinX, expandedMinY, expandedMinZ, expandedMaxX, expandedMaxY, expandedMaxZ);
double randomX = expandedMinX + java.lang.Math.random() * (expandedMaxX - expandedMinX);
double randomY = expandedMinY + java.lang.Math.random() * (expandedMaxY - expandedMinY);
double randomZ = expandedMinZ + java.lang.Math.random() * (expandedMaxZ - expandedMinZ);
Client.rotation.setYaw(Math.getYaw(new BlockPos(randomX, randomY, randomZ)), 5);
Client.rotation.setPitch(Math.getPitch(new BlockPos(randomX, randomY, randomZ)), 5);
}
for (Entity entity : Client.mc.theWorld.loadedEntityList) {
if (entity instanceof EntityFishHook && ((EntityFishHook) entity).angler == Client.mc.thePlayer) {
fishingHook = entity;
}
}
if (fishingHook == null) {
currentStep = FishingSteps.FIND_ROD;
return;
}
if (fishingMarker != null && fishingMarker.isEntityAlive() && fishingMarker.getName().contains("!!!")) {
currentStep = FishingSteps.CATCH;
fishingMarker = null;
return;
}
return;
}
case CATCH: {
KeyBinding.onTick(Client.mc.gameSettings.keyBindUseItem.getKeyCode());
if (Config.AutoKill) {
currentStep = FishingSteps.KILL_DELAY;
} else {
currentStep = FishingSteps.FIND_ROD;
}
catches++;
}
case KILL_DELAY: {
if (MainCounter.countUntil(Config.KillDelay)) {
return;
}
currentStep = FishingSteps.KILL_MONSTER;
}
case KILL_MONSTER: {
if (fishingMonster == null || !fishingMonster.isEntityAlive() || !Client.mc.thePlayer.canEntityBeSeen(fishingMonster)) {
currentStep = FishingSteps.FIND_ROD;
fishingMonster = null;
return;
}
Client.mc.thePlayer.inventory.currentItem = Config.WeaponSlot - 1;
AxisAlignedBB boundingBox = fishingMonster.getEntityBoundingBox();
double deltaX = boundingBox.maxX - boundingBox.minX;
double deltaY = boundingBox.maxY - boundingBox.minY;
double deltaZ = boundingBox.maxZ - boundingBox.minZ;
BlockPos randomPositionOnBoundingBox = new BlockPos(boundingBox.minX + deltaX, boundingBox.minY + deltaY, boundingBox.minZ + deltaZ);
Client.rotation.setYaw(Math.getYaw(randomPositionOnBoundingBox), Config.RotationSmoothing);
Client.rotation.setPitch(Math.getPitch(randomPositionOnBoundingBox), Config.RotationSmoothing);
if (!MainCounter.countUntil(20 / Config.AttackCps)) {
MainCounter.add(java.lang.Math.random() * 100 > 70 ? 1 : 0);
if (Config.RightClick) {
KeyBinding.onTick(Client.mc.gameSettings.keyBindUseItem.getKeyCode());
return;
}
KeyBinding.onTick(Client.mc.gameSettings.keyBindAttack.getKeyCode());
}
}
}
}
@SubscribeEvent
public void renderWorld(RenderWorldLastEvent event) {
if (lastAABB != null) {
Render.drawOutlinedFilledBoundingBox(lastAABB, Config.VisualColor.toJavaColor(), event.partialTicks);
}
}
@SubscribeEvent
public void entitySpawn(EntityJoinWorldEvent event) {
if (fishingHook == null || event.entity instanceof EntitySquid || event.entity.getName().equals("item.tile.stone.stone")) {
return;
}
if (event.entity instanceof EntityArmorStand && event.entity.getDistanceToEntity(fishingHook) <= 0.1) {
fishingMarker = event.entity;
return;
}
if (fishingMonster == null &&
event.entity.getDistanceToEntity(fishingHook) <= 1.5
) {
fishingMonster = event.entity;
}
}
@SubscribeEvent
public void chatReceive(ClientChatReceivedEvent event) {
if (event.type != 2) {
return;
}
Matcher matcher = Regex.FishingSkillPattern.matcher(event.message.getFormattedText());
if (matcher.find()) {
xpGain += Float.parseFloat(matcher.group(1));
}
}
@SubscribeEvent | public void packetReceive(PacketEvent.ReceiveEvent event) { | 1 | 2023-11-16 10:12:20+00:00 | 8k |
maarlakes/common | src/main/java/cn/maarlakes/common/factory/datetime/DateTimeFactories.java | [
{
"identifier": "Ordered",
"path": "src/main/java/cn/maarlakes/common/Ordered.java",
"snippet": "public interface Ordered {\n\n int HIGHEST = Integer.MIN_VALUE;\n\n int LOWEST = Integer.MAX_VALUE;\n\n int order();\n}"
},
{
"identifier": "OrderedComparator",
"path": "src/main/java/cn... | import cn.maarlakes.common.Ordered;
import cn.maarlakes.common.OrderedComparator;
import cn.maarlakes.common.spi.SpiServiceLoader;
import cn.maarlakes.common.utils.Comparators;
import cn.maarlakes.common.utils.Lazy;
import jakarta.annotation.Nonnull;
import java.time.*;
import java.time.chrono.ChronoLocalDate;
import java.time.chrono.ChronoLocalDateTime;
import java.time.chrono.ChronoZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.format.SignStyle;
import java.time.temporal.TemporalAccessor;
import java.time.temporal.TemporalQueries;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import static java.time.temporal.ChronoField.*; | 6,565 | @Nonnull
public static LocalDateTime fromEpochMilli(long epocMilli, @Nonnull ZoneId zone) {
return LocalDateTime.ofInstant(Instant.ofEpochMilli(epocMilli), zone);
}
public static long toEpochSecond(@Nonnull LocalDateTime dateTime) {
return toEpochSecond(dateTime, ZoneOffset.systemDefault().getRules().getOffset(dateTime));
}
public static long toEpochSecond(@Nonnull LocalDateTime dateTime, @Nonnull ZoneOffset offset) {
return toEpochMilli(dateTime, offset) / 1000;
}
public static long toEpochMilli(@Nonnull LocalDateTime dateTime) {
return toEpochMilli(dateTime, ZoneOffset.systemDefault().getRules().getOffset(dateTime));
}
public static long toEpochMilli(@Nonnull LocalDateTime dateTime, @Nonnull ZoneOffset offset) {
return dateTime.toInstant(offset).toEpochMilli();
}
private static LocalDateTime toLocalDateTime(@Nonnull TemporalAccessor accessor) {
if (accessor instanceof LocalDateTime) {
return (LocalDateTime) accessor;
}
if (accessor instanceof ZonedDateTime) {
return ((ZonedDateTime) accessor).toLocalDateTime();
}
if (accessor instanceof OffsetDateTime) {
return ((OffsetDateTime) accessor).toLocalDateTime();
}
if (accessor instanceof LocalDate) {
return LocalDateTime.of((LocalDate) accessor, LocalTime.MIN);
}
if (accessor instanceof LocalTime) {
return LocalDateTime.of(LocalDate.now(), (LocalTime) accessor);
}
if (accessor instanceof OffsetTime) {
return LocalDateTime.of(LocalDate.now(), ((OffsetTime) accessor).toLocalTime());
}
if (accessor instanceof Instant) {
final Instant instant = (Instant) accessor;
return LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
}
final LocalDate date = tryToLocalDate(accessor);
final LocalTime time = tryToLocalTime(accessor);
if (date != null) {
if (time == null) {
return LocalDateTime.of(date, LocalTime.MIDNIGHT);
}
return LocalDateTime.of(date, time);
}
if (time != null) {
return LocalDateTime.of(LocalDate.now(), time);
}
return LocalDateTime.from(accessor);
}
private static LocalDate tryToLocalDate(@Nonnull TemporalAccessor accessor) {
if (accessor instanceof LocalDate) {
return (LocalDate) accessor;
}
if (accessor.isSupported(EPOCH_DAY)) {
return LocalDate.ofEpochDay(accessor.getLong(EPOCH_DAY));
}
if (!accessor.isSupported(YEAR)) {
if (!accessor.isSupported(MONTH_OF_YEAR)) {
return null;
}
final int month = accessor.get(MONTH_OF_YEAR);
final LocalDate now = LocalDate.now();
if (!accessor.isSupported(DAY_OF_MONTH)) {
return LocalDate.of(now.getYear(), month, 1);
}
return LocalDate.of(now.getYear(), month, accessor.get(DAY_OF_MONTH));
}
if (!accessor.isSupported(MONTH_OF_YEAR)) {
return LocalDate.of(accessor.get(YEAR), 1, 1);
}
if (!accessor.isSupported(DAY_OF_MONTH)) {
return LocalDate.of(accessor.get(YEAR), accessor.get(MONTH_OF_YEAR), 1);
}
return LocalDate.of(accessor.get(YEAR), accessor.get(MONTH_OF_YEAR), accessor.get(DAY_OF_MONTH));
}
private static LocalTime tryToLocalTime(@Nonnull TemporalAccessor accessor) {
if (accessor instanceof LocalTime) {
return (LocalTime) accessor;
}
if (accessor instanceof OffsetTime) {
return ((OffsetTime) accessor).toLocalTime();
}
final LocalTime time = accessor.query(TemporalQueries.localTime());
if (time != null) {
return time;
}
if (accessor.isSupported(SECOND_OF_DAY)) {
return LocalTime.ofSecondOfDay(accessor.getLong(SECOND_OF_DAY));
}
if (!accessor.isSupported(HOUR_OF_DAY)) {
return null;
}
final int hour = accessor.get(HOUR_OF_DAY);
if (!accessor.isSupported(MINUTE_OF_HOUR)) {
return LocalTime.of(hour, 0);
}
final int minute = accessor.get(MINUTE_OF_HOUR);
if (!accessor.isSupported(SECOND_OF_MINUTE)) {
return LocalTime.of(hour, minute);
}
final int second = accessor.get(SECOND_OF_MINUTE);
if (!accessor.isSupported(NANO_OF_SECOND)) {
return LocalTime.of(hour, minute, second);
}
return LocalTime.of(hour, minute, second, accessor.get(NANO_OF_SECOND));
}
| package cn.maarlakes.common.factory.datetime;
/**
* @author linjpxc
*/
public final class DateTimeFactories {
private DateTimeFactories() {
}
private static final Supplier<List<ParserWrapper>> PARSER = Lazy.of(() ->
StreamSupport.stream(SpiServiceLoader.loadShared(DateTimeParser.class, DateTimeParser.class.getClassLoader()).spliterator(), false)
.map(ParserWrapper::new)
.collect(Collectors.toList())
);
private static final Comparator<Object> COMPARATOR = OrderedComparator.getInstance().reversed();
public static final DateTimeFormatter TIME_FORMATTER = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendValue(HOUR_OF_DAY, 1, 2, SignStyle.NOT_NEGATIVE)
.optionalStart()
.appendLiteral(':')
.optionalEnd()
.appendValue(MINUTE_OF_HOUR, 1, 2, SignStyle.NOT_NEGATIVE)
.optionalStart()
.appendLiteral(':')
.optionalEnd()
.optionalStart()
.appendValue(SECOND_OF_MINUTE, 1, 2, SignStyle.NOT_NEGATIVE)
.optionalStart()
.appendFraction(NANO_OF_SECOND, 0, 9, true)
.optionalEnd()
.optionalStart()
.appendFraction(NANO_OF_SECOND, 0, 9, false)
.optionalEnd()
.optionalStart()
.appendOffsetId()
.toFormatter();
public static final DateTimeFormatter DATE_FORMATTER = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.optionalStart()
.appendValueReduced(YEAR_OF_ERA, 2, 4, LocalDate.of(2000, 1, 1))
.optionalEnd()
.optionalStart()
.appendLiteral('-')
.optionalEnd()
.optionalStart()
.appendLiteral('/')
.optionalEnd()
.optionalStart()
.appendLiteral('年')
.optionalEnd()
.appendValue(MONTH_OF_YEAR, 1, 2, SignStyle.NORMAL)
.optionalStart()
.appendLiteral('-')
.optionalEnd()
.optionalStart()
.appendLiteral('/')
.optionalEnd()
.optionalStart()
.appendLiteral('月')
.optionalEnd()
.appendValue(DAY_OF_MONTH, 1, 2, SignStyle.NORMAL)
.optionalStart()
.appendLiteral('日')
.optionalEnd()
.toFormatter();
public static final DateTimeFormatter DATE_TIME_FORMATTER = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.append(DATE_FORMATTER)
.optionalStart()
.appendLiteral(' ')
.optionalEnd()
.optionalStart()
.appendLiteral('T')
.optionalEnd()
.optionalStart()
.append(TIME_FORMATTER)
.optionalEnd()
.toFormatter();
@Nonnull
public static LocalDateTime parse(@Nonnull String datetime) {
return parse(datetime, Locale.getDefault(Locale.Category.FORMAT));
}
@Nonnull
public static LocalDateTime parse(@Nonnull String datetime, @Nonnull Locale locale) {
final String newDatetime = datetime.trim();
return PARSER.get().stream().sorted(COMPARATOR)
.filter(item -> item.parser.supported(newDatetime, LocalDateTime.class, locale))
.findFirst()
.map(item -> {
final LocalDateTime time = toLocalDateTime(item.parser.parse(newDatetime, locale));
item.counter.incrementAndGet();
return time;
}).orElseGet(() -> LocalDateTime.parse(newDatetime, DATE_TIME_FORMATTER.withLocale(locale)));
}
@Nonnull
@SafeVarargs
public static <T extends ChronoLocalDateTime<?>> T min(@Nonnull T first, @Nonnull T... others) {
final T min = Comparators.min(others);
if (min != null && first.compareTo(min) > 0) {
return min;
}
return first;
}
@Nonnull
@SafeVarargs
public static <T extends ChronoLocalDateTime<?>> T max(@Nonnull T first, @Nonnull T... others) {
final T max = Comparators.max(others);
if (max != null && first.compareTo(max) < 0) {
return max;
}
return first;
}
@Nonnull
@SafeVarargs
public static <T extends ChronoLocalDate> T min(@Nonnull T first, @Nonnull T... others) {
final T min = Comparators.min(others);
if (min != null && first.compareTo(min) > 0) {
return min;
}
return first;
}
@Nonnull
@SafeVarargs
public static <T extends ChronoLocalDate> T max(@Nonnull T first, @Nonnull T... others) {
final T max = Comparators.max(others);
if (max != null && first.compareTo(max) < 0) {
return max;
}
return first;
}
@Nonnull
@SafeVarargs
public static <T extends ChronoZonedDateTime<?>> T min(@Nonnull T first, @Nonnull T... others) {
final T min = Comparators.min(others);
if (min != null && first.compareTo(min) > 0) {
return min;
}
return first;
}
@Nonnull
@SafeVarargs
public static <T extends ChronoZonedDateTime<?>> T max(@Nonnull T first, @Nonnull T... others) {
final T max = Comparators.max(others);
if (max != null && first.compareTo(max) < 0) {
return max;
}
return first;
}
@Nonnull
public static LocalTime min(@Nonnull LocalTime first, @Nonnull LocalTime... others) {
final LocalTime min = Comparators.min(others);
if (min != null && first.isAfter(min)) {
return min;
}
return first;
}
@Nonnull
public static LocalTime max(@Nonnull LocalTime first, @Nonnull LocalTime... others) {
final LocalTime max = Comparators.max(others);
if (max != null && first.isBefore(max)) {
return max;
}
return first;
}
@Nonnull
public static Instant min(@Nonnull Instant first, @Nonnull Instant... others) {
final Instant min = Comparators.min(others);
if (min != null && first.isAfter(min)) {
return min;
}
return first;
}
@Nonnull
public static Instant max(@Nonnull Instant first, @Nonnull Instant... others) {
final Instant max = Comparators.max(others);
if (max != null && first.isBefore(max)) {
return max;
}
return first;
}
@Nonnull
public static OffsetDateTime min(@Nonnull OffsetDateTime first, @Nonnull OffsetDateTime... others) {
final OffsetDateTime min = Comparators.min(others);
if (min != null && first.isAfter(min)) {
return min;
}
return first;
}
@Nonnull
public static OffsetDateTime max(@Nonnull OffsetDateTime first, @Nonnull OffsetDateTime... others) {
final OffsetDateTime max = Comparators.max(others);
if (max != null && first.isBefore(max)) {
return max;
}
return first;
}
@Nonnull
public static OffsetTime min(@Nonnull OffsetTime first, @Nonnull OffsetTime... others) {
final OffsetTime min = Comparators.min(others);
if (min != null && first.isAfter(min)) {
return min;
}
return first;
}
@Nonnull
public static OffsetTime max(@Nonnull OffsetTime first, @Nonnull OffsetTime... others) {
final OffsetTime max = Comparators.max(others);
if (max != null && first.isBefore(max)) {
return max;
}
return first;
}
@Nonnull
public static LocalDateTime parse(@Nonnull String datetime, @Nonnull String pattern) {
return LocalDateTime.parse(datetime, DateTimeFormatter.ofPattern(pattern));
}
@Nonnull
public static LocalDateTime fromEpochSecond(long epochSecond) {
return fromEpochSecond(epochSecond, ZoneId.systemDefault());
}
@Nonnull
public static LocalDateTime fromEpochSecond(long epochSecond, @Nonnull ZoneId zone) {
return LocalDateTime.ofInstant(Instant.ofEpochSecond(epochSecond), zone);
}
@Nonnull
public static LocalDateTime fromEpochSecond(long epochSecond, long nanoAdjustment) {
return fromEpochSecond(epochSecond, nanoAdjustment, ZoneId.systemDefault());
}
@Nonnull
public static LocalDateTime fromEpochSecond(long epochSecond, long nanoAdjustment, @Nonnull ZoneId zone) {
return LocalDateTime.ofInstant(Instant.ofEpochSecond(epochSecond, nanoAdjustment), zone);
}
@Nonnull
public static LocalDateTime fromEpochMilli(long epocMilli) {
return fromEpochMilli(epocMilli, ZoneId.systemDefault());
}
@Nonnull
public static LocalDateTime fromEpochMilli(long epocMilli, @Nonnull ZoneId zone) {
return LocalDateTime.ofInstant(Instant.ofEpochMilli(epocMilli), zone);
}
public static long toEpochSecond(@Nonnull LocalDateTime dateTime) {
return toEpochSecond(dateTime, ZoneOffset.systemDefault().getRules().getOffset(dateTime));
}
public static long toEpochSecond(@Nonnull LocalDateTime dateTime, @Nonnull ZoneOffset offset) {
return toEpochMilli(dateTime, offset) / 1000;
}
public static long toEpochMilli(@Nonnull LocalDateTime dateTime) {
return toEpochMilli(dateTime, ZoneOffset.systemDefault().getRules().getOffset(dateTime));
}
public static long toEpochMilli(@Nonnull LocalDateTime dateTime, @Nonnull ZoneOffset offset) {
return dateTime.toInstant(offset).toEpochMilli();
}
private static LocalDateTime toLocalDateTime(@Nonnull TemporalAccessor accessor) {
if (accessor instanceof LocalDateTime) {
return (LocalDateTime) accessor;
}
if (accessor instanceof ZonedDateTime) {
return ((ZonedDateTime) accessor).toLocalDateTime();
}
if (accessor instanceof OffsetDateTime) {
return ((OffsetDateTime) accessor).toLocalDateTime();
}
if (accessor instanceof LocalDate) {
return LocalDateTime.of((LocalDate) accessor, LocalTime.MIN);
}
if (accessor instanceof LocalTime) {
return LocalDateTime.of(LocalDate.now(), (LocalTime) accessor);
}
if (accessor instanceof OffsetTime) {
return LocalDateTime.of(LocalDate.now(), ((OffsetTime) accessor).toLocalTime());
}
if (accessor instanceof Instant) {
final Instant instant = (Instant) accessor;
return LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
}
final LocalDate date = tryToLocalDate(accessor);
final LocalTime time = tryToLocalTime(accessor);
if (date != null) {
if (time == null) {
return LocalDateTime.of(date, LocalTime.MIDNIGHT);
}
return LocalDateTime.of(date, time);
}
if (time != null) {
return LocalDateTime.of(LocalDate.now(), time);
}
return LocalDateTime.from(accessor);
}
private static LocalDate tryToLocalDate(@Nonnull TemporalAccessor accessor) {
if (accessor instanceof LocalDate) {
return (LocalDate) accessor;
}
if (accessor.isSupported(EPOCH_DAY)) {
return LocalDate.ofEpochDay(accessor.getLong(EPOCH_DAY));
}
if (!accessor.isSupported(YEAR)) {
if (!accessor.isSupported(MONTH_OF_YEAR)) {
return null;
}
final int month = accessor.get(MONTH_OF_YEAR);
final LocalDate now = LocalDate.now();
if (!accessor.isSupported(DAY_OF_MONTH)) {
return LocalDate.of(now.getYear(), month, 1);
}
return LocalDate.of(now.getYear(), month, accessor.get(DAY_OF_MONTH));
}
if (!accessor.isSupported(MONTH_OF_YEAR)) {
return LocalDate.of(accessor.get(YEAR), 1, 1);
}
if (!accessor.isSupported(DAY_OF_MONTH)) {
return LocalDate.of(accessor.get(YEAR), accessor.get(MONTH_OF_YEAR), 1);
}
return LocalDate.of(accessor.get(YEAR), accessor.get(MONTH_OF_YEAR), accessor.get(DAY_OF_MONTH));
}
private static LocalTime tryToLocalTime(@Nonnull TemporalAccessor accessor) {
if (accessor instanceof LocalTime) {
return (LocalTime) accessor;
}
if (accessor instanceof OffsetTime) {
return ((OffsetTime) accessor).toLocalTime();
}
final LocalTime time = accessor.query(TemporalQueries.localTime());
if (time != null) {
return time;
}
if (accessor.isSupported(SECOND_OF_DAY)) {
return LocalTime.ofSecondOfDay(accessor.getLong(SECOND_OF_DAY));
}
if (!accessor.isSupported(HOUR_OF_DAY)) {
return null;
}
final int hour = accessor.get(HOUR_OF_DAY);
if (!accessor.isSupported(MINUTE_OF_HOUR)) {
return LocalTime.of(hour, 0);
}
final int minute = accessor.get(MINUTE_OF_HOUR);
if (!accessor.isSupported(SECOND_OF_MINUTE)) {
return LocalTime.of(hour, minute);
}
final int second = accessor.get(SECOND_OF_MINUTE);
if (!accessor.isSupported(NANO_OF_SECOND)) {
return LocalTime.of(hour, minute, second);
}
return LocalTime.of(hour, minute, second, accessor.get(NANO_OF_SECOND));
}
| private static final class ParserWrapper implements Ordered { | 0 | 2023-11-18 07:49:00+00:00 | 8k |
Mightinity/store-management-system | src/main/java/com/systeminventory/controller/cashierController.java | [
{
"identifier": "App",
"path": "src/main/java/com/systeminventory/App.java",
"snippet": "public class App extends Application {\n\n private static Stage primaryStage;\n\n public static void main(String[] args) {\n launch(args);\n }\n\n public void start(Stage stage) throws IOException... | import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.systeminventory.App;
import com.systeminventory.interfaces.*;
import com.systeminventory.model.Cashier;
import com.systeminventory.model.Product;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Insets;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List; | 4,312 | }
if (status == 0){
Gson gson = new GsonBuilder().setPrettyPrinting().create();
try (InputStream inputStream = new FileInputStream(jsonPath)) {
InputStreamReader reader = new InputStreamReader(inputStream);
JsonObject jsonObject = gson.fromJson(reader, JsonObject.class);
JsonObject profileKey = jsonObject.getAsJsonObject(keyProfileOnPopup.getText());
if (keyProfileOnPopup != null){
String imageFileName = addProfileProfileImagePathLabel.getText();
if(!(imageProfilePath+imageFileName).equals(profileKey.get("Image").getAsString())){
Path newSourceImagePath = Paths.get(addProfileProfileImageFullPathLabel.getText());
Path targetImagePath = Paths.get(imageProfilePath, imageFileName);
try {
Files.copy(newSourceImagePath, targetImagePath, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException err){
err.printStackTrace();
}
}
profileKey.addProperty("Name", addProfileNameField.getText());
profileKey.addProperty("Email", addProfileEmailField.getText());
profileKey.addProperty("Phone", addProfileNoPhoneField.getText());
profileKey.addProperty("DateOfBirth", addProfileDateOfBirthField.getText());
profileKey.addProperty("Address", addProfileAddressField.getText());
profileKey.addProperty("Image", imageProfilePath+imageFileName);
profileKey.addProperty("Password", profileKey.get("Password").getAsString());
try (Writer writer = new FileWriter(jsonPath)){
gson.toJson(jsonObject, writer);
}
}
} catch (IOException err){
err.printStackTrace();
}
}
App.loadCashierScene();
}
}
@FXML
private void onAddProfileApplyButtonMouseEnter(MouseEvent mouseEvent) {
addProfileApplyButton.setStyle("-fx-background-color: #33b8ff;" + "-fx-background-radius: 13");
}
@FXML
private void onAddProfileApplyButtonMouseExit(MouseEvent mouseEvent) {
addProfileApplyButton.setStyle("-fx-background-color: #00a6ff;" + "-fx-background-radius: 13");
}
@FXML
private void onAddProfileCancelButtonClick(ActionEvent actionEvent) {
backgroundPopup.setVisible(false);
addProfilePopup.setVisible(false);
}
@FXML
private void onAddProfileCancelButtonMouseEnter(MouseEvent mouseEvent) {
addProfileCancelButton.setStyle("-fx-background-color: #e0005c;" + "-fx-background-radius: 13");
}
@FXML
private void onAddProfileCancelButtonMouseExit(MouseEvent mouseEvent) {
addProfileCancelButton.setStyle("-fx-background-color: #ff1474;" + "-fx-background-radius: 13");
}
public void deleteProfileData(String keyProfile){
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String jsonPath = "./src/main/java/com/systeminventory/assets/json/cashierList.json";
try (InputStream inputStream = new FileInputStream(jsonPath)){
InputStreamReader reader = new InputStreamReader(inputStream);
JsonObject jsonObject = gson.fromJson(reader, JsonObject.class);
jsonObject.remove(keyProfile);
try (Writer writer = new FileWriter(jsonPath)){
gson.toJson(jsonObject, writer);
}
App.loadCashierScene();
} catch (IOException err){
err.printStackTrace();
}
}
@FXML
private void onConfirmDeleteDeleteButtonProfileClick(ActionEvent event) {
deleteProfileData(confirmDeleteKeyProfile.getText());
confirmDeleteVariableProfileName.setText("");
confirmDeleteKeyProfile.setText("");
confirmDeleteProfilePane.setVisible(false);
backgroundPopup.setVisible(false);
}
@FXML
private void onConfirmDeleteDeleteButtonProfileMouseEnter(MouseEvent event) {
confirmDeleteDeleteButtonProfile.setStyle("-fx-background-color: #e0005c;"+"-fx-background-radius: 13;");
}
@FXML
private void onConfirmDeleteDeleteButtonProfileMouseExit(MouseEvent event) {
confirmDeleteDeleteButtonProfile.setStyle("-fx-background-color: #ff1474;"+"-fx-background-radius: 13;");
}
@FXML
private void onConfirmDeleteCancelButtonProfileMouseEnter(MouseEvent event) {
confirmDeleteCancelButtonProfile.setStyle("-fx-background-color: #19a6b7;" + "-fx-background-radius: 13;");
}
@FXML
private void onConfirmDeleteCancelButtonProfileMouseExit(MouseEvent mouseEvent) {
confirmDeleteCancelButtonProfile.setStyle("-fx-background-color: #1ecbe1;" + "-fx-background-radius: 13;");
}
@FXML
private void onConfirmDeleteCancelButtonProfileClick(ActionEvent event) {
backgroundPopup.setVisible(false);
confirmDeleteProfilePane.setVisible(false);
confirmDeleteKeyProfile.setText("");
confirmDeleteVariableProfileName.setText("");
}
| package com.systeminventory.controller;
public class cashierController {
@FXML
private Pane backgroundPopup;
@FXML
private Button buttonCashier;
@FXML
private Button buttonDashboard;
@FXML
private Button buttonProduct;
@FXML
private Button logoutDropdown;
@FXML
private Pane profileDropdown;
@FXML
private Button settingsDropdown;
@FXML
private Pane addProfilePopup;
@FXML
private Label addProfileNameLabel;
@FXML
private TextField addProfileNameField;
@FXML
private Label addProfileEmailLabel;
@FXML
private TextField addProfileEmailField;
@FXML
private Label addProfileNoPhoneLabel;
@FXML
private TextField addProfileNoPhoneField;
@FXML
private Label addProfileDateOfBirthLabel;
@FXML
private TextField addProfileDateOfBirthField;
@FXML
private Label addProfileAddressLabel;
@FXML
private TextField addProfileAddressField;
@FXML
private Label addProfileProfilePictureLabel;
@FXML
private Label addProfileProfileImagePathLabel;
@FXML
private Button addProfileApplyButton;
@FXML
private Button addProfileCancelButton;
@FXML
private Label addProfileProfileImageFullPathLabel;
@FXML
private Button buttonAddProfile;
@FXML
private Pane addProfileChooseFilePane;
@FXML
private GridPane profileCardContainer;
@FXML
private Label profileDetailsVarFullName;
@FXML
private Label profileDetailsVarPhone;
@FXML
private Label profileDetailsVarDateOfBirth;
@FXML
private Label profileDetailsVarEmail;
@FXML
private Label profileDetailsVarAddress;
@FXML
public Pane paneSelectAProfile;
private ProfileDetailsListener profileDetailsListener;
private DeleteCashierListener deleteCashierListener;
private EditCashierListener editCashierListener;
@FXML
private ImageView profileDetailsVarImage;
@FXML
private TextField searchTermProfile;
@FXML
private Pane confirmDeleteProfilePane;
@FXML
private Label confirmDeleteVariableProfileName;
@FXML
private Button confirmDeleteDeleteButtonProfile;
@FXML
private Button confirmDeleteCancelButtonProfile;
@FXML
private Label confirmDeleteKeyProfile;
@FXML
private Label keyProfileOnPopup;
@FXML
private Label addProfileLabel;
private static String hashMD5(String input) {
StringBuilder result = new StringBuilder();
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(input.getBytes());
byte[] byteData = md.digest();
for (byte aByteData : byteData) {
result.append(Integer.toString((aByteData & 0xff) + 0x100, 16).substring(1));
}
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return result.toString();
}
@FXML
void onAddProfileChooseFilePaneMouseClick(MouseEvent event) {
FileChooser filechooser = new FileChooser();
filechooser.setTitle("Select profile picture");
filechooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("PNG Files", "*.png"));
File selectedFile = filechooser.showOpenDialog(App.getPrimaryStage());
if(selectedFile != null){
setLabelPropertiesTextFillWhite(addProfileProfilePictureLabel, "Profile picture:");
addProfileProfileImagePathLabel.setText(selectedFile.getName());
addProfileProfileImageFullPathLabel.setText(selectedFile.getPath());
}
}
@FXML
void onAddProfileChooseFilePaneMouseEnter(MouseEvent event) {
addProfileChooseFilePane.setStyle("-fx-background-color: #ffa132;" + "-fx-background-radius: 5;" + "-fx-border-color: #f6f6f6;" + "-fx-border-radius: 5;");
}
@FXML
void onAddProfileChooseFilePaneMouseExit(MouseEvent event) {
addProfileChooseFilePane.setStyle("-fx-background-color: #fe8a00;" + "-fx-background-radius: 5;" + "-fx-border-color: #f6f6f6;" + "-fx-border-radius: 5;");
}
@FXML
private void onButtonAddProfileMouseExit(MouseEvent mouseEvent) {
buttonAddProfile.setStyle("-fx-background-color: #fe8a00;" + "-fx-background-radius: 20;");
}
@FXML
private void onButtonAddProfileMouseEnter(MouseEvent mouseEvent) {
buttonAddProfile.setStyle("-fx-background-color: #ffa132;" + "-fx-background-radius: 20;");
}
@FXML
void onButtonDashboardClick(ActionEvent event) throws IOException {
App.loadDashboardScene();
}
@FXML
private void onButtonDashboardMouseEnter(MouseEvent mouseEvent) {
buttonDashboard.setStyle("-fx-background-color: #697b7b;" + "-fx-border-color: #697b7b;" + "-fx-text-fill: #151d26;" + "-fx-background-radius: 20;" + "-fx-border-radius: 20;");
}
@FXML
private void onButtonDashboardMouseExit(MouseEvent mouseEvent) {
buttonDashboard.setStyle("-fx-background-color: #151d26;" + "-fx-border-color: #697b7b;" + "-fx-text-fill: #697b7b;" + "-fx-background-radius: 20;" + "-fx-border-radius: 20;");
}
@FXML
void onButtonProductClick(ActionEvent event) throws IOException {
App.loadProductScene();
}
@FXML
void onButtonProductMouseEnter(MouseEvent event) {
buttonProduct.setStyle("-fx-background-color: #697b7b;" + "-fx-border-color: #697b7b;" + "-fx-text-fill: #151d26;" + "-fx-background-radius: 20;" + "-fx-border-radius: 20;");
}
@FXML
void onButtonProductMouseExit(MouseEvent event) {
buttonProduct.setStyle("-fx-background-color: #151d26;" + "-fx-border-color: #697b7b;" + "-fx-text-fill: #697b7b;" + "-fx-background-radius: 20;" + "-fx-border-radius: 20;");
}
@FXML
void onButtonCashierClick(ActionEvent event) {
}
@FXML
void onCashierProductMouseEnter(MouseEvent event) {
}
@FXML
void onCashierProductMouseExit(MouseEvent event) {
}
@FXML
void onLogoutClick(ActionEvent event) throws IOException {
App.loadLogoutScene();
}
@FXML
void onLogoutDropdownMouseEnter(MouseEvent event) {
logoutDropdown.setStyle("-fx-background-color: #2f3d4e;" + "-fx-background-radius: 11");
}
@FXML
void onLogoutDropdownMouseExit(MouseEvent event) {
logoutDropdown.setStyle("-fx-background-color: #1c242e;" + "-fx-background-radius: 11");
}
@FXML
void onProfileClick(MouseEvent event) {
profileDropdown.setVisible(!profileDropdown.isVisible());
}
@FXML
void onProfileDropdownMouseExit(MouseEvent event) {
profileDropdown.setVisible(false);
}
@FXML
void onSettingsDropdownMouseEnter(MouseEvent event) {
settingsDropdown.setStyle("-fx-background-color: #2f3d4e;" + "-fx-background-radius: 11");
}
@FXML
void onSettingsDropdownMouseExit(MouseEvent event) {
settingsDropdown.setStyle("-fx-background-color: #1c242e;" + "-fx-background-radius: 11");
}
private void setLabelPropertiesTextFillWhite(Label label, String text){
label.setText(text);
label.setStyle("-fx-text-fill: #f6f6f6;");
}
@FXML
void onButtonAddProfileClick(ActionEvent event) {
addProfileLabel.setText("Add Profile");
addProfileNameField.setText("");
addProfileNameField.setDisable(false);
addProfileEmailField.setText("");
addProfileNoPhoneField.setText("");
addProfileDateOfBirthField.setText("");
addProfileAddressField.setText("");
addProfileProfileImagePathLabel.setText("");
setLabelPropertiesTextFillWhite(addProfileNameLabel, "Name:");
setLabelPropertiesTextFillWhite(addProfileEmailLabel, "Email:");
setLabelPropertiesTextFillWhite(addProfileNoPhoneLabel, "No phone:");
setLabelPropertiesTextFillWhite(addProfileDateOfBirthLabel, "Date of birth:");
setLabelPropertiesTextFillWhite(addProfileAddressLabel, "Address:");
setLabelPropertiesTextFillWhite(addProfileProfilePictureLabel, "Profile picture:");
backgroundPopup.setVisible(true);
addProfilePopup.setVisible(true);
}
@FXML
private void onAddProfileApplyButtonClick(ActionEvent actionEvent) throws IOException {
String jsonPath = "./src/main/java/com/systeminventory/assets/json/cashierList.json";
String imageProfilePath = "./src/main/java/com/systeminventory/assets/imagesCashier/";
setLabelPropertiesTextFillWhite(addProfileNameLabel, "Name:");
setLabelPropertiesTextFillWhite(addProfileEmailLabel, "Email:");
setLabelPropertiesTextFillWhite(addProfileNoPhoneLabel, "No phone:");
setLabelPropertiesTextFillWhite(addProfileDateOfBirthLabel, "Date of birth:");
setLabelPropertiesTextFillWhite(addProfileAddressLabel, "Address:");
setLabelPropertiesTextFillWhite(addProfileProfilePictureLabel, "Profile picture:");
TextField[] fields = { addProfileNameField, addProfileEmailField, addProfileNoPhoneField, addProfileDateOfBirthField, addProfileAddressField };
Label[] labels = { addProfileNameLabel, addProfileEmailLabel, addProfileNoPhoneLabel, addProfileDateOfBirthLabel, addProfileAddressLabel };
if (addProfileLabel.getText().equals("Add Profile")){ // ADD PROFILE
int status = 0;
for (int i = 0; i < fields.length; i++){
TextField field = fields[i];
Label label = labels[i];
if (field.getText().isEmpty()){
label.setText(label.getText()+" (Required)");
label.setStyle("-fx-text-fill: #ff1474;");
status++;
}
}
if (addProfileProfileImagePathLabel.getText().isEmpty()){
addProfileProfilePictureLabel.setText("Profile picture: (Required)");
addProfileProfilePictureLabel.setStyle("-fx-text-fill: #ff1474;");
status++;
}
if (status == 0){
Gson gson = new GsonBuilder().setPrettyPrinting().create();
try (InputStream inputStream = new FileInputStream(jsonPath)){
InputStreamReader reader = new InputStreamReader(inputStream);
JsonObject jsonObject = gson.fromJson(reader, JsonObject.class);
List<String> profileKeys = new ArrayList<>(jsonObject.keySet());
//Collections.sort(profileKeys);
int nextKeyNumber = profileKeys.size()+1;
String newProfileKey = "cashier"+nextKeyNumber;
while (profileKeys.contains(newProfileKey)){
nextKeyNumber++;
newProfileKey = "cashier"+nextKeyNumber;
}
JsonObject newProfileData = new JsonObject();
String imageFileName = addProfileProfileImagePathLabel.getText();
Path sourceImagePath = Paths.get(addProfileProfileImageFullPathLabel.getText());
Path targetImagePath = Paths.get(imageProfilePath, imageFileName);
newProfileData.addProperty("Name", addProfileNameField.getText());
newProfileData.addProperty("Email", addProfileEmailField.getText());
newProfileData.addProperty("Phone", addProfileNoPhoneField.getText());
newProfileData.addProperty("DateOfBirth", addProfileDateOfBirthField.getText());
newProfileData.addProperty("Address", addProfileAddressField.getText());
newProfileData.addProperty("Image", imageProfilePath+imageFileName);
newProfileData.addProperty("Password", hashMD5("123456"));
try{
Files.copy(sourceImagePath, targetImagePath, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException err){
err.printStackTrace();
}
jsonObject.add(newProfileKey, newProfileData);
try (Writer writer = new FileWriter(jsonPath)){
gson.toJson(jsonObject, writer);
}
} catch (IOException err){
err.printStackTrace();
}
App.loadCashierScene();
}
} else if (addProfileLabel.getText().equals("Edit Profile")){ // EDIT PROFILE
int status = 0;
for (int i = 0; i < fields.length; i++){
TextField field = fields[i];
Label label = labels[i];
if (field.getText().isEmpty()){
label.setText(label.getText()+" (Required)");
label.setStyle("-fx-text-fill: #ff1474;");
status++;
}
}
if (addProfileProfileImagePathLabel.getText().isEmpty()){
addProfileProfilePictureLabel.setText("Profile picture: (Required)");
addProfileProfilePictureLabel.setStyle("-fx-text-fill: #ff1474;");
status++;
}
if (status == 0){
Gson gson = new GsonBuilder().setPrettyPrinting().create();
try (InputStream inputStream = new FileInputStream(jsonPath)) {
InputStreamReader reader = new InputStreamReader(inputStream);
JsonObject jsonObject = gson.fromJson(reader, JsonObject.class);
JsonObject profileKey = jsonObject.getAsJsonObject(keyProfileOnPopup.getText());
if (keyProfileOnPopup != null){
String imageFileName = addProfileProfileImagePathLabel.getText();
if(!(imageProfilePath+imageFileName).equals(profileKey.get("Image").getAsString())){
Path newSourceImagePath = Paths.get(addProfileProfileImageFullPathLabel.getText());
Path targetImagePath = Paths.get(imageProfilePath, imageFileName);
try {
Files.copy(newSourceImagePath, targetImagePath, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException err){
err.printStackTrace();
}
}
profileKey.addProperty("Name", addProfileNameField.getText());
profileKey.addProperty("Email", addProfileEmailField.getText());
profileKey.addProperty("Phone", addProfileNoPhoneField.getText());
profileKey.addProperty("DateOfBirth", addProfileDateOfBirthField.getText());
profileKey.addProperty("Address", addProfileAddressField.getText());
profileKey.addProperty("Image", imageProfilePath+imageFileName);
profileKey.addProperty("Password", profileKey.get("Password").getAsString());
try (Writer writer = new FileWriter(jsonPath)){
gson.toJson(jsonObject, writer);
}
}
} catch (IOException err){
err.printStackTrace();
}
}
App.loadCashierScene();
}
}
@FXML
private void onAddProfileApplyButtonMouseEnter(MouseEvent mouseEvent) {
addProfileApplyButton.setStyle("-fx-background-color: #33b8ff;" + "-fx-background-radius: 13");
}
@FXML
private void onAddProfileApplyButtonMouseExit(MouseEvent mouseEvent) {
addProfileApplyButton.setStyle("-fx-background-color: #00a6ff;" + "-fx-background-radius: 13");
}
@FXML
private void onAddProfileCancelButtonClick(ActionEvent actionEvent) {
backgroundPopup.setVisible(false);
addProfilePopup.setVisible(false);
}
@FXML
private void onAddProfileCancelButtonMouseEnter(MouseEvent mouseEvent) {
addProfileCancelButton.setStyle("-fx-background-color: #e0005c;" + "-fx-background-radius: 13");
}
@FXML
private void onAddProfileCancelButtonMouseExit(MouseEvent mouseEvent) {
addProfileCancelButton.setStyle("-fx-background-color: #ff1474;" + "-fx-background-radius: 13");
}
public void deleteProfileData(String keyProfile){
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String jsonPath = "./src/main/java/com/systeminventory/assets/json/cashierList.json";
try (InputStream inputStream = new FileInputStream(jsonPath)){
InputStreamReader reader = new InputStreamReader(inputStream);
JsonObject jsonObject = gson.fromJson(reader, JsonObject.class);
jsonObject.remove(keyProfile);
try (Writer writer = new FileWriter(jsonPath)){
gson.toJson(jsonObject, writer);
}
App.loadCashierScene();
} catch (IOException err){
err.printStackTrace();
}
}
@FXML
private void onConfirmDeleteDeleteButtonProfileClick(ActionEvent event) {
deleteProfileData(confirmDeleteKeyProfile.getText());
confirmDeleteVariableProfileName.setText("");
confirmDeleteKeyProfile.setText("");
confirmDeleteProfilePane.setVisible(false);
backgroundPopup.setVisible(false);
}
@FXML
private void onConfirmDeleteDeleteButtonProfileMouseEnter(MouseEvent event) {
confirmDeleteDeleteButtonProfile.setStyle("-fx-background-color: #e0005c;"+"-fx-background-radius: 13;");
}
@FXML
private void onConfirmDeleteDeleteButtonProfileMouseExit(MouseEvent event) {
confirmDeleteDeleteButtonProfile.setStyle("-fx-background-color: #ff1474;"+"-fx-background-radius: 13;");
}
@FXML
private void onConfirmDeleteCancelButtonProfileMouseEnter(MouseEvent event) {
confirmDeleteCancelButtonProfile.setStyle("-fx-background-color: #19a6b7;" + "-fx-background-radius: 13;");
}
@FXML
private void onConfirmDeleteCancelButtonProfileMouseExit(MouseEvent mouseEvent) {
confirmDeleteCancelButtonProfile.setStyle("-fx-background-color: #1ecbe1;" + "-fx-background-radius: 13;");
}
@FXML
private void onConfirmDeleteCancelButtonProfileClick(ActionEvent event) {
backgroundPopup.setVisible(false);
confirmDeleteProfilePane.setVisible(false);
confirmDeleteKeyProfile.setText("");
confirmDeleteVariableProfileName.setText("");
}
| private List<Cashier> readProfilesFromJson(String searchTerm) { | 1 | 2023-11-18 02:53:02+00:00 | 8k |
CivilisationPlot/CivilisationPlot_Papermc | src/main/java/fr/laptoff/civilisationplot/CivilisationPlot.java | [
{
"identifier": "ConfigManager",
"path": "src/main/java/fr/laptoff/civilisationplot/Managers/ConfigManager.java",
"snippet": "public class ConfigManager {\n\n private final File file;\n File file_;\n private final FileConfiguration configFile;\n\n public ConfigManager(String filePath){\n ... | import fr.laptoff.civilisationplot.Managers.ConfigManager;
import fr.laptoff.civilisationplot.Managers.DatabaseManager;
import fr.laptoff.civilisationplot.civils.Civil;
import fr.laptoff.civilisationplot.civils.joinListener;
import fr.laptoff.civilisationplot.nation.Nation;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.logging.Logger; | 5,949 | package fr.laptoff.civilisationplot;
public final class CivilisationPlot extends JavaPlugin {
public static final Logger LOGGER = Logger.getLogger("CivilisationPlot");
private static CivilisationPlot instance;
private DatabaseManager database;
private FileConfiguration configMessages; //Messages Manager (at /resources/config/english.yml)
@Override
public void onEnable() {
instance = this;
saveDefaultConfig();
ConfigManager configManagerMessages = new ConfigManager(getConfig().getString("Language.language"));
configMessages = configManagerMessages.getFileConfiguration();
if (getConfig().getBoolean("Database.enable")){
database = new DatabaseManager();
database.connection();
database.setup();
LOGGER.info(configMessages.getString("Messages.Database.success_connection"));
}
Civil.load();
Nation.load();
LOGGER.info("#### ## ### ## ## ## ###### ### ##");
LOGGER.info("## ## ## ## ## ## ## ##");
LOGGER.info("## ## ## ### ## ### ##### #### ##### ### #### ##### ## ## ## #### #####");
LOGGER.info("## ## ## ## ## ## ## ## ## ## ## ## ## ## ##### ## ## ## ##");
LOGGER.info("## ## ## ## ## ## ##### ##### ## ## ## ## ## ## ## ## ## ## ##");
LOGGER.info("## ## #### ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##");
LOGGER.info("#### ## #### #### #### ###### ##### ### #### #### ## ## #### #### #### ###");
| package fr.laptoff.civilisationplot;
public final class CivilisationPlot extends JavaPlugin {
public static final Logger LOGGER = Logger.getLogger("CivilisationPlot");
private static CivilisationPlot instance;
private DatabaseManager database;
private FileConfiguration configMessages; //Messages Manager (at /resources/config/english.yml)
@Override
public void onEnable() {
instance = this;
saveDefaultConfig();
ConfigManager configManagerMessages = new ConfigManager(getConfig().getString("Language.language"));
configMessages = configManagerMessages.getFileConfiguration();
if (getConfig().getBoolean("Database.enable")){
database = new DatabaseManager();
database.connection();
database.setup();
LOGGER.info(configMessages.getString("Messages.Database.success_connection"));
}
Civil.load();
Nation.load();
LOGGER.info("#### ## ### ## ## ## ###### ### ##");
LOGGER.info("## ## ## ## ## ## ## ##");
LOGGER.info("## ## ## ### ## ### ##### #### ##### ### #### ##### ## ## ## #### #####");
LOGGER.info("## ## ## ## ## ## ## ## ## ## ## ## ## ## ##### ## ## ## ##");
LOGGER.info("## ## ## ## ## ## ##### ##### ## ## ## ## ## ## ## ## ## ## ##");
LOGGER.info("## ## #### ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##");
LOGGER.info("#### ## #### #### #### ###### ##### ### #### #### ## ## #### #### #### ###");
| getServer().getPluginManager().registerEvents(new joinListener(), this); | 3 | 2023-11-11 18:26:55+00:00 | 8k |
JohnTWD/meteor-rejects-vanillacpvp | src/main/java/anticope/rejects/MeteorRejectsAddon.java | [
{
"identifier": "RadarHud",
"path": "src/main/java/anticope/rejects/gui/hud/RadarHud.java",
"snippet": "public class RadarHud extends HudElement {\n public static final HudElementInfo<RadarHud> INFO = new HudElementInfo<>(MeteorRejectsAddon.HUD_GROUP, \"radar\", \"Draws a Radar on your HUD telling yo... | import anticope.rejects.commands.*;
import anticope.rejects.gui.hud.RadarHud;
import anticope.rejects.gui.themes.rounded.MeteorRoundedGuiTheme;
import anticope.rejects.modules.*;
import meteordevelopment.meteorclient.addons.GithubRepo;
import meteordevelopment.meteorclient.addons.MeteorAddon;
import meteordevelopment.meteorclient.commands.Commands;
import meteordevelopment.meteorclient.gui.GuiThemes;
import meteordevelopment.meteorclient.systems.Systems;
import meteordevelopment.meteorclient.systems.hud.Hud;
import meteordevelopment.meteorclient.systems.hud.HudGroup;
import meteordevelopment.meteorclient.systems.modules.Category;
import meteordevelopment.meteorclient.systems.modules.Modules;
import net.fabricmc.loader.api.FabricLoader;
import net.minecraft.item.Items;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | 5,766 | package anticope.rejects;
public class MeteorRejectsAddon extends MeteorAddon {
public static final Logger LOG = LoggerFactory.getLogger("Rejects");
public static final Category CATEGORY = new Category("Rejects", Items.BARRIER.getDefaultStack());
public static final HudGroup HUD_GROUP = new HudGroup("Rejects");
@Override
public void onInitialize() {
LOG.info("Initializing Meteor Rejects Addon");
// Modules
Modules modules = Modules.get();
modules.add(new BetterAimbot());
modules.add(new NewerNewChunks());
modules.add(new BaseFinderNew());
modules.add(new Shield());
modules.add(new TestModule());
modules.add(((new HitboxDesync())));
modules.add(new Announcer());
modules.add(new PacketLogger());
modules.add(new ManualCrystal());
modules.add(new TweakedAutoTool());
modules.add(new MacroAnchorAuto());
modules.add(new AutoMend());
modules.add(new BowBomb());
modules.add(new AutoCityPlus());
modules.add(new PistonAura());
modules.add(new CevBreaker());
modules.add(new AimAssist());
modules.add(new AntiBot());
modules.add(new AntiCrash());
modules.add(new AntiSpawnpoint());
modules.add(new AntiVanish());
modules.add(new ArrowDmg());
modules.add(new AutoBedTrap());
modules.add(new AutoCraft());
modules.add(new AutoExtinguish());
modules.add(new AutoFarm());
modules.add(new AutoGrind());
modules.add(new AutoLogin());
modules.add(new AutoPot());
modules.add(new AutoSoup());
modules.add(new AutoTNT());
modules.add(new AutoWither());
modules.add(new BoatGlitch());
modules.add(new BlockIn());
modules.add(new BoatPhase());
modules.add(new Boost());
modules.add(new BungeeCordSpoof());
modules.add(new ChatBot());
modules.add(new ChestAura());
modules.add(new ChorusExploit());
modules.add(new ColorSigns());
modules.add(new Confuse());
modules.add(new CoordLogger());
modules.add(new CustomPackets());
modules.add(new ExtraElytra());
modules.add(new FullFlight());
modules.add(new GamemodeNotifier());
modules.add(new GhostMode());
modules.add(new Glide());
modules.add(new InstaMine());
modules.add(new ItemGenerator());
modules.add(new InteractionMenu());
modules.add(new Jetpack());
modules.add(new KnockbackPlus());
modules.add(new Lavacast());
modules.add(new MossBot());
modules.add(new NewChunks());
modules.add(new NoJumpDelay());
modules.add(new ObsidianFarm());
modules.add(new OreSim());
modules.add(new PacketFly());
modules.add(new Painter());
modules.add(new Rendering());
modules.add(new RoboWalk());
modules.add(new ShieldBypass());
modules.add(new SilentDisconnect());
modules.add(new SkeletonESP());
modules.add(new SoundLocator());
modules.add(new TreeAura());
modules.add(new VehicleOneHit());
// Commands
Commands.add(new CenterCommand());
Commands.add(new ClearChatCommand());
Commands.add(new GhostCommand());
Commands.add(new GiveCommand());
Commands.add(new HeadsCommand());
Commands.add(new KickCommand());
Commands.add(new LocateCommand());
Commands.add(new PanicCommand());
Commands.add(new ReconnectCommand());
Commands.add(new ServerCommand());
Commands.add(new SaveSkinCommand());
Commands.add(new SeedCommand());
Commands.add(new SetBlockCommand());
Commands.add(new SetVelocityCommand());
Commands.add(new TeleportCommand());
Commands.add(new TerrainExport());
Commands.add(new EntityDesyncCommand());
Commands.add(new BaseFinderNewCommands());
Commands.add(new NewChunkCounter());
// HUD
Hud hud = Systems.get(Hud.class); | package anticope.rejects;
public class MeteorRejectsAddon extends MeteorAddon {
public static final Logger LOG = LoggerFactory.getLogger("Rejects");
public static final Category CATEGORY = new Category("Rejects", Items.BARRIER.getDefaultStack());
public static final HudGroup HUD_GROUP = new HudGroup("Rejects");
@Override
public void onInitialize() {
LOG.info("Initializing Meteor Rejects Addon");
// Modules
Modules modules = Modules.get();
modules.add(new BetterAimbot());
modules.add(new NewerNewChunks());
modules.add(new BaseFinderNew());
modules.add(new Shield());
modules.add(new TestModule());
modules.add(((new HitboxDesync())));
modules.add(new Announcer());
modules.add(new PacketLogger());
modules.add(new ManualCrystal());
modules.add(new TweakedAutoTool());
modules.add(new MacroAnchorAuto());
modules.add(new AutoMend());
modules.add(new BowBomb());
modules.add(new AutoCityPlus());
modules.add(new PistonAura());
modules.add(new CevBreaker());
modules.add(new AimAssist());
modules.add(new AntiBot());
modules.add(new AntiCrash());
modules.add(new AntiSpawnpoint());
modules.add(new AntiVanish());
modules.add(new ArrowDmg());
modules.add(new AutoBedTrap());
modules.add(new AutoCraft());
modules.add(new AutoExtinguish());
modules.add(new AutoFarm());
modules.add(new AutoGrind());
modules.add(new AutoLogin());
modules.add(new AutoPot());
modules.add(new AutoSoup());
modules.add(new AutoTNT());
modules.add(new AutoWither());
modules.add(new BoatGlitch());
modules.add(new BlockIn());
modules.add(new BoatPhase());
modules.add(new Boost());
modules.add(new BungeeCordSpoof());
modules.add(new ChatBot());
modules.add(new ChestAura());
modules.add(new ChorusExploit());
modules.add(new ColorSigns());
modules.add(new Confuse());
modules.add(new CoordLogger());
modules.add(new CustomPackets());
modules.add(new ExtraElytra());
modules.add(new FullFlight());
modules.add(new GamemodeNotifier());
modules.add(new GhostMode());
modules.add(new Glide());
modules.add(new InstaMine());
modules.add(new ItemGenerator());
modules.add(new InteractionMenu());
modules.add(new Jetpack());
modules.add(new KnockbackPlus());
modules.add(new Lavacast());
modules.add(new MossBot());
modules.add(new NewChunks());
modules.add(new NoJumpDelay());
modules.add(new ObsidianFarm());
modules.add(new OreSim());
modules.add(new PacketFly());
modules.add(new Painter());
modules.add(new Rendering());
modules.add(new RoboWalk());
modules.add(new ShieldBypass());
modules.add(new SilentDisconnect());
modules.add(new SkeletonESP());
modules.add(new SoundLocator());
modules.add(new TreeAura());
modules.add(new VehicleOneHit());
// Commands
Commands.add(new CenterCommand());
Commands.add(new ClearChatCommand());
Commands.add(new GhostCommand());
Commands.add(new GiveCommand());
Commands.add(new HeadsCommand());
Commands.add(new KickCommand());
Commands.add(new LocateCommand());
Commands.add(new PanicCommand());
Commands.add(new ReconnectCommand());
Commands.add(new ServerCommand());
Commands.add(new SaveSkinCommand());
Commands.add(new SeedCommand());
Commands.add(new SetBlockCommand());
Commands.add(new SetVelocityCommand());
Commands.add(new TeleportCommand());
Commands.add(new TerrainExport());
Commands.add(new EntityDesyncCommand());
Commands.add(new BaseFinderNewCommands());
Commands.add(new NewChunkCounter());
// HUD
Hud hud = Systems.get(Hud.class); | hud.register(RadarHud.INFO); | 0 | 2023-11-13 08:11:28+00:00 | 8k |
stiemannkj1/java-utilities | src/test/java/dev/stiemannkj1/collection/fixmapping/FixMappingsTests.java | [
{
"identifier": "binarySearchArrayPrefixMapping",
"path": "src/main/java/dev/stiemannkj1/collection/fixmapping/FixMappings.java",
"snippet": "public static <T> ImmutablePrefixMapping<T> binarySearchArrayPrefixMapping(\n final Map<String, T> prefixes) {\n return new BinarySearchArrayPrefixMapping<>(p... | import static dev.stiemannkj1.collection.fixmapping.FixMappings.binarySearchArrayPrefixMapping;
import static dev.stiemannkj1.collection.fixmapping.FixMappings.binarySearchArraySuffixMapping;
import static dev.stiemannkj1.collection.fixmapping.FixMappings.limitedCharArrayTriePrefixMapping;
import static dev.stiemannkj1.collection.fixmapping.FixMappings.limitedCharArrayTrieSuffixMapping;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import dev.stiemannkj1.collection.fixmapping.FixMappings.ImmutablePrefixMapping;
import dev.stiemannkj1.collection.fixmapping.FixMappings.ImmutableSuffixMapping;
import dev.stiemannkj1.util.Pair;
import java.util.AbstractMap;
import java.util.AbstractSet;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.MethodSource; | 3,919 | suffixes.put("aaa", 4);
suffixMap = newSuffixMap(suffixes);
firstSearchSteps.set(0);
longestSearchSteps.set(0);
assertEquals(
Pair.of(firstMatchOddKeys, suffixes.get(firstMatchOddKeys)),
((FixMappings.FixMapping<Integer>) suffixMap)
.getKeyAndValue(false, string, firstSearchSteps));
assertEquals(
Pair.of("abdicate", 3),
((FixMappings.FixMapping<Integer>) suffixMap)
.getKeyAndValue(true, string, longestSearchSteps));
assertEquals(firstMatchStepsOddKeys, firstSearchSteps.get());
assertEquals(longestMatchStepsOddKeys, longestSearchSteps.get());
}
@Test
default void allows_suffixes_with_matching_prefixes() {
// Test odd number of suffixes.
final Map<String, Integer> suffixes =
newTestMapBuilder().add("abdicat", 0).add("abdicate", 2).map;
assertDoesNotThrow(() -> newSuffixMap(suffixes));
}
static Stream<Map<String, Integer>> invalidSuffixes() {
return Stream.of(
Collections.emptyMap(),
newTestMapBuilder().add(null, 1).map,
newTestMapBuilder().add(null, 1).add("asdf", 1).map,
newTestMapBuilder().add("", 1).map,
newTestMapBuilder().add("", 1).add("asdf", 1).map,
// Invalid map with duplicate keys:
toMap(Arrays.asList(Pair.of("asdf", 1), Pair.of("asdf", 1))),
// Invalid map with null entry:
toMap(Arrays.asList(null, Pair.of("asdf", 1))));
}
@MethodSource("invalidSuffixes")
@ParameterizedTest
default void throws_illegal_arg_when_provided_invalid_values(
final Map<String, Integer> suffixes) {
final Class<? extends Exception> expectedExceptionType =
suffixes != null ? IllegalArgumentException.class : NullPointerException.class;
assertThrows(expectedExceptionType, () -> newSuffixMap(suffixes));
}
ImmutableSuffixMapping<Integer> newSuffixMap(final Map<String, Integer> prefixes);
}
private static void assertFirstMatchSearchTakesLessSteps(
String string, Integer expectedValue, FixMappings.FixMapping<Integer> fixMapping) {
final AtomicLong firstSearchSteps = new AtomicLong(0);
final AtomicLong longestSearchSteps = new AtomicLong(0);
final Pair<String, Integer> firstMatch =
fixMapping.getKeyAndValue(false, string, firstSearchSteps);
if (expectedValue != null) {
assertNotNull(firstMatch);
} else {
assertNull(firstMatch);
}
final Pair<String, Integer> longestMatch =
fixMapping.getKeyAndValue(true, string, longestSearchSteps);
if (expectedValue != null) {
assertNotNull(longestMatch);
} else {
assertNull(longestMatch);
}
assertTrue(firstSearchSteps.get() <= longestSearchSteps.get());
}
static final class BinarySearchArrayPrefixMapTests implements PrefixMappersTests {
@Override
public ImmutablePrefixMapping<Integer> newPrefixMap(final Map<String, Integer> prefixes) {
return binarySearchArrayPrefixMapping(prefixes);
}
@CsvSource(
value = {
"abdicate,abd,abdicate,3,11,8,8",
"abdicated,abd,abdicate,3,14,8,11",
})
@ParameterizedTest
@Override
public void detects_prefixes_with_minimal_steps(
final String string,
final String firstMatchEvenKeys,
final String firstMatchOddKeys,
final int firstMatchStepsEvenKeys,
final int longestMatchStepsEvenKeys,
final int firstMatchStepsOddKeys,
final int longestMatchStepsOddKeys) {
PrefixMappersTests.super.detects_prefixes_with_minimal_steps(
string,
firstMatchEvenKeys,
firstMatchOddKeys,
firstMatchStepsEvenKeys,
longestMatchStepsEvenKeys,
firstMatchStepsOddKeys,
longestMatchStepsOddKeys);
}
}
static final class BinarySearchArraySuffixMapTests implements SuffixMappersTests {
@Override
public ImmutableSuffixMapping<Integer> newSuffixMap(final Map<String, Integer> suffixes) { | /*
Copyright 2023 Kyle J. Stiemann
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 dev.stiemannkj1.collection.fixmapping;
final class FixMappingsTests {
// TODO test unicode
interface PrefixMappersTests {
@CsvSource(
value = {
"null,false,null",
",false,null",
"123456,false,null",
"~~~~~~,false,null",
"a,false,null",
"ab,false,null",
"abc,true,0",
"abe,true,1",
"abd,true,2",
"aba,false,null",
"abd,true,2",
"abdi,true,2",
"abdic,true,2",
"abdica,true,2",
"abdicat,true,2",
"abdicat,true,2",
"abdicate,true,3",
"abdicated,true,3",
"x,false,null",
"xy,false,null"
},
nullValues = "null")
@ParameterizedTest
@SuppressWarnings("unchecked")
default void detects_prefixes(
final String string, final boolean expectPrefixed, final Integer expectedValue) {
// Test odd number of prefixes.
final Map<String, Integer> prefixes =
newTestMapBuilder().add("abc", 0).add("abe", 1).add("abd", 2).add("abdicate", 3).map;
ImmutablePrefixMapping<Integer> prefixMap = newPrefixMap(prefixes);
assertEquals(expectPrefixed, prefixMap.matchesAnyPrefix(string));
assertEquals(expectedValue, prefixMap.valueForPrefix(string));
assertEquals(
getKeyAndValueByValue(prefixes, expectedValue), prefixMap.keyAndValueForPrefix(string));
assertFirstMatchSearchTakesLessSteps(
string, expectedValue, (FixMappings.FixMapping<Integer>) prefixMap);
// Test odd number of prefixes.
prefixes.put("xyz", 4);
prefixMap = newPrefixMap(prefixes);
assertEquals(expectPrefixed, prefixMap.matchesAnyPrefix(string));
assertEquals(expectedValue, prefixMap.valueForPrefix(string));
assertEquals(
getKeyAndValueByValue(prefixes, expectedValue), prefixMap.keyAndValueForPrefix(string));
assertFirstMatchSearchTakesLessSteps(
string, expectedValue, (FixMappings.FixMapping<Integer>) prefixMap);
}
@SuppressWarnings("unchecked")
default void detects_prefixes_with_minimal_steps(
final String string,
final String firstMatchEvenKeys,
final String firstMatchOddKeys,
final int firstMatchStepsEvenKeys,
final int longestMatchStepsEvenKeys,
final int firstMatchStepsOddKeys,
final int longestMatchStepsOddKeys) {
// Test even number of prefixes.
final Map<String, Integer> prefixes =
newTestMapBuilder().add("abc", 0).add("abe", 1).add("abd", 2).add("abdicate", 3).map;
ImmutablePrefixMapping<Integer> prefixMap = newPrefixMap(prefixes);
final AtomicLong firstSearchSteps = new AtomicLong();
final AtomicLong longestSearchSteps = new AtomicLong();
firstSearchSteps.set(0);
longestSearchSteps.set(0);
assertEquals(
Pair.of(firstMatchEvenKeys, prefixes.get(firstMatchEvenKeys)),
((FixMappings.FixMapping<Integer>) prefixMap)
.getKeyAndValue(false, string, firstSearchSteps));
assertEquals(
Pair.of("abdicate", 3),
((FixMappings.FixMapping<Integer>) prefixMap)
.getKeyAndValue(true, string, longestSearchSteps));
assertEquals(firstMatchStepsEvenKeys, firstSearchSteps.get());
assertEquals(longestMatchStepsEvenKeys, longestSearchSteps.get());
// Test odd number of prefixes.
prefixes.put("aaa", 4);
prefixMap = newPrefixMap(prefixes);
firstSearchSteps.set(0);
longestSearchSteps.set(0);
assertEquals(
Pair.of(firstMatchOddKeys, prefixes.get(firstMatchOddKeys)),
((FixMappings.FixMapping<Integer>) prefixMap)
.getKeyAndValue(false, string, firstSearchSteps));
assertEquals(
Pair.of("abdicate", 3),
((FixMappings.FixMapping<Integer>) prefixMap)
.getKeyAndValue(true, string, longestSearchSteps));
assertEquals(firstMatchStepsOddKeys, firstSearchSteps.get());
assertEquals(longestMatchStepsOddKeys, longestSearchSteps.get());
}
@Test
default void allows_prefixes_with_matching_suffixes() {
// Test odd number of suffixes.
final Map<String, Integer> suffixes =
newTestMapBuilder().add("bdicate", 0).add("abdicate", 2).map;
assertDoesNotThrow(() -> newPrefixMap(suffixes));
}
static Stream<Map<String, Integer>> invalidPrefixes() {
return Stream.of(
Collections.emptyMap(),
newTestMapBuilder().add(null, 1).map,
newTestMapBuilder().add(null, 1).add("asdf", 1).map,
newTestMapBuilder().add("", 1).map,
newTestMapBuilder().add("", 1).add("asdf", 1).map,
// Invalid map with duplicate keys:
toMap(Arrays.asList(Pair.of("asdf", 1), Pair.of("asdf", 1))),
// Invalid map with null entry:
toMap(Arrays.asList(null, Pair.of("asdf", 1))));
}
@MethodSource("invalidPrefixes")
@ParameterizedTest
default void throws_illegal_arg_when_provided_invalid_values(
final Map<String, Integer> prefixes) {
final Class<? extends Exception> expectedExceptionType =
prefixes != null ? IllegalArgumentException.class : NullPointerException.class;
assertThrows(expectedExceptionType, () -> newPrefixMap(prefixes));
}
ImmutablePrefixMapping<Integer> newPrefixMap(final Map<String, Integer> prefixes);
}
interface SuffixMappersTests {
@CsvSource(
value = {
"null,false,null",
",false,null",
"123456,false,null",
"~~~~~~,false,null",
"a,false,null",
"ab,false,null",
"abc,true,0",
"1abc,true,0",
"abe,true,1",
"abed,false,null",
"abd,false,null",
"aba,false,null",
"at,false,null",
"ate,true,2",
"cate,true,2",
"icate,true,2",
"dicate,true,2",
"bdicate,true,2",
"abdicate,true,3",
"i abdicate,true,3",
"abdicated,false,null",
"z,false,null",
"yz,false,null"
},
nullValues = "null")
@ParameterizedTest
@SuppressWarnings("unchecked")
default void detects_suffixes(
final String string, final boolean expectSuffixed, final Integer expectedValue) {
// Test even number of suffixes.
final Map<String, Integer> suffixes =
newTestMapBuilder().add("abc", 0).add("abe", 1).add("ate", 2).add("abdicate", 3).map;
ImmutableSuffixMapping<Integer> suffixMap = newSuffixMap(suffixes);
assertEquals(expectSuffixed, suffixMap.matchesAnySuffix(string));
assertEquals(expectedValue, suffixMap.valueForSuffix(string));
assertEquals(
getKeyAndValueByValue(suffixes, expectedValue), suffixMap.keyAndValueForSuffix(string));
assertFirstMatchSearchTakesLessSteps(
string, expectedValue, (FixMappings.FixMapping<Integer>) suffixMap);
// Test odd number of suffixes.
suffixes.put("xyz", 4);
suffixMap = newSuffixMap(suffixes);
assertEquals(expectSuffixed, suffixMap.matchesAnySuffix(string));
assertEquals(expectedValue, suffixMap.valueForSuffix(string));
assertEquals(
getKeyAndValueByValue(suffixes, expectedValue), suffixMap.keyAndValueForSuffix(string));
assertFirstMatchSearchTakesLessSteps(
string, expectedValue, (FixMappings.FixMapping<Integer>) suffixMap);
}
@SuppressWarnings("unchecked")
default void detects_suffixes_with_minimal_steps(
final String string,
final String firstMatchEvenKeys,
final String firstMatchOddKeys,
final int firstMatchStepsEvenKeys,
final int longestMatchStepsEvenKeys,
final int firstMatchStepsOddKeys,
final int longestMatchStepsOddKeys) {
// Test even number of suffixes.
final Map<String, Integer> suffixes =
newTestMapBuilder().add("abc", 0).add("abe", 1).add("ate", 2).add("abdicate", 3).map;
ImmutableSuffixMapping<Integer> suffixMap = newSuffixMap(suffixes);
final AtomicLong firstSearchSteps = new AtomicLong();
final AtomicLong longestSearchSteps = new AtomicLong();
firstSearchSteps.set(0);
longestSearchSteps.set(0);
assertEquals(
Pair.of(firstMatchEvenKeys, suffixes.get(firstMatchEvenKeys)),
((FixMappings.FixMapping<Integer>) suffixMap)
.getKeyAndValue(false, string, firstSearchSteps));
assertEquals(
Pair.of("abdicate", 3),
((FixMappings.FixMapping<Integer>) suffixMap)
.getKeyAndValue(true, string, longestSearchSteps));
assertEquals(firstMatchStepsEvenKeys, firstSearchSteps.get());
assertEquals(longestMatchStepsEvenKeys, longestSearchSteps.get());
// Test odd number of suffixes.
suffixes.put("aaa", 4);
suffixMap = newSuffixMap(suffixes);
firstSearchSteps.set(0);
longestSearchSteps.set(0);
assertEquals(
Pair.of(firstMatchOddKeys, suffixes.get(firstMatchOddKeys)),
((FixMappings.FixMapping<Integer>) suffixMap)
.getKeyAndValue(false, string, firstSearchSteps));
assertEquals(
Pair.of("abdicate", 3),
((FixMappings.FixMapping<Integer>) suffixMap)
.getKeyAndValue(true, string, longestSearchSteps));
assertEquals(firstMatchStepsOddKeys, firstSearchSteps.get());
assertEquals(longestMatchStepsOddKeys, longestSearchSteps.get());
}
@Test
default void allows_suffixes_with_matching_prefixes() {
// Test odd number of suffixes.
final Map<String, Integer> suffixes =
newTestMapBuilder().add("abdicat", 0).add("abdicate", 2).map;
assertDoesNotThrow(() -> newSuffixMap(suffixes));
}
static Stream<Map<String, Integer>> invalidSuffixes() {
return Stream.of(
Collections.emptyMap(),
newTestMapBuilder().add(null, 1).map,
newTestMapBuilder().add(null, 1).add("asdf", 1).map,
newTestMapBuilder().add("", 1).map,
newTestMapBuilder().add("", 1).add("asdf", 1).map,
// Invalid map with duplicate keys:
toMap(Arrays.asList(Pair.of("asdf", 1), Pair.of("asdf", 1))),
// Invalid map with null entry:
toMap(Arrays.asList(null, Pair.of("asdf", 1))));
}
@MethodSource("invalidSuffixes")
@ParameterizedTest
default void throws_illegal_arg_when_provided_invalid_values(
final Map<String, Integer> suffixes) {
final Class<? extends Exception> expectedExceptionType =
suffixes != null ? IllegalArgumentException.class : NullPointerException.class;
assertThrows(expectedExceptionType, () -> newSuffixMap(suffixes));
}
ImmutableSuffixMapping<Integer> newSuffixMap(final Map<String, Integer> prefixes);
}
private static void assertFirstMatchSearchTakesLessSteps(
String string, Integer expectedValue, FixMappings.FixMapping<Integer> fixMapping) {
final AtomicLong firstSearchSteps = new AtomicLong(0);
final AtomicLong longestSearchSteps = new AtomicLong(0);
final Pair<String, Integer> firstMatch =
fixMapping.getKeyAndValue(false, string, firstSearchSteps);
if (expectedValue != null) {
assertNotNull(firstMatch);
} else {
assertNull(firstMatch);
}
final Pair<String, Integer> longestMatch =
fixMapping.getKeyAndValue(true, string, longestSearchSteps);
if (expectedValue != null) {
assertNotNull(longestMatch);
} else {
assertNull(longestMatch);
}
assertTrue(firstSearchSteps.get() <= longestSearchSteps.get());
}
static final class BinarySearchArrayPrefixMapTests implements PrefixMappersTests {
@Override
public ImmutablePrefixMapping<Integer> newPrefixMap(final Map<String, Integer> prefixes) {
return binarySearchArrayPrefixMapping(prefixes);
}
@CsvSource(
value = {
"abdicate,abd,abdicate,3,11,8,8",
"abdicated,abd,abdicate,3,14,8,11",
})
@ParameterizedTest
@Override
public void detects_prefixes_with_minimal_steps(
final String string,
final String firstMatchEvenKeys,
final String firstMatchOddKeys,
final int firstMatchStepsEvenKeys,
final int longestMatchStepsEvenKeys,
final int firstMatchStepsOddKeys,
final int longestMatchStepsOddKeys) {
PrefixMappersTests.super.detects_prefixes_with_minimal_steps(
string,
firstMatchEvenKeys,
firstMatchOddKeys,
firstMatchStepsEvenKeys,
longestMatchStepsEvenKeys,
firstMatchStepsOddKeys,
longestMatchStepsOddKeys);
}
}
static final class BinarySearchArraySuffixMapTests implements SuffixMappersTests {
@Override
public ImmutableSuffixMapping<Integer> newSuffixMap(final Map<String, Integer> suffixes) { | return binarySearchArraySuffixMapping(suffixes); | 1 | 2023-11-12 05:05:22+00:00 | 8k |
slow3586/HypersomniaMapGen | src/main/java/com/slow3586/Main.java | [
{
"identifier": "RoomStyle",
"path": "src/main/java/com/slow3586/Main.java",
"snippet": "@Value\npublic static class RoomStyle {\n int height;\n Color floorColor;\n Color wallColor;\n int patternIdFloor;\n int patternIdWall;\n Color patternColorFloor;\n Color patternColorWall;\n}"
... | import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JacksonException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import com.slow3586.Main.Room.RoomStyle;
import com.slow3586.Main.Settings.Node.ExternalResource;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.Getter;
import lombok.ToString;
import lombok.Value;
import org.jooq.lambda.Sneaky;
import org.jooq.lambda.function.Consumer1;
import org.jooq.lambda.function.Consumer2;
import org.jooq.lambda.function.Consumer4;
import org.jooq.lambda.function.Function1;
import org.jooq.lambda.function.Function3;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Random;
import java.util.StringJoiner;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import static com.slow3586.Main.Color.WHITE;
import static com.slow3586.Main.MapTile.TileType.DOOR;
import static com.slow3586.Main.MapTile.TileType.WALL;
import static com.slow3586.Main.Settings.Layer;
import static com.slow3586.Main.Settings.Node;
import static com.slow3586.Main.Settings.Node.AsNonPhysical.AS_NON_PHYSICAL_DEFAULT;
import static com.slow3586.Main.Settings.Node.AsPhysical.AS_PHYSICAL_DEFAULT;
import static com.slow3586.Main.Settings.Node.ExternalResource.BASE_PNG_TEXTURE_FILENAME;
import static com.slow3586.Main.Settings.Node.ExternalResource.CRATE_BLOCKING;
import static com.slow3586.Main.Settings.Node.ExternalResource.CRATE_NON_BLOCKING;
import static com.slow3586.Main.Settings.Node.ExternalResource.DOMAIN_FOREGROUND;
import static com.slow3586.Main.Settings.Node.ExternalResource.DOMAIN_PHYSICAL;
import static com.slow3586.Main.Settings.Node.ExternalResource.LINE_FLOOR;
import static com.slow3586.Main.Settings.Node.ExternalResource.LINE_WALL;
import static com.slow3586.Main.Settings.Node.ExternalResource.MAP_GFX_PATH;
import static com.slow3586.Main.Settings.Node.ExternalResource.PNG_EXT;
import static com.slow3586.Main.Settings.Node.ExternalResource.RESOURCE_FLOOR_ID;
import static com.slow3586.Main.Settings.Node.ExternalResource.RESOURCE_ID_PREFIX;
import static com.slow3586.Main.Settings.Node.ExternalResource.RESOURCE_WALL_ID;
import static com.slow3586.Main.Settings.Node.ExternalResource.ROOM_NOISE_CIRCLE;
import static com.slow3586.Main.Settings.Node.ExternalResource.SHADOW_FLOOR_CORNER;
import static com.slow3586.Main.Settings.Node.ExternalResource.SHADOW_FLOOR_LINE;
import static com.slow3586.Main.Settings.Node.ExternalResource.SHADOW_WALL_CORNER;
import static com.slow3586.Main.Settings.Node.ExternalResource.SHADOW_WALL_LINE;
import static com.slow3586.Main.Settings.Playtesting;
import static com.slow3586.Main.Size.CRATE_SIZE;
import static com.slow3586.Main.Size.TILE_SIZE; | 5,935 | mapTilesCrop[y + 1][x + 1].tileType = MapTile.TileType.FLOOR;
}
}
}
}
//endregion
//region OUTPUT: PRINT MAP TO TEXT FILE
final StringJoiner wallJoiner = new StringJoiner("\n");
wallJoiner.add("Walls:");
final StringJoiner heightJoiner = new StringJoiner("\n");
heightJoiner.add("Heights:");
final StringJoiner styleIndexJoiner = new StringJoiner("\n");
styleIndexJoiner.add("Styles:");
final StringJoiner carcassJoiner = new StringJoiner("\n");
carcassJoiner.add("Carcass:");
pointsRectArrayByRow(mapTilesCrop)
.forEach(row -> {
final StringBuilder wallJoinerRow = new StringBuilder();
final StringBuilder heightJoinerRow = new StringBuilder();
final StringBuilder styleIndexJoinerRow = new StringBuilder();
final StringBuilder carcassJoinerRow = new StringBuilder();
row.forEach(point -> {
final MapTile mapTile = mapTilesCrop[point.y][point.x];
wallJoinerRow.append(
mapTile.tileType == WALL
? "#"
: mapTile.tileType == MapTile.TileType.DOOR
? "."
: "_");
heightJoinerRow.append(mapTile.height);
styleIndexJoinerRow.append(mapTile.styleIndex);
carcassJoinerRow.append(
mapTile.disabled && !mapTile.carcass
? "X"
: mapTile.carcass || point.x == 0 || point.y == 0
? "#"
: "_");
});
wallJoiner.add(wallJoinerRow.toString());
heightJoiner.add(heightJoinerRow.toString());
styleIndexJoiner.add(styleIndexJoinerRow.toString());
carcassJoiner.add(carcassJoinerRow.toString());
});
final StringJoiner textJoiner = new StringJoiner("\n\n");
textJoiner.add(carcassJoiner.toString());
textJoiner.add(wallJoiner.toString());
textJoiner.add(heightJoiner.toString());
textJoiner.add(styleIndexJoiner.toString());
Files.write(Path.of(config.outputTextFilePath), textJoiner.toString().getBytes());
//endregion
//region OUTPUT: CREATE MAP JSON FILE
//region BASE MAP JSON OBJECT
final Map mapJson = new Map(
new Meta(
config.gameVersion,
config.mapName,
"2023-11-14 17:28:36.619839 UTC"),
new About("Generated map"),
new Settings(
"bomb_defusal",
config.ambientLightColor.intArray()),
new Playtesting(Playtesting.QUICK_TEST),
new ArrayList<>(),
List.of(new Layer(
"default",
new ArrayList<>())),
new ArrayList<>());
//endregion
//region RESOURCES: FUNCTIONS
final File texturesDir = new File("textures");
final Path mapGfxPath = mapDirectory.resolve("gfx");
if (!Files.exists(mapGfxPath)) {
Files.createDirectories(mapGfxPath);
}
final BiConsumer<String, String> createTexture = Sneaky.biConsumer(
(sourceFilename, targetFilename) -> {
final Path sourcePath = texturesDir.toPath().resolve(sourceFilename + PNG_EXT);
final Path targetPath = mapGfxPath.resolve(targetFilename + PNG_EXT);
if (Files.exists(targetPath))
Files.delete(targetPath);
Files.copy(sourcePath, targetPath);
});
final Consumer<String> createTextureSameName = Sneaky.consumer(
(filename) -> createTexture.accept(filename, filename));
final Function3<Integer, Integer, Boolean, String> getCrateName = (
final Integer roomStyleIndex,
final Integer crateStyleIndex,
final Boolean isBlocking
) -> "style"
+ roomStyleIndex
+ "_crate"
+ crateStyleIndex
+ "_"
+ (isBlocking ? "" : "non")
+ "blocking";
//endregion
//region RESOURCES: ROOMS
mapJson.external_resources.add(
ExternalResource.builder()
.path(MAP_GFX_PATH + ROOM_NOISE_CIRCLE + PNG_EXT)
.id(RESOURCE_ID_PREFIX + ROOM_NOISE_CIRCLE)
.stretch_when_resized(true)
.domain(DOMAIN_FOREGROUND)
.color(new Color(255, 255, 255, 150).intArray())
.build());
createTextureSameName.accept(ROOM_NOISE_CIRCLE);
//endregion
//region RESOURCES: STYLES
IntStream.range(0, styles.length)
.boxed()
.forEach((final Integer roomStyleIndex) -> {
final RoomStyle style = styles[roomStyleIndex]; | package com.slow3586;
public class Main {
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
static Random baseRandom;
static Configuration config;
static {
OBJECT_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
OBJECT_MAPPER.setSerializationInclusion(JsonInclude.Include.NON_NULL);
}
public static void main(String[] args) throws IOException {
//region CONFIGURATION
final String configStr = Files.readString(Path.of("config.json"));
config = OBJECT_MAPPER.readValue(configStr, Configuration.class);
baseRandom = new Random(config.randomSeed);
final Path mapDirectory = Path.of(config.gameDirectoryPath, "user", "projects", config.mapName);
//endregion
//region GENERATION: ROOMS
//region RANDOMIZE DIAGONAL ROOM SIZES
final Size[] diagonalRoomSizes = Stream.generate(() -> config.roomMinMaxSize.randomize())
.limit(Math.max(config.roomsCount.x, config.roomsCount.y))
.toArray(Size[]::new);
//endregion
//region RANDOMIZE ROOM STYLES
final RoomStyle[] styles = IntStream.range(0, config.styleCount)
.boxed()
.map(styleIndex ->
new RoomStyle(
config.styleHeightOverride.length > styleIndex
? config.styleHeightOverride[styleIndex]
: styleIndex,
config.floorMinMaxTintBase
.randomize()
.add(config.floorTintPerHeight.mul(styleIndex)),
config.wallMinMaxTintBase
.randomize()
.add(config.wallTintPerHeight.mul(styleIndex)),
nextInt(1, config.patternResourceCount),
nextInt(1, config.patternResourceCount),
config.patternMinMaxTintFloor.randomize(),
config.patternMinMaxTintWall.randomize())
).toArray(RoomStyle[]::new);
//endregion
final Room[][] rooms = new Room[config.roomsCount.y][config.roomsCount.x];
pointsRect(0, 0, config.roomsCount.x, config.roomsCount.y)
.forEach(roomIndex -> {
final boolean disableRoom = Arrays.asList(config.roomsDisabled).contains(roomIndex);
final boolean disableDoorRight =
Arrays.asList(config.roomsDoorRightDisabled).contains(roomIndex)
|| (disableRoom && Arrays.asList(config.roomsDisabled).contains(roomIndex.add(Point.RIGHT)));
final boolean disableDoorDown =
Arrays.asList(config.roomsDoorDownDisabled).contains(roomIndex)
|| (disableRoom && Arrays.asList(config.roomsDisabled).contains(roomIndex.add(Point.DOWN)));
//region CALCULATE ABSOLUTE ROOM POSITION
final Point roomPosAbs = new Point(
Arrays.stream(diagonalRoomSizes)
.limit(roomIndex.x)
.map(Size::getW)
.reduce(0, Integer::sum),
Arrays.stream(diagonalRoomSizes)
.limit(roomIndex.y)
.map(Size::getH)
.reduce(0, Integer::sum));
//endregion
//region RANDOMIZE WALL
final Size wallSize =
config.wallMinMaxSize.randomize();
final Point wallOffset = new Point(
-nextInt(0, Math.min(wallSize.w, config.wallMaxOffset.x)),
-nextInt(0, Math.min(wallSize.h, config.wallMaxOffset.y)));
//endregion
//region RANDOMIZE DOOR
final Size roomFloorSpace = new Size(
diagonalRoomSizes[roomIndex.x].w + wallOffset.y,
diagonalRoomSizes[roomIndex.y].h + wallOffset.x);
final boolean needVerticalDoor =
!disableDoorRight
&& roomIndex.x > 0
&& roomIndex.x < rooms[0].length - 1;
final boolean needHorizontalDoor =
!disableDoorDown
&& roomIndex.y > 0
&& roomIndex.y < rooms.length - 1;
final Size doorSize = new Size(
needHorizontalDoor
? Math.min(config.doorMinMaxWidth.randomizeWidth(), roomFloorSpace.w - 1)
: 0,
needVerticalDoor
? Math.min(config.doorMinMaxWidth.randomizeHeight(), roomFloorSpace.h - 1)
: 0);
final Point doorOffset = new Point(
needHorizontalDoor
? nextInt(1, roomFloorSpace.w - doorSize.w + 1)
: 0,
needVerticalDoor
? nextInt(1, roomFloorSpace.h - doorSize.h + 1)
: 0);
//endregion
//region RANDOMIZE STYLE
final int styleIndex = nextInt(0, config.styleCount);
final Size styleSize = new Size(
roomIndex.x == config.roomsCount.x - 1 ? 1
: config.styleSizeMinMaxSize.randomizeWidth(),
roomIndex.y == config.roomsCount.y - 1 ? 1
: config.styleSizeMinMaxSize.randomizeHeight());
//endregion
//region PUT ROOM INTO ROOMS ARRAY
rooms[roomIndex.y][roomIndex.x] = new Room(
roomPosAbs,
new Size(
diagonalRoomSizes[roomIndex.x].w,
diagonalRoomSizes[roomIndex.y].h),
new Room.Rect(
wallOffset.x,
wallSize.w),
new Room.Rect(
wallOffset.y,
wallSize.h),
new Room.Rect(
doorOffset.x,
doorSize.w),
new Room.Rect(
doorOffset.y,
doorSize.h),
styleIndex,
styleSize,
disableRoom);
//endregion
});
//endregion
//region GENERATION: BASE MAP TILE ARRAY
final MapTile[][] mapTilesUncropped =
pointsRectRows(
Arrays.stream(diagonalRoomSizes)
.mapToInt(r -> r.w
+ Math.max(config.styleSizeMinMaxSize.max.w, config.wallMaxOffset.x))
.sum() + 1,
Arrays.stream(diagonalRoomSizes)
.mapToInt(r -> r.h
+ Math.max(config.styleSizeMinMaxSize.max.h, config.wallMaxOffset.y))
.sum() + 1)
.stream()
.map(row -> row.stream()
.map(point -> new MapTile(
MapTile.TileType.FLOOR,
null,
false,
false,
null))
.toArray(MapTile[]::new)
).toArray(MapTile[][]::new);
//endregion
//region GENERATION: RENDER BASE ROOMS ONTO BASE MAP TILE ARRAY
pointsRectArray(rooms)
.forEach(roomIndex -> {
final Room room = rooms[roomIndex.y][roomIndex.x];
//region FILL MAP TILES
//region WALL HORIZONTAL
pointsRect(
room.roomPosAbs.x,
room.roomPosAbs.y + room.roomSize.h + room.wallHoriz.offset,
room.roomSize.w,
room.wallHoriz.width
).forEach(pointAbs -> {
final boolean isDoorTile = (mapTilesUncropped[pointAbs.y][pointAbs.x].tileType == MapTile.TileType.DOOR)
|| (pointAbs.x >= room.roomPosAbs.x + room.doorHoriz.offset
&& pointAbs.x < room.roomPosAbs.x + room.doorHoriz.offset + room.doorHoriz.width);
mapTilesUncropped[pointAbs.y][pointAbs.x].disabled = !isDoorTile;
mapTilesUncropped[pointAbs.y][pointAbs.x].tileType =
isDoorTile
? MapTile.TileType.DOOR
: WALL;
});
//endregion
//region WALL VERTICAL
pointsRect(
room.roomPosAbs.x + room.roomSize.w + room.wallVert.offset,
room.roomPosAbs.y,
room.wallVert.width,
room.roomSize.h
).forEach(pointAbs -> {
final boolean isDoorTile = (mapTilesUncropped[pointAbs.y][pointAbs.x].tileType == MapTile.TileType.DOOR)
|| (pointAbs.y >= room.roomPosAbs.y + room.doorVert.offset
&& pointAbs.y < room.roomPosAbs.y + room.doorVert.offset + room.doorVert.width);
mapTilesUncropped[pointAbs.y][pointAbs.x].disabled = !isDoorTile;
mapTilesUncropped[pointAbs.y][pointAbs.x].tileType =
isDoorTile
? MapTile.TileType.DOOR
: WALL;
});
//endregion
//region DISABLE FLOOR
if (room.isDisabled()) {
pointsRect(
room.roomPosAbs.x,
room.roomPosAbs.y,
room.roomSize.w + room.wallVert.offset,
room.roomSize.h + room.wallHoriz.offset
).forEach(pointAbs -> {
final boolean isDoorTile = mapTilesUncropped[pointAbs.y][pointAbs.x].tileType == DOOR;
mapTilesUncropped[pointAbs.y][pointAbs.x].disabled = !isDoorTile;
mapTilesUncropped[pointAbs.y][pointAbs.x].tileType =
isDoorTile
? MapTile.TileType.DOOR
: WALL;
});
}
//endregion
//region CARCASS HORIZONTAL
pointsRect(
room.roomPosAbs.x,
room.roomPosAbs.y + room.roomSize.h,
room.roomSize.w,
1
).forEach(pointAbs ->
mapTilesUncropped[pointAbs.y][pointAbs.x].carcass = true);
//endregion
//region CARCASS VERTICAL
pointsRect(
room.roomPosAbs.x + room.roomSize.w,
room.roomPosAbs.y,
1,
room.roomSize.h
).forEach(pointAbs ->
mapTilesUncropped[pointAbs.y][pointAbs.x].carcass = true);
//endregion
//region TILE ROOM TYPE
pointsRect(
room.roomPosAbs.x,
room.roomPosAbs.y,
room.roomSize.w + room.styleSize.w,
room.roomSize.h + room.styleSize.h
).stream()
.map(pointAbs -> mapTilesUncropped[pointAbs.y][pointAbs.x])
.forEach(tile -> {
if (tile.styleIndex == null) {
tile.styleIndex = room.styleIndex;
}
tile.height = styles[room.styleIndex].height
+ (tile.tileType == WALL
? config.wallHeight
: 0);
});
//endregion
//endregion
});
//endregion
//region GENERATION: CROP MAP
final MapTile[][] mapTilesCrop;
if (config.cropMap) {
final Size croppedMapSize = new Size(
Arrays.stream(diagonalRoomSizes)
.limit(rooms[0].length)
.map(s -> s.w)
.reduce(0, Integer::sum)
- diagonalRoomSizes[0].w
+ 1,
Arrays.stream(diagonalRoomSizes)
.limit(rooms.length)
.map(s -> s.h)
.reduce(0, Integer::sum)
- diagonalRoomSizes[0].h
+ 1);
final MapTile[][] temp = new MapTile[croppedMapSize.h][croppedMapSize.w];
for (int y = 0; y < croppedMapSize.h; y++) {
temp[y] = Arrays.copyOfRange(
mapTilesUncropped[y + diagonalRoomSizes[0].h],
diagonalRoomSizes[0].w,
diagonalRoomSizes[0].w + croppedMapSize.w);
}
mapTilesCrop = temp;
} else {
mapTilesCrop = mapTilesUncropped;
}
//endregion
//region GENERATION: FIX MOST DOWN RIGHT TILE
mapTilesCrop[mapTilesCrop.length - 1][mapTilesCrop[0].length - 1] =
mapTilesCrop[mapTilesCrop.length - 1][mapTilesCrop[0].length - 2];
//endregion
//region GENERATION: FIX DIAGONAL WALLS TOUCH WITH EMPTY SIDES
// #_ _#
// _# OR #_
final Function1<MapTile, Boolean> isWall = (s) -> s.tileType == MapTile.TileType.WALL;
for (int iter = 0; iter < 2; iter++) {
for (int y = 1; y < mapTilesCrop.length - 1; y++) {
for (int x = 1; x < mapTilesCrop[y].length - 1; x++) {
final boolean wall = isWall.apply(mapTilesCrop[y][x]);
final boolean wallR = isWall.apply(mapTilesCrop[y][x + 1]);
final boolean wallD = isWall.apply(mapTilesCrop[y + 1][x]);
final boolean wallRD = isWall.apply(mapTilesCrop[y + 1][x + 1]);
if ((wall && wallRD && !wallR && !wallD)
|| (!wall && !wallRD && wallR && wallD)
) {
if (wall)
mapTilesCrop[y][x].height -= config.wallHeight;
mapTilesCrop[y][x].tileType = MapTile.TileType.FLOOR;
if (wallR)
mapTilesCrop[y][x + 1].height -= config.wallHeight;
mapTilesCrop[y][x + 1].tileType = MapTile.TileType.FLOOR;
if (wallD)
mapTilesCrop[y + 1][x].height -= config.wallHeight;
mapTilesCrop[y + 1][x].tileType = MapTile.TileType.FLOOR;
if (wallRD)
mapTilesCrop[y + 1][x + 1].height -= config.wallHeight;
mapTilesCrop[y + 1][x + 1].tileType = MapTile.TileType.FLOOR;
}
}
}
}
//endregion
//region OUTPUT: PRINT MAP TO TEXT FILE
final StringJoiner wallJoiner = new StringJoiner("\n");
wallJoiner.add("Walls:");
final StringJoiner heightJoiner = new StringJoiner("\n");
heightJoiner.add("Heights:");
final StringJoiner styleIndexJoiner = new StringJoiner("\n");
styleIndexJoiner.add("Styles:");
final StringJoiner carcassJoiner = new StringJoiner("\n");
carcassJoiner.add("Carcass:");
pointsRectArrayByRow(mapTilesCrop)
.forEach(row -> {
final StringBuilder wallJoinerRow = new StringBuilder();
final StringBuilder heightJoinerRow = new StringBuilder();
final StringBuilder styleIndexJoinerRow = new StringBuilder();
final StringBuilder carcassJoinerRow = new StringBuilder();
row.forEach(point -> {
final MapTile mapTile = mapTilesCrop[point.y][point.x];
wallJoinerRow.append(
mapTile.tileType == WALL
? "#"
: mapTile.tileType == MapTile.TileType.DOOR
? "."
: "_");
heightJoinerRow.append(mapTile.height);
styleIndexJoinerRow.append(mapTile.styleIndex);
carcassJoinerRow.append(
mapTile.disabled && !mapTile.carcass
? "X"
: mapTile.carcass || point.x == 0 || point.y == 0
? "#"
: "_");
});
wallJoiner.add(wallJoinerRow.toString());
heightJoiner.add(heightJoinerRow.toString());
styleIndexJoiner.add(styleIndexJoinerRow.toString());
carcassJoiner.add(carcassJoinerRow.toString());
});
final StringJoiner textJoiner = new StringJoiner("\n\n");
textJoiner.add(carcassJoiner.toString());
textJoiner.add(wallJoiner.toString());
textJoiner.add(heightJoiner.toString());
textJoiner.add(styleIndexJoiner.toString());
Files.write(Path.of(config.outputTextFilePath), textJoiner.toString().getBytes());
//endregion
//region OUTPUT: CREATE MAP JSON FILE
//region BASE MAP JSON OBJECT
final Map mapJson = new Map(
new Meta(
config.gameVersion,
config.mapName,
"2023-11-14 17:28:36.619839 UTC"),
new About("Generated map"),
new Settings(
"bomb_defusal",
config.ambientLightColor.intArray()),
new Playtesting(Playtesting.QUICK_TEST),
new ArrayList<>(),
List.of(new Layer(
"default",
new ArrayList<>())),
new ArrayList<>());
//endregion
//region RESOURCES: FUNCTIONS
final File texturesDir = new File("textures");
final Path mapGfxPath = mapDirectory.resolve("gfx");
if (!Files.exists(mapGfxPath)) {
Files.createDirectories(mapGfxPath);
}
final BiConsumer<String, String> createTexture = Sneaky.biConsumer(
(sourceFilename, targetFilename) -> {
final Path sourcePath = texturesDir.toPath().resolve(sourceFilename + PNG_EXT);
final Path targetPath = mapGfxPath.resolve(targetFilename + PNG_EXT);
if (Files.exists(targetPath))
Files.delete(targetPath);
Files.copy(sourcePath, targetPath);
});
final Consumer<String> createTextureSameName = Sneaky.consumer(
(filename) -> createTexture.accept(filename, filename));
final Function3<Integer, Integer, Boolean, String> getCrateName = (
final Integer roomStyleIndex,
final Integer crateStyleIndex,
final Boolean isBlocking
) -> "style"
+ roomStyleIndex
+ "_crate"
+ crateStyleIndex
+ "_"
+ (isBlocking ? "" : "non")
+ "blocking";
//endregion
//region RESOURCES: ROOMS
mapJson.external_resources.add(
ExternalResource.builder()
.path(MAP_GFX_PATH + ROOM_NOISE_CIRCLE + PNG_EXT)
.id(RESOURCE_ID_PREFIX + ROOM_NOISE_CIRCLE)
.stretch_when_resized(true)
.domain(DOMAIN_FOREGROUND)
.color(new Color(255, 255, 255, 150).intArray())
.build());
createTextureSameName.accept(ROOM_NOISE_CIRCLE);
//endregion
//region RESOURCES: STYLES
IntStream.range(0, styles.length)
.boxed()
.forEach((final Integer roomStyleIndex) -> {
final RoomStyle style = styles[roomStyleIndex]; | final String floorId = RESOURCE_FLOOR_ID + roomStyleIndex; | 16 | 2023-11-18 14:36:04+00:00 | 8k |
intrepidLi/BUAA_Food | app/src/main/java/com/buaa/food/ui/activity/PhoneResetActivity.java | [
{
"identifier": "AppActivity",
"path": "app/src/main/java/com/buaa/food/app/AppActivity.java",
"snippet": "public abstract class AppActivity extends BaseActivity\n implements ToastAction, TitleBarAction, OnHttpListener<Object> {\n\n /** 标题栏对象 */\n private TitleBar mTitleBar;\n /** 状态栏沉浸 ... | import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.buaa.food.R;
import com.buaa.food.aop.Log;
import com.buaa.food.aop.SingleClick;
import com.buaa.food.app.AppActivity;
import com.buaa.food.http.api.GetCodeApi;
import com.buaa.food.http.api.PhoneApi;
import com.buaa.food.http.model.HttpData;
import com.buaa.food.manager.InputTextManager;
import com.buaa.food.ui.dialog.TipsDialog;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.hjq.toast.ToastUtils;
import com.hjq.widget.view.CountdownView; | 5,317 | package com.buaa.food.ui.activity;
public final class PhoneResetActivity extends AppActivity
implements TextView.OnEditorActionListener {
private static final String INTENT_KEY_IN_CODE = "code";
@Log
public static void start(Context context, String code) {
Intent intent = new Intent(context, PhoneResetActivity.class);
intent.putExtra(INTENT_KEY_IN_CODE, code);
if (!(context instanceof Activity)) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
context.startActivity(intent);
}
private EditText mPhoneView;
private EditText mCodeView;
private CountdownView mCountdownView;
private Button mCommitView;
/** 验证码 */
private String mVerifyCode;
@Override
protected int getLayoutId() {
return R.layout.phone_reset_activity;
}
@Override
protected void initView() {
mPhoneView = findViewById(R.id.et_phone_reset_phone);
mCodeView = findViewById(R.id.et_phone_reset_code);
mCountdownView = findViewById(R.id.cv_phone_reset_countdown);
mCommitView = findViewById(R.id.btn_phone_reset_commit);
setOnClickListener(mCountdownView, mCommitView);
mCodeView.setOnEditorActionListener(this);
| package com.buaa.food.ui.activity;
public final class PhoneResetActivity extends AppActivity
implements TextView.OnEditorActionListener {
private static final String INTENT_KEY_IN_CODE = "code";
@Log
public static void start(Context context, String code) {
Intent intent = new Intent(context, PhoneResetActivity.class);
intent.putExtra(INTENT_KEY_IN_CODE, code);
if (!(context instanceof Activity)) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
context.startActivity(intent);
}
private EditText mPhoneView;
private EditText mCodeView;
private CountdownView mCountdownView;
private Button mCommitView;
/** 验证码 */
private String mVerifyCode;
@Override
protected int getLayoutId() {
return R.layout.phone_reset_activity;
}
@Override
protected void initView() {
mPhoneView = findViewById(R.id.et_phone_reset_phone);
mCodeView = findViewById(R.id.et_phone_reset_code);
mCountdownView = findViewById(R.id.cv_phone_reset_countdown);
mCommitView = findViewById(R.id.btn_phone_reset_commit);
setOnClickListener(mCountdownView, mCommitView);
mCodeView.setOnEditorActionListener(this);
| InputTextManager.with(this) | 4 | 2023-11-14 10:04:26+00:00 | 8k |
WallasAR/GUITest | src/main/java/com/example/guitest/MedController.java | [
{
"identifier": "Banco",
"path": "src/main/java/com/db/bank/Banco.java",
"snippet": "public class Banco {\n Scanner scanner1 = new Scanner(System.in);\n public static Connection connection = conexao();\n Statement executar;\n {\n try {\n executar = connection.createStateme... | import com.db.bank.Banco;
import com.table.view.FuncionarioTable;
import com.table.view.MedicamentoTable;
import com.warning.alert.AlertMsg;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.collections.transformation.SortedList;
import javafx.fxml.FXML;
import static com.db.bank.Banco.connection;
import javafx.fxml.Initializable;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;
import java.net.URL;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle; | 4,770 | package com.example.guitest;
public class MedController implements Initializable {
Banco banco = new Banco();
@FXML
protected void MainAction(MouseEvent e) {
if (AlertMsg.msgConfirm("Confimar Logout", "Deseja sair para a página de login?")) {
Main.changedScene("main");
}
}
@FXML
protected void HomeAction(MouseEvent e) {
Main.changedScene("home");
}
@FXML
protected void FuncAction(MouseEvent e) {
Main.changedScene("func");
}
@FXML
protected void ClientAction(MouseEvent e) {
Main.changedScene("client");
}
@FXML
protected void RecordAction(MouseEvent e) {
Main.changedScene("record");
}
@FXML
private TableView tbMedicamento;
@FXML
private TableColumn clIdmedi;
@FXML
private TableColumn clNomemedi;
@FXML
private TableColumn clQuantimedi;
@FXML
private TableColumn clTipomedi;
@FXML
private TableColumn clPreçomedi;
@FXML
private TextField tfSearch;
@FXML
private TextField tfNome;
@FXML
private TextField tfQuantidade;
@FXML
private TextField tfTipo;
@FXML
private TextField tfValor;
@FXML
private TextField tfId;
public void tabelamedi() throws SQLException {
List<MedicamentoTable> medicamentos = new ArrayList<>();
String consultaSQL = "SELECT * FROM medicamentos"; | package com.example.guitest;
public class MedController implements Initializable {
Banco banco = new Banco();
@FXML
protected void MainAction(MouseEvent e) {
if (AlertMsg.msgConfirm("Confimar Logout", "Deseja sair para a página de login?")) {
Main.changedScene("main");
}
}
@FXML
protected void HomeAction(MouseEvent e) {
Main.changedScene("home");
}
@FXML
protected void FuncAction(MouseEvent e) {
Main.changedScene("func");
}
@FXML
protected void ClientAction(MouseEvent e) {
Main.changedScene("client");
}
@FXML
protected void RecordAction(MouseEvent e) {
Main.changedScene("record");
}
@FXML
private TableView tbMedicamento;
@FXML
private TableColumn clIdmedi;
@FXML
private TableColumn clNomemedi;
@FXML
private TableColumn clQuantimedi;
@FXML
private TableColumn clTipomedi;
@FXML
private TableColumn clPreçomedi;
@FXML
private TextField tfSearch;
@FXML
private TextField tfNome;
@FXML
private TextField tfQuantidade;
@FXML
private TextField tfTipo;
@FXML
private TextField tfValor;
@FXML
private TextField tfId;
public void tabelamedi() throws SQLException {
List<MedicamentoTable> medicamentos = new ArrayList<>();
String consultaSQL = "SELECT * FROM medicamentos"; | Statement statement = connection.createStatement(); | 4 | 2023-11-16 14:55:08+00:00 | 8k |
wzh933/Buffer-Manager | src/main/java/cs/adb/wzh/dataStorageManager/DSMgr.java | [
{
"identifier": "Buffer",
"path": "src/main/java/cs/adb/wzh/Storage/Buffer.java",
"snippet": "public class Buffer {\n private final int bufSize;\n private final Frame[] buf;\n\n public int getBufSize() {\n return bufSize;\n }\n\n public Frame[] getBuf() {\n return buf;\n ... | import cs.adb.wzh.Storage.Buffer;
import cs.adb.wzh.Storage.Disk;
import cs.adb.wzh.Storage.File;
import cs.adb.wzh.StorageForm.Frame;
import cs.adb.wzh.StorageForm.Page;
import cs.adb.wzh.bufferManager.BMgr;
import java.io.IOException;
import java.util.Arrays; | 5,832 | package cs.adb.wzh.dataStorageManager;
/**
* @author Wang Zihui
* @date 2023/11/12
**/
public class DSMgr {
private final int maxPageNum;
private int pageNum = 0;//开始时被固定的页面数位0
private final int[] pages;
private int curRecordId;
private File curFile;
private final Buffer bf; | package cs.adb.wzh.dataStorageManager;
/**
* @author Wang Zihui
* @date 2023/11/12
**/
public class DSMgr {
private final int maxPageNum;
private int pageNum = 0;//开始时被固定的页面数位0
private final int[] pages;
private int curRecordId;
private File curFile;
private final Buffer bf; | private final Disk disk; | 1 | 2023-11-15 16:30:06+00:00 | 8k |
UselessBullets/DragonFly | src/main/java/useless/dragonfly/debug/testentity/Zombie/ZombieModelTest.java | [
{
"identifier": "AnimationHelper",
"path": "src/main/java/useless/dragonfly/helper/AnimationHelper.java",
"snippet": "public class AnimationHelper {\n\tpublic static final Map<String, Animation> registeredAnimations = new HashMap<>();\n\n\tpublic static Animation getOrCreateEntityAnimation(String modID,... | import net.minecraft.core.util.helper.MathHelper;
import useless.dragonfly.helper.AnimationHelper;
import useless.dragonfly.model.entity.BenchEntityModel;
import useless.dragonfly.model.entity.animation.Animation;
import static useless.dragonfly.DragonFly.MOD_ID; | 6,972 | package useless.dragonfly.debug.testentity.Zombie;
public class ZombieModelTest extends BenchEntityModel {
@Override
public void setRotationAngles(float limbSwing, float limbYaw, float ticksExisted, float headYaw, float headPitch, float scale) {
// If you need play some animation. you should reset with this
this.getIndexBones().forEach((s, benchEntityBones) -> benchEntityBones.resetPose());
super.setRotationAngles(limbSwing, limbYaw, ticksExisted, headYaw, headPitch, scale);
if (this.getIndexBones().containsKey("Head")) {
this.getIndexBones().get("Head").setRotationAngle((float) Math.toRadians(headPitch), (float) Math.toRadians(headYaw), 0);
}
if (this.getIndexBones().containsKey("bone")) {
this.getIndexBones().get("bone").setRotationAngle(0, ticksExisted, 0);
}
if (this.getIndexBones().containsKey("RightArm")) {
this.getIndexBones().get("RightArm").setRotationAngle(MathHelper.cos(limbSwing * (2f/3) + MathHelper.PI) * 2.0f * limbYaw * 0.5f, 0, 0);
}
if (this.getIndexBones().containsKey("LeftArm")) {
this.getIndexBones().get("LeftArm").setRotationAngle(MathHelper.cos(limbSwing * (2f/3)) * 2.0f * limbYaw * 0.5f, 0, 0);
} | package useless.dragonfly.debug.testentity.Zombie;
public class ZombieModelTest extends BenchEntityModel {
@Override
public void setRotationAngles(float limbSwing, float limbYaw, float ticksExisted, float headYaw, float headPitch, float scale) {
// If you need play some animation. you should reset with this
this.getIndexBones().forEach((s, benchEntityBones) -> benchEntityBones.resetPose());
super.setRotationAngles(limbSwing, limbYaw, ticksExisted, headYaw, headPitch, scale);
if (this.getIndexBones().containsKey("Head")) {
this.getIndexBones().get("Head").setRotationAngle((float) Math.toRadians(headPitch), (float) Math.toRadians(headYaw), 0);
}
if (this.getIndexBones().containsKey("bone")) {
this.getIndexBones().get("bone").setRotationAngle(0, ticksExisted, 0);
}
if (this.getIndexBones().containsKey("RightArm")) {
this.getIndexBones().get("RightArm").setRotationAngle(MathHelper.cos(limbSwing * (2f/3) + MathHelper.PI) * 2.0f * limbYaw * 0.5f, 0, 0);
}
if (this.getIndexBones().containsKey("LeftArm")) {
this.getIndexBones().get("LeftArm").setRotationAngle(MathHelper.cos(limbSwing * (2f/3)) * 2.0f * limbYaw * 0.5f, 0, 0);
} | Animation testAnimation = AnimationHelper.getOrCreateEntityAnimation(MOD_ID, "zombie_test.animation"); | 0 | 2023-11-16 01:10:52+00:00 | 8k |
AntonyCheng/ai-bi | src/main/java/top/sharehome/springbootinittemplate/controller/ChartController.java | [
{
"identifier": "R",
"path": "src/main/java/top/sharehome/springbootinittemplate/common/base/R.java",
"snippet": "@Data\n@NoArgsConstructor\npublic class R<T> {\n\n private static final long serialVersionUID = 1L;\n\n /**\n * 成功状态码\n */\n public static final int SUCCESS = ReturnCode.SUC... | import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import top.sharehome.springbootinittemplate.common.base.R;
import top.sharehome.springbootinittemplate.common.base.ReturnCode;
import top.sharehome.springbootinittemplate.exception.customize.CustomizeReturnException;
import top.sharehome.springbootinittemplate.model.dto.chart.ChartGenDto;
import top.sharehome.springbootinittemplate.model.dto.chart.ChartQueryDto;
import top.sharehome.springbootinittemplate.model.entity.Chart;
import top.sharehome.springbootinittemplate.model.entity.PageModel;
import top.sharehome.springbootinittemplate.model.vo.chart.ChartGenVo;
import top.sharehome.springbootinittemplate.service.ChartService;
import top.sharehome.springbootinittemplate.utils.chat.ChatUtils;
import top.sharehome.springbootinittemplate.utils.excel.ExcelUtils;
import top.sharehome.springbootinittemplate.utils.satoken.LoginUtils;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List; | 5,980 | package top.sharehome.springbootinittemplate.controller;
/**
* 图表接口
*
* @author AntonyCheng
*/
@RestController
@RequestMapping("/chart")
@Slf4j
@SaCheckLogin
public class ChartController {
@Resource
private ChartService chartService;
/**
* 分页获取当前用户创建的资源列表
* todo 修改返回参数
*
* @param chartQueryDto 分页查询Dto类
* @param pageModel 分页实体类
* @return
*/
@PostMapping("/user/list/page")
public R<Page<Chart>> listMyChartByPage(@Validated @RequestBody PageModel pageModel, @Validated @RequestBody ChartQueryDto chartQueryDto) { | package top.sharehome.springbootinittemplate.controller;
/**
* 图表接口
*
* @author AntonyCheng
*/
@RestController
@RequestMapping("/chart")
@Slf4j
@SaCheckLogin
public class ChartController {
@Resource
private ChartService chartService;
/**
* 分页获取当前用户创建的资源列表
* todo 修改返回参数
*
* @param chartQueryDto 分页查询Dto类
* @param pageModel 分页实体类
* @return
*/
@PostMapping("/user/list/page")
public R<Page<Chart>> listMyChartByPage(@Validated @RequestBody PageModel pageModel, @Validated @RequestBody ChartQueryDto chartQueryDto) { | chartQueryDto.setUserId(LoginUtils.getLoginUserId()); | 11 | 2023-11-12 07:49:59+00:00 | 8k |
rmheuer/azalea | azalea-core/src/main/java/com/github/rmheuer/azalea/render2d/VertexBatch.java | [
{
"identifier": "AttribType",
"path": "azalea-core/src/main/java/com/github/rmheuer/azalea/render/mesh/AttribType.java",
"snippet": "public enum AttribType {\n /** GLSL {@code float} */\n FLOAT(1),\n /** GLSL {@code vec2} */\n VEC2(2),\n /** GLSL {@code vec3} */\n VEC3(3),\n /** GLS... | import com.github.rmheuer.azalea.render.mesh.AttribType;
import com.github.rmheuer.azalea.render.mesh.MeshData;
import com.github.rmheuer.azalea.render.mesh.PrimitiveType;
import com.github.rmheuer.azalea.render.mesh.VertexLayout;
import com.github.rmheuer.azalea.render.texture.Texture2D;
import com.github.rmheuer.azalea.render.texture.Texture2DRegion;
import java.util.List; | 4,195 | package com.github.rmheuer.azalea.render2d;
/**
* A batch of vertices to draw.
*/
final class VertexBatch {
/**
* The layout of the generated vertex data.
*/
public static final VertexLayout LAYOUT = new VertexLayout(
AttribType.VEC3, // Position
AttribType.VEC2, // Texture coord
AttribType.VEC4, // Color
AttribType.FLOAT // Texture slot
);
private final Texture2D[] textures; | package com.github.rmheuer.azalea.render2d;
/**
* A batch of vertices to draw.
*/
final class VertexBatch {
/**
* The layout of the generated vertex data.
*/
public static final VertexLayout LAYOUT = new VertexLayout(
AttribType.VEC3, // Position
AttribType.VEC2, // Texture coord
AttribType.VEC4, // Color
AttribType.FLOAT // Texture slot
);
private final Texture2D[] textures; | private final MeshData data; | 1 | 2023-11-16 04:46:53+00:00 | 8k |
Shushandr/offroad | src/net/osmand/binary/BinaryMapDataObject.java | [
{
"identifier": "MapIndex",
"path": "src/net/osmand/binary/BinaryMapIndexReader.java",
"snippet": "public static class MapIndex extends BinaryIndexPart {\n\tList<MapRoot> roots = new ArrayList<MapRoot>();\n\t\t\n\tMap<String, Map<String, Integer> > encodingRules = new HashMap<String, Map<String, Integer... | import java.util.LinkedHashMap;
import java.util.Map;
import gnu.trove.list.array.TIntArrayList;
import gnu.trove.map.hash.TIntObjectHashMap;
import net.osmand.binary.BinaryMapIndexReader.MapIndex;
import net.osmand.render.RenderingRulesStorage; | 6,542 | package net.osmand.binary;
public class BinaryMapDataObject {
protected int[] coordinates = null;
protected int[][] polygonInnerCoordinates = null;
protected boolean area = false;
protected int[] types = null;
protected int[] additionalTypes = null;
protected int objectType = RenderingRulesStorage.POINT_RULES;
protected TIntObjectHashMap<String> objectNames = null;
protected TIntArrayList namesOrder = null;
protected long id = 0;
| package net.osmand.binary;
public class BinaryMapDataObject {
protected int[] coordinates = null;
protected int[][] polygonInnerCoordinates = null;
protected boolean area = false;
protected int[] types = null;
protected int[] additionalTypes = null;
protected int objectType = RenderingRulesStorage.POINT_RULES;
protected TIntObjectHashMap<String> objectNames = null;
protected TIntArrayList namesOrder = null;
protected long id = 0;
| protected MapIndex mapIndex = null; | 0 | 2023-11-15 05:04:55+00:00 | 8k |
orijer/IvritInterpreter | src/Evaluation/VariableValueSwapper.java | [
{
"identifier": "UnevenBracketsException",
"path": "src/IvritExceptions/InterpreterExceptions/EvaluatorExceptions/UnevenBracketsException.java",
"snippet": "public class UnevenBracketsException extends UncheckedIOException{\r\n public UnevenBracketsException(String str) {\r\n super(\"נמצאה שגי... | import java.io.IOException;
import java.io.UncheckedIOException;
import IvritExceptions.InterpreterExceptions.EvaluatorExceptions.UnevenBracketsException;
import Variables.BooleanVariable;
import Variables.FloatVariable;
import Variables.IntegerVariable;
import Variables.NumericVariable;
import Variables.VariablesController;
| 4,979 | package Evaluation;
/**
* Handles switching the variables with their values for the evaluation.
*/
public class VariableValueSwapper {
//Contains the variables of the program:
private VariablesController variablesController;
/**
* Constructor.
* @param variablesController - The object that handles the variables of the program.
*/
public VariableValueSwapper(VariablesController variablesController) {
this.variablesController = variablesController;
}
/**
* Reads through a given data string and switches every occurence of a variable with its correct value.
* @param data - The data to process.
* @return a new string that is similar to the given string, but every occurence of a variable is switched with its value.
*/
public String swap(String originalData) {
String data = originalData; //We want to keep the original data to be used when throwing an exception.
StringBuilder swappedLine = new StringBuilder();
int endAt;
while (data.length() > 0) {
char firstChar = data.charAt(0);
if (firstChar == '"') {
data = copyStringLiteral(data, swappedLine, originalData);
} else if (firstChar == ' ' || isBracket(firstChar) || NumericVariable.isNumericOperator(firstChar)) {
//We are reading a space, a bracket, or an operator, just copy it:
swappedLine.append(firstChar);
data = data.substring(1);
} else if ((endAt = BooleanVariable.startsWithBooleanOperator(data)) > 0) {
//We are reading a boolean operator:
swappedLine.append(data.substring(0, endAt));
data = data.substring(endAt);
} else {
//We are reading a literal (non-string) value or a variable:
endAt = dataEndAt(data);
String literalValueOrVariable = data.substring(0, endAt);
if (this.variablesController.isVariable(literalValueOrVariable)) {
//If it is a variable, switch it with its value:
swappedLine.append(this.variablesController.getVariableValue(literalValueOrVariable));
} else {
//If it is literal data, try to copy it:
copyNonStringLiteral(literalValueOrVariable, swappedLine);
}
data = data.substring(endAt);
}
}
return swappedLine.toString();
}
/**
* If given a valid string literal, add its value to the given StringBuilder,
* and return the data without the string literal that was found.
* @param data - The data that should start with a string literal.
* @param swappedLine - The StringBuilder we build the evaluated result in.
* @return a substring of the given data string that starts after the string literal that was found.
*/
private String copyStringLiteral(String data, StringBuilder swappedLine, String originalData) {
int endAt = data.indexOf('"', 1);
if (endAt == -1) {
| package Evaluation;
/**
* Handles switching the variables with their values for the evaluation.
*/
public class VariableValueSwapper {
//Contains the variables of the program:
private VariablesController variablesController;
/**
* Constructor.
* @param variablesController - The object that handles the variables of the program.
*/
public VariableValueSwapper(VariablesController variablesController) {
this.variablesController = variablesController;
}
/**
* Reads through a given data string and switches every occurence of a variable with its correct value.
* @param data - The data to process.
* @return a new string that is similar to the given string, but every occurence of a variable is switched with its value.
*/
public String swap(String originalData) {
String data = originalData; //We want to keep the original data to be used when throwing an exception.
StringBuilder swappedLine = new StringBuilder();
int endAt;
while (data.length() > 0) {
char firstChar = data.charAt(0);
if (firstChar == '"') {
data = copyStringLiteral(data, swappedLine, originalData);
} else if (firstChar == ' ' || isBracket(firstChar) || NumericVariable.isNumericOperator(firstChar)) {
//We are reading a space, a bracket, or an operator, just copy it:
swappedLine.append(firstChar);
data = data.substring(1);
} else if ((endAt = BooleanVariable.startsWithBooleanOperator(data)) > 0) {
//We are reading a boolean operator:
swappedLine.append(data.substring(0, endAt));
data = data.substring(endAt);
} else {
//We are reading a literal (non-string) value or a variable:
endAt = dataEndAt(data);
String literalValueOrVariable = data.substring(0, endAt);
if (this.variablesController.isVariable(literalValueOrVariable)) {
//If it is a variable, switch it with its value:
swappedLine.append(this.variablesController.getVariableValue(literalValueOrVariable));
} else {
//If it is literal data, try to copy it:
copyNonStringLiteral(literalValueOrVariable, swappedLine);
}
data = data.substring(endAt);
}
}
return swappedLine.toString();
}
/**
* If given a valid string literal, add its value to the given StringBuilder,
* and return the data without the string literal that was found.
* @param data - The data that should start with a string literal.
* @param swappedLine - The StringBuilder we build the evaluated result in.
* @return a substring of the given data string that starts after the string literal that was found.
*/
private String copyStringLiteral(String data, StringBuilder swappedLine, String originalData) {
int endAt = data.indexOf('"', 1);
if (endAt == -1) {
| throw new UnevenBracketsException(originalData);
| 0 | 2023-11-17 09:15:07+00:00 | 8k |
WuKongOpenSource/Wukong_HRM | hrm/hrm-web/src/main/java/com/kakarote/hrm/controller/HrmEmployeeSocialSecurityController.java | [
{
"identifier": "OperationLog",
"path": "common/common-log/src/main/java/com/kakarote/common/log/entity/OperationLog.java",
"snippet": "@Getter\n@Setter\npublic class OperationLog {\n //操作对象\n private Object operationObject;\n //操作详情\n private String operationInfo;\n\n private BehaviorEnu... | import com.kakarote.common.log.annotation.OperateLog;
import com.kakarote.common.log.entity.OperationLog;
import com.kakarote.common.log.entity.OperationResult;
import com.kakarote.core.common.Result;
import com.kakarote.core.entity.BasePage;
import com.kakarote.hrm.entity.BO.QuerySalaryListBO;
import com.kakarote.hrm.entity.PO.HrmEmployeeSalaryCard;
import com.kakarote.hrm.entity.PO.HrmEmployeeSocialSecurityInfo;
import com.kakarote.hrm.entity.VO.QuerySalaryListVO;
import com.kakarote.hrm.entity.VO.SalaryOptionHeadVO;
import com.kakarote.hrm.entity.VO.SalarySocialSecurityVO;
import com.kakarote.hrm.service.IHrmEmployeeSocialSecurityService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List; | 5,644 | package com.kakarote.hrm.controller;
/**
* <p>
* 员工工资社保
* </p>
*
* @author huangmingbo
* @since 2020-05-12
*/
@RestController
@RequestMapping("/hrmEmployee/SocialSecurity")
@Api(tags = "员工管理-员工工资社保")
public class HrmEmployeeSocialSecurityController {
@Autowired
private IHrmEmployeeSocialSecurityService socialSecurityService;
@PostMapping("/salarySocialSecurityInformation/{employeeId}")
@ApiOperation("工资社保基本信息")
public Result<SalarySocialSecurityVO> salarySocialSecurityInformation(@PathVariable("employeeId") Long employeeId) {
SalarySocialSecurityVO salarySocialSecurityVO = socialSecurityService.salarySocialSecurityInformation(employeeId);
return Result.ok(salarySocialSecurityVO);
}
@PostMapping("/addSalaryCard")
@ApiOperation("添加工资卡")
public Result addSalaryCard(@RequestBody HrmEmployeeSalaryCard salaryCard) {
socialSecurityService.addOrUpdateSalaryCard(salaryCard);
return Result.ok();
}
@PostMapping("/setSalaryCard")
@ApiOperation("修改工资卡")
public Result setSalaryCard(@RequestBody HrmEmployeeSalaryCard salaryCard) {
socialSecurityService.addOrUpdateSalaryCard(salaryCard);
return Result.ok();
}
/**
* 删除工资卡
*/
@PostMapping("/deleteSalaryCard/{salaryCardId}")
@ApiOperation("删除工资卡")
public Result deleteSalaryCard(@PathVariable("salaryCardId") Long salaryCardId) {
socialSecurityService.deleteSalaryCard(salaryCardId);
return Result.ok();
}
@PostMapping("/addSocialSecurity")
@ApiOperation("添加社保信息")
public Result addSocialSecurity(@RequestBody HrmEmployeeSocialSecurityInfo socialSecurityInfo) {
socialSecurityService.addOrUpdateSocialSecurity(socialSecurityInfo);
return Result.ok();
}
@PostMapping("/setSocialSecurity")
@ApiOperation("修改社保信息")
@OperateLog()
public Result setSocialSecurity(@RequestBody HrmEmployeeSocialSecurityInfo socialSecurityInfo) {
OperationLog operationLog = socialSecurityService.addOrUpdateSocialSecurity(socialSecurityInfo);
return OperationResult.ok(operationLog);
}
@PostMapping("/deleteSocialSecurity/{socialSecurityInfoId}")
@ApiOperation("删除社保信息")
public Result deleteSocialSecurity(@PathVariable("socialSecurityInfoId") Long socialSecurityInfoId) {
socialSecurityService.deleteSocialSecurity(socialSecurityInfoId);
return Result.ok();
}
@PostMapping("/querySalaryList")
@ApiOperation("查询薪资列表") | package com.kakarote.hrm.controller;
/**
* <p>
* 员工工资社保
* </p>
*
* @author huangmingbo
* @since 2020-05-12
*/
@RestController
@RequestMapping("/hrmEmployee/SocialSecurity")
@Api(tags = "员工管理-员工工资社保")
public class HrmEmployeeSocialSecurityController {
@Autowired
private IHrmEmployeeSocialSecurityService socialSecurityService;
@PostMapping("/salarySocialSecurityInformation/{employeeId}")
@ApiOperation("工资社保基本信息")
public Result<SalarySocialSecurityVO> salarySocialSecurityInformation(@PathVariable("employeeId") Long employeeId) {
SalarySocialSecurityVO salarySocialSecurityVO = socialSecurityService.salarySocialSecurityInformation(employeeId);
return Result.ok(salarySocialSecurityVO);
}
@PostMapping("/addSalaryCard")
@ApiOperation("添加工资卡")
public Result addSalaryCard(@RequestBody HrmEmployeeSalaryCard salaryCard) {
socialSecurityService.addOrUpdateSalaryCard(salaryCard);
return Result.ok();
}
@PostMapping("/setSalaryCard")
@ApiOperation("修改工资卡")
public Result setSalaryCard(@RequestBody HrmEmployeeSalaryCard salaryCard) {
socialSecurityService.addOrUpdateSalaryCard(salaryCard);
return Result.ok();
}
/**
* 删除工资卡
*/
@PostMapping("/deleteSalaryCard/{salaryCardId}")
@ApiOperation("删除工资卡")
public Result deleteSalaryCard(@PathVariable("salaryCardId") Long salaryCardId) {
socialSecurityService.deleteSalaryCard(salaryCardId);
return Result.ok();
}
@PostMapping("/addSocialSecurity")
@ApiOperation("添加社保信息")
public Result addSocialSecurity(@RequestBody HrmEmployeeSocialSecurityInfo socialSecurityInfo) {
socialSecurityService.addOrUpdateSocialSecurity(socialSecurityInfo);
return Result.ok();
}
@PostMapping("/setSocialSecurity")
@ApiOperation("修改社保信息")
@OperateLog()
public Result setSocialSecurity(@RequestBody HrmEmployeeSocialSecurityInfo socialSecurityInfo) {
OperationLog operationLog = socialSecurityService.addOrUpdateSocialSecurity(socialSecurityInfo);
return OperationResult.ok(operationLog);
}
@PostMapping("/deleteSocialSecurity/{socialSecurityInfoId}")
@ApiOperation("删除社保信息")
public Result deleteSocialSecurity(@PathVariable("socialSecurityInfoId") Long socialSecurityInfoId) {
socialSecurityService.deleteSocialSecurity(socialSecurityInfoId);
return Result.ok();
}
@PostMapping("/querySalaryList")
@ApiOperation("查询薪资列表") | public Result<BasePage<QuerySalaryListVO>> querySalaryList(@RequestBody QuerySalaryListBO querySalaryListBO) { | 3 | 2023-10-17 05:49:52+00:00 | 8k |
WisdomShell/codeshell-intellij | src/main/java/com/codeshell/intellij/utils/CodeShellUtils.java | [
{
"identifier": "PrefixString",
"path": "src/main/java/com/codeshell/intellij/constant/PrefixString.java",
"snippet": "public interface PrefixString {\n\n String EXPLAIN_CODE = \"请解释以下%s代码: %s\";\n\n String OPTIMIZE_CODE = \"请优化以下%s代码: %s\";\n\n String CLEAN_CODE = \"请清理以下%s代码: %s\";\n\n Str... | import com.alibaba.fastjson2.JSONObject;
import com.codeshell.intellij.constant.PrefixString;
import com.codeshell.intellij.model.GenerateModel;
import com.codeshell.intellij.settings.CodeShellSettings;
import com.codeshell.intellij.widget.CodeShellWidget;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.intellij.openapi.application.ApplicationInfo;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.Inlay;
import com.intellij.openapi.editor.InlayModel;
import com.intellij.openapi.vfs.VirtualFile;
import org.apache.commons.lang3.StringUtils;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern; | 4,573 | package com.codeshell.intellij.utils;
public class CodeShellUtils {
public static String includePreText(String preText, String language, String text) {
String sufText = "\n```" + language + "\n" + text + "\n```\n";
return String.format(preText, language, sufText);
}
public static int prefixHandle(int begin, int end) {
if (end - begin > 3000) {
return end - 3000;
} else {
return begin;
}
}
public static int suffixHandle(int begin, int end) {
if (end - begin > 256) {
return begin + 256;
} else {
return end;
}
}
public static JsonObject pakgHttpRequestBodyForCPU(CodeShellSettings settings, String prefix, String suffix){
JsonObject httpBody = new JsonObject();
httpBody.addProperty("input_prefix", prefix);
httpBody.addProperty("input_suffix", suffix);
httpBody.addProperty("n_predict", Integer.parseInt(settings.getCompletionMaxToken().getDescription()));
httpBody.addProperty("temperature", 0.2);
httpBody.addProperty("repetition_penalty", 1.0);
httpBody.addProperty("top_k", 10);
httpBody.addProperty("top_p", 0.95);
// httpBody.addProperty("prompt", PrefixString.REQUST_END_TAG + codeShellPrompt);
// httpBody.addProperty("frequency_penalty", 1.2);
// httpBody.addProperty("n_predict", Integer.parseInt(settings.getCompletionMaxToken().getDescription()));
// httpBody.addProperty("stream", false);
// JsonArray stopArray = new JsonArray();
// stopArray.add("|<end>|");
// httpBody.add("stop", stopArray);
return httpBody;
}
public static JsonObject pakgHttpRequestBodyForGPU(CodeShellSettings settings, String codeShellPrompt){
JsonObject httpBody = new JsonObject();
httpBody.addProperty("inputs", codeShellPrompt);
JsonObject parameters = new JsonObject();
parameters.addProperty("max_new_tokens", Integer.parseInt(settings.getCompletionMaxToken().getDescription()));
httpBody.add("parameters", parameters);
return httpBody;
}
public static String parseHttpResponseContentForCPU(CodeShellSettings settings, String responseBody, Pattern pattern){
String generatedText = "";
Matcher matcher = pattern.matcher(responseBody);
StringBuilder contentBuilder = new StringBuilder();
while (matcher.find()) {
String jsonString = matcher.group(1);
JSONObject json = JSONObject.parseObject(jsonString);
String content = json.getString("content");
if(StringUtils.equalsAny(content, "<|endoftext|>", "")){
continue;
}
contentBuilder.append(content);
}
return contentBuilder.toString().replace(PrefixString.RESPONSE_END_TAG, "");
}
public static String parseHttpResponseContentForGPU(CodeShellSettings settings, String responseBody){
String generatedText = "";
Gson gson = new Gson(); | package com.codeshell.intellij.utils;
public class CodeShellUtils {
public static String includePreText(String preText, String language, String text) {
String sufText = "\n```" + language + "\n" + text + "\n```\n";
return String.format(preText, language, sufText);
}
public static int prefixHandle(int begin, int end) {
if (end - begin > 3000) {
return end - 3000;
} else {
return begin;
}
}
public static int suffixHandle(int begin, int end) {
if (end - begin > 256) {
return begin + 256;
} else {
return end;
}
}
public static JsonObject pakgHttpRequestBodyForCPU(CodeShellSettings settings, String prefix, String suffix){
JsonObject httpBody = new JsonObject();
httpBody.addProperty("input_prefix", prefix);
httpBody.addProperty("input_suffix", suffix);
httpBody.addProperty("n_predict", Integer.parseInt(settings.getCompletionMaxToken().getDescription()));
httpBody.addProperty("temperature", 0.2);
httpBody.addProperty("repetition_penalty", 1.0);
httpBody.addProperty("top_k", 10);
httpBody.addProperty("top_p", 0.95);
// httpBody.addProperty("prompt", PrefixString.REQUST_END_TAG + codeShellPrompt);
// httpBody.addProperty("frequency_penalty", 1.2);
// httpBody.addProperty("n_predict", Integer.parseInt(settings.getCompletionMaxToken().getDescription()));
// httpBody.addProperty("stream", false);
// JsonArray stopArray = new JsonArray();
// stopArray.add("|<end>|");
// httpBody.add("stop", stopArray);
return httpBody;
}
public static JsonObject pakgHttpRequestBodyForGPU(CodeShellSettings settings, String codeShellPrompt){
JsonObject httpBody = new JsonObject();
httpBody.addProperty("inputs", codeShellPrompt);
JsonObject parameters = new JsonObject();
parameters.addProperty("max_new_tokens", Integer.parseInt(settings.getCompletionMaxToken().getDescription()));
httpBody.add("parameters", parameters);
return httpBody;
}
public static String parseHttpResponseContentForCPU(CodeShellSettings settings, String responseBody, Pattern pattern){
String generatedText = "";
Matcher matcher = pattern.matcher(responseBody);
StringBuilder contentBuilder = new StringBuilder();
while (matcher.find()) {
String jsonString = matcher.group(1);
JSONObject json = JSONObject.parseObject(jsonString);
String content = json.getString("content");
if(StringUtils.equalsAny(content, "<|endoftext|>", "")){
continue;
}
contentBuilder.append(content);
}
return contentBuilder.toString().replace(PrefixString.RESPONSE_END_TAG, "");
}
public static String parseHttpResponseContentForGPU(CodeShellSettings settings, String responseBody){
String generatedText = "";
Gson gson = new Gson(); | GenerateModel generateModel = gson.fromJson(responseBody, GenerateModel.class); | 1 | 2023-10-18 06:29:13+00:00 | 8k |
djkcyl/Shamrock | qqinterface/src/main/java/tencent/im/oidb/cmd0x5eb/oidb_0x5eb.java | [
{
"identifier": "ByteStringMicro",
"path": "qqinterface/src/main/java/com/tencent/mobileqq/pb/ByteStringMicro.java",
"snippet": "public class ByteStringMicro {\n public static final ByteStringMicro EMPTY = null;\n\n public static ByteStringMicro copyFrom(String str, String str2) {\n return ... | import com.tencent.mobileqq.pb.ByteStringMicro;
import com.tencent.mobileqq.pb.MessageMicro;
import com.tencent.mobileqq.pb.PBBytesField;
import com.tencent.mobileqq.pb.PBField;
import com.tencent.mobileqq.pb.PBStringField;
import com.tencent.mobileqq.pb.PBUInt32Field;
import com.tencent.mobileqq.pb.PBUInt64Field; | 4,143 | public final PBUInt32Field uint32_flag_use_mobile_net_switch;
public final PBUInt32Field uint32_flag_zplan_edit_avatar;
public final PBUInt32Field uint32_forbid_flag;
public final PBUInt32Field uint32_freshnews_notify_flag;
public final PBUInt32Field uint32_gender;
public final PBUInt32Field uint32_global_group_level;
public final PBUInt32Field uint32_god_flag;
public final PBUInt32Field uint32_god_forbid;
public final PBUInt32Field uint32_group_mem_credit_flag;
public final PBUInt32Field uint32_guild_gray_flag;
public final PBUInt32Field uint32_has_close_leba_youth_mode_plugin;
public final PBUInt32Field uint32_hidden_session_switch;
public final PBUInt32Field uint32_hidden_session_video_switch;
public final PBUInt32Field uint32_input_status_flag;
public final PBUInt32Field uint32_lang1;
public final PBUInt32Field uint32_lang2;
public final PBUInt32Field uint32_lang3;
public final PBUInt32Field uint32_lflag;
public final PBUInt32Field uint32_lightalk_switch;
public final PBUInt32Field uint32_love_status;
public final PBUInt32Field uint32_mss_update_time;
public final PBUInt32Field uint32_music_ring_autoplay;
public final PBUInt32Field uint32_music_ring_redpoint;
public final PBUInt32Field uint32_music_ring_visible;
public final PBUInt32Field uint32_normal_night_mode_flag;
public final PBUInt32Field uint32_notify_on_like_ranking_list_flag;
public final PBUInt32Field uint32_notify_partake_like_ranking_list_flag;
public final PBUInt32Field uint32_oin;
public final PBUInt32Field uint32_online_status_avatar_switch;
public final PBUInt32Field uint32_plate_of_king_dan;
public final PBUInt32Field uint32_plate_of_king_dan_display_switch;
public final PBUInt32Field uint32_posterfont_id;
public final PBUInt32Field uint32_preload_disable_flag;
public final PBUInt32Field uint32_profession;
public final PBUInt32Field uint32_profile_age_visible;
public final PBUInt32Field uint32_profile_anonymous_answer_switch;
public final PBUInt32Field uint32_profile_birthday_visible;
public final PBUInt32Field uint32_profile_college_visible;
public final PBUInt32Field uint32_profile_company_visible;
public final PBUInt32Field uint32_profile_constellation_visible;
public final PBUInt32Field uint32_profile_dressup_switch;
public final PBUInt32Field uint32_profile_email_visible;
public final PBUInt32Field uint32_profile_hometown_visible;
public final PBUInt32Field uint32_profile_interest_switch;
public final PBUInt32Field uint32_profile_life_achievement_switch;
public final PBUInt32Field uint32_profile_location_visible;
public final PBUInt32Field uint32_profile_membership_and_rank;
public final PBUInt32Field uint32_profile_miniapp_switch;
public final PBUInt32Field uint32_profile_music_switch;
public final PBUInt32Field uint32_profile_musicbox_switch;
public final PBUInt32Field uint32_profile_personal_note_visible;
public final PBUInt32Field uint32_profile_personality_label_switch;
public final PBUInt32Field uint32_profile_present_switch;
public final PBUInt32Field uint32_profile_privilege;
public final PBUInt32Field uint32_profile_profession_visible;
public final PBUInt32Field uint32_profile_qqcard_switch;
public final PBUInt32Field uint32_profile_qqcircle_switch;
public final PBUInt32Field uint32_profile_sex_visible;
public final PBUInt32Field uint32_profile_show_idol_switch;
public final PBUInt32Field uint32_profile_splendid_switch;
public final PBUInt32Field uint32_profile_sticky_note_offline;
public final PBUInt32Field uint32_profile_sticky_note_switch;
public final PBUInt32Field uint32_profile_weishi_switch;
public final PBUInt32Field uint32_profile_wz_game_card_switch;
public final PBUInt32Field uint32_profile_wz_game_skin_switch;
public final PBUInt32Field uint32_pstn_c2c_call_time;
public final PBUInt32Field uint32_pstn_c2c_last_guide_recharge_time;
public final PBUInt32Field uint32_pstn_c2c_try_flag;
public final PBUInt32Field uint32_pstn_c2c_vip;
public final PBUInt32Field uint32_pstn_ever_c2c_vip;
public final PBUInt32Field uint32_pstn_ever_multi_vip;
public final PBUInt32Field uint32_pstn_multi_call_time;
public final PBUInt32Field uint32_pstn_multi_last_guide_recharge_time;
public final PBUInt32Field uint32_pstn_multi_try_flag;
public final PBUInt32Field uint32_pstn_multi_vip;
public final PBUInt32Field uint32_qq_assistant_switch;
public final PBUInt32Field uint32_req_font_effect_id;
public final PBUInt32Field uint32_req_global_ring_id;
public final PBUInt32Field uint32_req_invite2group_auto_agree_flag;
public final PBUInt32Field uint32_req_medalwall_flag;
public final PBUInt32Field uint32_req_push_notice_flag;
public final PBUInt32Field uint32_req_small_world_head_flag;
public final PBUInt32Field uint32_rsp_connections_switch_id;
public final PBUInt32Field uint32_rsp_listen_together_player_id;
public final PBUInt32Field uint32_rsp_qq_level_icon_type;
public final PBUInt32Field uint32_rsp_theme_font_id;
public final PBUInt32Field uint32_school_status_flag;
public final PBUInt32Field uint32_simple_ui_pref;
public final PBUInt32Field uint32_simple_ui_switch;
public final PBUInt32Field uint32_simple_update_time;
public final PBUInt32Field uint32_stranger_vote_switch;
public final PBUInt32Field uint32_subaccount_display_third_qq_flag;
public final PBUInt32Field uint32_subscribe_nearbyassistant_switch;
public final PBUInt32Field uint32_suspend_effect_id;
public final PBUInt32Field uint32_sync_C2C_message_switch;
public final PBUInt32Field uint32_torch_disable_flag;
public final PBUInt32Field uint32_torchbearer_flag;
public final PBUInt32Field uint32_troop_honor_rich_flag;
public final PBUInt32Field uint32_troop_lucky_character_switch;
public final PBUInt32Field uint32_troophonor_switch;
public final PBUInt32Field uint32_vas_colorring_id;
public final PBUInt32Field uint32_vas_diy_font_timestamp;
public final PBUInt32Field uint32_vas_emoticon_usage_info;
public final PBUInt32Field uint32_vas_face_id;
public final PBUInt32Field uint32_vas_font_id;
public final PBUInt32Field uint32_vas_magicfont_flag;
public final PBUInt32Field uint32_vas_pendant_diy_id;
public final PBUInt32Field uint32_vas_praise_id;
public final PBUInt32Field uint32_vas_voicebubble_id;
public final PBUInt32Field uint32_vip_flag;
public final PBUInt32Field uint32_zplan_add_frd;
public final PBUInt32Field uint32_zplan_cmshow_month_active_user;
public final PBUInt32Field uint32_zplan_master_show;
public final PBUInt32Field uint32_zplan_message_notice_switch;
public final PBUInt32Field uint32_zplan_open;
public final PBUInt32Field uint32_zplan_operators_network_switch;
public final PBUInt32Field uint32_zplan_profile_card_show;
public final PBUInt32Field uint32_zplan_qzone_show;
public final PBUInt32Field uint32_zplan_samestyle_asset_switch;
public final PBUInt32Field uint32_zplan_samestyle_package_switch; | package tencent.im.oidb.cmd0x5eb;
public class oidb_0x5eb {
public static final class UdcUinData extends MessageMicro<UdcUinData> {
public final PBBytesField bytes_basic_cli_flag;
public final PBBytesField bytes_basic_svr_flag;
public final PBBytesField bytes_birthday;
public final PBBytesField bytes_city;
public final PBBytesField bytes_city_id;
public final PBBytesField bytes_country;
public final PBBytesField bytes_full_age;
public final PBBytesField bytes_full_birthday;
public final PBBytesField bytes_mss1_service;
public final PBBytesField bytes_mss2_identity;
public final PBBytesField bytes_mss3_bitmapextra;
public final PBBytesField bytes_music_gene;
public final PBBytesField bytes_nick;
public final PBBytesField bytes_openid;
public final PBBytesField bytes_province;
public final PBBytesField bytes_req_vip_ext_id;
public final PBBytesField bytes_stranger_declare;
public final PBBytesField bytes_stranger_nick;
public final PBUInt32Field int32_history_num_flag;
public final PBUInt32Field roam_flag_qq_7day;
public final PBUInt32Field roam_flag_svip_2year;
public final PBUInt32Field roam_flag_svip_5year;
public final PBUInt32Field roam_flag_svip_forever;
public final PBUInt32Field roam_flag_vip_30day;
public final PBStringField str_zplanphoto_url;
public final PBUInt32Field uint32_400_flag;
public final PBUInt32Field uint32_age;
public final PBUInt32Field uint32_allow;
public final PBUInt32Field uint32_alphabetic_font_flag;
public final PBUInt32Field uint32_apollo_status;
public final PBUInt32Field uint32_apollo_timestamp;
public final PBUInt32Field uint32_apollo_vip_flag;
public final PBUInt32Field uint32_apollo_vip_level;
public final PBUInt32Field uint32_auth_flag;
public final PBUInt32Field uint32_auto_to_text_flag;
public final PBUInt32Field uint32_bubble_id;
public final PBUInt32Field uint32_bubble_unread_switch;
public final PBUInt32Field uint32_business_user;
public final PBUInt32Field uint32_c2c_aio_shortcut_switch;
public final PBUInt32Field uint32_charm;
public final PBUInt32Field uint32_charm_level;
public final PBUInt32Field uint32_charm_shown;
public final PBUInt32Field uint32_city_zone_id;
public final PBUInt32Field uint32_cmshow_3d_flag;
public final PBUInt32Field uint32_common_place1;
public final PBUInt32Field uint32_constellation;
public final PBUInt32Field uint32_dance_max_score;
public final PBUInt32Field uint32_default_cover_in_use;
public final PBUInt32Field uint32_do_not_disturb_mode_time;
public final PBUInt32Field uint32_elder_mode_flag;
public final PBUInt32Field uint32_ext_flag;
public final PBUInt32Field uint32_extend_friend_card_shown;
public final PBUInt32Field uint32_extend_friend_flag;
public final PBUInt32Field uint32_extend_friend_switch;
public final PBUInt32Field uint32_face_id;
public final PBUInt32Field uint32_file_assist_top;
public final PBUInt32Field uint32_flag_color_note_recent_switch;
public final PBUInt32Field uint32_flag_hide_pretty_group_owner_identity;
public final PBUInt32Field uint32_flag_is_pretty_group_owner;
public final PBUInt32Field uint32_flag_kid_mode_can_pull_group;
public final PBUInt32Field uint32_flag_kid_mode_can_search_by_strangers;
public final PBUInt32Field uint32_flag_kid_mode_can_search_friends;
public final PBUInt32Field uint32_flag_kid_mode_need_phone_verify;
public final PBUInt32Field uint32_flag_kid_mode_switch;
public final PBUInt32Field uint32_flag_qcircle_cover_switch;
public final PBUInt32Field uint32_flag_school_verified;
public final PBUInt32Field uint32_flag_study_mode_student;
public final PBUInt32Field uint32_flag_study_mode_switch;
public final PBUInt32Field uint32_flag_super_yellow_diamond;
public final PBUInt32Field uint32_flag_use_mobile_net_switch;
public final PBUInt32Field uint32_flag_zplan_edit_avatar;
public final PBUInt32Field uint32_forbid_flag;
public final PBUInt32Field uint32_freshnews_notify_flag;
public final PBUInt32Field uint32_gender;
public final PBUInt32Field uint32_global_group_level;
public final PBUInt32Field uint32_god_flag;
public final PBUInt32Field uint32_god_forbid;
public final PBUInt32Field uint32_group_mem_credit_flag;
public final PBUInt32Field uint32_guild_gray_flag;
public final PBUInt32Field uint32_has_close_leba_youth_mode_plugin;
public final PBUInt32Field uint32_hidden_session_switch;
public final PBUInt32Field uint32_hidden_session_video_switch;
public final PBUInt32Field uint32_input_status_flag;
public final PBUInt32Field uint32_lang1;
public final PBUInt32Field uint32_lang2;
public final PBUInt32Field uint32_lang3;
public final PBUInt32Field uint32_lflag;
public final PBUInt32Field uint32_lightalk_switch;
public final PBUInt32Field uint32_love_status;
public final PBUInt32Field uint32_mss_update_time;
public final PBUInt32Field uint32_music_ring_autoplay;
public final PBUInt32Field uint32_music_ring_redpoint;
public final PBUInt32Field uint32_music_ring_visible;
public final PBUInt32Field uint32_normal_night_mode_flag;
public final PBUInt32Field uint32_notify_on_like_ranking_list_flag;
public final PBUInt32Field uint32_notify_partake_like_ranking_list_flag;
public final PBUInt32Field uint32_oin;
public final PBUInt32Field uint32_online_status_avatar_switch;
public final PBUInt32Field uint32_plate_of_king_dan;
public final PBUInt32Field uint32_plate_of_king_dan_display_switch;
public final PBUInt32Field uint32_posterfont_id;
public final PBUInt32Field uint32_preload_disable_flag;
public final PBUInt32Field uint32_profession;
public final PBUInt32Field uint32_profile_age_visible;
public final PBUInt32Field uint32_profile_anonymous_answer_switch;
public final PBUInt32Field uint32_profile_birthday_visible;
public final PBUInt32Field uint32_profile_college_visible;
public final PBUInt32Field uint32_profile_company_visible;
public final PBUInt32Field uint32_profile_constellation_visible;
public final PBUInt32Field uint32_profile_dressup_switch;
public final PBUInt32Field uint32_profile_email_visible;
public final PBUInt32Field uint32_profile_hometown_visible;
public final PBUInt32Field uint32_profile_interest_switch;
public final PBUInt32Field uint32_profile_life_achievement_switch;
public final PBUInt32Field uint32_profile_location_visible;
public final PBUInt32Field uint32_profile_membership_and_rank;
public final PBUInt32Field uint32_profile_miniapp_switch;
public final PBUInt32Field uint32_profile_music_switch;
public final PBUInt32Field uint32_profile_musicbox_switch;
public final PBUInt32Field uint32_profile_personal_note_visible;
public final PBUInt32Field uint32_profile_personality_label_switch;
public final PBUInt32Field uint32_profile_present_switch;
public final PBUInt32Field uint32_profile_privilege;
public final PBUInt32Field uint32_profile_profession_visible;
public final PBUInt32Field uint32_profile_qqcard_switch;
public final PBUInt32Field uint32_profile_qqcircle_switch;
public final PBUInt32Field uint32_profile_sex_visible;
public final PBUInt32Field uint32_profile_show_idol_switch;
public final PBUInt32Field uint32_profile_splendid_switch;
public final PBUInt32Field uint32_profile_sticky_note_offline;
public final PBUInt32Field uint32_profile_sticky_note_switch;
public final PBUInt32Field uint32_profile_weishi_switch;
public final PBUInt32Field uint32_profile_wz_game_card_switch;
public final PBUInt32Field uint32_profile_wz_game_skin_switch;
public final PBUInt32Field uint32_pstn_c2c_call_time;
public final PBUInt32Field uint32_pstn_c2c_last_guide_recharge_time;
public final PBUInt32Field uint32_pstn_c2c_try_flag;
public final PBUInt32Field uint32_pstn_c2c_vip;
public final PBUInt32Field uint32_pstn_ever_c2c_vip;
public final PBUInt32Field uint32_pstn_ever_multi_vip;
public final PBUInt32Field uint32_pstn_multi_call_time;
public final PBUInt32Field uint32_pstn_multi_last_guide_recharge_time;
public final PBUInt32Field uint32_pstn_multi_try_flag;
public final PBUInt32Field uint32_pstn_multi_vip;
public final PBUInt32Field uint32_qq_assistant_switch;
public final PBUInt32Field uint32_req_font_effect_id;
public final PBUInt32Field uint32_req_global_ring_id;
public final PBUInt32Field uint32_req_invite2group_auto_agree_flag;
public final PBUInt32Field uint32_req_medalwall_flag;
public final PBUInt32Field uint32_req_push_notice_flag;
public final PBUInt32Field uint32_req_small_world_head_flag;
public final PBUInt32Field uint32_rsp_connections_switch_id;
public final PBUInt32Field uint32_rsp_listen_together_player_id;
public final PBUInt32Field uint32_rsp_qq_level_icon_type;
public final PBUInt32Field uint32_rsp_theme_font_id;
public final PBUInt32Field uint32_school_status_flag;
public final PBUInt32Field uint32_simple_ui_pref;
public final PBUInt32Field uint32_simple_ui_switch;
public final PBUInt32Field uint32_simple_update_time;
public final PBUInt32Field uint32_stranger_vote_switch;
public final PBUInt32Field uint32_subaccount_display_third_qq_flag;
public final PBUInt32Field uint32_subscribe_nearbyassistant_switch;
public final PBUInt32Field uint32_suspend_effect_id;
public final PBUInt32Field uint32_sync_C2C_message_switch;
public final PBUInt32Field uint32_torch_disable_flag;
public final PBUInt32Field uint32_torchbearer_flag;
public final PBUInt32Field uint32_troop_honor_rich_flag;
public final PBUInt32Field uint32_troop_lucky_character_switch;
public final PBUInt32Field uint32_troophonor_switch;
public final PBUInt32Field uint32_vas_colorring_id;
public final PBUInt32Field uint32_vas_diy_font_timestamp;
public final PBUInt32Field uint32_vas_emoticon_usage_info;
public final PBUInt32Field uint32_vas_face_id;
public final PBUInt32Field uint32_vas_font_id;
public final PBUInt32Field uint32_vas_magicfont_flag;
public final PBUInt32Field uint32_vas_pendant_diy_id;
public final PBUInt32Field uint32_vas_praise_id;
public final PBUInt32Field uint32_vas_voicebubble_id;
public final PBUInt32Field uint32_vip_flag;
public final PBUInt32Field uint32_zplan_add_frd;
public final PBUInt32Field uint32_zplan_cmshow_month_active_user;
public final PBUInt32Field uint32_zplan_master_show;
public final PBUInt32Field uint32_zplan_message_notice_switch;
public final PBUInt32Field uint32_zplan_open;
public final PBUInt32Field uint32_zplan_operators_network_switch;
public final PBUInt32Field uint32_zplan_profile_card_show;
public final PBUInt32Field uint32_zplan_qzone_show;
public final PBUInt32Field uint32_zplan_samestyle_asset_switch;
public final PBUInt32Field uint32_zplan_samestyle_package_switch; | public final PBUInt64Field uint64_face_addon_id; | 6 | 2023-10-20 10:43:47+00:00 | 8k |
zhaoeryu/eu-backend | eu-admin/src/main/java/cn/eu/system/service/impl/SysMenuServiceImpl.java | [
{
"identifier": "EuServiceImpl",
"path": "eu-common-core/src/main/java/cn/eu/common/base/service/impl/EuServiceImpl.java",
"snippet": "public abstract class EuServiceImpl<M extends BaseMapper<T>, T> extends ServiceImpl<M, T> implements IEuService<T> {\n\n /**\n * 分页参数从1开始\n */\n protected ... | import cn.dev33.satoken.stp.StpUtil;
import cn.eu.common.base.service.impl.EuServiceImpl;
import cn.eu.common.enums.MenuStatus;
import cn.eu.common.enums.MenuType;
import cn.eu.common.model.PageResult;
import cn.eu.common.utils.MpQueryHelper;
import cn.eu.security.SecurityUtil;
import cn.eu.system.domain.SysMenu;
import cn.eu.system.mapper.SysMenuMapper;
import cn.eu.system.model.query.SysMenuQueryCriteria;
import cn.eu.system.service.ISysMenuService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.stream.Collectors; | 4,255 | package cn.eu.system.service.impl;
/**
* @author zhaoeryu
* @since 2023/5/31
*/
@Service
public class SysMenuServiceImpl extends EuServiceImpl<SysMenuMapper, SysMenu> implements ISysMenuService {
@Autowired
SysMenuMapper sysMenuMapper;
@Override
public List<SysMenu> list(SysMenuQueryCriteria criteria) { | package cn.eu.system.service.impl;
/**
* @author zhaoeryu
* @since 2023/5/31
*/
@Service
public class SysMenuServiceImpl extends EuServiceImpl<SysMenuMapper, SysMenu> implements ISysMenuService {
@Autowired
SysMenuMapper sysMenuMapper;
@Override
public List<SysMenu> list(SysMenuQueryCriteria criteria) { | criteria.setStatus(MenuStatus.NORMAL.getValue()); | 1 | 2023-10-20 07:08:37+00:00 | 8k |
Nxer/Twist-Space-Technology-Mod | src/main/java/com/Nxer/TwistSpaceTechnology/recipe/machineRecipe/CokingFactoryRecipePool.java | [
{
"identifier": "copyAmount",
"path": "src/main/java/com/Nxer/TwistSpaceTechnology/util/Utils.java",
"snippet": "public static ItemStack copyAmount(int aAmount, ItemStack aStack) {\n ItemStack rStack = aStack.copy();\n if (isStackInvalid(rStack)) return null;\n // if (aAmount > 64) aAmount = 64... | import static com.Nxer.TwistSpaceTechnology.util.Utils.copyAmount;
import static com.Nxer.TwistSpaceTechnology.util.enums.TierEU.RECIPE_MV;
import static com.Nxer.TwistSpaceTechnology.util.enums.TierEU.RECIPE_UV;
import net.minecraft.item.ItemStack;
import net.minecraftforge.oredict.OreDictionary;
import com.Nxer.TwistSpaceTechnology.common.recipeMap.GTCMRecipe;
import com.Nxer.TwistSpaceTechnology.recipe.IRecipePool;
import com.dreammaster.gthandler.GT_CoreModSupport;
import gregtech.api.enums.GT_Values;
import gregtech.api.enums.Materials;
import gregtech.api.interfaces.IRecipeMap;
import gregtech.api.util.GT_ModHandler;
import gregtech.api.util.GT_Utility; | 6,593 | package com.Nxer.TwistSpaceTechnology.recipe.machineRecipe;
public class CokingFactoryRecipePool implements IRecipePool {
@Override
public void loadRecipes() {
final IRecipeMap coke = GTCMRecipe.CokingFactoryRecipes;
// Raw Radox
GT_Values.RA.stdBuilder()
.itemInputs(
GT_Utility.getIntegratedCircuit(24),
GT_ModHandler.getModItem("GalaxySpace", "barnardaClog", 64))
.fluidInputs(GT_CoreModSupport.Xenoxene.getFluid(1000))
.fluidOutputs(GT_CoreModSupport.RawRadox.getFluid(1000 * 2)) | package com.Nxer.TwistSpaceTechnology.recipe.machineRecipe;
public class CokingFactoryRecipePool implements IRecipePool {
@Override
public void loadRecipes() {
final IRecipeMap coke = GTCMRecipe.CokingFactoryRecipes;
// Raw Radox
GT_Values.RA.stdBuilder()
.itemInputs(
GT_Utility.getIntegratedCircuit(24),
GT_ModHandler.getModItem("GalaxySpace", "barnardaClog", 64))
.fluidInputs(GT_CoreModSupport.Xenoxene.getFluid(1000))
.fluidOutputs(GT_CoreModSupport.RawRadox.getFluid(1000 * 2)) | .eut(RECIPE_UV) | 2 | 2023-10-16 09:57:15+00:00 | 8k |
wyjsonGo/GoRouter | GoRouter-Api/src/main/java/com/wyjson/router/core/Warehouse.java | [
{
"identifier": "IApplicationModule",
"path": "GoRouter-Api/src/main/java/com/wyjson/router/interfaces/IApplicationModule.java",
"snippet": "public interface IApplicationModule {\n\n int PRIORITY_MAX = 100;\n int PRIORITY_NORM = 50;\n int PRIORITY_MIN = 1;\n\n /**\n * The priority of the... | import androidx.lifecycle.MutableLiveData;
import com.wyjson.router.interfaces.IApplicationModule;
import com.wyjson.router.interfaces.IInterceptor;
import com.wyjson.router.model.CardMeta;
import com.wyjson.router.model.ServiceMeta;
import com.wyjson.router.module.interfaces.IRouteModuleGroup;
import com.wyjson.router.utils.InterceptorTreeMap;
import com.wyjson.router.utils.RouteGroupHashMap;
import com.wyjson.router.utils.RouteHashMap;
import com.wyjson.router.utils.ServiceHashMap;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; | 3,704 | package com.wyjson.router.core;
class Warehouse {
static final List<IApplicationModule> applicationModules = new ArrayList<>();
static final Map<String, IRouteModuleGroup> routeGroups = new RouteGroupHashMap();
| package com.wyjson.router.core;
class Warehouse {
static final List<IApplicationModule> applicationModules = new ArrayList<>();
static final Map<String, IRouteModuleGroup> routeGroups = new RouteGroupHashMap();
| static final Map<String, CardMeta> routes = new RouteHashMap(); | 7 | 2023-10-18 13:52:07+00:00 | 8k |
trpc-group/trpc-java | trpc-core/src/test/java/com/tencent/trpc/core/rpc/AbstractRpcServerTest.java | [
{
"identifier": "ProtocolConfig",
"path": "trpc-core/src/main/java/com/tencent/trpc/core/common/config/ProtocolConfig.java",
"snippet": "public class ProtocolConfig extends BaseProtocolConfig implements Cloneable {\n\n protected String name;\n protected String ip;\n protected int port;\n pro... | import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import com.tencent.trpc.core.common.config.ProtocolConfig;
import com.tencent.trpc.core.common.config.ProviderConfig;
import com.tencent.trpc.core.rpc.def.DefProviderInvoker;
import java.util.concurrent.CompletionStage;
import org.junit.Before;
import org.junit.Test; | 5,702 | /*
* Tencent is pleased to support the open source community by making tRPC available.
*
* Copyright (C) 2023 THL A29 Limited, a Tencent company.
* All rights reserved.
*
* If you have downloaded a copy of the tRPC source code from Tencent,
* please note that tRPC source code is licensed under the Apache 2.0 License,
* A copy of the Apache 2.0 License can be found in the LICENSE file.
*/
package com.tencent.trpc.core.rpc;
public class AbstractRpcServerTest {
private AbstractRpcServer abstractRpcServer;
private ProtocolConfig protocolConfig;
@Before
public void setUp() {
abstractRpcServer = new AbstractRpcServer() {
@Override
protected <T> void doExport(ProviderInvoker<T> invoker) {
}
@Override
protected <T> void doUnExport(ProviderConfig<T> config) {
}
@Override
protected void doOpen() throws Exception {
}
@Override
protected void doClose() {
}
};
protocolConfig = new ProtocolConfig();
protocolConfig.setIp("127.0.0.1");
protocolConfig.setPort(12345);
abstractRpcServer.setConfig(protocolConfig);
}
@Test
public void testExport() {
ProviderConfig<GenericClient> objectProviderConfig = new ProviderConfig<>();
objectProviderConfig.setServiceInterface(GenericClient.class);
objectProviderConfig.setRef(new GenericClient() {
@Override
public CompletionStage<byte[]> asyncInvoke(RpcClientContext context, byte[] body) {
return null;
}
@Override
public byte[] invoke(RpcClientContext context, byte[] body) {
return new byte[0];
}
}); | /*
* Tencent is pleased to support the open source community by making tRPC available.
*
* Copyright (C) 2023 THL A29 Limited, a Tencent company.
* All rights reserved.
*
* If you have downloaded a copy of the tRPC source code from Tencent,
* please note that tRPC source code is licensed under the Apache 2.0 License,
* A copy of the Apache 2.0 License can be found in the LICENSE file.
*/
package com.tencent.trpc.core.rpc;
public class AbstractRpcServerTest {
private AbstractRpcServer abstractRpcServer;
private ProtocolConfig protocolConfig;
@Before
public void setUp() {
abstractRpcServer = new AbstractRpcServer() {
@Override
protected <T> void doExport(ProviderInvoker<T> invoker) {
}
@Override
protected <T> void doUnExport(ProviderConfig<T> config) {
}
@Override
protected void doOpen() throws Exception {
}
@Override
protected void doClose() {
}
};
protocolConfig = new ProtocolConfig();
protocolConfig.setIp("127.0.0.1");
protocolConfig.setPort(12345);
abstractRpcServer.setConfig(protocolConfig);
}
@Test
public void testExport() {
ProviderConfig<GenericClient> objectProviderConfig = new ProviderConfig<>();
objectProviderConfig.setServiceInterface(GenericClient.class);
objectProviderConfig.setRef(new GenericClient() {
@Override
public CompletionStage<byte[]> asyncInvoke(RpcClientContext context, byte[] body) {
return null;
}
@Override
public byte[] invoke(RpcClientContext context, byte[] body) {
return new byte[0];
}
}); | abstractRpcServer.export(new DefProviderInvoker<>(protocolConfig, objectProviderConfig)); | 2 | 2023-10-19 10:54:11+00:00 | 8k |
freedom-introvert/YouTubeSendCommentAntiFraud | YTSendCommAntiFraud/app/src/main/java/icu/freedomintrovert/YTSendCommAntiFraud/rxObservables/FindCommentObservableOnSubscribe.java | [
{
"identifier": "Config",
"path": "YTSendCommAntiFraud/app/src/main/java/icu/freedomintrovert/YTSendCommAntiFraud/Config.java",
"snippet": "public class Config {\r\n public static final int SORT_RULER_DATE_DESC = 0;\r\n public static final int SORT_RULER_DATE_ASC = 1;\r\n private final SharedPr... | import java.io.IOException;
import java.util.Date;
import java.util.List;
import icu.freedomintrovert.YTSendCommAntiFraud.Config;
import icu.freedomintrovert.YTSendCommAntiFraud.comment.Comment;
import icu.freedomintrovert.YTSendCommAntiFraud.comment.HistoryComment;
import icu.freedomintrovert.YTSendCommAntiFraud.comment.ToBeCheckedComment;
import icu.freedomintrovert.YTSendCommAntiFraud.comment.VideoComment;
import icu.freedomintrovert.YTSendCommAntiFraud.comment.VideoCommentSection;
import icu.freedomintrovert.YTSendCommAntiFraud.comment.VideoHistoryComment;
import icu.freedomintrovert.YTSendCommAntiFraud.db.StatisticsDB;
import icu.freedomintrovert.YTSendCommAntiFraud.view.ProgressBarDialog;
import icu.freedomintrovert.YTSendCommAntiFraud.view.ProgressTimer;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.ObservableEmitter;
import io.reactivex.rxjava3.core.ObservableOnSubscribe;
| 6,225 | package icu.freedomintrovert.YTSendCommAntiFraud.rxObservables;
public class FindCommentObservableOnSubscribe implements ObservableOnSubscribe<FindCommentObservableOnSubscribe.BaseNextValue> {
private final VideoCommentSection videoCommentSection;
private VideoComment toBeCheckedComment;
private final long waitTimeAfterCommentSent;
private final long intervalOfSearchAgain;
private final int maximumNumberOfSearchAgain;
private StatisticsDB statisticsDB;
private boolean needToWait;
private final Date sendDate;
| package icu.freedomintrovert.YTSendCommAntiFraud.rxObservables;
public class FindCommentObservableOnSubscribe implements ObservableOnSubscribe<FindCommentObservableOnSubscribe.BaseNextValue> {
private final VideoCommentSection videoCommentSection;
private VideoComment toBeCheckedComment;
private final long waitTimeAfterCommentSent;
private final long intervalOfSearchAgain;
private final int maximumNumberOfSearchAgain;
private StatisticsDB statisticsDB;
private boolean needToWait;
private final Date sendDate;
| private ProgressTimer progressTimer;
| 9 | 2023-10-15 01:18:28+00:00 | 8k |
New-Barams/This-Year-Ajaja-BE | src/test/java/com/newbarams/ajaja/module/plan/domain/repository/PlanQueryRepositoryTest.java | [
{
"identifier": "MonkeySupport",
"path": "src/test/java/com/newbarams/ajaja/common/support/MonkeySupport.java",
"snippet": "public abstract class MonkeySupport {\n\tprotected final FixtureMonkey sut = FixtureMonkey.builder()\n\t\t.objectIntrospector(new FailoverIntrospector(\n\t\t\tList.of(\n\t\t\t\tFie... | import static org.assertj.core.api.Assertions.*;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
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.transaction.annotation.Transactional;
import com.newbarams.ajaja.common.support.MonkeySupport;
import com.newbarams.ajaja.global.common.TimeValue;
import com.newbarams.ajaja.module.plan.domain.Plan;
import com.newbarams.ajaja.module.plan.domain.PlanRepository;
import com.newbarams.ajaja.module.plan.domain.PlanStatus;
import com.newbarams.ajaja.module.plan.dto.PlanRequest;
import com.newbarams.ajaja.module.plan.dto.PlanResponse;
import com.newbarams.ajaja.module.plan.infra.PlanQueryRepository;
import com.newbarams.ajaja.module.user.adapter.out.persistence.UserJpaRepository;
import com.newbarams.ajaja.module.user.adapter.out.persistence.model.UserEntity;
import com.newbarams.ajaja.module.user.domain.User;
import com.newbarams.ajaja.module.user.mapper.UserMapper; | 6,676 | package com.newbarams.ajaja.module.plan.domain.repository;
@SpringBootTest
@Transactional
class PlanQueryRepositoryTest extends MonkeySupport {
@Autowired
private PlanQueryRepository planQueryRepository;
@Autowired
private PlanRepository planRepository;
@Autowired
private UserJpaRepository userRepository;
@Autowired
private UserMapper userMapper;
private User user; | package com.newbarams.ajaja.module.plan.domain.repository;
@SpringBootTest
@Transactional
class PlanQueryRepositoryTest extends MonkeySupport {
@Autowired
private PlanQueryRepository planQueryRepository;
@Autowired
private PlanRepository planRepository;
@Autowired
private UserJpaRepository userRepository;
@Autowired
private UserMapper userMapper;
private User user; | private Plan plan; | 2 | 2023-10-23 07:24:17+00:00 | 8k |
eclipse-jgit/jgit | org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/diffmergetool/ExternalMergeToolTest.java | [
{
"identifier": "CONFIG_KEY_CMD",
"path": "org.eclipse.jgit/src/org/eclipse/jgit/lib/ConfigConstants.java",
"snippet": "public static final String CONFIG_KEY_CMD = \"cmd\";"
},
{
"identifier": "CONFIG_KEY_GUITOOL",
"path": "org.eclipse.jgit/src/org/eclipse/jgit/lib/ConfigConstants.java",
... | import static org.eclipse.jgit.lib.ConfigConstants.CONFIG_KEY_CMD;
import static org.eclipse.jgit.lib.ConfigConstants.CONFIG_KEY_GUITOOL;
import static org.eclipse.jgit.lib.ConfigConstants.CONFIG_KEY_PATH;
import static org.eclipse.jgit.lib.ConfigConstants.CONFIG_KEY_PROMPT;
import static org.eclipse.jgit.lib.ConfigConstants.CONFIG_KEY_TOOL;
import static org.eclipse.jgit.lib.ConfigConstants.CONFIG_KEY_TRUST_EXIT_CODE;
import static org.eclipse.jgit.lib.ConfigConstants.CONFIG_MERGETOOL_SECTION;
import static org.eclipse.jgit.lib.ConfigConstants.CONFIG_MERGE_SECTION;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.junit.Assume.assumeTrue;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import org.eclipse.jgit.lib.internal.BooleanTriState;
import org.eclipse.jgit.storage.file.FileBasedConfig;
import org.eclipse.jgit.util.FS.ExecutionResult;
import org.junit.Test; | 4,434 | ExternalMergeTool externalTool = tools.get(customToolName);
manager.merge(local, remote, merged, base, null, externalTool);
assertEchoCommandHasCorrectOutput();
}
@Test
public void testUserDefinedToolWithPrompt() throws Exception {
String customToolName = "customTool";
String command = getEchoCommand();
FileBasedConfig config = db.getConfig();
config.setString(CONFIG_MERGETOOL_SECTION, customToolName,
CONFIG_KEY_CMD, command);
MergeTools manager = new MergeTools(db);
PromptHandler promptHandler = PromptHandler.acceptPrompt();
MissingToolHandler noToolHandler = new MissingToolHandler();
manager.merge(local, remote, merged, base, null,
Optional.of(customToolName), BooleanTriState.TRUE, false,
promptHandler, noToolHandler);
assertEchoCommandHasCorrectOutput();
List<String> actualToolPrompts = promptHandler.toolPrompts;
List<String> expectedToolPrompts = Arrays.asList("customTool");
assertEquals("Expected a user prompt for custom tool call",
expectedToolPrompts, actualToolPrompts);
assertEquals("Expected to no informing about missing tools",
Collections.EMPTY_LIST, noToolHandler.missingTools);
}
@Test
public void testUserDefinedToolWithCancelledPrompt() throws Exception {
MergeTools manager = new MergeTools(db);
PromptHandler promptHandler = PromptHandler.cancelPrompt();
MissingToolHandler noToolHandler = new MissingToolHandler();
Optional<ExecutionResult> result = manager.merge(local, remote, merged,
base, null, Optional.empty(), BooleanTriState.TRUE, false,
promptHandler, noToolHandler);
assertFalse("Expected no result if user cancels the operation",
result.isPresent());
}
@Test
public void testAllTools() {
FileBasedConfig config = db.getConfig();
String customToolName = "customTool";
config.setString(CONFIG_MERGETOOL_SECTION, customToolName,
CONFIG_KEY_CMD, "echo");
MergeTools manager = new MergeTools(db);
Set<String> actualToolNames = manager.getAllToolNames();
Set<String> expectedToolNames = new LinkedHashSet<>();
expectedToolNames.add(customToolName);
CommandLineMergeTool[] defaultTools = CommandLineMergeTool.values();
for (CommandLineMergeTool defaultTool : defaultTools) {
String toolName = defaultTool.name();
expectedToolNames.add(toolName);
}
assertEquals("Incorrect set of external merge tools", expectedToolNames,
actualToolNames);
}
@Test
public void testOverridePredefinedToolPath() {
String toolName = CommandLineMergeTool.guiffy.name();
String customToolPath = "/usr/bin/echo";
FileBasedConfig config = db.getConfig();
config.setString(CONFIG_MERGETOOL_SECTION, toolName, CONFIG_KEY_CMD,
"echo");
config.setString(CONFIG_MERGETOOL_SECTION, toolName, CONFIG_KEY_PATH,
customToolPath);
MergeTools manager = new MergeTools(db);
Map<String, ExternalMergeTool> tools = manager.getUserDefinedTools();
ExternalMergeTool mergeTool = tools.get(toolName);
assertNotNull("Expected tool \"" + toolName + "\" to be user defined",
mergeTool);
String toolPath = mergeTool.getPath();
assertEquals("Expected external merge tool to have an overriden path",
customToolPath, toolPath);
}
@Test
public void testUserDefinedTools() {
FileBasedConfig config = db.getConfig();
String customToolname = "customTool";
config.setString(CONFIG_MERGETOOL_SECTION, customToolname,
CONFIG_KEY_CMD, "echo");
config.setString(CONFIG_MERGETOOL_SECTION, customToolname,
CONFIG_KEY_PATH, "/usr/bin/echo");
config.setString(CONFIG_MERGETOOL_SECTION, customToolname,
CONFIG_KEY_PROMPT, String.valueOf(false));
config.setString(CONFIG_MERGETOOL_SECTION, customToolname,
CONFIG_KEY_GUITOOL, String.valueOf(false));
config.setString(CONFIG_MERGETOOL_SECTION, customToolname,
CONFIG_KEY_TRUST_EXIT_CODE, String.valueOf(false));
MergeTools manager = new MergeTools(db);
Set<String> actualToolNames = manager.getUserDefinedTools().keySet();
Set<String> expectedToolNames = new LinkedHashSet<>();
expectedToolNames.add(customToolname);
assertEquals("Incorrect set of external merge tools", expectedToolNames,
actualToolNames);
}
@Test
public void testCompare() throws ToolException {
String toolName = "customTool";
FileBasedConfig config = db.getConfig();
// the default merge tool is configured without a subsection
String subsection = null; | /*
* Copyright (C) 2020-2022, Simeon Andreev <simeon.danailov.andreev@gmail.com> and others.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Distribution License v. 1.0 which is available at
* https://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
package org.eclipse.jgit.internal.diffmergetool;
/**
* Testing external merge tools.
*/
public class ExternalMergeToolTest extends ExternalToolTestCase {
@Test(expected = ToolException.class)
public void testUserToolWithError() throws Exception {
String toolName = "customTool";
int errorReturnCode = 1;
String command = "exit " + errorReturnCode;
FileBasedConfig config = db.getConfig();
config.setString(CONFIG_MERGETOOL_SECTION, toolName, CONFIG_KEY_CMD,
command);
config.setString(CONFIG_MERGETOOL_SECTION, toolName,
CONFIG_KEY_TRUST_EXIT_CODE, String.valueOf(Boolean.TRUE));
invokeMerge(toolName);
fail("Expected exception to be thrown due to external tool exiting with error code: "
+ errorReturnCode);
}
@Test(expected = ToolException.class)
public void testUserToolWithCommandNotFoundError() throws Exception {
String toolName = "customTool";
int errorReturnCode = 127; // command not found
String command = "exit " + errorReturnCode;
FileBasedConfig config = db.getConfig();
config.setString(CONFIG_MERGETOOL_SECTION, toolName, CONFIG_KEY_CMD,
command);
invokeMerge(toolName);
fail("Expected exception to be thrown due to external tool exiting with error code: "
+ errorReturnCode);
}
@Test
public void testKdiff3() throws Exception {
assumePosixPlatform();
CommandLineMergeTool autoMergingTool = CommandLineMergeTool.kdiff3;
assumeMergeToolIsAvailable(autoMergingTool);
CommandLineMergeTool tool = autoMergingTool;
PreDefinedMergeTool externalTool = new PreDefinedMergeTool(tool.name(),
tool.getPath(), tool.getParameters(true),
tool.getParameters(false),
tool.isExitCodeTrustable() ? BooleanTriState.TRUE
: BooleanTriState.FALSE);
MergeTools manager = new MergeTools(db);
ExecutionResult result = manager.merge(local, remote, merged, null,
null, externalTool);
assertEquals("Expected merge tool to succeed", 0, result.getRc());
List<String> actualLines = Files.readAllLines(mergedFile.toPath());
String actualMergeResult = String.join(System.lineSeparator(),
actualLines);
String expectedMergeResult = DEFAULT_CONTENT;
assertEquals(
"Failed to merge equal local and remote versions with pre-defined tool: "
+ tool.getPath(),
expectedMergeResult, actualMergeResult);
}
@Test
public void testUserDefinedTool() throws Exception {
String customToolName = "customTool";
String command = getEchoCommand();
FileBasedConfig config = db.getConfig();
config.setString(CONFIG_MERGETOOL_SECTION, customToolName,
CONFIG_KEY_CMD, command);
MergeTools manager = new MergeTools(db);
Map<String, ExternalMergeTool> tools = manager.getUserDefinedTools();
ExternalMergeTool externalTool = tools.get(customToolName);
manager.merge(local, remote, merged, base, null, externalTool);
assertEchoCommandHasCorrectOutput();
}
@Test
public void testUserDefinedToolWithPrompt() throws Exception {
String customToolName = "customTool";
String command = getEchoCommand();
FileBasedConfig config = db.getConfig();
config.setString(CONFIG_MERGETOOL_SECTION, customToolName,
CONFIG_KEY_CMD, command);
MergeTools manager = new MergeTools(db);
PromptHandler promptHandler = PromptHandler.acceptPrompt();
MissingToolHandler noToolHandler = new MissingToolHandler();
manager.merge(local, remote, merged, base, null,
Optional.of(customToolName), BooleanTriState.TRUE, false,
promptHandler, noToolHandler);
assertEchoCommandHasCorrectOutput();
List<String> actualToolPrompts = promptHandler.toolPrompts;
List<String> expectedToolPrompts = Arrays.asList("customTool");
assertEquals("Expected a user prompt for custom tool call",
expectedToolPrompts, actualToolPrompts);
assertEquals("Expected to no informing about missing tools",
Collections.EMPTY_LIST, noToolHandler.missingTools);
}
@Test
public void testUserDefinedToolWithCancelledPrompt() throws Exception {
MergeTools manager = new MergeTools(db);
PromptHandler promptHandler = PromptHandler.cancelPrompt();
MissingToolHandler noToolHandler = new MissingToolHandler();
Optional<ExecutionResult> result = manager.merge(local, remote, merged,
base, null, Optional.empty(), BooleanTriState.TRUE, false,
promptHandler, noToolHandler);
assertFalse("Expected no result if user cancels the operation",
result.isPresent());
}
@Test
public void testAllTools() {
FileBasedConfig config = db.getConfig();
String customToolName = "customTool";
config.setString(CONFIG_MERGETOOL_SECTION, customToolName,
CONFIG_KEY_CMD, "echo");
MergeTools manager = new MergeTools(db);
Set<String> actualToolNames = manager.getAllToolNames();
Set<String> expectedToolNames = new LinkedHashSet<>();
expectedToolNames.add(customToolName);
CommandLineMergeTool[] defaultTools = CommandLineMergeTool.values();
for (CommandLineMergeTool defaultTool : defaultTools) {
String toolName = defaultTool.name();
expectedToolNames.add(toolName);
}
assertEquals("Incorrect set of external merge tools", expectedToolNames,
actualToolNames);
}
@Test
public void testOverridePredefinedToolPath() {
String toolName = CommandLineMergeTool.guiffy.name();
String customToolPath = "/usr/bin/echo";
FileBasedConfig config = db.getConfig();
config.setString(CONFIG_MERGETOOL_SECTION, toolName, CONFIG_KEY_CMD,
"echo");
config.setString(CONFIG_MERGETOOL_SECTION, toolName, CONFIG_KEY_PATH,
customToolPath);
MergeTools manager = new MergeTools(db);
Map<String, ExternalMergeTool> tools = manager.getUserDefinedTools();
ExternalMergeTool mergeTool = tools.get(toolName);
assertNotNull("Expected tool \"" + toolName + "\" to be user defined",
mergeTool);
String toolPath = mergeTool.getPath();
assertEquals("Expected external merge tool to have an overriden path",
customToolPath, toolPath);
}
@Test
public void testUserDefinedTools() {
FileBasedConfig config = db.getConfig();
String customToolname = "customTool";
config.setString(CONFIG_MERGETOOL_SECTION, customToolname,
CONFIG_KEY_CMD, "echo");
config.setString(CONFIG_MERGETOOL_SECTION, customToolname,
CONFIG_KEY_PATH, "/usr/bin/echo");
config.setString(CONFIG_MERGETOOL_SECTION, customToolname,
CONFIG_KEY_PROMPT, String.valueOf(false));
config.setString(CONFIG_MERGETOOL_SECTION, customToolname,
CONFIG_KEY_GUITOOL, String.valueOf(false));
config.setString(CONFIG_MERGETOOL_SECTION, customToolname,
CONFIG_KEY_TRUST_EXIT_CODE, String.valueOf(false));
MergeTools manager = new MergeTools(db);
Set<String> actualToolNames = manager.getUserDefinedTools().keySet();
Set<String> expectedToolNames = new LinkedHashSet<>();
expectedToolNames.add(customToolname);
assertEquals("Incorrect set of external merge tools", expectedToolNames,
actualToolNames);
}
@Test
public void testCompare() throws ToolException {
String toolName = "customTool";
FileBasedConfig config = db.getConfig();
// the default merge tool is configured without a subsection
String subsection = null; | config.setString(CONFIG_MERGE_SECTION, subsection, CONFIG_KEY_TOOL, | 4 | 2023-10-20 15:09:17+00:00 | 8k |
starfish-studios/Naturalist | common/src/main/java/com/starfish_studios/naturalist/common/entity/Lizard.java | [
{
"identifier": "NaturalistEntityTypes",
"path": "common/src/main/java/com/starfish_studios/naturalist/core/registry/NaturalistEntityTypes.java",
"snippet": "public class NaturalistEntityTypes {\n\n // PROJECTILES\n\n\n public static final Supplier<EntityType<ThrownDuckEgg>> DUCK_EGG = CommonPlatf... | import com.starfish_studios.naturalist.core.registry.NaturalistEntityTypes;
import com.starfish_studios.naturalist.core.registry.NaturalistTags;
import net.minecraft.core.Holder;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.syncher.EntityDataAccessor;
import net.minecraft.network.syncher.EntityDataSerializers;
import net.minecraft.network.syncher.SynchedEntityData;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.sounds.SoundEvents;
import net.minecraft.tags.BiomeTags;
import net.minecraft.util.Mth;
import net.minecraft.world.DifficultyInstance;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.damagesource.DamageSource;
import net.minecraft.world.entity.*;
import net.minecraft.world.entity.ai.attributes.AttributeSupplier;
import net.minecraft.world.entity.ai.attributes.Attributes;
import net.minecraft.world.entity.ai.goal.*;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.*;
import net.minecraft.world.item.crafting.Ingredient;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.ServerLevelAccessor;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.biome.Biomes;
import org.jetbrains.annotations.Nullable;
import software.bernie.geckolib3.core.IAnimatable;
import software.bernie.geckolib3.core.PlayState;
import software.bernie.geckolib3.core.builder.AnimationBuilder;
import software.bernie.geckolib3.core.controller.AnimationController;
import software.bernie.geckolib3.core.event.predicate.AnimationEvent;
import software.bernie.geckolib3.core.manager.AnimationData;
import software.bernie.geckolib3.core.manager.AnimationFactory;
import software.bernie.geckolib3.util.GeckoLibUtil; | 3,916 | package com.starfish_studios.naturalist.common.entity;
public class Lizard extends TamableAnimal implements IAnimatable {
private final AnimationFactory factory = GeckoLibUtil.createFactory(this);
private static final EntityDataAccessor<Integer> VARIANT_ID = SynchedEntityData.defineId(Lizard.class, EntityDataSerializers.INT);
private static final EntityDataAccessor<Boolean> HAS_TAIL = SynchedEntityData.defineId(Lizard.class, EntityDataSerializers.BOOLEAN); | package com.starfish_studios.naturalist.common.entity;
public class Lizard extends TamableAnimal implements IAnimatable {
private final AnimationFactory factory = GeckoLibUtil.createFactory(this);
private static final EntityDataAccessor<Integer> VARIANT_ID = SynchedEntityData.defineId(Lizard.class, EntityDataSerializers.INT);
private static final EntityDataAccessor<Boolean> HAS_TAIL = SynchedEntityData.defineId(Lizard.class, EntityDataSerializers.BOOLEAN); | private static final Ingredient TEMPT_INGREDIENT = Ingredient.of(NaturalistTags.ItemTags.LIZARD_TEMPT_ITEMS); | 1 | 2023-10-16 21:54:32+00:00 | 8k |
wangqi060934/MyAndroidToolsPro | app/src/main/java/cn/wq/myandroidtoolspro/helper/IfwUtil.java | [
{
"identifier": "BackupEntry",
"path": "app/src/main/java/cn/wq/myandroidtoolspro/model/BackupEntry.java",
"snippet": "public class BackupEntry extends ComponentEntry {\n public String appName;\n /**\n * @see cn.wq.myandroidtoolspro.helper.IfwUtil#COMPONENT_FLAG_ACTIVITY\n */\n public i... | import android.content.ComponentName;
import android.content.Context;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.util.ArrayMap;
import android.text.TextUtils;
import android.util.Xml;
import com.tencent.mars.xlog.Log;
import org.xmlpull.v1.XmlPullParser;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import cn.wq.myandroidtoolspro.model.BackupEntry;
import cn.wq.myandroidtoolspro.model.ComponentEntry;
import cn.wq.myandroidtoolspro.recyclerview.adapter.AbstractComponentAdapter;
import cn.wq.myandroidtoolspro.recyclerview.fragment.AppInfoForManageFragment2; | 4,091 | package cn.wq.myandroidtoolspro.helper;
public class IfwUtil {
private static final String TAG = "IfwUtil";
private static final String SYSTEM_PROPERTY_EFS_ENABLED = "persist.security.efs.enabled";
public static final int COMPONENT_FLAG_EMPTY = 0x00;
public static final int COMPONENT_FLAG_ACTIVITY = 0x01;
public static final int COMPONENT_FLAG_RECEIVER = 0x10;
public static final int COMPONENT_FLAG_SERVICE = 0x100;
public static final int COMPONENT_FLAG_ALL = 0x111;
public static final String BACKUP_LOCAL_FILE_EXT = ".ifw";
public static final String BACKUP_SYSTEM_FILE_EXT_OF_STANDARD = ".xml"; //标准ifw备份后缀
public static final String BACKUP_SYSTEM_FILE_EXT_OF_MINE = "$" + BACKUP_SYSTEM_FILE_EXT_OF_STANDARD; //本App备份ifw使用的后缀
/**
* 组件列表中修改选中位置component的ifw状态,并保存所有component到ifw文件<br>
* 每个类型的list中(例如ServiceRecyclerListFragment)的修改都需要完整保存整个ifw内容
*
* @param positions 某一类component的位置
*/
public static boolean saveComponentIfw(Context context,
@NonNull String packageName,
IfwEntry ifwEntry, | package cn.wq.myandroidtoolspro.helper;
public class IfwUtil {
private static final String TAG = "IfwUtil";
private static final String SYSTEM_PROPERTY_EFS_ENABLED = "persist.security.efs.enabled";
public static final int COMPONENT_FLAG_EMPTY = 0x00;
public static final int COMPONENT_FLAG_ACTIVITY = 0x01;
public static final int COMPONENT_FLAG_RECEIVER = 0x10;
public static final int COMPONENT_FLAG_SERVICE = 0x100;
public static final int COMPONENT_FLAG_ALL = 0x111;
public static final String BACKUP_LOCAL_FILE_EXT = ".ifw";
public static final String BACKUP_SYSTEM_FILE_EXT_OF_STANDARD = ".xml"; //标准ifw备份后缀
public static final String BACKUP_SYSTEM_FILE_EXT_OF_MINE = "$" + BACKUP_SYSTEM_FILE_EXT_OF_STANDARD; //本App备份ifw使用的后缀
/**
* 组件列表中修改选中位置component的ifw状态,并保存所有component到ifw文件<br>
* 每个类型的list中(例如ServiceRecyclerListFragment)的修改都需要完整保存整个ifw内容
*
* @param positions 某一类component的位置
*/
public static boolean saveComponentIfw(Context context,
@NonNull String packageName,
IfwEntry ifwEntry, | @NonNull AbstractComponentAdapter<? extends ComponentEntry> adapter, | 2 | 2023-10-18 14:32:49+00:00 | 8k |
instana/otel-dc | host/src/main/java/com/instana/dc/host/impl/SimpHostDc.java | [
{
"identifier": "AbstractHostDc",
"path": "host/src/main/java/com/instana/dc/host/AbstractHostDc.java",
"snippet": "public abstract class AbstractHostDc extends AbstractDc implements IDc {\n private static final Logger logger = Logger.getLogger(AbstractHostDc.class.getName());\n\n private final St... | import com.instana.dc.host.AbstractHostDc;
import com.instana.dc.host.HostDcUtil;
import io.opentelemetry.api.common.Attributes;
import io.opentelemetry.sdk.resources.Resource;
import io.opentelemetry.semconv.ResourceAttributes;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import static com.instana.dc.DcUtil.mergeResourceAttributesFromEnv;
import static com.instana.dc.host.HostDcUtil.*; | 4,874 | /*
* (c) Copyright IBM Corp. 2023
* (c) Copyright Instana Inc.
*/
package com.instana.dc.host.impl;
public class SimpHostDc extends AbstractHostDc {
private static final Logger logger = Logger.getLogger(SimpHostDc.class.getName());
public SimpHostDc(Map<String, String> properties, String hostSystem) {
super(properties, hostSystem);
}
public String getHostName() {
try {
return InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
return "UnknownName";
}
}
public String getHostId() {
try {
return HostDcUtil.readFileText("/etc/machine-id");
} catch (IOException e) {
return "UnknownID";
}
}
@Override
public Resource getResourceAttributes() {
String hostName = getHostName();
Resource resource = Resource.getDefault().merge(
Resource.create(Attributes.of(ResourceAttributes.SERVICE_NAME, getServiceName(),
ResourceAttributes.SERVICE_INSTANCE_ID, hostName
))
);
resource = resource.merge(
Resource.create(Attributes.of(ResourceAttributes.HOST_NAME, hostName,
ResourceAttributes.OS_TYPE, "linux",
ResourceAttributes.HOST_ID, getHostId()
))
);
| /*
* (c) Copyright IBM Corp. 2023
* (c) Copyright Instana Inc.
*/
package com.instana.dc.host.impl;
public class SimpHostDc extends AbstractHostDc {
private static final Logger logger = Logger.getLogger(SimpHostDc.class.getName());
public SimpHostDc(Map<String, String> properties, String hostSystem) {
super(properties, hostSystem);
}
public String getHostName() {
try {
return InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
return "UnknownName";
}
}
public String getHostId() {
try {
return HostDcUtil.readFileText("/etc/machine-id");
} catch (IOException e) {
return "UnknownID";
}
}
@Override
public Resource getResourceAttributes() {
String hostName = getHostName();
Resource resource = Resource.getDefault().merge(
Resource.create(Attributes.of(ResourceAttributes.SERVICE_NAME, getServiceName(),
ResourceAttributes.SERVICE_INSTANCE_ID, hostName
))
);
resource = resource.merge(
Resource.create(Attributes.of(ResourceAttributes.HOST_NAME, hostName,
ResourceAttributes.OS_TYPE, "linux",
ResourceAttributes.HOST_ID, getHostId()
))
);
| return mergeResourceAttributesFromEnv(resource); | 2 | 2023-10-23 01:16:38+00:00 | 8k |
A1anSong/jd_unidbg | unidbg-ios/src/main/java/com/github/unidbg/file/ios/BaseDarwinFileIO.java | [
{
"identifier": "Emulator",
"path": "unidbg-api/src/main/java/com/github/unidbg/Emulator.java",
"snippet": "public interface Emulator<T extends NewFileIO> extends Closeable, ArmDisassembler, Serializable {\n\n int getPointerSize();\n\n boolean is64Bit();\n boolean is32Bit();\n\n int getPageA... | import com.alibaba.fastjson.JSON;
import com.github.unidbg.Emulator;
import com.github.unidbg.file.BaseFileIO;
import com.github.unidbg.file.UnidbgFileFilter;
import com.github.unidbg.ios.file.DirectoryFileIO;
import com.github.unidbg.ios.struct.attr.AttrList;
import com.github.unidbg.ios.struct.attr.AttrReference;
import com.github.unidbg.ios.struct.attr.AttributeSet;
import com.github.unidbg.ios.struct.attr.Dev;
import com.github.unidbg.ios.struct.attr.FinderInfo;
import com.github.unidbg.ios.struct.attr.Fsid;
import com.github.unidbg.ios.struct.attr.ObjId;
import com.github.unidbg.ios.struct.attr.ObjType;
import com.github.unidbg.ios.struct.attr.UserAccess;
import com.github.unidbg.ios.struct.kernel.StatFS;
import com.github.unidbg.pointer.UnidbgStructure;
import com.github.unidbg.unix.UnixEmulator;
import com.github.unidbg.unix.struct.TimeSpec32;
import com.sun.jna.Pointer;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List; | 7,154 | package com.github.unidbg.file.ios;
public abstract class BaseDarwinFileIO extends BaseFileIO implements DarwinFileIO {
private static final Log log = LogFactory.getLog(BaseDarwinFileIO.class);
public static File createAttrFile(File dest) {
if (!dest.exists()) {
throw new IllegalStateException("dest=" + dest);
}
File file;
if (dest.isDirectory()) { | package com.github.unidbg.file.ios;
public abstract class BaseDarwinFileIO extends BaseFileIO implements DarwinFileIO {
private static final Log log = LogFactory.getLog(BaseDarwinFileIO.class);
public static File createAttrFile(File dest) {
if (!dest.exists()) {
throw new IllegalStateException("dest=" + dest);
}
File file;
if (dest.isDirectory()) { | file = new File(dest, UnidbgFileFilter.UNIDBG_PREFIX + ".json"); | 2 | 2023-10-17 06:13:28+00:00 | 8k |
EyeOfDarkness/FlameOut | src/flame/graphics/VaporizeBatch.java | [
{
"identifier": "Disintegration",
"path": "src/flame/effects/Disintegration.java",
"snippet": "public class Disintegration implements Poolable{\n float[] xs, ys;\n int width, height;\n float drawWidth, drawHeight;\n TextureRegion region;\n int uses = 0;\n\n public float z = Layer.flyin... | import arc.*;
import arc.func.*;
import arc.graphics.*;
import arc.graphics.g2d.*;
import arc.graphics.gl.*;
import arc.math.*;
import arc.math.geom.*;
import arc.util.*;
import flame.effects.*;
import flame.effects.Disintegration.*;
import flame.entities.*;
import flame.entities.RenderGroupEntity.*;
import flame.graphics.CutBatch.*; | 4,923 | package flame.graphics;
public class VaporizeBatch extends Batch{
public VaporizeHandler cons;
public SpriteHandler spriteHandler;
public Cons<Disintegration> discon;
final static Rect tr = new Rect();
public void switchBatch(Runnable drawer, SpriteHandler handler, VaporizeHandler cons){
Batch last = Core.batch;
GL20 lgl = Core.gl;
Core.batch = this;
Core.gl = FragmentationBatch.mock;
Lines.useLegacyLine = true; | package flame.graphics;
public class VaporizeBatch extends Batch{
public VaporizeHandler cons;
public SpriteHandler spriteHandler;
public Cons<Disintegration> discon;
final static Rect tr = new Rect();
public void switchBatch(Runnable drawer, SpriteHandler handler, VaporizeHandler cons){
Batch last = Core.batch;
GL20 lgl = Core.gl;
Core.batch = this;
Core.gl = FragmentationBatch.mock;
Lines.useLegacyLine = true; | RenderGroupEntity.capture(); | 1 | 2023-10-18 08:41:59+00:00 | 8k |
ItzGreenCat/SkyImprover | src/main/java/me/greencat/skyimprover/SkyImprover.java | [
{
"identifier": "Config",
"path": "src/main/java/me/greencat/skyimprover/config/Config.java",
"snippet": "public class Config extends MidnightConfig {\n @Comment(category = \"render\")\n public static Comment damageSplash;\n @Entry(category = \"render\")\n public static boolean damageSplashE... | import eu.midnightdust.lib.config.MidnightConfig;
import me.greencat.skyimprover.config.Config;
import me.greencat.skyimprover.feature.FeatureLoader;
import me.greencat.skyimprover.feature.damageSplash.DamageSplash;
import me.greencat.skyimprover.feature.dungeonDeathMessage.DungeonDeathMessage;
import me.greencat.skyimprover.feature.kuudraHelper.KuudraHelper;
import me.greencat.skyimprover.feature.m3Freeze.M3FreezeHelper;
import me.greencat.skyimprover.feature.rainTimer.RainTimer;
import me.greencat.skyimprover.utils.LocationUtils;
import net.fabricmc.api.ClientModInitializer;
import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents; | 4,768 | package me.greencat.skyimprover;
public class SkyImprover implements ClientModInitializer {
public static final String MODID = "skyimprover";
@Override
public void onInitializeClient() {
MidnightConfig.init(MODID, Config.class); | package me.greencat.skyimprover;
public class SkyImprover implements ClientModInitializer {
public static final String MODID = "skyimprover";
@Override
public void onInitializeClient() {
MidnightConfig.init(MODID, Config.class); | FeatureLoader.loadAll("me.greencat.skyimprover.feature"); | 1 | 2023-10-19 09:19:09+00:00 | 8k |
histevehu/12306 | business/src/main/java/com/steve/train/business/controller/admin/DailyTrainStationAdminController.java | [
{
"identifier": "DailyTrainStationQueryReq",
"path": "business/src/main/java/com/steve/train/business/req/DailyTrainStationQueryReq.java",
"snippet": "public class DailyTrainStationQueryReq extends PageReq {\n\n /**\n * 日期\n */\n @DateTimeFormat(pattern = \"yyyy-MM-dd\")\n private Date ... | import com.steve.train.business.req.DailyTrainStationQueryReq;
import com.steve.train.business.req.DailyTrainStationSaveReq;
import com.steve.train.business.resp.DailyTrainStationQueryResp;
import com.steve.train.business.service.DailyTrainStationService;
import com.steve.train.common.resp.CommonResp;
import com.steve.train.common.resp.PageResp;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*; | 4,507 | package com.steve.train.business.controller.admin;
/*
* @author : Steve Hu
* @date : 2023-11-01 09:10:50
* @description: 每日车站管理员接口(FreeMarker生成)
*/
@RestController
@RequestMapping("/admin/dailyTrainStation")
public class DailyTrainStationAdminController {
@Resource
private DailyTrainStationService dailyTrainStationService;
@PostMapping("/save") | package com.steve.train.business.controller.admin;
/*
* @author : Steve Hu
* @date : 2023-11-01 09:10:50
* @description: 每日车站管理员接口(FreeMarker生成)
*/
@RestController
@RequestMapping("/admin/dailyTrainStation")
public class DailyTrainStationAdminController {
@Resource
private DailyTrainStationService dailyTrainStationService;
@PostMapping("/save") | public CommonResp<Object> save(@Valid @RequestBody DailyTrainStationSaveReq req) { | 4 | 2023-10-23 01:20:56+00:00 | 8k |
team-moabam/moabam-BE | src/test/java/com/moabam/api/presentation/ReportControllerTest.java | [
{
"identifier": "Member",
"path": "src/main/java/com/moabam/api/domain/member/Member.java",
"snippet": "@Entity\n@Getter\n@Table(name = \"member\")\n@SQLDelete(sql = \"UPDATE member SET deleted_at = CURRENT_TIMESTAMP where id = ?\")\n@NoArgsConstructor(access = AccessLevel.PROTECTED)\npublic class Membe... | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import java.time.LocalDateTime;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.transaction.annotation.Transactional;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.moabam.api.domain.member.Member;
import com.moabam.api.domain.member.repository.MemberRepository;
import com.moabam.api.domain.room.Certification;
import com.moabam.api.domain.room.Room;
import com.moabam.api.domain.room.Routine;
import com.moabam.api.domain.room.repository.CertificationRepository;
import com.moabam.api.domain.room.repository.RoomRepository;
import com.moabam.api.domain.room.repository.RoutineRepository;
import com.moabam.api.dto.report.ReportRequest;
import com.moabam.support.annotation.WithMember;
import com.moabam.support.common.WithoutFilterSupporter;
import com.moabam.support.fixture.MemberFixture;
import com.moabam.support.fixture.ReportFixture;
import com.moabam.support.fixture.RoomFixture;
import jakarta.persistence.EntityManagerFactory; | 6,350 | package com.moabam.api.presentation;
@Transactional
@SpringBootTest
@AutoConfigureMockMvc
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class ReportControllerTest extends WithoutFilterSupporter {
@Autowired
MockMvc mockMvc;
@Autowired
ObjectMapper objectMapper;
@Autowired
MemberRepository memberRepository;
@Autowired
RoomRepository roomRepository;
@Autowired
CertificationRepository certificationRepository;
@Autowired
RoutineRepository routineRepository;
@Autowired
EntityManagerFactory entityManagerFactory;
| package com.moabam.api.presentation;
@Transactional
@SpringBootTest
@AutoConfigureMockMvc
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class ReportControllerTest extends WithoutFilterSupporter {
@Autowired
MockMvc mockMvc;
@Autowired
ObjectMapper objectMapper;
@Autowired
MemberRepository memberRepository;
@Autowired
RoomRepository roomRepository;
@Autowired
CertificationRepository certificationRepository;
@Autowired
RoutineRepository routineRepository;
@Autowired
EntityManagerFactory entityManagerFactory;
| Member reportedMember; | 0 | 2023-10-20 06:15:43+00:00 | 8k |
liukanshan1/PrivateTrace-Core | src/main/java/Priloc/protocol/TestEncode.java | [
{
"identifier": "TimeLocationData",
"path": "src/main/java/Priloc/data/TimeLocationData.java",
"snippet": "public class TimeLocationData implements Serializable {\n private Location loc;\n private Date date;\n private double accuracy = Constant.RADIUS;\n private TimeLocationData nTLD = null;... | import Priloc.data.TimeLocationData;
import Priloc.data.Trajectory;
import Priloc.data.TrajectoryReader;
import Priloc.geo.Location;
import Priloc.utils.Constant;
import java.util.List;
import static java.lang.System.exit; | 4,049 | package Priloc.protocol;
public class TestEncode {
// public static void main(String[] args) throws Exception {
// String[] negativePath = new String[]{
// "./Geolife Trajectories 1.3/Data/000/Trajectory/20090503033926.plt",
// "./Geolife Trajectories 1.3/Data/000/Trajectory/20090705025307.plt"
// };
// TrajectoryReader[] negativeReaders = new TrajectoryReader[negativePath.length];
// for (int i = 0; i < negativePath.length; i++) {
// negativeReaders[i] = new TrajectoryReader(negativePath[i]);
// }
// Trajectory[] negativeTrajectories = new Trajectory[negativePath.length];
// for (int i = 0; i < negativePath.length; i++) {
// negativeTrajectories[i] = negativeReaders[i].load();
// }
// double maxError = 0;
// for (int i = 0; i < negativeTrajectories.length; i++) {
// List<TimeLocationData> tlds = negativeTrajectories[i].getTLDs();
// for(int j = 0; j < tlds.size() - 1; j++) {
// Location l1 = tlds.get(j).getLoc();
// Location l2 = tlds.get(j + 1).getLoc();
// double expect = l1.distance(l2);
// if (expect > 2 * Constant.RADIUS) {
// continue;
// }
// double actual = l1.encodeDistance(l2);
// //System.out.println(Math.abs(expect - actual));
// if (Math.abs(expect - actual) > maxError) {
// maxError = Math.abs(expect - actual);
// System.out.println(maxError);
// }
//// if (Math.abs(expect - actual) > 1) {
//// System.out.println(l1);
//// System.out.println(l2);
//// System.out.println(expect);
//// System.out.println(actual);
//// }
// }
// }
// }
public static void main(String[] args) throws Exception {
String[] negativePath = new String[]{
"./C++/dataset",
};
TrajectoryReader[] negativeReaders = new TrajectoryReader[negativePath.length];
for (int i = 0; i < negativePath.length; i++) {
negativeReaders[i] = new TrajectoryReader(negativePath[i]);
}
Trajectory[] negativeTrajectories = new Trajectory[negativePath.length];
for (int i = 0; i < negativePath.length; i++) {
negativeTrajectories[i] = negativeReaders[i].load();
}
double maxError = 0;
for (int i = 0; i < negativeTrajectories.length; i++) {
List<TimeLocationData> tlds = negativeTrajectories[i].getTLDs();
for(int j = 0; j < tlds.size() - 1; j++) {
Location l1 = tlds.get(j).getLoc();
Location l2 = tlds.get(j + 1).getLoc();
double expect = l1.distance(l2); | package Priloc.protocol;
public class TestEncode {
// public static void main(String[] args) throws Exception {
// String[] negativePath = new String[]{
// "./Geolife Trajectories 1.3/Data/000/Trajectory/20090503033926.plt",
// "./Geolife Trajectories 1.3/Data/000/Trajectory/20090705025307.plt"
// };
// TrajectoryReader[] negativeReaders = new TrajectoryReader[negativePath.length];
// for (int i = 0; i < negativePath.length; i++) {
// negativeReaders[i] = new TrajectoryReader(negativePath[i]);
// }
// Trajectory[] negativeTrajectories = new Trajectory[negativePath.length];
// for (int i = 0; i < negativePath.length; i++) {
// negativeTrajectories[i] = negativeReaders[i].load();
// }
// double maxError = 0;
// for (int i = 0; i < negativeTrajectories.length; i++) {
// List<TimeLocationData> tlds = negativeTrajectories[i].getTLDs();
// for(int j = 0; j < tlds.size() - 1; j++) {
// Location l1 = tlds.get(j).getLoc();
// Location l2 = tlds.get(j + 1).getLoc();
// double expect = l1.distance(l2);
// if (expect > 2 * Constant.RADIUS) {
// continue;
// }
// double actual = l1.encodeDistance(l2);
// //System.out.println(Math.abs(expect - actual));
// if (Math.abs(expect - actual) > maxError) {
// maxError = Math.abs(expect - actual);
// System.out.println(maxError);
// }
//// if (Math.abs(expect - actual) > 1) {
//// System.out.println(l1);
//// System.out.println(l2);
//// System.out.println(expect);
//// System.out.println(actual);
//// }
// }
// }
// }
public static void main(String[] args) throws Exception {
String[] negativePath = new String[]{
"./C++/dataset",
};
TrajectoryReader[] negativeReaders = new TrajectoryReader[negativePath.length];
for (int i = 0; i < negativePath.length; i++) {
negativeReaders[i] = new TrajectoryReader(negativePath[i]);
}
Trajectory[] negativeTrajectories = new Trajectory[negativePath.length];
for (int i = 0; i < negativePath.length; i++) {
negativeTrajectories[i] = negativeReaders[i].load();
}
double maxError = 0;
for (int i = 0; i < negativeTrajectories.length; i++) {
List<TimeLocationData> tlds = negativeTrajectories[i].getTLDs();
for(int j = 0; j < tlds.size() - 1; j++) {
Location l1 = tlds.get(j).getLoc();
Location l2 = tlds.get(j + 1).getLoc();
double expect = l1.distance(l2); | if (expect > 2 * Constant.RADIUS) { | 4 | 2023-10-22 06:28:51+00:00 | 8k |
tuxming/xmfx | BaseUI/src/main/java/com/xm2013/jfx/control/listview/XmListViewSkin.java | [
{
"identifier": "HueType",
"path": "BaseUI/src/main/java/com/xm2013/jfx/control/base/HueType.java",
"snippet": "public enum HueType {\n /**\n * 暗色调, 在背景色是暗色的情况下,组件应该有的表现\n */\n DARK,\n /**\n * 亮色调, 在北京是亮色的情况下,组件应该有的表现\n */\n LIGHT,\n\n /**\n * 无色,就是没有背景色,没有边框色,只有文本或者图标... | import javafx.scene.paint.Color;
import javafx.scene.paint.Paint;
import com.xm2013.jfx.control.base.HueType;
import com.xm2013.jfx.control.base.SizeType;
import com.xm2013.jfx.control.base.VirtualFlowScrollHelper;
import javafx.geometry.Insets;
import javafx.scene.control.skin.ListViewSkin;
import javafx.scene.layout.*; | 3,737 | /*
* MIT License
*
* Copyright (c) 2023 tuxming@sina.com / wechat: t5x5m5
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package com.xm2013.jfx.control.listview;
public class XmListViewSkin<T> extends ListViewSkin<T> {
private XmListView<T> control;
public XmListViewSkin(XmListView<T> control) {
super(control);
this.control = control;
updateSkin();
VirtualFlowScrollHelper helper = new VirtualFlowScrollHelper(getVirtualFlow());
helper.colorTypeProperty().bind(control.colorTypeProperty());
this.control.focusedProperty().addListener((ob, ov, nv)->{
setBackground();
});
registerChangeListener(control.sizeTypeProperty(), e -> updateSkin());
registerChangeListener(control.colorTypeProperty(), e->updateSkin());
registerChangeListener(control.hueTypeProperty(), e->updateSkin());
}
private void updateSkin(){
SizeType sizeType = control.getSizeType();
double size = 40;
if(SizeType.SMALL.equals(sizeType)){
size = 30;
}else if(SizeType.LARGE.equals(sizeType)){
size = 50;
}
this.control.setFixedCellSize(size);
setBackground();
}
private void setBackground(){
Paint bgColor = null; | /*
* MIT License
*
* Copyright (c) 2023 tuxming@sina.com / wechat: t5x5m5
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package com.xm2013.jfx.control.listview;
public class XmListViewSkin<T> extends ListViewSkin<T> {
private XmListView<T> control;
public XmListViewSkin(XmListView<T> control) {
super(control);
this.control = control;
updateSkin();
VirtualFlowScrollHelper helper = new VirtualFlowScrollHelper(getVirtualFlow());
helper.colorTypeProperty().bind(control.colorTypeProperty());
this.control.focusedProperty().addListener((ob, ov, nv)->{
setBackground();
});
registerChangeListener(control.sizeTypeProperty(), e -> updateSkin());
registerChangeListener(control.colorTypeProperty(), e->updateSkin());
registerChangeListener(control.hueTypeProperty(), e->updateSkin());
}
private void updateSkin(){
SizeType sizeType = control.getSizeType();
double size = 40;
if(SizeType.SMALL.equals(sizeType)){
size = 30;
}else if(SizeType.LARGE.equals(sizeType)){
size = 50;
}
this.control.setFixedCellSize(size);
setBackground();
}
private void setBackground(){
Paint bgColor = null; | HueType hueType = control.getHueType(); | 0 | 2023-10-17 08:57:08+00:00 | 8k |
Dwight-Studio/JArmEmu | src/main/java/fr/dwightstudio/jarmemu/gui/controllers/EditorController.java | [
{
"identifier": "AbstractJArmEmuModule",
"path": "src/main/java/fr/dwightstudio/jarmemu/gui/AbstractJArmEmuModule.java",
"snippet": "public class AbstractJArmEmuModule implements Initializable {\n\n protected final JArmEmuApplication application;\n\n public AbstractJArmEmuModule(JArmEmuApplication... | import atlantafx.base.controls.Notification;
import atlantafx.base.theme.Styles;
import fr.dwightstudio.jarmemu.gui.AbstractJArmEmuModule;
import fr.dwightstudio.jarmemu.gui.JArmEmuApplication;
import fr.dwightstudio.jarmemu.sim.SourceScanner;
import fr.dwightstudio.jarmemu.sim.exceptions.SyntaxASMException;
import fr.dwightstudio.jarmemu.sim.obj.FilePos;
import fr.dwightstudio.jarmemu.util.FileUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.kordamp.ikonli.javafx.FontIcon;
import org.kordamp.ikonli.material2.Material2OutlinedAL;
import org.kordamp.ikonli.material2.Material2OutlinedMZ;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger; | 5,655 | /*
* ____ _ __ __ _____ __ ___
* / __ \_ __(_)___ _/ /_ / /_ / ___// /___ ______/ (_)___
* / / / / | /| / / / __ `/ __ \/ __/ \__ \/ __/ / / / __ / / __ \
* / /_/ /| |/ |/ / / /_/ / / / / /_ ___/ / /_/ /_/ / /_/ / / /_/ /
* /_____/ |__/|__/_/\__, /_/ /_/\__/ /____/\__/\__,_/\__,_/_/\____/
* /____/
* Copyright (C) 2023 Dwight Studio
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package fr.dwightstudio.jarmemu.gui.controllers;
public class EditorController extends AbstractJArmEmuModule {
public static final String SAMPLE_CODE = String.join("\n", new String[]{".global _start", ".text", "_start:", "\t@ Beginning of the program"});
private final Logger logger = Logger.getLogger(getClass().getName());
private final ArrayList<FileEditor> fileEditors;
private FileEditor lastScheduledEditor;
private FileEditor lastExecutedEditor;
| /*
* ____ _ __ __ _____ __ ___
* / __ \_ __(_)___ _/ /_ / /_ / ___// /___ ______/ (_)___
* / / / / | /| / / / __ `/ __ \/ __/ \__ \/ __/ / / / __ / / __ \
* / /_/ /| |/ |/ / / /_/ / / / / /_ ___/ / /_/ /_/ / /_/ / / /_/ /
* /_____/ |__/|__/_/\__, /_/ /_/\__/ /____/\__/\__,_/\__,_/_/\____/
* /____/
* Copyright (C) 2023 Dwight Studio
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package fr.dwightstudio.jarmemu.gui.controllers;
public class EditorController extends AbstractJArmEmuModule {
public static final String SAMPLE_CODE = String.join("\n", new String[]{".global _start", ".text", "_start:", "\t@ Beginning of the program"});
private final Logger logger = Logger.getLogger(getClass().getName());
private final ArrayList<FileEditor> fileEditors;
private FileEditor lastScheduledEditor;
private FileEditor lastExecutedEditor;
| public EditorController(JArmEmuApplication application) { | 1 | 2023-10-17 18:22:09+00:00 | 8k |
GTNewHorizons/FarmingForEngineers | src/main/java/com/guigs44/farmingforengineers/container/ContainerMarket.java | [
{
"identifier": "MessageMarketList",
"path": "src/main/java/com/guigs44/farmingforengineers/network/MessageMarketList.java",
"snippet": "public class MessageMarketList implements IMessage {\n\n private Collection<MarketEntry> entryList;\n\n public MessageMarketList() {}\n\n public MessageMarket... | import java.util.List;
import javax.annotation.Nullable;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.init.Items;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.InventoryBasic;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
import com.google.common.collect.Lists;
import com.guigs44.farmingforengineers.network.MessageMarketList;
import com.guigs44.farmingforengineers.network.NetworkHandler;
import com.guigs44.farmingforengineers.registry.MarketEntry;
import com.guigs44.farmingforengineers.registry.MarketRegistry; | 3,891 | package com.guigs44.farmingforengineers.container;
public class ContainerMarket extends Container {
private final EntityPlayer player;
private final int posX;
private final int posY;
private final int posZ;
private final InventoryBasic marketInputBuffer = new InventoryBasic(
"container.farmingforengineers:market",
false,
1);
private final InventoryBasic marketOutputBuffer = new InventoryBasic(
"container.farmingforengineers:market",
false,
1);
protected final List<FakeSlotMarket> marketSlots = Lists.newArrayList();
private boolean sentItemList;
protected MarketEntry selectedEntry;
public ContainerMarket(EntityPlayer player, int posX, int posY, int posZ) {
this.player = player;
this.posX = posX;
this.posY = posY;
this.posZ = posZ;
addSlotToContainer(new Slot(marketInputBuffer, 0, 23, 39));
addSlotToContainer(new SlotMarketBuy(this, marketOutputBuffer, 0, 61, 39));
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 3; j++) {
FakeSlotMarket slot = new FakeSlotMarket(j + i * 3, 102 + j * 18, 11 + i * 18);
marketSlots.add(slot);
addSlotToContainer(slot);
}
}
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 9; j++) {
addSlotToContainer(new Slot(player.inventory, j + i * 9 + 9, 8 + j * 18, 92 + i * 18));
}
}
for (int i = 0; i < 9; i++) {
addSlotToContainer(new Slot(player.inventory, i, 8 + i * 18, 150));
}
}
@Override
public ItemStack transferStackInSlot(EntityPlayer player, int slotIndex) {
ItemStack itemStack = null;
Slot slot = (Slot) this.inventorySlots.get(slotIndex);
if (slot != null && slot.getHasStack()) {
ItemStack slotStack = slot.getStack();
// noinspection ConstantConditions
itemStack = slotStack.copy();
if (slotIndex == 1) {
if (!this.mergeItemStack(slotStack, 14, 50, true)) {
return null;
}
slot.onSlotChange(slotStack, itemStack);
} else if (slotIndex == 0) {
if (!mergeItemStack(slotStack, 14, 50, true)) {
return null;
}
} else if ((selectedEntry == null && slotStack.getItem() == Items.emerald)
|| (selectedEntry != null && selectedEntry.getCostItem().isItemEqual(slotStack))) {
if (!this.mergeItemStack(slotStack, 0, 1, true)) {
return null;
}
} else
if (slotIndex >= 41 && slotIndex < 50) {
if (!mergeItemStack(slotStack, 14, 41, true)) {
return null;
}
} else if (slotIndex >= 14 && slotIndex < 41) {
if (!mergeItemStack(slotStack, 41, 50, false)) {
return null;
}
}
if (slotStack.stackSize == 0) {
slot.putStack(null);
} else {
slot.onSlotChanged();
}
if (slotStack.stackSize == itemStack.stackSize) {
return null;
}
slot.onPickupFromSlot(player, slotStack);
}
return itemStack;
}
@Override
public void detectAndSendChanges() {
super.detectAndSendChanges();
if (!player.worldObj.isRemote && !sentItemList) { | package com.guigs44.farmingforengineers.container;
public class ContainerMarket extends Container {
private final EntityPlayer player;
private final int posX;
private final int posY;
private final int posZ;
private final InventoryBasic marketInputBuffer = new InventoryBasic(
"container.farmingforengineers:market",
false,
1);
private final InventoryBasic marketOutputBuffer = new InventoryBasic(
"container.farmingforengineers:market",
false,
1);
protected final List<FakeSlotMarket> marketSlots = Lists.newArrayList();
private boolean sentItemList;
protected MarketEntry selectedEntry;
public ContainerMarket(EntityPlayer player, int posX, int posY, int posZ) {
this.player = player;
this.posX = posX;
this.posY = posY;
this.posZ = posZ;
addSlotToContainer(new Slot(marketInputBuffer, 0, 23, 39));
addSlotToContainer(new SlotMarketBuy(this, marketOutputBuffer, 0, 61, 39));
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 3; j++) {
FakeSlotMarket slot = new FakeSlotMarket(j + i * 3, 102 + j * 18, 11 + i * 18);
marketSlots.add(slot);
addSlotToContainer(slot);
}
}
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 9; j++) {
addSlotToContainer(new Slot(player.inventory, j + i * 9 + 9, 8 + j * 18, 92 + i * 18));
}
}
for (int i = 0; i < 9; i++) {
addSlotToContainer(new Slot(player.inventory, i, 8 + i * 18, 150));
}
}
@Override
public ItemStack transferStackInSlot(EntityPlayer player, int slotIndex) {
ItemStack itemStack = null;
Slot slot = (Slot) this.inventorySlots.get(slotIndex);
if (slot != null && slot.getHasStack()) {
ItemStack slotStack = slot.getStack();
// noinspection ConstantConditions
itemStack = slotStack.copy();
if (slotIndex == 1) {
if (!this.mergeItemStack(slotStack, 14, 50, true)) {
return null;
}
slot.onSlotChange(slotStack, itemStack);
} else if (slotIndex == 0) {
if (!mergeItemStack(slotStack, 14, 50, true)) {
return null;
}
} else if ((selectedEntry == null && slotStack.getItem() == Items.emerald)
|| (selectedEntry != null && selectedEntry.getCostItem().isItemEqual(slotStack))) {
if (!this.mergeItemStack(slotStack, 0, 1, true)) {
return null;
}
} else
if (slotIndex >= 41 && slotIndex < 50) {
if (!mergeItemStack(slotStack, 14, 41, true)) {
return null;
}
} else if (slotIndex >= 14 && slotIndex < 41) {
if (!mergeItemStack(slotStack, 41, 50, false)) {
return null;
}
}
if (slotStack.stackSize == 0) {
slot.putStack(null);
} else {
slot.onSlotChanged();
}
if (slotStack.stackSize == itemStack.stackSize) {
return null;
}
slot.onPickupFromSlot(player, slotStack);
}
return itemStack;
}
@Override
public void detectAndSendChanges() {
super.detectAndSendChanges();
if (!player.worldObj.isRemote && !sentItemList) { | NetworkHandler.instance.sendTo(new MessageMarketList(MarketRegistry.getEntries()), (EntityPlayerMP) player); | 0 | 2023-10-17 00:25:50+00:00 | 8k |
clclab/pcfg-lm | src/berkeley_parser/edu/berkeley/nlp/util/functional/FunctionalUtils.java | [
{
"identifier": "CollectionUtils",
"path": "src/berkeley_parser/edu/berkeley/nlp/util/CollectionUtils.java",
"snippet": "public class CollectionUtils {\n\n\tpublic interface CollectionFactory<V> {\n\n\t\tCollection<V> newCollection();\n\n\t}\n\n\tpublic static <E extends Comparable<E>> List<E> sort(Coll... | import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import edu.berkeley.nlp.util.CollectionUtils;
import edu.berkeley.nlp.util.Factory;
import edu.berkeley.nlp.util.LazyIterable;
import edu.berkeley.nlp.util.Pair; | 6,174 | package edu.berkeley.nlp.util.functional;
/**
* Collection of Functional Utilities you'd find in any functional programming
* language. Things like map, filter, reduce, etc..
*
* Created by IntelliJ IDEA. User: aria42 Date: Oct 7, 2008 Time: 1:06:08 PM
*/
public class FunctionalUtils {
public static <T> List<T> take(Iterator<T> it, int n) {
List<T> result = new ArrayList<T>();
for (int i = 0; i < n && it.hasNext(); ++i) {
result.add(it.next());
}
return result;
}
private static Method getMethod(Class c, String field) {
Method[] methods = c.getDeclaredMethods();
String trgMethName = "get" + field;
Method trgMeth = null;
for (Method m : methods) {
if (m.getName().equalsIgnoreCase(trgMethName)
|| m.getName().equalsIgnoreCase(field)) {
return m;
}
}
return null;
}
private static Field getField(Class c, String fieldName) {
Field[] fields = c.getDeclaredFields();
for (Field f : fields) {
if (f.getName().equalsIgnoreCase(fieldName)) {
return f;
}
}
return null;
}
public static <T> Pair<T, Double> findMax(Iterable<T> xs,
Function<T, Double> fn) {
double max = Double.NEGATIVE_INFINITY;
T argMax = null;
for (T x : xs) {
double val = fn.apply(x);
if (val > max) {
max = val;
argMax = x;
}
}
return Pair.newPair(argMax, max);
}
public static <T> Pair<T, Double> findMin(Iterable<T> xs,
Function<T, Double> fn) {
double min = Double.POSITIVE_INFINITY;
T argMin = null;
for (T x : xs) {
double val = fn.apply(x);
if (val < min) {
min = val;
argMin = x;
}
}
return Pair.newPair(argMin, min);
}
public static <K, I, V> Map<K, V> compose(Map<K, I> map, Function<I, V> fn) {
return map(map, fn, (Predicate<K>) Predicates.getTruePredicate(),
new HashMap<K, V>());
}
public static <K, I, V> Map<K, V> compose(Map<K, I> map, Function<I, V> fn,
Predicate<K> pred) {
return map(map, fn, pred, new HashMap<K, V>());
}
public static <C> List make(Factory<C> factory, int k) {
List<C> insts = new ArrayList<C>();
for (int i = 0; i < k; i++) {
insts.add(factory.newInstance());
}
// Fuck you cvs
return insts;
}
public static <K, I, V> Map<K, V> map(Map<K, I> map, Function<I, V> fn,
Predicate<K> pred, Map<K, V> resultMap) {
for (Map.Entry<K, I> entry : map.entrySet()) {
K key = entry.getKey();
I inter = entry.getValue();
if (pred.apply(key))
resultMap.put(key, fn.apply(inter));
}
return resultMap;
}
public static <I, O> Map<I, O> mapPairs(Iterable<I> lst, Function<I, O> fn) {
return mapPairs(lst, fn, new HashMap<I, O>());
}
public static <I, O> Map<I, O> mapPairs(Iterable<I> lst, Function<I, O> fn,
Map<I, O> resultMap) {
for (I input : lst) {
O output = fn.apply(input);
resultMap.put(input, output);
}
return resultMap;
}
public static <I, O> List<O> map(Iterable<I> lst, Function<I, O> fn) {
return map(lst, fn, (Predicate<O>) Predicates.getTruePredicate());
}
public static <I, O> Iterable<O> lazyMap(Iterable<I> lst, Function<I, O> fn) {
return lazyMap(lst, fn, (Predicate<O>) Predicates.getTruePredicate());
}
public static <I, O> Iterable<O> lazyMap(Iterable<I> lst,
Function<I, O> fn, Predicate<O> pred) { | package edu.berkeley.nlp.util.functional;
/**
* Collection of Functional Utilities you'd find in any functional programming
* language. Things like map, filter, reduce, etc..
*
* Created by IntelliJ IDEA. User: aria42 Date: Oct 7, 2008 Time: 1:06:08 PM
*/
public class FunctionalUtils {
public static <T> List<T> take(Iterator<T> it, int n) {
List<T> result = new ArrayList<T>();
for (int i = 0; i < n && it.hasNext(); ++i) {
result.add(it.next());
}
return result;
}
private static Method getMethod(Class c, String field) {
Method[] methods = c.getDeclaredMethods();
String trgMethName = "get" + field;
Method trgMeth = null;
for (Method m : methods) {
if (m.getName().equalsIgnoreCase(trgMethName)
|| m.getName().equalsIgnoreCase(field)) {
return m;
}
}
return null;
}
private static Field getField(Class c, String fieldName) {
Field[] fields = c.getDeclaredFields();
for (Field f : fields) {
if (f.getName().equalsIgnoreCase(fieldName)) {
return f;
}
}
return null;
}
public static <T> Pair<T, Double> findMax(Iterable<T> xs,
Function<T, Double> fn) {
double max = Double.NEGATIVE_INFINITY;
T argMax = null;
for (T x : xs) {
double val = fn.apply(x);
if (val > max) {
max = val;
argMax = x;
}
}
return Pair.newPair(argMax, max);
}
public static <T> Pair<T, Double> findMin(Iterable<T> xs,
Function<T, Double> fn) {
double min = Double.POSITIVE_INFINITY;
T argMin = null;
for (T x : xs) {
double val = fn.apply(x);
if (val < min) {
min = val;
argMin = x;
}
}
return Pair.newPair(argMin, min);
}
public static <K, I, V> Map<K, V> compose(Map<K, I> map, Function<I, V> fn) {
return map(map, fn, (Predicate<K>) Predicates.getTruePredicate(),
new HashMap<K, V>());
}
public static <K, I, V> Map<K, V> compose(Map<K, I> map, Function<I, V> fn,
Predicate<K> pred) {
return map(map, fn, pred, new HashMap<K, V>());
}
public static <C> List make(Factory<C> factory, int k) {
List<C> insts = new ArrayList<C>();
for (int i = 0; i < k; i++) {
insts.add(factory.newInstance());
}
// Fuck you cvs
return insts;
}
public static <K, I, V> Map<K, V> map(Map<K, I> map, Function<I, V> fn,
Predicate<K> pred, Map<K, V> resultMap) {
for (Map.Entry<K, I> entry : map.entrySet()) {
K key = entry.getKey();
I inter = entry.getValue();
if (pred.apply(key))
resultMap.put(key, fn.apply(inter));
}
return resultMap;
}
public static <I, O> Map<I, O> mapPairs(Iterable<I> lst, Function<I, O> fn) {
return mapPairs(lst, fn, new HashMap<I, O>());
}
public static <I, O> Map<I, O> mapPairs(Iterable<I> lst, Function<I, O> fn,
Map<I, O> resultMap) {
for (I input : lst) {
O output = fn.apply(input);
resultMap.put(input, output);
}
return resultMap;
}
public static <I, O> List<O> map(Iterable<I> lst, Function<I, O> fn) {
return map(lst, fn, (Predicate<O>) Predicates.getTruePredicate());
}
public static <I, O> Iterable<O> lazyMap(Iterable<I> lst, Function<I, O> fn) {
return lazyMap(lst, fn, (Predicate<O>) Predicates.getTruePredicate());
}
public static <I, O> Iterable<O> lazyMap(Iterable<I> lst,
Function<I, O> fn, Predicate<O> pred) { | return new LazyIterable<O, I>(lst, fn, pred, 20); | 2 | 2023-10-22 13:13:22+00:00 | 8k |
UZ9/cs-1331-drivers | src/StartMenuTests.java | [
{
"identifier": "TestFailedException",
"path": "src/com/cs1331/drivers/exception/TestFailedException.java",
"snippet": "public class TestFailedException extends Exception {\n public TestFailedException() {\n }\n\n public TestFailedException(String message) {\n super(message);\n }\n}"
... | import java.io.File;
import com.cs1331.drivers.annotations.AfterTest;
import com.cs1331.drivers.annotations.InjectData;
import com.cs1331.drivers.annotations.TestCase;
import com.cs1331.drivers.annotations.Tip;
import com.cs1331.drivers.exception.TestFailedException;
import com.cs1331.drivers.javafx.RecursiveSearch;
import com.cs1331.drivers.testing.TestFunction;
import com.cs1331.drivers.testing.TestManager;
import javafx.application.Platform;
import javafx.event.Event;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.Pane;
import javafx.stage.Stage; | 4,900 |
public class StartMenuTests {
@TestCase(name = "valid title property")
@Tip(description = "Make sure you're setting your stage title correctly!")
public void checkApplicationTitle() throws TestFailedException {
TestFunction.assertEqual(StageData.stage.getTitle(), "Battleship");
}
@TestCase(name = "battleshipImage.jpg exists")
@Tip(description = "Make sure you have battleshipImage.jpg (NOT png) in the same directory as your files!")
public void checkBattleshipImage() throws TestFailedException {
File file = new File("battleshipImage.jpg");
TestFunction.assertEqual(file.exists(), true);
}
@TestCase(name = "enemy.txt exists")
@Tip(description = "Make sure you have enemy.txt in the same directory as your files!")
public void checkEnemyTxt() throws TestFailedException {
File file = new File("enemy.txt");
TestFunction.assertEqual(file.exists(), true);
}
@TestCase(name = "player.txt exists")
@Tip(description = "Make sure you have player.txt in the same directory as your files!")
public void checkPlayerTxt() throws TestFailedException {
File file = new File("player.txt");
TestFunction.assertEqual(file.exists(), true);
}
@TestCase(name = "Start menu contains a button with text \"Start Game!\"")
@Tip(description = "Make sure your button formatting is correct!")
public void checkForButton() throws TestFailedException {
Scene scene = StageData.stage.getScene();
Button returned = RecursiveSearch.recursiveSearch(
((Button b) -> b.getText().equals("Start Game!")),
Button.class,
(Pane) scene.getRoot());
TestFunction.assertEqual(true, returned != null);
}
@TestCase(name = "Start menu contains a label somewhere with \"Battleship\"")
@Tip(description = "Make sure your button formatting is correct!")
public void checkForBattleshipLabel() throws TestFailedException {
Scene scene = StageData.stage.getScene();
Label returned = RecursiveSearch.recursiveSearch(
((Label b) -> b.getText().equals("Battleship")),
Label.class,
(Pane) scene.getRoot());
TestFunction.assertEqual(true, returned != null);
}
@AfterTest
public void afterTest() {
Scene scene = StageData.stage.getScene();
Button returned = RecursiveSearch.recursiveSearch(
((Button b) -> b.getText().equals("Start Game!")),
Button.class,
(Pane) scene.getRoot());
if (returned != null) {
Platform.runLater(() -> { returned.fire(); System.out.println("set scene"); StageData.currentScene = returned.getScene(); |
public class StartMenuTests {
@TestCase(name = "valid title property")
@Tip(description = "Make sure you're setting your stage title correctly!")
public void checkApplicationTitle() throws TestFailedException {
TestFunction.assertEqual(StageData.stage.getTitle(), "Battleship");
}
@TestCase(name = "battleshipImage.jpg exists")
@Tip(description = "Make sure you have battleshipImage.jpg (NOT png) in the same directory as your files!")
public void checkBattleshipImage() throws TestFailedException {
File file = new File("battleshipImage.jpg");
TestFunction.assertEqual(file.exists(), true);
}
@TestCase(name = "enemy.txt exists")
@Tip(description = "Make sure you have enemy.txt in the same directory as your files!")
public void checkEnemyTxt() throws TestFailedException {
File file = new File("enemy.txt");
TestFunction.assertEqual(file.exists(), true);
}
@TestCase(name = "player.txt exists")
@Tip(description = "Make sure you have player.txt in the same directory as your files!")
public void checkPlayerTxt() throws TestFailedException {
File file = new File("player.txt");
TestFunction.assertEqual(file.exists(), true);
}
@TestCase(name = "Start menu contains a button with text \"Start Game!\"")
@Tip(description = "Make sure your button formatting is correct!")
public void checkForButton() throws TestFailedException {
Scene scene = StageData.stage.getScene();
Button returned = RecursiveSearch.recursiveSearch(
((Button b) -> b.getText().equals("Start Game!")),
Button.class,
(Pane) scene.getRoot());
TestFunction.assertEqual(true, returned != null);
}
@TestCase(name = "Start menu contains a label somewhere with \"Battleship\"")
@Tip(description = "Make sure your button formatting is correct!")
public void checkForBattleshipLabel() throws TestFailedException {
Scene scene = StageData.stage.getScene();
Label returned = RecursiveSearch.recursiveSearch(
((Label b) -> b.getText().equals("Battleship")),
Label.class,
(Pane) scene.getRoot());
TestFunction.assertEqual(true, returned != null);
}
@AfterTest
public void afterTest() {
Scene scene = StageData.stage.getScene();
Button returned = RecursiveSearch.recursiveSearch(
((Button b) -> b.getText().equals("Start Game!")),
Button.class,
(Pane) scene.getRoot());
if (returned != null) {
Platform.runLater(() -> { returned.fire(); System.out.println("set scene"); StageData.currentScene = returned.getScene(); | TestManager.executeNextTest(StageData.stage); | 3 | 2023-10-20 03:06:59+00:00 | 8k |
AkramLZ/ServerSync | serversync-bungee/src/main/java/me/akraml/serversync/bungee/BungeeServerSyncPlugin.java | [
{
"identifier": "ServerSync",
"path": "serversync-common/src/main/java/me/akraml/serversync/ServerSync.java",
"snippet": "@Getter\npublic class ServerSync {\n\n private static ServerSync INSTANCE;\n\n private final ServersManager serversManager;\n private final MessageBrokerService messageBroke... | import me.akraml.serversync.connection.auth.ConnectionCredentials;
import me.akraml.serversync.connection.auth.credentials.RedisCredentialsKeys;
import me.akraml.serversync.server.ServersManager;
import net.md_5.bungee.api.plugin.Plugin;
import net.md_5.bungee.config.Configuration;
import net.md_5.bungee.config.ConfigurationProvider;
import net.md_5.bungee.config.YamlConfiguration;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import lombok.Getter;
import me.akraml.serversync.ServerSync;
import me.akraml.serversync.VersionInfo;
import me.akraml.serversync.broker.RedisMessageBrokerService;
import me.akraml.serversync.connection.ConnectionResult;
import me.akraml.serversync.connection.ConnectionType; | 3,709 | /*
* MIT License
*
* Copyright (c) 2023 Akram Louze
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package me.akraml.serversync.bungee;
/**
* An implementation for ServerSync in BungeeCord platform.
*/
@Getter
public final class BungeeServerSyncPlugin extends Plugin {
private Configuration config;
@SuppressWarnings("ResultOfMethodCallIgnored")
@Override
public void onLoad() {
if (!getDataFolder().exists()) {
getDataFolder().mkdir();
}
try {
loadConfig();
} catch (Exception exception) {
exception.printStackTrace(System.err);
}
}
@Override
public void onEnable() {
final long start = System.currentTimeMillis();
getLogger().info("\n" +
" __ __ \n" +
"/ _\\ ___ _ ____ _____ _ __/ _\\_ _ _ __ ___ \n" +
"\\ \\ / _ \\ '__\\ \\ / / _ \\ '__\\ \\| | | | '_ \\ / __|\n" +
"_\\ \\ __/ | \\ V / __/ | _\\ \\ |_| | | | | (__ \n" +
"\\__/\\___|_| \\_/ \\___|_| \\__/\\__, |_| |_|\\___|\n" +
" |___/ \n");
getLogger().info("This server is running ServerSync " + VersionInfo.VERSION + " by AkramL.");
final ServersManager serversManager = new BungeeServersManager(this);
// Initialize message broker service.
final ConnectionType connectionType = ConnectionType.valueOf(config.getString("message-broker-service"));
switch (connectionType) {
case REDIS: {
getLogger().info("ServerSync will run under Redis message broker...");
long redisStartTime = System.currentTimeMillis();
final Configuration redisSection = config.getSection("redis");
final ConnectionCredentials credentials = ConnectionCredentials.newBuilder()
.addKey(RedisCredentialsKeys.HOST, redisSection.getString("host"))
.addKey(RedisCredentialsKeys.PORT, redisSection.getInt("port"))
.addKey(RedisCredentialsKeys.PASSWORD, redisSection.getString("password"))
.addKey(RedisCredentialsKeys.TIMEOUT, redisSection.getInt("timeout"))
.addKey(RedisCredentialsKeys.MAX_TOTAL, redisSection.getInt("max-total"))
.addKey(RedisCredentialsKeys.MAX_IDLE, redisSection.getInt("max-idle"))
.addKey(RedisCredentialsKeys.MIN_IDLE, redisSection.getInt("min-idle"))
.addKey(RedisCredentialsKeys.MIN_EVICTABLE_IDLE_TIME, redisSection.getLong("min-evictable-idle-time"))
.addKey(RedisCredentialsKeys.TIME_BETWEEN_EVICTION_RUNS, redisSection.getLong("time-between-eviction-runs"))
.addKey(RedisCredentialsKeys.BLOCK_WHEN_EXHAUSTED, redisSection.getBoolean("block-when-exhausted"))
.build();
final RedisMessageBrokerService messageBrokerService = new RedisMessageBrokerService(
serversManager,
credentials
); | /*
* MIT License
*
* Copyright (c) 2023 Akram Louze
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package me.akraml.serversync.bungee;
/**
* An implementation for ServerSync in BungeeCord platform.
*/
@Getter
public final class BungeeServerSyncPlugin extends Plugin {
private Configuration config;
@SuppressWarnings("ResultOfMethodCallIgnored")
@Override
public void onLoad() {
if (!getDataFolder().exists()) {
getDataFolder().mkdir();
}
try {
loadConfig();
} catch (Exception exception) {
exception.printStackTrace(System.err);
}
}
@Override
public void onEnable() {
final long start = System.currentTimeMillis();
getLogger().info("\n" +
" __ __ \n" +
"/ _\\ ___ _ ____ _____ _ __/ _\\_ _ _ __ ___ \n" +
"\\ \\ / _ \\ '__\\ \\ / / _ \\ '__\\ \\| | | | '_ \\ / __|\n" +
"_\\ \\ __/ | \\ V / __/ | _\\ \\ |_| | | | | (__ \n" +
"\\__/\\___|_| \\_/ \\___|_| \\__/\\__, |_| |_|\\___|\n" +
" |___/ \n");
getLogger().info("This server is running ServerSync " + VersionInfo.VERSION + " by AkramL.");
final ServersManager serversManager = new BungeeServersManager(this);
// Initialize message broker service.
final ConnectionType connectionType = ConnectionType.valueOf(config.getString("message-broker-service"));
switch (connectionType) {
case REDIS: {
getLogger().info("ServerSync will run under Redis message broker...");
long redisStartTime = System.currentTimeMillis();
final Configuration redisSection = config.getSection("redis");
final ConnectionCredentials credentials = ConnectionCredentials.newBuilder()
.addKey(RedisCredentialsKeys.HOST, redisSection.getString("host"))
.addKey(RedisCredentialsKeys.PORT, redisSection.getInt("port"))
.addKey(RedisCredentialsKeys.PASSWORD, redisSection.getString("password"))
.addKey(RedisCredentialsKeys.TIMEOUT, redisSection.getInt("timeout"))
.addKey(RedisCredentialsKeys.MAX_TOTAL, redisSection.getInt("max-total"))
.addKey(RedisCredentialsKeys.MAX_IDLE, redisSection.getInt("max-idle"))
.addKey(RedisCredentialsKeys.MIN_IDLE, redisSection.getInt("min-idle"))
.addKey(RedisCredentialsKeys.MIN_EVICTABLE_IDLE_TIME, redisSection.getLong("min-evictable-idle-time"))
.addKey(RedisCredentialsKeys.TIME_BETWEEN_EVICTION_RUNS, redisSection.getLong("time-between-eviction-runs"))
.addKey(RedisCredentialsKeys.BLOCK_WHEN_EXHAUSTED, redisSection.getBoolean("block-when-exhausted"))
.build();
final RedisMessageBrokerService messageBrokerService = new RedisMessageBrokerService(
serversManager,
credentials
); | final ConnectionResult connectionResult = messageBrokerService.connect(); | 2 | 2023-10-21 12:47:58+00:00 | 8k |
neftalito/R-Info-Plus | form/Robot.java | [
{
"identifier": "Variable",
"path": "arbol/Variable.java",
"snippet": "public class Variable extends Expresion {\n private String value;\n private boolean editable;\n Robot rob;\n RobotAST r;\n private String nombreTipoRobot;\n DeclaracionRobots dr;\n\n public Variable(final Identif... | import arbol.Variable;
import arbol.sentencia.Sentencia;
import arbol.ParametroFormal;
import arbol.Proceso;
import java.beans.PropertyChangeListener;
import java.awt.Image;
import arbol.Identificador;
import java.io.IOException;
import java.net.UnknownHostException;
import java.io.DataOutputStream;
import java.net.Socket;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.util.logging.Level;
import java.util.logging.Logger;
import arbol.sentencia.primitiva.Mover;
import java.io.FileReader;
import java.io.File;
import java.awt.Color;
import java.beans.PropertyChangeSupport;
import javax.swing.ImageIcon;
import arbol.DeclaracionVariable;
import arbol.Cuerpo;
import arbol.DeclaracionProcesos;
import java.util.ArrayList; | 5,558 | this.esperarRefresco.esperar(this.id);
this.getCity().form.jsp.refresh();
return;
}
this.city.parseError("No se puede ejecutar la instrucci\u00f3n \"Pos\" debido a que hay un obst\u00e1culo");
throw new Exception("No se puede ejecutar la instrucci\u00f3n \"Pos\" debido a que hay un obst\u00e1culo");
}
public ArrayList<Coord> getRuta() {
return this.ruta;
}
public Ciudad getCity() {
return this.city;
}
public void tomarFlor() throws Exception {
if (this.getCity().levantarFlor(this.PosAv(), this.PosCa())) {
this.setFlores(this.getFlores() + 1);
this.esperarRefresco.esperar(this.id);
return;
}
this.setFlores(this.getFlores());
throw new Exception(
"No se puede ejecutar la instrucci\u00f3n \"tomarFlor\" debido a que no hay ninguna flor en la esquina");
}
public int getFlores() {
return this.floresEnBolsa;
}
public void setFlores(final int flores) {
final int old = this.getFlores();
this.floresEnBolsa = flores;
this.pcs.firePropertyChange("flores", old, flores);
}
public void tomarPapel() throws Exception {
if (this.getCity().levantarPapel(this.PosAv(), this.PosCa())) {
this.setPapeles(this.getPapeles() + 1);
this.esperarRefresco.esperar(this.id);
return;
}
this.setPapeles(this.getPapeles());
throw new Exception(
"No se puede ejecutar la instrucci\u00f3n \"tomarPapel\" debido a que no hay ningun papel en la esquina");
}
public boolean HayPapelEnLaBolsa() {
return this.getPapeles() > 0;
}
public boolean HayFlorEnLaBolsa() {
return this.getFlores() > 0;
}
public int getPapeles() {
return this.papelesEnBolsa;
}
public void setColor(final Color col) {
final Color old = this.color;
this.color = col;
this.pcs.firePropertyChange("color", old, col);
}
public Color getColor() {
return this.color;
}
public void setPapeles(final int papeles) {
final int old = this.getPapeles();
this.papelesEnBolsa = papeles;
this.pcs.firePropertyChange("papeles", old, papeles);
}
public void depositarPapel() throws Exception {
if (this.getPapeles() > 0) {
this.setPapeles(this.getPapeles() - 1);
this.getCity().dejarPapel(this.PosAv(), this.PosCa());
this.esperarRefresco.esperar(this.id);
return;
}
this.city.parseError(
"No se puede ejecutar la instrucci\u00f3n \"depositarPapel\" debido a que no hay ningun papel en la bolsa");
throw new Exception(
"No se puede ejecutar la instrucci\u00f3n \"depositarPapel\" debido a que no hay ningun papel en la bolsa");
}
public void depositarFlor() throws Exception {
if (this.getFlores() > 0) {
this.setFlores(this.getFlores() - 1);
this.getCity().dejarFlor(this.PosAv(), this.PosCa());
this.esperarRefresco.esperar(this.id);
return;
}
this.city.parseError(
"No se puede ejecutar la instrucci\u00f3n \"depositarFlor\" debido a que no hay ninguna en la bolsa de flores");
throw new Exception(
"No se puede ejecutar la instrucci\u00f3n \"depositarFlor\" debido a que no hay ninguna en la bolsa de flores");
}
public ArrayList<ArrayList<Coord>> getRutas() {
return this.rutas;
}
public void setRuta(final ArrayList<Coord> ruta) {
this.ruta = ruta;
}
public void setRutas(final ArrayList<ArrayList<Coord>> rutas) {
this.rutas = rutas;
}
public DeclaracionProcesos getProcAST() {
return this.procAST;
}
public void setProcAST(final DeclaracionProcesos procAST) throws CloneNotSupportedException {
synchronized (this) { |
package form;
public class Robot {
private int ciclos;
private ArrayList<Coord> misCalles;
private DeclaracionProcesos procAST;
private Cuerpo cueAST;
private DeclaracionVariable varAST;
private ImageIcon robotImage;
private ArrayList<Coord> ruta;
private ArrayList<ArrayList<Coord>> rutas;
public int Av;
public int Ca;
private int direccion;
private final PropertyChangeSupport pcs;
private Ciudad city;
private int floresEnBolsa;
private int papelesEnBolsa;
private int floresEnBolsaDeConfiguracion;
private int papelesEnBolsaDeConfiguracion;
private ArrayList<Area> areas;
MonitorEsquinas esquinas;
MonitorActualizarVentana esperarRefresco;
public int id;
private static int cant;
public int offsetAv;
public int offsetCa;
public String dir;
public MonitorMensajes monitor;
String nombre;
Color color;
public String estado;
public Robot(final Ciudad city, final String nombre) throws Exception {
this.robotImage = new ImageIcon(this.getClass().getResource("/images/robotAbajo.png"));
this.ruta = new ArrayList<Coord>();
this.rutas = new ArrayList<ArrayList<Coord>>();
this.Av = 0;
this.Ca = 0;
this.direccion = 90;
this.pcs = new PropertyChangeSupport(this);
this.floresEnBolsa = 0;
this.papelesEnBolsa = 0;
this.floresEnBolsaDeConfiguracion = 0;
this.papelesEnBolsaDeConfiguracion = 0;
this.esquinas = MonitorEsquinas.getInstance();
this.esperarRefresco = MonitorActualizarVentana.getInstance();
this.offsetAv = 0;
this.offsetCa = 0;
this.misCalles = new ArrayList<Coord>();
this.areas = new ArrayList<Area>();
this.Av = 0;
this.Ca = 0;
this.getRuta().add(new Coord(this.Av, this.Ca));
this.setNombre(nombre);
this.city = city;
this.rutas.add(this.ruta);
this.id = this.getCity().robots.size();
this.color = this.getColorById(this.id);
this.setDireccion(90);
this.setFlores(this.getFloresEnBolsaDeConfiguracion());
this.setPapeles(this.getPapelesEnBolsaDeConfiguracion());
this.estado = "Nuevo ";
}
public void crear() throws UnknownHostException, IOException {
this.dir = "";
System.out.println(this.getId());
if (this.id == 0) {
final int puerto = 4000;
File archivo = null;
FileReader fr = null;
BufferedReader br = null;
archivo = new File(System.getProperty("user.dir") + System.getProperty("file.separator") + "Conf.txt");
try {
fr = new FileReader(archivo);
} catch (FileNotFoundException ex) {
Logger.getLogger(Mover.class.getName()).log(Level.SEVERE, null, ex);
}
br = new BufferedReader(fr);
String ip = null;
String linea;
while ((linea = br.readLine()) != null) {
System.out.println(linea);
final String[] lineas = linea.split(" ");
final String robot = lineas[0];
ip = lineas[1];
System.out.println(" el robot es : " + robot + " y la ip es : " + ip);
}
this.dir = "192.168.0.100";
this.dir = ip;
} else {
System.out.println("Entre al else");
this.dir = "192.168.0.104";
final int puerto = 4000;
}
try (final Socket s = new Socket(this.dir, 4000)) {
System.out.println("conectados");
final DataOutputStream dOut = new DataOutputStream(s.getOutputStream());
dOut.writeByte(this.getId());
dOut.flush();
dOut.close();
}
}
public int getCiclos() {
return this.ciclos;
}
public void setCiclos(final int ciclos) {
this.ciclos = ciclos;
}
public Color getColorById(final int id) {
switch (id) {
case 0: {
return Color.RED;
}
case 1: {
return new Color(0, 137, 221);
}
case 2: {
return Color.PINK;
}
case 3: {
return new Color(0, 153, 68);
}
case 4: {
return Color.MAGENTA;
}
default: {
final int max = 255;
final int min = 1;
final int x = (int) (Math.random() * (max - min + 1)) + min;
final int y = (int) (Math.random() * (max - min + 1)) + min;
final int z = (int) (Math.random() * (max - min + 1)) + min;
return new Color(x, y, z);
}
}
}
public void almacenarMensaje(final String nombreDestino, final String valor) throws Exception {
final Dato d = new Dato(valor, nombreDestino);
final int id = this.getCity().getRobotByNombre(nombreDestino).id;
this.monitor.llegoMensaje(id, d);
}
public void recibirMensaje(final Identificador nombreVariable, final int id, final Identificador NombreRobot)
throws Exception {
this.monitor.recibirMensaje(nombreVariable, id, NombreRobot);
}
public void Informar(final String msj) {
this.getCity().Informar(msj, this.id);
this.esperarRefresco.esperar(this.id);
}
public void bloquearEsquina(final int Av, final int Ca) {
this.esquinas.bloquear(Av, Ca);
this.esperarRefresco.esperar(this.id);
this.getCity().form.jsp.refresh();
}
public void liberarEsquina(final int Av, final int Ca) {
this.esquinas.liberar(Av, Ca);
this.esperarRefresco.esperar(this.id);
this.getCity().form.jsp.refresh();
}
public Cuerpo getCuerpo() {
return this.cueAST;
}
public void agregarArea(final Area a) {
this.areas.add(a);
for (int i = a.getAv1(); i <= a.getAv2(); ++i) {
for (int j = a.getCa1(); j <= a.getCa2(); ++j) {
this.misCalles.add(new Coord(i, j));
}
}
}
public boolean esAreaVacia() {
return this.areas.isEmpty();
}
public void crearMonitor(final int cant) {
this.monitor = MonitorMensajes.crearMonitorActualizarVentana(cant, this);
}
public void setCuerpo(final Cuerpo cueAST) {
this.cueAST = cueAST;
}
public DeclaracionVariable getVariables() {
return this.varAST;
}
public void setVariables(final DeclaracionVariable varAST) {
this.varAST = varAST;
}
public int getFloresEnBolsaDeConfiguracion() {
return this.floresEnBolsaDeConfiguracion;
}
public void setFloresEnBolsaDeConfiguracion(final int floresEnBolsaDeConfiguracion) {
this.setFlores(this.floresEnBolsaDeConfiguracion = floresEnBolsaDeConfiguracion);
}
public int getPapelesEnBolsaDeConfiguracion() {
return this.papelesEnBolsaDeConfiguracion;
}
public void setPapelesEnBolsaDeConfiguracion(final int papelesEnBolsaDeConfiguracion) {
this.setPapeles(this.papelesEnBolsaDeConfiguracion = papelesEnBolsaDeConfiguracion);
}
public void reset() {
this.misCalles = new ArrayList<Coord>();
this.ruta = new ArrayList<Coord>();
this.rutas = new ArrayList<ArrayList<Coord>>();
this.areas = new ArrayList<Area>();
this.rutas.add(this.ruta);
this.setFlores(this.getFloresEnBolsaDeConfiguracion());
this.setPapeles(this.getPapelesEnBolsaDeConfiguracion());
try {
this.setAv(0);
this.setCa(0);
} catch (Exception ex) {
Logger.getLogger(Robot.class.getName()).log(Level.SEVERE, null, ex);
}
this.setDireccion(90);
}
public Image getImage() {
switch (this.getDireccion()) {
case 0: {
this.robotImage = new ImageIcon(this.getClass().getResource("/images/robotDerecha.png"));
break;
}
case 90: {
this.robotImage = new ImageIcon(this.getClass().getResource("/images/robotArriba.png"));
break;
}
case 180: {
this.robotImage = new ImageIcon(this.getClass().getResource("/images/robotIzquierda.png"));
break;
}
default: {
this.robotImage = new ImageIcon(this.getClass().getResource("/images/robotAbajo.png"));
break;
}
}
return this.robotImage.getImage();
}
public String getNombre() {
return this.nombre;
}
public void setNombre(final String nombre) {
this.nombre = nombre;
}
public void iniciar(final int x, final int y) throws Exception {
this.Pos(x, y);
this.setNewX(x);
this.setNewY(y);
this.setFlores(this.getFlores());
this.setPapeles(this.getPapeles());
this.getCity().form.jsp.refresh();
}
public void choque(final String nom, final int id, final int av, final int ca) throws Exception {
for (final Robot r : this.getCity().robots) {
if (r.id != id && r.Av == av && r.Ca == ca) {
this.city.parseError(" Se produjo un choque entre el robot " + nom + " y el robot " + r.getNombre()
+ " en la avenida " + av + " y la calle " + ca);
throw new Exception(" Se produjo un choque entre el robot " + nom + " y el robot " + r.getNombre()
+ " en la avenida " + av + " y la calle " + ca);
}
}
}
public void mover() throws Exception {
int av = this.PosAv();
int ca = this.PosCa();
switch (this.getDireccion()) {
case 0: {
++av;
break;
}
case 180: {
--av;
break;
}
case 90: {
++ca;
break;
}
case 270: {
--ca;
break;
}
}
if (!this.puedeMover(av, ca, this.areas)) {
this.city.parseError(
"No se puede ejecutar la instrucci\u00f3n \"mover\" debido a que no corresponde a un area asignada del robot");
throw new Exception(
"No se puede ejecutar la instrucci\u00f3n \"mover\" debido a que no corresponde a un area asignada del robot");
}
if (this.getCity().isFreePos(ca, av)) {
this.addPos(av, ca);
this.setFlores(this.getFlores());
this.setPapeles(this.getPapeles());
this.choque(this.nombre, this.id, this.Av, this.Ca);
this.esperarRefresco.esperar(this.id);
this.getCity().form.jsp.refresh();
return;
}
this.city.parseError("No se puede ejecutar la instrucci\u00f3n \"mover\" debido a que hay un obst\u00e1culo");
throw new Exception("No se puede ejecutar la instrucci\u00f3n \"mover\" debido a que hay un obst\u00e1culo");
}
public boolean puedeMover(final int av, final int ca, final ArrayList<Area> areas) {
for (final Coord c : this.misCalles) {
if (c.getX() == av && c.getY() == ca) {
return true;
}
}
return false;
}
public int[] getXCoord() {
final int[] x = new int[this.ruta.size()];
for (int c = 0; c < this.ruta.size(); ++c) {
final Coord p = this.ruta.get(c);
x[c] = p.getX();
}
return x;
}
public int[] getYCoord() {
final int[] y = new int[this.ruta.size() + 1];
for (int c = 0; c < this.ruta.size(); ++c) {
final Coord p = this.ruta.get(c);
y[c] = p.getY();
}
return y;
}
public void addPos(final int av, final int ca) throws Exception {
try {
final int old = this.city.ciudad[av][ca].getFlores();
this.setAv(av);
this.setCa(ca);
this.pcs.firePropertyChange("esquinaFlores", old, this.city.ciudad[av][ca].getFlores());
} catch (Exception e) {
throw new Exception("Una de las nuevas coordenadas cae fuera de la ciudad.Av: " + av + " Ca: " + ca
+ " Calles: " + this.city.getNumCa() + " Avenidas: " + this.city.getNumAv());
}
}
public void setAv(final int av) throws Exception {
if (av > this.city.getNumAv()) {
throw new Exception();
}
if (av != this.PosAv()) {
this.ruta.add(new Coord(av, this.PosCa()));
if (av > this.PosAv()) {
this.setDireccion(0);
} else {
this.setDireccion(180);
}
}
this.setNewX(av);
this.setNewY(this.Ca);
}
public void setNewX(final int av) {
final int old = this.PosAv();
this.Av = av;
this.pcs.firePropertyChange("av", old, av);
}
public void setNewY(final int ca) {
final int old = this.PosCa();
this.Ca = ca;
this.pcs.firePropertyChange("ca", old, ca);
}
public void setCa(final int ca) throws Exception {
if (ca > this.city.getNumCa()) {
throw new Exception();
}
if (ca != this.PosCa()) {
this.ruta.add(new Coord(this.PosAv(), ca));
if (ca < this.PosCa()) {
this.setDireccion(270);
} else {
this.setDireccion(90);
}
}
this.setNewY(ca);
this.setNewX(this.Av);
}
public void setDireccion(final int direccion) {
final int old = this.direccion;
this.direccion = direccion;
this.pcs.firePropertyChange("direccion", old, direccion);
}
public void setEstado(final String str) {
final String s = this.getEstado();
this.estado = str;
this.pcs.firePropertyChange("estado", s, str);
}
public String getEstado() {
return this.estado;
}
public int getDireccion() {
return this.direccion;
}
public void addPropertyChangeListener(final PropertyChangeListener listener) {
this.pcs.addPropertyChangeListener(listener);
}
public void removePropertyChangeListener(final PropertyChangeListener listener) {
this.pcs.removePropertyChangeListener(listener);
}
public void mirarEnDireccion(final int direccion) throws Exception {
int c;
for (c = 0; c < 5 && this.getDireccion() != direccion; ++c) {
this.derecha();
}
if (c == 5) {
throw new Exception("La direcci\u00f3n especificada no corresponde.");
}
}
public void izquierda() {
switch (this.getDireccion()) {
case 0: {
this.setDireccion(90);
break;
}
case 270: {
this.setDireccion(0);
break;
}
case 180: {
this.setDireccion(270);
break;
}
case 90: {
this.setDireccion(180);
break;
}
}
this.esperarRefresco.esperar(this.id);
this.getCity().form.jsp.refresh();
}
public void derecha() {
switch (this.getDireccion()) {
case 0: {
this.setDireccion(270);
break;
}
case 270: {
this.setDireccion(180);
break;
}
case 180: {
this.setDireccion(90);
break;
}
case 90: {
this.setDireccion(0);
break;
}
}
this.esperarRefresco.esperar(this.id);
this.getCity().form.jsp.refresh();
}
public int PosCa() {
return this.Ca;
}
public int PosAv() {
return this.Av;
}
public void Pos(final int Av, final int Ca) throws Exception {
if (!this.puedeMover(Av, Ca, this.areas)) {
this.city.parseError(
"No se puede ejecutar la instrucci\u00f3n \"Pos\" debido a que no corresponde a un area asignada del robot");
throw new Exception(
"No se puede ejecutar la instrucci\u00f3n \"Pos\" debido a que no corresponde a un area asignada del robot");
}
if (this.getCity().isFreePos(Ca, Av)) {
this.getRutas().add(this.getRuta());
this.setRuta(new ArrayList<Coord>());
this.getRuta().add(new Coord(Av, Ca));
this.setNewX(Av);
this.setNewY(Ca);
this.choque(this.nombre, this.id, Av, Ca);
this.esperarRefresco.esperar(this.id);
this.getCity().form.jsp.refresh();
return;
}
this.city.parseError("No se puede ejecutar la instrucci\u00f3n \"Pos\" debido a que hay un obst\u00e1culo");
throw new Exception("No se puede ejecutar la instrucci\u00f3n \"Pos\" debido a que hay un obst\u00e1culo");
}
public ArrayList<Coord> getRuta() {
return this.ruta;
}
public Ciudad getCity() {
return this.city;
}
public void tomarFlor() throws Exception {
if (this.getCity().levantarFlor(this.PosAv(), this.PosCa())) {
this.setFlores(this.getFlores() + 1);
this.esperarRefresco.esperar(this.id);
return;
}
this.setFlores(this.getFlores());
throw new Exception(
"No se puede ejecutar la instrucci\u00f3n \"tomarFlor\" debido a que no hay ninguna flor en la esquina");
}
public int getFlores() {
return this.floresEnBolsa;
}
public void setFlores(final int flores) {
final int old = this.getFlores();
this.floresEnBolsa = flores;
this.pcs.firePropertyChange("flores", old, flores);
}
public void tomarPapel() throws Exception {
if (this.getCity().levantarPapel(this.PosAv(), this.PosCa())) {
this.setPapeles(this.getPapeles() + 1);
this.esperarRefresco.esperar(this.id);
return;
}
this.setPapeles(this.getPapeles());
throw new Exception(
"No se puede ejecutar la instrucci\u00f3n \"tomarPapel\" debido a que no hay ningun papel en la esquina");
}
public boolean HayPapelEnLaBolsa() {
return this.getPapeles() > 0;
}
public boolean HayFlorEnLaBolsa() {
return this.getFlores() > 0;
}
public int getPapeles() {
return this.papelesEnBolsa;
}
public void setColor(final Color col) {
final Color old = this.color;
this.color = col;
this.pcs.firePropertyChange("color", old, col);
}
public Color getColor() {
return this.color;
}
public void setPapeles(final int papeles) {
final int old = this.getPapeles();
this.papelesEnBolsa = papeles;
this.pcs.firePropertyChange("papeles", old, papeles);
}
public void depositarPapel() throws Exception {
if (this.getPapeles() > 0) {
this.setPapeles(this.getPapeles() - 1);
this.getCity().dejarPapel(this.PosAv(), this.PosCa());
this.esperarRefresco.esperar(this.id);
return;
}
this.city.parseError(
"No se puede ejecutar la instrucci\u00f3n \"depositarPapel\" debido a que no hay ningun papel en la bolsa");
throw new Exception(
"No se puede ejecutar la instrucci\u00f3n \"depositarPapel\" debido a que no hay ningun papel en la bolsa");
}
public void depositarFlor() throws Exception {
if (this.getFlores() > 0) {
this.setFlores(this.getFlores() - 1);
this.getCity().dejarFlor(this.PosAv(), this.PosCa());
this.esperarRefresco.esperar(this.id);
return;
}
this.city.parseError(
"No se puede ejecutar la instrucci\u00f3n \"depositarFlor\" debido a que no hay ninguna en la bolsa de flores");
throw new Exception(
"No se puede ejecutar la instrucci\u00f3n \"depositarFlor\" debido a que no hay ninguna en la bolsa de flores");
}
public ArrayList<ArrayList<Coord>> getRutas() {
return this.rutas;
}
public void setRuta(final ArrayList<Coord> ruta) {
this.ruta = ruta;
}
public void setRutas(final ArrayList<ArrayList<Coord>> rutas) {
this.rutas = rutas;
}
public DeclaracionProcesos getProcAST() {
return this.procAST;
}
public void setProcAST(final DeclaracionProcesos procAST) throws CloneNotSupportedException {
synchronized (this) { | final ArrayList<Proceso> ps = new ArrayList<Proceso>(); | 3 | 2023-10-20 15:45:37+00:00 | 8k |
wevez/ClientCoderPack | src/tech/tenamen/Main.java | [
{
"identifier": "Client",
"path": "src/tech/tenamen/client/Client.java",
"snippet": "public class Client implements Downloadable {\n\n private String VERSION_NAME;\n private File JSON_FILE, JAR_FILE;\n\n private final List<Library> LIBRARIES = new ArrayList<>();\n public Asset asset;\n\n ... | import tech.tenamen.client.Client;
import tech.tenamen.ide.IDE;
import tech.tenamen.ide.InteliJIDE;
import tech.tenamen.property.OS;
import java.io.File;
import java.util.Scanner; | 4,623 | package tech.tenamen;
public class Main {
public static IDE IDE = new InteliJIDE();
public static Client client;
public static File WORKING_DIR = new File(System.getProperty("user.dir")),
ASSETS_DIR = new File(WORKING_DIR, "assets"),
LIBRARIES_DIR = new File(WORKING_DIR, "libraries"),
OBJECTS_DIR = new File(ASSETS_DIR, "objects"),
INDEXES_DIR = new File(ASSETS_DIR, "indexes"),
SRC_DIR = new File(WORKING_DIR, "src"),
NATIVES_DIR = new File(LIBRARIES_DIR, "natives");
public static void main(String[] main) throws Exception {
final Scanner scanner = new Scanner(System.in);
System.out.println("ClientCoderPack");
System.out.print("Version<<");
final File versionFile = new File(String.format("%s\\.minecraft\\versions\\%s", System.getenv("APPDATA"), scanner.next()));
if (!versionFile.exists()) {
System.out.printf("File %s not found%n", versionFile.getAbsolutePath());
return;
}
ASSETS_DIR.mkdirs();
LIBRARIES_DIR.mkdirs();
OBJECTS_DIR.mkdirs();
INDEXES_DIR.mkdirs();
SRC_DIR.mkdirs();
NATIVES_DIR.mkdirs();
client = new Client(versionFile);
System.out.println("Downloading dependencies");
client.parseDependencies();
client.download(getOs());
System.out.println("Making IDE property file");
IDE.createProperties();
System.out.println("Process has finished!");
}
| package tech.tenamen;
public class Main {
public static IDE IDE = new InteliJIDE();
public static Client client;
public static File WORKING_DIR = new File(System.getProperty("user.dir")),
ASSETS_DIR = new File(WORKING_DIR, "assets"),
LIBRARIES_DIR = new File(WORKING_DIR, "libraries"),
OBJECTS_DIR = new File(ASSETS_DIR, "objects"),
INDEXES_DIR = new File(ASSETS_DIR, "indexes"),
SRC_DIR = new File(WORKING_DIR, "src"),
NATIVES_DIR = new File(LIBRARIES_DIR, "natives");
public static void main(String[] main) throws Exception {
final Scanner scanner = new Scanner(System.in);
System.out.println("ClientCoderPack");
System.out.print("Version<<");
final File versionFile = new File(String.format("%s\\.minecraft\\versions\\%s", System.getenv("APPDATA"), scanner.next()));
if (!versionFile.exists()) {
System.out.printf("File %s not found%n", versionFile.getAbsolutePath());
return;
}
ASSETS_DIR.mkdirs();
LIBRARIES_DIR.mkdirs();
OBJECTS_DIR.mkdirs();
INDEXES_DIR.mkdirs();
SRC_DIR.mkdirs();
NATIVES_DIR.mkdirs();
client = new Client(versionFile);
System.out.println("Downloading dependencies");
client.parseDependencies();
client.download(getOs());
System.out.println("Making IDE property file");
IDE.createProperties();
System.out.println("Process has finished!");
}
| private static OS getOs() { | 3 | 2023-10-20 06:56:19+00:00 | 8k |
Invadermonky/Omniwand | src/main/java/com/invadermonky/omniwand/proxy/ClientProxy.java | [
{
"identifier": "GuiWand",
"path": "src/main/java/com/invadermonky/omniwand/client/GuiWand.java",
"snippet": "public class GuiWand extends GuiScreen {\n ItemStack wand;\n\n public GuiWand(ItemStack wand) {\n this.wand = wand;\n }\n\n public void drawScreen(int mouseX, int mouseY, floa... | import com.invadermonky.omniwand.client.GuiWand;
import com.invadermonky.omniwand.handlers.ConfigHandler;
import com.invadermonky.omniwand.handlers.MouseEventOW;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; | 4,060 | package com.invadermonky.omniwand.proxy;
public class ClientProxy extends CommonProxy {
@Override
public void preInit(FMLPreInitializationEvent event) {
super.preInit(event); | package com.invadermonky.omniwand.proxy;
public class ClientProxy extends CommonProxy {
@Override
public void preInit(FMLPreInitializationEvent event) {
super.preInit(event); | MinecraftForge.EVENT_BUS.register(MouseEventOW.INSTANCE); | 2 | 2023-10-16 00:48:26+00:00 | 8k |
hmcts/opal-fines-service | src/main/java/uk/gov/hmcts/opal/repository/jpa/DefendantAccountSpecs.java | [
{
"identifier": "AccountSearchDto",
"path": "src/main/java/uk/gov/hmcts/opal/dto/AccountSearchDto.java",
"snippet": "@Data\n@Builder\npublic class AccountSearchDto implements ToJsonString {\n /** The court (CT) or MET (metropolitan area). */\n private String court;\n /** Defendant Surname, Comp... | import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.Join;
import jakarta.persistence.criteria.ListJoin;
import jakarta.persistence.criteria.Root;
import org.springframework.data.jpa.domain.Specification;
import uk.gov.hmcts.opal.dto.AccountSearchDto;
import uk.gov.hmcts.opal.dto.DateDto;
import uk.gov.hmcts.opal.entity.CourtsEntity;
import uk.gov.hmcts.opal.entity.CourtsEntity_;
import uk.gov.hmcts.opal.entity.DefendantAccountEntity;
import uk.gov.hmcts.opal.entity.DefendantAccountEntity_;
import uk.gov.hmcts.opal.entity.DefendantAccountPartiesEntity;
import uk.gov.hmcts.opal.entity.DefendantAccountPartiesEntity_;
import uk.gov.hmcts.opal.entity.PartyEntity;
import uk.gov.hmcts.opal.entity.PartyEntity_;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors; | 4,244 | package uk.gov.hmcts.opal.repository.jpa;
public class DefendantAccountSpecs {
public static Specification<DefendantAccountEntity> findByAccountSearch(AccountSearchDto accountSearchDto) {
return Specification.allOf(specificationList(
notBlank(accountSearchDto.getSurname()).map(DefendantAccountSpecs::likeSurname),
notBlank(accountSearchDto.getForename()).map(DefendantAccountSpecs::likeForename),
notBlank(accountSearchDto.getInitials()).map(DefendantAccountSpecs::likeInitials),
notBlank(accountSearchDto.getNiNumber()).map(DefendantAccountSpecs::likeNiNumber),
notBlank(accountSearchDto.getAddressLineOne()).map(DefendantAccountSpecs::likeAddressLine1),
notNullLocalDate(accountSearchDto.getDateOfBirth()).map(DefendantAccountSpecs::equalsDateOfBirth),
Optional.ofNullable(accountSearchDto.getCourt()).filter(s -> s.matches("[0-9]+")).map(Long::parseLong)
.map(DefendantAccountSpecs::equalsAnyCourtId)
));
}
@SafeVarargs
public static List<Specification<DefendantAccountEntity>> specificationList(
Optional<Specification<DefendantAccountEntity>>... optionalSpecs) {
return Arrays.stream(optionalSpecs)
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toList());
}
public static Optional<String> notBlank(String candidate) {
return Optional.ofNullable(candidate).filter(s -> !s.isBlank());
}
public static Optional<LocalDate> notNullLocalDate(DateDto candidate) {
return Optional.ofNullable(candidate).map(DateDto::toLocalDate);
}
public static Specification<DefendantAccountEntity> equalsAccountNumber(String accountNo) {
return (root, query, builder) -> {
return builder.equal(root.get(DefendantAccountEntity_.accountNumber), accountNo);
};
}
public static Specification<DefendantAccountEntity> equalsAnyCourtId(Long courtId) {
return Specification.anyOf(
equalsImposingCourtId(courtId),
equalsEnforcingCourtId(courtId),
equalsLastHearingCourtId(courtId));
}
public static Specification<DefendantAccountEntity> equalsImposingCourtId(Long courtId) {
return (root, query, builder) -> {
return builder.equal(root.get(DefendantAccountEntity_.imposingCourtId), courtId);
};
}
public static Specification<DefendantAccountEntity> equalsEnforcingCourtId(Long courtId) {
return (root, query, builder) -> {
return builder.equal(joinEnforcingCourt(root).get(CourtsEntity_.courtId), courtId);
};
}
public static Specification<DefendantAccountEntity> equalsLastHearingCourtId(Long courtId) {
return (root, query, builder) -> {
return builder.equal(joinLastHearingCourt(root).get(CourtsEntity_.courtId), courtId);
};
}
public static Specification<DefendantAccountEntity> likeSurname(String surname) {
return (root, query, builder) -> {
return builder.like(joinPartyOnAssociationType(root, builder, "Defendant")
.get(PartyEntity_.surname), "%" + surname + "%");
};
}
public static Specification<DefendantAccountEntity> likeForename(String forename) {
return (root, query, builder) -> {
return builder.like(joinPartyOnAssociationType(root, builder, "Defendant")
.get(PartyEntity_.forenames), "%" + forename + "%");
};
}
public static Specification<DefendantAccountEntity> likeOrganisationName(String organisation) {
return (root, query, builder) -> {
return builder.like(joinPartyOnAssociationType(root, builder, "Defendant")
.get(PartyEntity_.organisationName), "%" + organisation + "%");
};
}
public static Specification<DefendantAccountEntity> equalsDateOfBirth(LocalDate dob) {
return (root, query, builder) -> {
return builder.equal(joinPartyOnAssociationType(root, builder, "Defendant")
.get(PartyEntity_.dateOfBirth), dob);
};
}
public static Specification<DefendantAccountEntity> likeNiNumber(String niNumber) {
return (root, query, builder) -> {
return builder.like(joinPartyOnAssociationType(root, builder, "Defendant")
.get(PartyEntity_.niNumber), "%" + niNumber + "%");
};
}
public static Specification<DefendantAccountEntity> likeAddressLine1(String addressLine) {
return (root, query, builder) -> {
return builder.like(joinPartyOnAssociationType(root, builder, "Defendant")
.get(PartyEntity_.addressLine1), "%" + addressLine + "%");
};
}
public static Specification<DefendantAccountEntity> likeInitials(String initials) {
return (root, query, builder) -> {
return builder.like(joinPartyOnAssociationType(root, builder, "Defendant")
.get(PartyEntity_.initials), "%" + initials + "%");
};
}
public static Join<DefendantAccountEntity, CourtsEntity> joinEnforcingCourt(Root<DefendantAccountEntity> root) {
return root.join(DefendantAccountEntity_.enforcingCourtId);
}
public static Join<DefendantAccountEntity, CourtsEntity> joinLastHearingCourt(Root<DefendantAccountEntity> root) {
return root.join(DefendantAccountEntity_.lastHearingCourtId);
}
| package uk.gov.hmcts.opal.repository.jpa;
public class DefendantAccountSpecs {
public static Specification<DefendantAccountEntity> findByAccountSearch(AccountSearchDto accountSearchDto) {
return Specification.allOf(specificationList(
notBlank(accountSearchDto.getSurname()).map(DefendantAccountSpecs::likeSurname),
notBlank(accountSearchDto.getForename()).map(DefendantAccountSpecs::likeForename),
notBlank(accountSearchDto.getInitials()).map(DefendantAccountSpecs::likeInitials),
notBlank(accountSearchDto.getNiNumber()).map(DefendantAccountSpecs::likeNiNumber),
notBlank(accountSearchDto.getAddressLineOne()).map(DefendantAccountSpecs::likeAddressLine1),
notNullLocalDate(accountSearchDto.getDateOfBirth()).map(DefendantAccountSpecs::equalsDateOfBirth),
Optional.ofNullable(accountSearchDto.getCourt()).filter(s -> s.matches("[0-9]+")).map(Long::parseLong)
.map(DefendantAccountSpecs::equalsAnyCourtId)
));
}
@SafeVarargs
public static List<Specification<DefendantAccountEntity>> specificationList(
Optional<Specification<DefendantAccountEntity>>... optionalSpecs) {
return Arrays.stream(optionalSpecs)
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toList());
}
public static Optional<String> notBlank(String candidate) {
return Optional.ofNullable(candidate).filter(s -> !s.isBlank());
}
public static Optional<LocalDate> notNullLocalDate(DateDto candidate) {
return Optional.ofNullable(candidate).map(DateDto::toLocalDate);
}
public static Specification<DefendantAccountEntity> equalsAccountNumber(String accountNo) {
return (root, query, builder) -> {
return builder.equal(root.get(DefendantAccountEntity_.accountNumber), accountNo);
};
}
public static Specification<DefendantAccountEntity> equalsAnyCourtId(Long courtId) {
return Specification.anyOf(
equalsImposingCourtId(courtId),
equalsEnforcingCourtId(courtId),
equalsLastHearingCourtId(courtId));
}
public static Specification<DefendantAccountEntity> equalsImposingCourtId(Long courtId) {
return (root, query, builder) -> {
return builder.equal(root.get(DefendantAccountEntity_.imposingCourtId), courtId);
};
}
public static Specification<DefendantAccountEntity> equalsEnforcingCourtId(Long courtId) {
return (root, query, builder) -> {
return builder.equal(joinEnforcingCourt(root).get(CourtsEntity_.courtId), courtId);
};
}
public static Specification<DefendantAccountEntity> equalsLastHearingCourtId(Long courtId) {
return (root, query, builder) -> {
return builder.equal(joinLastHearingCourt(root).get(CourtsEntity_.courtId), courtId);
};
}
public static Specification<DefendantAccountEntity> likeSurname(String surname) {
return (root, query, builder) -> {
return builder.like(joinPartyOnAssociationType(root, builder, "Defendant")
.get(PartyEntity_.surname), "%" + surname + "%");
};
}
public static Specification<DefendantAccountEntity> likeForename(String forename) {
return (root, query, builder) -> {
return builder.like(joinPartyOnAssociationType(root, builder, "Defendant")
.get(PartyEntity_.forenames), "%" + forename + "%");
};
}
public static Specification<DefendantAccountEntity> likeOrganisationName(String organisation) {
return (root, query, builder) -> {
return builder.like(joinPartyOnAssociationType(root, builder, "Defendant")
.get(PartyEntity_.organisationName), "%" + organisation + "%");
};
}
public static Specification<DefendantAccountEntity> equalsDateOfBirth(LocalDate dob) {
return (root, query, builder) -> {
return builder.equal(joinPartyOnAssociationType(root, builder, "Defendant")
.get(PartyEntity_.dateOfBirth), dob);
};
}
public static Specification<DefendantAccountEntity> likeNiNumber(String niNumber) {
return (root, query, builder) -> {
return builder.like(joinPartyOnAssociationType(root, builder, "Defendant")
.get(PartyEntity_.niNumber), "%" + niNumber + "%");
};
}
public static Specification<DefendantAccountEntity> likeAddressLine1(String addressLine) {
return (root, query, builder) -> {
return builder.like(joinPartyOnAssociationType(root, builder, "Defendant")
.get(PartyEntity_.addressLine1), "%" + addressLine + "%");
};
}
public static Specification<DefendantAccountEntity> likeInitials(String initials) {
return (root, query, builder) -> {
return builder.like(joinPartyOnAssociationType(root, builder, "Defendant")
.get(PartyEntity_.initials), "%" + initials + "%");
};
}
public static Join<DefendantAccountEntity, CourtsEntity> joinEnforcingCourt(Root<DefendantAccountEntity> root) {
return root.join(DefendantAccountEntity_.enforcingCourtId);
}
public static Join<DefendantAccountEntity, CourtsEntity> joinLastHearingCourt(Root<DefendantAccountEntity> root) {
return root.join(DefendantAccountEntity_.lastHearingCourtId);
}
| public static Join<DefendantAccountPartiesEntity, PartyEntity> joinPartyOnAssociationType( | 4 | 2023-10-23 14:12:11+00:00 | 8k |
IronRiders/MockSeason23-24 | src/main/java/org/ironriders/robot/RobotContainer.java | [
{
"identifier": "DriveCommands",
"path": "src/main/java/org/ironriders/commands/DriveCommands.java",
"snippet": "public class DriveCommands {\n private final DriveSubsystem drive;\n private final SwerveDrive swerve;\n private final VisionSubsystem vision;\n\n public DriveCommands(DriveSubsys... | import com.pathplanner.lib.auto.AutoBuilder;
import edu.wpi.first.wpilibj.smartdashboard.SendableChooser;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import edu.wpi.first.wpilibj2.command.Command;
import edu.wpi.first.wpilibj2.command.Commands;
import edu.wpi.first.wpilibj2.command.button.CommandJoystick;
import edu.wpi.first.wpilibj2.command.button.CommandXboxController;
import org.ironriders.commands.DriveCommands;
import org.ironriders.commands.RobotCommands;
import org.ironriders.constants.Ports;
import org.ironriders.constants.Teleop;
import org.ironriders.lib.Utils;
import org.ironriders.subsystems.ArmSubsystem;
import org.ironriders.subsystems.DriveSubsystem;
import org.ironriders.subsystems.ManipulatorSubsystem;
import static org.ironriders.constants.Auto.DEFAULT_AUTO;
import static org.ironriders.constants.Teleop.Controllers.Joystick;
import static org.ironriders.constants.Teleop.Speed.DEADBAND;
import static org.ironriders.constants.Teleop.Speed.MIN_MULTIPLIER; | 6,095 | // Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
package org.ironriders.robot;
/**
* This class is where the bulk of the robot should be declared. Since Command-based is a
* "declarative" paradigm, very little robot logic should actually be handled in the {@link Robot}
* periodic methods (other than the scheduler calls). Instead, the structure of the robot (including
* subsystems, commands, and trigger mappings) should be declared here.
*/
public class RobotContainer {
private final DriveSubsystem drive = new DriveSubsystem();
private final ManipulatorSubsystem manipulator = new ManipulatorSubsystem();
private final ArmSubsystem arm = new ArmSubsystem();
private final CommandXboxController primaryController =
new CommandXboxController(Ports.Controllers.PRIMARY_CONTROLLER);
private final CommandJoystick secondaryController =
new CommandJoystick(Ports.Controllers.SECONDARY_CONTROLLER);
private final RobotCommands commands = new RobotCommands(arm, drive, manipulator);
private final DriveCommands driveCommands = drive.getCommands();
private final SendableChooser<String> autoOptionSelector = new SendableChooser<>();
/**
* The container for the robot. Contains subsystems, IO devices, and commands.
*/
public RobotContainer() {
for (String auto : AutoBuilder.getAllAutoNames()) {
if (auto.equals("REGISTERED_COMMANDS")) continue;
autoOptionSelector.addOption(auto, auto);
} | // Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
package org.ironriders.robot;
/**
* This class is where the bulk of the robot should be declared. Since Command-based is a
* "declarative" paradigm, very little robot logic should actually be handled in the {@link Robot}
* periodic methods (other than the scheduler calls). Instead, the structure of the robot (including
* subsystems, commands, and trigger mappings) should be declared here.
*/
public class RobotContainer {
private final DriveSubsystem drive = new DriveSubsystem();
private final ManipulatorSubsystem manipulator = new ManipulatorSubsystem();
private final ArmSubsystem arm = new ArmSubsystem();
private final CommandXboxController primaryController =
new CommandXboxController(Ports.Controllers.PRIMARY_CONTROLLER);
private final CommandJoystick secondaryController =
new CommandJoystick(Ports.Controllers.SECONDARY_CONTROLLER);
private final RobotCommands commands = new RobotCommands(arm, drive, manipulator);
private final DriveCommands driveCommands = drive.getCommands();
private final SendableChooser<String> autoOptionSelector = new SendableChooser<>();
/**
* The container for the robot. Contains subsystems, IO devices, and commands.
*/
public RobotContainer() {
for (String auto : AutoBuilder.getAllAutoNames()) {
if (auto.equals("REGISTERED_COMMANDS")) continue;
autoOptionSelector.addOption(auto, auto);
} | autoOptionSelector.setDefaultOption(DEFAULT_AUTO, DEFAULT_AUTO); | 8 | 2023-10-23 20:31:46+00:00 | 8k |
ChrisGenti/DiscordTickets | src/main/java/com/github/chrisgenti/discordtickets/DiscordTickets.java | [
{
"identifier": "CommandListener",
"path": "src/main/java/com/github/chrisgenti/discordtickets/listeners/CommandListener.java",
"snippet": "public class CommandListener implements SlashCommandCreateListener {\n private final DiscordApi discordAPI;\n private final MongoManager mongoManager;\n pr... | import com.github.chrisgenti.discordtickets.listeners.CommandListener;
import com.github.chrisgenti.discordtickets.listeners.menus.MenuListener;
import com.github.chrisgenti.discordtickets.listeners.modals.ModalListener;
import com.github.chrisgenti.discordtickets.managers.TicketManager;
import com.github.chrisgenti.discordtickets.managers.mongo.MongoManager;
import com.github.chrisgenti.discordtickets.tools.ObjectTriple;
import com.github.chrisgenti.discordtickets.tools.enums.files.FileResult;
import com.github.chrisgenti.discordtickets.tools.utils.files.FileUtil;
import com.github.chrisgenti.discordtickets.tools.utils.messages.MessageUtil;
import org.javacord.api.DiscordApi;
import org.javacord.api.DiscordApiBuilder;
import org.javacord.api.entity.intent.Intent;
import org.javacord.api.entity.permission.PermissionType;
import org.javacord.api.interaction.SlashCommand;
import org.jetbrains.annotations.NotNull;
import org.tinylog.Logger;
import java.nio.file.Paths;
import java.text.DecimalFormat; | 6,473 | package com.github.chrisgenti.discordtickets;
public class DiscordTickets {
private final DecimalFormat decimalFormat = new DecimalFormat("##0,000");
private DiscordApi discord;
private MongoManager mongoManager;
private TicketManager ticketManager;
public static final String CONFIG_LOCATION = System.getProperty("config.location", "config.json");
public void init() {
/*
LAUNCH MESSAGE
*/
Logger.info(MessageUtil.LAUNCH_MESSAGE);
/*
LOAD
*/
this.load();
}
private void load() {
long mills = System.currentTimeMillis();
| package com.github.chrisgenti.discordtickets;
public class DiscordTickets {
private final DecimalFormat decimalFormat = new DecimalFormat("##0,000");
private DiscordApi discord;
private MongoManager mongoManager;
private TicketManager ticketManager;
public static final String CONFIG_LOCATION = System.getProperty("config.location", "config.json");
public void init() {
/*
LAUNCH MESSAGE
*/
Logger.info(MessageUtil.LAUNCH_MESSAGE);
/*
LOAD
*/
this.load();
}
private void load() {
long mills = System.currentTimeMillis();
| ObjectTriple<FileResult, DiscordData, Exception> objectTriple = FileUtil.loadData(Paths.get(CONFIG_LOCATION)); | 5 | 2023-10-23 13:24:05+00:00 | 8k |
moonstoneid/aero-cast | apps/feed-aggregator/src/main/java/com/moonstoneid/aerocast/aggregator/eth/EthPublisherAdapter.java | [
{
"identifier": "BaseEthAdapter",
"path": "apps/feed-common/src/main/java/com/moonstoneid/aerocast/common/eth/BaseEthAdapter.java",
"snippet": "public abstract class BaseEthAdapter {\n\n private static final BigInteger GAS_LIMIT = BigInteger.valueOf(6721975L);\n private static final BigInteger GAS... | import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import com.moonstoneid.aerocast.common.eth.BaseEthAdapter;
import com.moonstoneid.aerocast.common.eth.EthUtil;
import com.moonstoneid.aerocast.common.eth.contracts.FeedPublisher;
import com.moonstoneid.aerocast.common.eth.contracts.FeedPublisher.NewPubItemEventResponse;
import com.moonstoneid.aerocast.common.eth.contracts.FeedPublisher.PubItem;
import io.reactivex.disposables.Disposable;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.web3j.crypto.Credentials;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.methods.request.EthFilter; | 5,824 | package com.moonstoneid.aerocast.aggregator.eth;
@Component
@Slf4j
public class EthPublisherAdapter extends BaseEthAdapter {
public interface EventListener { | package com.moonstoneid.aerocast.aggregator.eth;
@Component
@Slf4j
public class EthPublisherAdapter extends BaseEthAdapter {
public interface EventListener { | void onNewPubItem(String pubContractAddr, String blockNumber, PubItem pubItem); | 4 | 2023-10-23 20:33:07+00:00 | 8k |
UnityFoundation-io/Libre311 | app/src/test/java/app/JurisdictionSupportRootControllerTest.java | [
{
"identifier": "ServiceDTO",
"path": "app/src/main/java/app/dto/service/ServiceDTO.java",
"snippet": "@Introspected\npublic class ServiceDTO {\n\n @JsonProperty(\"service_code\")\n private String serviceCode;\n\n @JsonProperty(\"jurisdiction_id\")\n private String jurisdictionId;\n\n @Js... | import app.dto.service.ServiceDTO;
import app.dto.servicerequest.PostRequestServiceRequestDTO;
import app.dto.servicerequest.PostResponseServiceRequestDTO;
import app.dto.servicerequest.ServiceRequestDTO;
import app.model.service.ServiceRepository;
import app.model.servicerequest.ServiceRequestRepository;
import app.util.DbCleanup;
import app.util.MockAuthenticationFetcher;
import app.util.MockReCaptchaService;
import app.util.MockSecurityService;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.opencsv.CSVReader;
import com.opencsv.exceptions.CsvValidationException;
import io.micronaut.core.util.StringUtils;
import io.micronaut.http.HttpRequest;
import io.micronaut.http.HttpResponse;
import io.micronaut.http.HttpStatus;
import io.micronaut.http.MediaType;
import io.micronaut.http.client.HttpClient;
import io.micronaut.http.client.annotation.Client;
import io.micronaut.http.client.exceptions.HttpClientResponseException;
import io.micronaut.test.extensions.junit5.annotation.MicronautTest;
import jakarta.inject.Inject;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Map;
import java.util.Optional;
import static io.micronaut.http.HttpStatus.INTERNAL_SERVER_ERROR;
import static io.micronaut.http.HttpStatus.UNAUTHORIZED;
import static org.junit.jupiter.api.Assertions.*; | 6,761 | // Copyright 2023 Libre311 Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package app;
@MicronautTest(environments={"test-jurisdiction-support"})
public class JurisdictionSupportRootControllerTest {
@Inject
@Client("/api")
HttpClient client;
@Inject
MockReCaptchaService mockReCaptchaService;
@Inject
ServiceRepository serviceRepository;
@Inject
ServiceRequestRepository serviceRequestRepository;
@Inject
MockSecurityService mockSecurityService;
@Inject
MockAuthenticationFetcher mockAuthenticationFetcher;
@Inject | // Copyright 2023 Libre311 Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package app;
@MicronautTest(environments={"test-jurisdiction-support"})
public class JurisdictionSupportRootControllerTest {
@Inject
@Client("/api")
HttpClient client;
@Inject
MockReCaptchaService mockReCaptchaService;
@Inject
ServiceRepository serviceRepository;
@Inject
ServiceRequestRepository serviceRequestRepository;
@Inject
MockSecurityService mockSecurityService;
@Inject
MockAuthenticationFetcher mockAuthenticationFetcher;
@Inject | DbCleanup dbCleanup; | 6 | 2023-10-18 15:37:36+00:00 | 8k |
JonnyOnlineYT/xenza | src/minecraft/net/augustus/modules/player/Regen.java | [
{
"identifier": "EventTick",
"path": "src/minecraft/net/augustus/events/EventTick.java",
"snippet": "public class EventTick extends Event {\n}"
},
{
"identifier": "Categorys",
"path": "src/minecraft/net/augustus/modules/Categorys.java",
"snippet": "public enum Categorys {\n MOVEMENT,\... | import java.awt.Color;
import net.augustus.events.EventTick;
import net.augustus.modules.Categorys;
import net.augustus.modules.Module;
import net.augustus.settings.BooleanValue;
import net.augustus.settings.DoubleValue;
import net.lenni0451.eventapi.reflection.EventTarget;
import net.minecraft.network.play.client.C03PacketPlayer; | 4,132 | package net.augustus.modules.player;
public class Regen extends Module {
public final DoubleValue health = new DoubleValue(2, "Health", this, 20.0, 0.0, 20.0, 0);
public final DoubleValue hunger = new DoubleValue(1, "MinHunger", this, 5.0, 0.0, 20.0, 0);
public final DoubleValue packets = new DoubleValue(3, "Packets", this, 100.0, 0.0, 200.0, 0);
public final BooleanValue groundCheck = new BooleanValue(4, "GroundCheck", this, false);
public Regen() {
super("Regen", new Color(224, 111, 49), Categorys.PLAYER);
}
@EventTarget
public void onEventTick(EventTick eventTick) {
if ((double)mc.thePlayer.getFoodStats().getFoodLevel() > this.hunger.getValue() && (double)mc.thePlayer.getHealth() < this.health.getValue()) {
for(int i = 0; (double)i < this.packets.getValue(); ++i) {
if (this.groundCheck.getBoolean()) { | package net.augustus.modules.player;
public class Regen extends Module {
public final DoubleValue health = new DoubleValue(2, "Health", this, 20.0, 0.0, 20.0, 0);
public final DoubleValue hunger = new DoubleValue(1, "MinHunger", this, 5.0, 0.0, 20.0, 0);
public final DoubleValue packets = new DoubleValue(3, "Packets", this, 100.0, 0.0, 200.0, 0);
public final BooleanValue groundCheck = new BooleanValue(4, "GroundCheck", this, false);
public Regen() {
super("Regen", new Color(224, 111, 49), Categorys.PLAYER);
}
@EventTarget
public void onEventTick(EventTick eventTick) {
if ((double)mc.thePlayer.getFoodStats().getFoodLevel() > this.hunger.getValue() && (double)mc.thePlayer.getHealth() < this.health.getValue()) {
for(int i = 0; (double)i < this.packets.getValue(); ++i) {
if (this.groundCheck.getBoolean()) { | mc.thePlayer.sendQueue.addToSendQueueDirect(new C03PacketPlayer(mc.thePlayer.onGround)); | 5 | 2023-10-15 00:21:15+00:00 | 8k |
Radekyspec/TasksMaster | src/main/java/data_access/HttpDataAccessObject.java | [
{
"identifier": "LoginUserDataAccessInterface",
"path": "src/main/java/data_access/login/LoginUserDataAccessInterface.java",
"snippet": "public interface LoginUserDataAccessInterface {\n User login(String username, String password);\n}"
},
{
"identifier": "MessageBoardUserDataAccessInterface"... | import data_access.login.LoginUserDataAccessInterface;
import data_access.message_board.MessageBoardUserDataAccessInterface;
import data_access.project.ProjectUserDataAccessInterface;
import data_access.project.add.AddProjectUserDataAccessInterface;
import data_access.project.choose.ChooseProjectUserDataAccessInterface;
import data_access.schedule.ScheduleDataAccessInterface;
import data_access.signup.SignupUserDataAccessInterface;
import data_access.todo.add.AddToDoUserDataAccessInterface;
import data_access.todolist.ToDoListDataAccessInterface;
import data_access.todolist.add.AddToDoListUserDataAccessInterface;
import data_access.todopanel.ToDoPanelDataAccessInterface;
import entities.comment.Comment;
import entities.comment.CommonCommentFactory;
import entities.event.CommonEventFactory;
import entities.event.Event;
import entities.message.CommonMessageFactory;
import entities.message.Message;
import entities.message_board.CommonMessageBoardFactory;
import entities.project.CommonProjectFactory;
import entities.project.Project;
import entities.schedule.CommonScheduleFactory;
import entities.todo.CommonToDoFactory;
import entities.todo.ToDo;
import entities.todo_list.CommonToDoListFactory;
import entities.todo_list.ToDoList;
import entities.todo_panel.CommonToDoPanelFactory;
import entities.user.User;
import exceptions.InvalidApiKeyException;
import okhttp3.*;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors; | 5,141 | package data_access;
public abstract class HttpDataAccessObject implements SignupUserDataAccessInterface,
LoginUserDataAccessInterface, ProjectUserDataAccessInterface, ChooseProjectUserDataAccessInterface,
AddProjectUserDataAccessInterface, MessageBoardUserDataAccessInterface,
AddToDoUserDataAccessInterface, ToDoListDataAccessInterface, AddToDoListUserDataAccessInterface,
ToDoPanelDataAccessInterface, ScheduleDataAccessInterface {
private final String API_KEY;
private final OkHttpClient client = new OkHttpClient().newBuilder()
.build();
private long orgId;
private String error;
public HttpDataAccessObject(String apiKey) throws InvalidApiKeyException {
API_KEY = apiKey;
if (!isValidApiKey()) {
throw new InvalidApiKeyException(getApiErrorMessage());
}
}
private Request.Builder buildRequest() {
return new Request.Builder()
.addHeader("Authorization", "Bearer " + API_KEY)
.addHeader("Content-Type", "application/json; charset=utf-8")
.addHeader("User-Agent", "TasksMaster (w41k3r15347@gmail.com)");
}
private boolean isValidApiKey() {
if (API_KEY == null || API_KEY.isEmpty() || API_KEY.isBlank()) {
return false;
}
Request request = buildRequest()
.url("https://launchpad.37signals.com/authorization.json")
.build();
try {
Response response = client.newCall(request).execute();
if (response.code() != 200 || response.body() == null) {
setErrorMessage("Network Error");
return false;
}
JSONObject lastResponse = new JSONObject(response.body().string());
if (!lastResponse.has("error")) {
orgId = lastResponse.getJSONArray("accounts").getJSONObject(0).getLong("id");
return true;
}
setErrorMessage(lastResponse.getString("error"));
} catch (IOException e) {
setErrorMessage("Network Error");
return false;
}
return false;
}
public String getApiErrorMessage() {
if (API_KEY == null || API_KEY.isEmpty() || API_KEY.isBlank()) {
return "API key is empty.";
}
return error;
}
private void setErrorMessage(String message) {
this.error = message;
}
private Project jsonToProject(JSONObject projectJson) {
JSONObject projectInfo = new JSONObject(projectJson.getString("description"));
Project project = CommonProjectFactory.create(projectJson.getLong("id"),
projectJson.getString("name"),
projectInfo.getString("description"));
project.setLeader(projectInfo.getString("owner"));
JSONArray members = projectInfo.getJSONArray("members");
for (int i = 0; i < members.length(); i++) {
project.addNewMember(members.getString(i));
}
JSONArray docks = projectJson.getJSONArray("dock");
long toDoPanelId = 0, messageBoardId = 0, scheduleId = 0;
for (int j = 0; j < docks.length(); j++) {
JSONObject dock = docks.getJSONObject(j);
switch (dock.getString("name")) {
case "message_board" -> messageBoardId = dock.getLong("id");
case "todoset" -> toDoPanelId = dock.getLong("id");
case "schedule" -> scheduleId = dock.getLong("id");
}
} | package data_access;
public abstract class HttpDataAccessObject implements SignupUserDataAccessInterface,
LoginUserDataAccessInterface, ProjectUserDataAccessInterface, ChooseProjectUserDataAccessInterface,
AddProjectUserDataAccessInterface, MessageBoardUserDataAccessInterface,
AddToDoUserDataAccessInterface, ToDoListDataAccessInterface, AddToDoListUserDataAccessInterface,
ToDoPanelDataAccessInterface, ScheduleDataAccessInterface {
private final String API_KEY;
private final OkHttpClient client = new OkHttpClient().newBuilder()
.build();
private long orgId;
private String error;
public HttpDataAccessObject(String apiKey) throws InvalidApiKeyException {
API_KEY = apiKey;
if (!isValidApiKey()) {
throw new InvalidApiKeyException(getApiErrorMessage());
}
}
private Request.Builder buildRequest() {
return new Request.Builder()
.addHeader("Authorization", "Bearer " + API_KEY)
.addHeader("Content-Type", "application/json; charset=utf-8")
.addHeader("User-Agent", "TasksMaster (w41k3r15347@gmail.com)");
}
private boolean isValidApiKey() {
if (API_KEY == null || API_KEY.isEmpty() || API_KEY.isBlank()) {
return false;
}
Request request = buildRequest()
.url("https://launchpad.37signals.com/authorization.json")
.build();
try {
Response response = client.newCall(request).execute();
if (response.code() != 200 || response.body() == null) {
setErrorMessage("Network Error");
return false;
}
JSONObject lastResponse = new JSONObject(response.body().string());
if (!lastResponse.has("error")) {
orgId = lastResponse.getJSONArray("accounts").getJSONObject(0).getLong("id");
return true;
}
setErrorMessage(lastResponse.getString("error"));
} catch (IOException e) {
setErrorMessage("Network Error");
return false;
}
return false;
}
public String getApiErrorMessage() {
if (API_KEY == null || API_KEY.isEmpty() || API_KEY.isBlank()) {
return "API key is empty.";
}
return error;
}
private void setErrorMessage(String message) {
this.error = message;
}
private Project jsonToProject(JSONObject projectJson) {
JSONObject projectInfo = new JSONObject(projectJson.getString("description"));
Project project = CommonProjectFactory.create(projectJson.getLong("id"),
projectJson.getString("name"),
projectInfo.getString("description"));
project.setLeader(projectInfo.getString("owner"));
JSONArray members = projectInfo.getJSONArray("members");
for (int i = 0; i < members.length(); i++) {
project.addNewMember(members.getString(i));
}
JSONArray docks = projectJson.getJSONArray("dock");
long toDoPanelId = 0, messageBoardId = 0, scheduleId = 0;
for (int j = 0; j < docks.length(); j++) {
JSONObject dock = docks.getJSONObject(j);
switch (dock.getString("name")) {
case "message_board" -> messageBoardId = dock.getLong("id");
case "todoset" -> toDoPanelId = dock.getLong("id");
case "schedule" -> scheduleId = dock.getLong("id");
}
} | project.setToDoPanel(CommonToDoPanelFactory.create(toDoPanelId)); | 25 | 2023-10-23 15:17:21+00:00 | 8k |
denis-vp/toy-language-interpreter | src/main/java/view/cli/CliInterpreter.java | [
{
"identifier": "Controller",
"path": "src/main/java/controller/Controller.java",
"snippet": "public class Controller {\n private final IRepository repository;\n private Boolean logOutput;\n private final ExecutorService executor = Executors.newFixedThreadPool(8);\n\n public Controller(IRepo... | import adt.*;
import controller.Controller;
import programgenerator.ProgramGenerator;
import model.ProgramState;
import model.statement.Statement;
import repository.IRepository;
import repository.Repository;
import view.cli.commands.ExitCommand;
import view.cli.commands.RunExampleCommand;
import java.util.List;
import java.util.Objects;
import java.util.Scanner; | 5,195 | package view.cli;
public class CliInterpreter {
public static void main(String[] args) {
TextMenu menu = new TextMenu();
CliInterpreter.addCommands(CliInterpreter.getLogFile(), menu);
menu.show();
}
private static String getLogFile() {
String logFilePath = "./logs/";
Scanner scanner = new Scanner(System.in);
System.out.print("Please enter the log file name: ");
String input = scanner.nextLine();
if (Objects.equals(input, "")) {
logFilePath += "log.txt";
} else {
logFilePath += input;
}
return logFilePath;
}
private static void addCommands(String logFilePath, TextMenu menu) {
List<Statement> programs = ProgramGenerator.getPrograms();
for (int i = 0; i < programs.size(); i++) {
Statement program = programs.get(i);
ProgramState programState = new ProgramState(program, new MyStack<>(), new MyDictionary<>(),
new MyHeap(), new MyConcurrentDictionary<>(), new MyList<>());
IRepository repository = new Repository(programState, logFilePath);
Controller controller = new Controller(repository, true);
| package view.cli;
public class CliInterpreter {
public static void main(String[] args) {
TextMenu menu = new TextMenu();
CliInterpreter.addCommands(CliInterpreter.getLogFile(), menu);
menu.show();
}
private static String getLogFile() {
String logFilePath = "./logs/";
Scanner scanner = new Scanner(System.in);
System.out.print("Please enter the log file name: ");
String input = scanner.nextLine();
if (Objects.equals(input, "")) {
logFilePath += "log.txt";
} else {
logFilePath += input;
}
return logFilePath;
}
private static void addCommands(String logFilePath, TextMenu menu) {
List<Statement> programs = ProgramGenerator.getPrograms();
for (int i = 0; i < programs.size(); i++) {
Statement program = programs.get(i);
ProgramState programState = new ProgramState(program, new MyStack<>(), new MyDictionary<>(),
new MyHeap(), new MyConcurrentDictionary<>(), new MyList<>());
IRepository repository = new Repository(programState, logFilePath);
Controller controller = new Controller(repository, true);
| menu.addCommand(new RunExampleCommand(String.valueOf(i + 1), "run example " + (i + 1), controller)); | 7 | 2023-10-21 18:08:59+00:00 | 8k |
NewStudyGround/NewStudyGround | server/src/main/java/com/codestates/server/domain/comment/controller/CommentController.java | [
{
"identifier": "Answer",
"path": "server/src/main/java/com/codestates/server/domain/answer/entity/Answer.java",
"snippet": "@Entity\n@Getter\n@Setter\npublic class Answer {\n\n\t@Id\n\t@GeneratedValue(strategy = GenerationType.IDENTITY)\n\tprivate Long answerId;\n\n\t@Column(length = 10000, nullable = ... | import com.codestates.server.domain.answer.entity.Answer;
import com.codestates.server.domain.answer.service.AnswerService;
import com.codestates.server.domain.comment.dto.CommentPatchDto;
import com.codestates.server.domain.comment.dto.CommentPostDto;
import com.codestates.server.domain.comment.entity.Comment;
import com.codestates.server.domain.comment.mapper.CommentMapper;
import com.codestates.server.domain.comment.service.CommentService;
import com.codestates.server.domain.member.entity.Member;
import com.codestates.server.domain.member.service.MemberService;
import com.codestates.server.global.uri.UriCreator;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.net.URI;
import java.util.Map; | 4,480 | package com.codestates.server.domain.comment.controller;
@RestController
@RequestMapping("/answers/{answer-id}/comments")
@RequiredArgsConstructor
public class CommentController {
private final CommentService commentService;
private final MemberService memberService; | package com.codestates.server.domain.comment.controller;
@RestController
@RequestMapping("/answers/{answer-id}/comments")
@RequiredArgsConstructor
public class CommentController {
private final CommentService commentService;
private final MemberService memberService; | private final AnswerService answerService; | 1 | 2023-10-23 09:41:00+00:00 | 8k |
metacosm/quarkus-power | runtime/src/main/java/io/quarkiverse/power/runtime/sensors/macos/powermetrics/MacOSPowermetricsSensor.java | [
{
"identifier": "PowerMeasure",
"path": "runtime/src/main/java/io/quarkiverse/power/runtime/PowerMeasure.java",
"snippet": "public interface PowerMeasure extends SensorMeasure {\n int numberOfSamples();\n\n long duration();\n\n default double average() {\n return total() / numberOfSample... | import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Optional;
import io.quarkiverse.power.runtime.PowerMeasure;
import io.quarkiverse.power.runtime.PowerMeasurer;
import io.quarkiverse.power.runtime.sensors.OngoingPowerMeasure;
import io.quarkiverse.power.runtime.sensors.PowerSensor;
import io.quarkiverse.power.runtime.sensors.macos.AppleSiliconMeasure; | 3,694 | package io.quarkiverse.power.runtime.sensors.macos.powermetrics;
public class MacOSPowermetricsSensor implements PowerSensor<AppleSiliconMeasure> {
private Process powermetrics;
private final static String pid = " " + ProcessHandle.current().pid() + " ";
private double accumulatedCPUShareDiff = 0.0;
private final int cpu;
private final int gpu;
private final int ane;
public MacOSPowermetricsSensor() {
ane = AppleSiliconMeasure.METADATA.indexFor(AppleSiliconMeasure.ANE);
cpu = AppleSiliconMeasure.METADATA.indexFor(AppleSiliconMeasure.CPU);
gpu = AppleSiliconMeasure.METADATA.indexFor(AppleSiliconMeasure.GPU);
}
private static class ProcessRecord {
final double cpu;
final double gpu;
public ProcessRecord(String line) {
//Name ID CPU ms/s samp ms/s User% Deadlines (<2 ms, 2-5 ms) Wakeups (Intr, Pkg idle) GPU ms/s
//iTerm2 1008 46.66 46.91 83.94 0.00 0.00 30.46 0.00 0.00
final var processData = line.split("\\s+");
cpu = Double.parseDouble(processData[3]);
gpu = Double.parseDouble(processData[9]);
}
}
@Override
public void update(OngoingPowerMeasure ongoingMeasure) {
extractPowerMeasure(ongoingMeasure, powermetrics.getInputStream(), pid, false);
}
AppleSiliconMeasure extractPowerMeasure(InputStream powerMeasureInput, long pid) {
// one measure only
return extractPowerMeasure(new OngoingPowerMeasure(AppleSiliconMeasure.METADATA, 1, 1), powerMeasureInput,
" " + pid + " ",
true);
}
AppleSiliconMeasure extractPowerMeasure(OngoingPowerMeasure ongoingMeasure, InputStream powerMeasureInput,
String paddedPIDAsString, boolean returnCurrent) {
try {
// Should not be closed since it closes the process
BufferedReader input = new BufferedReader(new InputStreamReader(powerMeasureInput));
String line;
double cpuShare = -1, gpuShare = -1;
boolean totalDone = false;
boolean cpuDone = false;
// start measure
ongoingMeasure.startNewMeasure();
while ((line = input.readLine()) != null) {
if (line.isEmpty() || line.startsWith("*")) {
continue;
}
// first, look for process line detailing share
if (cpuShare < 0) {
if (line.contains(paddedPIDAsString)) {
final var procInfo = new ProcessRecord(line);
cpuShare = procInfo.cpu;
gpuShare = procInfo.gpu;
}
continue;
}
if (!totalDone) {
// then skip all lines until we get the totals
if (line.startsWith("ALL_TASKS")) {
final var totals = new ProcessRecord(line);
// compute ratio
cpuShare = cpuShare / totals.cpu;
gpuShare = totals.gpu > 0 ? gpuShare / totals.gpu : 0;
totalDone = true;
}
continue;
}
if (!cpuDone) {
// look for line that contains CPU power measure
if (line.startsWith("CPU Power")) {
final var jmxCpuShare = PowerMeasurer.instance().cpuShareOfJVMProcess();
ongoingMeasure.setComponent(cpu, extractAttributedMeasure(line, cpuShare));
accumulatedCPUShareDiff += (cpuShare - jmxCpuShare);
cpuDone = true;
}
continue;
}
if (line.startsWith("GPU Power")) {
ongoingMeasure.setComponent(gpu, extractAttributedMeasure(line, gpuShare));
continue;
}
if (line.startsWith("ANE Power")) {
ongoingMeasure.setComponent(ane, extractAttributedMeasure(line, 1));
break;
}
}
final var measure = ongoingMeasure.stopMeasure();
return returnCurrent ? new AppleSiliconMeasure(measure) : null;
} catch (Exception exception) {
throw new RuntimeException(exception);
}
}
private static double extractAttributedMeasure(String line, double attributionRatio) {
final var powerValue = line.split(":")[1];
final var powerInMilliwatts = powerValue.split("m")[0];
return Double.parseDouble(powerInMilliwatts) * attributionRatio;
}
@Override
public OngoingPowerMeasure start(long duration, long frequency) throws Exception {
// it takes some time for the external process in addition to the sampling time so adjust the sampling frequency to account for this so that at most one measure occurs during the sampling time window
final var freq = Long.toString(frequency - 50);
powermetrics = Runtime.getRuntime()
.exec("sudo powermetrics --samplers cpu_power,tasks --show-process-samp-norm --show-process-gpu -i " + freq);
accumulatedCPUShareDiff = 0.0;
return new OngoingPowerMeasure(AppleSiliconMeasure.METADATA, duration, frequency);
}
@Override
public void stop() {
powermetrics.destroy();
}
@Override | package io.quarkiverse.power.runtime.sensors.macos.powermetrics;
public class MacOSPowermetricsSensor implements PowerSensor<AppleSiliconMeasure> {
private Process powermetrics;
private final static String pid = " " + ProcessHandle.current().pid() + " ";
private double accumulatedCPUShareDiff = 0.0;
private final int cpu;
private final int gpu;
private final int ane;
public MacOSPowermetricsSensor() {
ane = AppleSiliconMeasure.METADATA.indexFor(AppleSiliconMeasure.ANE);
cpu = AppleSiliconMeasure.METADATA.indexFor(AppleSiliconMeasure.CPU);
gpu = AppleSiliconMeasure.METADATA.indexFor(AppleSiliconMeasure.GPU);
}
private static class ProcessRecord {
final double cpu;
final double gpu;
public ProcessRecord(String line) {
//Name ID CPU ms/s samp ms/s User% Deadlines (<2 ms, 2-5 ms) Wakeups (Intr, Pkg idle) GPU ms/s
//iTerm2 1008 46.66 46.91 83.94 0.00 0.00 30.46 0.00 0.00
final var processData = line.split("\\s+");
cpu = Double.parseDouble(processData[3]);
gpu = Double.parseDouble(processData[9]);
}
}
@Override
public void update(OngoingPowerMeasure ongoingMeasure) {
extractPowerMeasure(ongoingMeasure, powermetrics.getInputStream(), pid, false);
}
AppleSiliconMeasure extractPowerMeasure(InputStream powerMeasureInput, long pid) {
// one measure only
return extractPowerMeasure(new OngoingPowerMeasure(AppleSiliconMeasure.METADATA, 1, 1), powerMeasureInput,
" " + pid + " ",
true);
}
AppleSiliconMeasure extractPowerMeasure(OngoingPowerMeasure ongoingMeasure, InputStream powerMeasureInput,
String paddedPIDAsString, boolean returnCurrent) {
try {
// Should not be closed since it closes the process
BufferedReader input = new BufferedReader(new InputStreamReader(powerMeasureInput));
String line;
double cpuShare = -1, gpuShare = -1;
boolean totalDone = false;
boolean cpuDone = false;
// start measure
ongoingMeasure.startNewMeasure();
while ((line = input.readLine()) != null) {
if (line.isEmpty() || line.startsWith("*")) {
continue;
}
// first, look for process line detailing share
if (cpuShare < 0) {
if (line.contains(paddedPIDAsString)) {
final var procInfo = new ProcessRecord(line);
cpuShare = procInfo.cpu;
gpuShare = procInfo.gpu;
}
continue;
}
if (!totalDone) {
// then skip all lines until we get the totals
if (line.startsWith("ALL_TASKS")) {
final var totals = new ProcessRecord(line);
// compute ratio
cpuShare = cpuShare / totals.cpu;
gpuShare = totals.gpu > 0 ? gpuShare / totals.gpu : 0;
totalDone = true;
}
continue;
}
if (!cpuDone) {
// look for line that contains CPU power measure
if (line.startsWith("CPU Power")) {
final var jmxCpuShare = PowerMeasurer.instance().cpuShareOfJVMProcess();
ongoingMeasure.setComponent(cpu, extractAttributedMeasure(line, cpuShare));
accumulatedCPUShareDiff += (cpuShare - jmxCpuShare);
cpuDone = true;
}
continue;
}
if (line.startsWith("GPU Power")) {
ongoingMeasure.setComponent(gpu, extractAttributedMeasure(line, gpuShare));
continue;
}
if (line.startsWith("ANE Power")) {
ongoingMeasure.setComponent(ane, extractAttributedMeasure(line, 1));
break;
}
}
final var measure = ongoingMeasure.stopMeasure();
return returnCurrent ? new AppleSiliconMeasure(measure) : null;
} catch (Exception exception) {
throw new RuntimeException(exception);
}
}
private static double extractAttributedMeasure(String line, double attributionRatio) {
final var powerValue = line.split(":")[1];
final var powerInMilliwatts = powerValue.split("m")[0];
return Double.parseDouble(powerInMilliwatts) * attributionRatio;
}
@Override
public OngoingPowerMeasure start(long duration, long frequency) throws Exception {
// it takes some time for the external process in addition to the sampling time so adjust the sampling frequency to account for this so that at most one measure occurs during the sampling time window
final var freq = Long.toString(frequency - 50);
powermetrics = Runtime.getRuntime()
.exec("sudo powermetrics --samplers cpu_power,tasks --show-process-samp-norm --show-process-gpu -i " + freq);
accumulatedCPUShareDiff = 0.0;
return new OngoingPowerMeasure(AppleSiliconMeasure.METADATA, duration, frequency);
}
@Override
public void stop() {
powermetrics.destroy();
}
@Override | public Optional<String> additionalInfo(PowerMeasure measure) { | 0 | 2023-10-23 16:44:57+00:00 | 8k |
LeGhast/Miniaturise | src/main/java/de/leghast/miniaturise/listener/PlayerInteractListener.java | [
{
"identifier": "Miniaturise",
"path": "src/main/java/de/leghast/miniaturise/Miniaturise.java",
"snippet": "public final class Miniaturise extends JavaPlugin {\n\n private MiniatureManager miniatureManager;\n private RegionManager regionManager;\n private SettingsManager settingsManager;\n\n ... | import de.leghast.miniaturise.Miniaturise;
import de.leghast.miniaturise.instance.miniature.PlacedMiniature;
import de.leghast.miniaturise.instance.region.SelectedLocations;
import de.leghast.miniaturise.instance.settings.AdjusterSettings;
import de.leghast.miniaturise.manager.ConfigManager;
import de.leghast.miniaturise.ui.UserInterface;
import de.leghast.miniaturise.util.Util;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.EquipmentSlot; | 4,555 | package de.leghast.miniaturise.listener;
/**
* This class listens for player interactions, that are relevant for the Miniaturise plugin
* @author GhastCraftHD
* */
public class PlayerInteractListener implements Listener {
private Miniaturise main;
public PlayerInteractListener(Miniaturise main){
this.main = main;
}
@EventHandler
public void onPlayerInteract(PlayerInteractEvent e){
Player player = e.getPlayer();
Material material = player.getInventory().getItemInMainHand().getType();
if(player.hasPermission("miniaturise.use")){
if(material == ConfigManager.getSelectorToolMaterial()){
e.setCancelled(true);
handleSelectorInteraction(player, e.getAction(), e.getClickedBlock(), e.getHand());
}else if(material == ConfigManager.getAdjusterToolMaterial()){
e.setCancelled(true);
if(main.getMiniatureManager().hasPlacedMiniature(player.getUniqueId())){
handleAdjusterInteraction(player, e.getAction(), e.getHand());
}else{
player.sendMessage(Util.PREFIX + "§cYou have not selected a placed miniature");
}
}
}
}
private void handleSelectorInteraction(Player player, Action action, Block block, EquipmentSlot hand){
switch (action){
case LEFT_CLICK_BLOCK -> {
if (main.getRegionManager().hasSelectedLocations(player.getUniqueId())) {
main.getRegionManager().getSelectedLocations(player.getUniqueId()).setLoc1(block.getLocation());
} else {
main.getRegionManager().addSelectedLocations(player.getUniqueId(), new SelectedLocations(block.getLocation(), null));
}
player.sendMessage(Util.PREFIX + "§aThe first position was set to §e" +
(int) block.getLocation().getX() + ", " +
(int) block.getLocation().getY() + ", " +
(int) block.getLocation().getZ() + " §a(" +
Util.getDimensionName(block.getLocation().getWorld().getEnvironment().name()) + ")");
}
case RIGHT_CLICK_BLOCK -> {
if(hand == EquipmentSlot.HAND){
if (main.getRegionManager().hasSelectedLocations(player.getUniqueId())) {
main.getRegionManager().getSelectedLocations(player.getUniqueId()).setLoc2(block.getLocation());
} else {
main.getRegionManager().addSelectedLocations(player.getUniqueId(), new SelectedLocations(null, block.getLocation()));
}
player.sendMessage(Util.PREFIX + "§aThe second position was set to §e" +
(int) block.getLocation().getX() + ", " +
(int) block.getLocation().getY() + ", " +
(int) block.getLocation().getZ()+ " §a(" +
Util.getDimensionName(block.getLocation().getWorld().getEnvironment().name()) + ")");
}
}
}
}
private void handleAdjusterInteraction(Player player, Action action, EquipmentSlot hand){
if(!main.getSettingsManager().hasAdjusterSettings(player.getUniqueId())){
main.getSettingsManager().addAdjusterSettings(player.getUniqueId());
}
if(action.isLeftClick()){ | package de.leghast.miniaturise.listener;
/**
* This class listens for player interactions, that are relevant for the Miniaturise plugin
* @author GhastCraftHD
* */
public class PlayerInteractListener implements Listener {
private Miniaturise main;
public PlayerInteractListener(Miniaturise main){
this.main = main;
}
@EventHandler
public void onPlayerInteract(PlayerInteractEvent e){
Player player = e.getPlayer();
Material material = player.getInventory().getItemInMainHand().getType();
if(player.hasPermission("miniaturise.use")){
if(material == ConfigManager.getSelectorToolMaterial()){
e.setCancelled(true);
handleSelectorInteraction(player, e.getAction(), e.getClickedBlock(), e.getHand());
}else if(material == ConfigManager.getAdjusterToolMaterial()){
e.setCancelled(true);
if(main.getMiniatureManager().hasPlacedMiniature(player.getUniqueId())){
handleAdjusterInteraction(player, e.getAction(), e.getHand());
}else{
player.sendMessage(Util.PREFIX + "§cYou have not selected a placed miniature");
}
}
}
}
private void handleSelectorInteraction(Player player, Action action, Block block, EquipmentSlot hand){
switch (action){
case LEFT_CLICK_BLOCK -> {
if (main.getRegionManager().hasSelectedLocations(player.getUniqueId())) {
main.getRegionManager().getSelectedLocations(player.getUniqueId()).setLoc1(block.getLocation());
} else {
main.getRegionManager().addSelectedLocations(player.getUniqueId(), new SelectedLocations(block.getLocation(), null));
}
player.sendMessage(Util.PREFIX + "§aThe first position was set to §e" +
(int) block.getLocation().getX() + ", " +
(int) block.getLocation().getY() + ", " +
(int) block.getLocation().getZ() + " §a(" +
Util.getDimensionName(block.getLocation().getWorld().getEnvironment().name()) + ")");
}
case RIGHT_CLICK_BLOCK -> {
if(hand == EquipmentSlot.HAND){
if (main.getRegionManager().hasSelectedLocations(player.getUniqueId())) {
main.getRegionManager().getSelectedLocations(player.getUniqueId()).setLoc2(block.getLocation());
} else {
main.getRegionManager().addSelectedLocations(player.getUniqueId(), new SelectedLocations(null, block.getLocation()));
}
player.sendMessage(Util.PREFIX + "§aThe second position was set to §e" +
(int) block.getLocation().getX() + ", " +
(int) block.getLocation().getY() + ", " +
(int) block.getLocation().getZ()+ " §a(" +
Util.getDimensionName(block.getLocation().getWorld().getEnvironment().name()) + ")");
}
}
}
}
private void handleAdjusterInteraction(Player player, Action action, EquipmentSlot hand){
if(!main.getSettingsManager().hasAdjusterSettings(player.getUniqueId())){
main.getSettingsManager().addAdjusterSettings(player.getUniqueId());
}
if(action.isLeftClick()){ | PlacedMiniature placedMiniature = main.getMiniatureManager().getPlacedMiniature(player.getUniqueId()); | 1 | 2023-10-15 09:08:33+00:00 | 8k |
zendo-games/zenlib | src/main/java/zendo/games/zenlib/screens/transitions/Transition.java | [
{
"identifier": "ZenConfig",
"path": "src/main/java/zendo/games/zenlib/ZenConfig.java",
"snippet": "public class ZenConfig {\n\n public final Window window;\n public final UI ui;\n\n public ZenConfig() {\n this(\"zenlib\", 1280, 720, null);\n }\n\n public ZenConfig(String title, in... | import aurelienribon.tweenengine.Timeline;
import aurelienribon.tweenengine.Tween;
import aurelienribon.tweenengine.primitives.MutableFloat;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.*;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.glutils.FrameBuffer;
import com.badlogic.gdx.graphics.glutils.ShaderProgram;
import com.badlogic.gdx.utils.Disposable;
import zendo.games.zenlib.ZenConfig;
import zendo.games.zenlib.ZenMain;
import zendo.games.zenlib.assets.ZenTransition;
import zendo.games.zenlib.screens.ZenScreen;
import zendo.games.zenlib.utils.Time; | 4,075 | package zendo.games.zenlib.screens.transitions;
public class Transition implements Disposable {
public static final float DEFAULT_SPEED = 0.66f;
public boolean active;
public MutableFloat percent;
public ShaderProgram shader;
public final Screens screens = new Screens();
public final FrameBuffers fbo = new FrameBuffers();
public final Textures tex = new Textures();
private final ZenConfig config;
public Transition(ZenConfig config) {
this.config = config;
this.active = false;
this.percent = new MutableFloat(0);
this.fbo.from = new FrameBuffer(Pixmap.Format.RGBA8888, config.window.width, config.window.height, false);
this.fbo.to = new FrameBuffer(Pixmap.Format.RGBA8888, config.window.width, config.window.height, false);
this.tex.from = this.fbo.from.getColorBufferTexture();
this.tex.to = this.fbo.to.getColorBufferTexture();
}
@Override
public void dispose() {
screens.dispose();
fbo.dispose();
// no need to dispose textures here,
// they are owned by the frame buffers
}
public void alwaysUpdate(float dt) {
screens.current.alwaysUpdate(dt);
if (screens.next != null) {
screens.next.alwaysUpdate(dt);
}
}
public void update(float dt) {
screens.current.update(dt);
if (screens.next != null) {
screens.next.update(dt);
}
}
public void render(SpriteBatch batch, OrthographicCamera windowCamera) {
screens.next.update(Time.delta);
screens.next.renderFrameBuffers(batch);
// draw the next screen to the 'to' buffer
fbo.to.begin();
{
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
screens.next.render(batch);
}
fbo.to.end();
// draw the current screen to the 'from' buffer
fbo.from.begin();
{
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
screens.current.render(batch);
}
fbo.from.end();
// draw the transition buffer to the screen
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.setShader(shader);
batch.setProjectionMatrix(windowCamera.combined);
batch.begin();
{
tex.from.bind(1);
shader.setUniformi("u_texture1", 1);
tex.to.bind(0);
shader.setUniformi("u_texture", 0);
shader.setUniformf("u_percent", percent.floatValue());
batch.setColor(Color.WHITE);
batch.draw(tex.to, 0, 0, config.window.width, config.window.height);
}
batch.end();
batch.setShader(null);
}
| package zendo.games.zenlib.screens.transitions;
public class Transition implements Disposable {
public static final float DEFAULT_SPEED = 0.66f;
public boolean active;
public MutableFloat percent;
public ShaderProgram shader;
public final Screens screens = new Screens();
public final FrameBuffers fbo = new FrameBuffers();
public final Textures tex = new Textures();
private final ZenConfig config;
public Transition(ZenConfig config) {
this.config = config;
this.active = false;
this.percent = new MutableFloat(0);
this.fbo.from = new FrameBuffer(Pixmap.Format.RGBA8888, config.window.width, config.window.height, false);
this.fbo.to = new FrameBuffer(Pixmap.Format.RGBA8888, config.window.width, config.window.height, false);
this.tex.from = this.fbo.from.getColorBufferTexture();
this.tex.to = this.fbo.to.getColorBufferTexture();
}
@Override
public void dispose() {
screens.dispose();
fbo.dispose();
// no need to dispose textures here,
// they are owned by the frame buffers
}
public void alwaysUpdate(float dt) {
screens.current.alwaysUpdate(dt);
if (screens.next != null) {
screens.next.alwaysUpdate(dt);
}
}
public void update(float dt) {
screens.current.update(dt);
if (screens.next != null) {
screens.next.update(dt);
}
}
public void render(SpriteBatch batch, OrthographicCamera windowCamera) {
screens.next.update(Time.delta);
screens.next.renderFrameBuffers(batch);
// draw the next screen to the 'to' buffer
fbo.to.begin();
{
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
screens.next.render(batch);
}
fbo.to.end();
// draw the current screen to the 'from' buffer
fbo.from.begin();
{
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
screens.current.render(batch);
}
fbo.from.end();
// draw the transition buffer to the screen
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.setShader(shader);
batch.setProjectionMatrix(windowCamera.combined);
batch.begin();
{
tex.from.bind(1);
shader.setUniformi("u_texture1", 1);
tex.to.bind(0);
shader.setUniformi("u_texture", 0);
shader.setUniformf("u_percent", percent.floatValue());
batch.setColor(Color.WHITE);
batch.draw(tex.to, 0, 0, config.window.width, config.window.height);
}
batch.end();
batch.setShader(null);
}
| public void startTransition(final ZenScreen newScreen, ZenTransition type, float transitionSpeed) { | 3 | 2023-10-21 19:36:50+00:00 | 8k |
tuna-pizza/GraphXings | src/GraphXings/Legacy/Game/Game.java | [
{
"identifier": "CrossingCalculator",
"path": "src/GraphXings/Algorithms/CrossingCalculator.java",
"snippet": "public class CrossingCalculator\r\n{\r\n /**\r\n * The graph g.\r\n */\r\n private Graph g;\r\n /**\r\n * The positions of the already placed vertices.\r\n */\r\n pr... | import GraphXings.Algorithms.CrossingCalculator;
import GraphXings.Game.GameMove;
import GraphXings.Game.GameState;
import GraphXings.Legacy.Algorithms.Player;
import GraphXings.Data.Graph;
import java.util.*; | 4,772 | package GraphXings.Legacy.Game;
/**
* A class for managing a game of GraphXings!
*/
public class Game
{
/**
* Decides whether or not data is copied before being passed on to players.
*/
public static boolean safeMode = true;
/**
* The width of the game board.
*/
private int width;
/**
* The height of the game board.
*/
private int height;
/**
* The graph to be drawn.
*/
private Graph g;
/**
* The first player.
*/
private Player player1;
/**
* The second player.
*/
private Player player2;
/**
* The time limit for players.
*/
private long timeLimit;
/**
* Instantiates a game of GraphXings.
* @param g The graph to be drawn.
* @param width The width of the game board.
* @param height The height of the game board.
* @param player1 The first player. Plays as the maximizer in round one.
* @param player2 The second player. Plays as the minimizer in round one.
*/
public Game(Graph g, int width, int height, Player player1, Player player2)
{
this.g = g;
this.width = width;
this.height = height;
this.player1 = player1;
this.player2 = player2;
this.timeLimit = Long.MAX_VALUE;
}
/**
* Instantiates a game of GraphXings.
* @param g The graph to be drawn.
* @param width The width of the game board.
* @param height The height of the game board.
* @param player1 The first player. Plays as the maximizer in round one.
* @param player2 The second player. Plays as the minimizer in round one.
* @param timeLimit The time limit for players.
*/
public Game(Graph g, int width, int height, Player player1, Player player2, long timeLimit)
{
this.g = g;
this.width = width;
this.height = height;
this.player1 = player1;
this.player2 = player2;
this.timeLimit = timeLimit;
}
/**
* Runs the full game of GraphXings.
* @return Provides a GameResult Object containing the game's results.
*/
public GameResult play()
{
Random r = new Random(System.nanoTime());
if (r.nextBoolean())
{
Player swap = player1;
player1 = player2;
player2 = swap;
}
try
{
player1.initializeNextRound(g.copy(),width,height, Player.Role.MAX);
player2.initializeNextRound(g.copy(),width,height, Player.Role.MIN);
int crossingsGame1 = playRound(player1, player2);
player1.initializeNextRound(g.copy(),width,height, Player.Role.MIN);
player2.initializeNextRound(g.copy(),width,height, Player.Role.MAX);
int crossingsGame2 = playRound(player2, player1);
return new GameResult(crossingsGame1,crossingsGame2,player1,player2,false,false,false,false);
}
catch (InvalidMoveException ex)
{
System.err.println(ex.getCheater().getName() + " cheated!");
if (ex.getCheater().equals(player1))
{
return new GameResult(0, 0, player1, player2,true,false,false,false);
}
else if (ex.getCheater().equals(player2))
{
return new GameResult(0,0,player1,player2,false,true,false,false);
}
else
{
return new GameResult(0,0,player1,player2,false,false,false,false);
}
}
catch (TimeOutException ex)
{
System.err.println(ex.getTimeOutPlayer().getName() + " ran out of time!");
if (ex.getTimeOutPlayer().equals(player1))
{
return new GameResult(0, 0, player1, player2,false,false,true,false);
}
else if (ex.getTimeOutPlayer().equals(player2))
{
return new GameResult(0,0,player1,player2,false,false,false,true);
}
else
{
return new GameResult(0,0,player1,player2,false,false,false,false);
}
}
}
/**
* Plays a single round of the game.
* @param maximizer The player with the goal to maximize the number of crossings.
* @param minimizer The player with the goal to minimize the number of crossings
* @return The number of crossings yielded in the final drawing.
* @throws InvalidMoveException An exception caused by cheating.
*/
private int playRound(Player maximizer, Player minimizer) throws InvalidMoveException, TimeOutException
{
int turn = 0;
GameState gs = new GameState(g,width,height); | package GraphXings.Legacy.Game;
/**
* A class for managing a game of GraphXings!
*/
public class Game
{
/**
* Decides whether or not data is copied before being passed on to players.
*/
public static boolean safeMode = true;
/**
* The width of the game board.
*/
private int width;
/**
* The height of the game board.
*/
private int height;
/**
* The graph to be drawn.
*/
private Graph g;
/**
* The first player.
*/
private Player player1;
/**
* The second player.
*/
private Player player2;
/**
* The time limit for players.
*/
private long timeLimit;
/**
* Instantiates a game of GraphXings.
* @param g The graph to be drawn.
* @param width The width of the game board.
* @param height The height of the game board.
* @param player1 The first player. Plays as the maximizer in round one.
* @param player2 The second player. Plays as the minimizer in round one.
*/
public Game(Graph g, int width, int height, Player player1, Player player2)
{
this.g = g;
this.width = width;
this.height = height;
this.player1 = player1;
this.player2 = player2;
this.timeLimit = Long.MAX_VALUE;
}
/**
* Instantiates a game of GraphXings.
* @param g The graph to be drawn.
* @param width The width of the game board.
* @param height The height of the game board.
* @param player1 The first player. Plays as the maximizer in round one.
* @param player2 The second player. Plays as the minimizer in round one.
* @param timeLimit The time limit for players.
*/
public Game(Graph g, int width, int height, Player player1, Player player2, long timeLimit)
{
this.g = g;
this.width = width;
this.height = height;
this.player1 = player1;
this.player2 = player2;
this.timeLimit = timeLimit;
}
/**
* Runs the full game of GraphXings.
* @return Provides a GameResult Object containing the game's results.
*/
public GameResult play()
{
Random r = new Random(System.nanoTime());
if (r.nextBoolean())
{
Player swap = player1;
player1 = player2;
player2 = swap;
}
try
{
player1.initializeNextRound(g.copy(),width,height, Player.Role.MAX);
player2.initializeNextRound(g.copy(),width,height, Player.Role.MIN);
int crossingsGame1 = playRound(player1, player2);
player1.initializeNextRound(g.copy(),width,height, Player.Role.MIN);
player2.initializeNextRound(g.copy(),width,height, Player.Role.MAX);
int crossingsGame2 = playRound(player2, player1);
return new GameResult(crossingsGame1,crossingsGame2,player1,player2,false,false,false,false);
}
catch (InvalidMoveException ex)
{
System.err.println(ex.getCheater().getName() + " cheated!");
if (ex.getCheater().equals(player1))
{
return new GameResult(0, 0, player1, player2,true,false,false,false);
}
else if (ex.getCheater().equals(player2))
{
return new GameResult(0,0,player1,player2,false,true,false,false);
}
else
{
return new GameResult(0,0,player1,player2,false,false,false,false);
}
}
catch (TimeOutException ex)
{
System.err.println(ex.getTimeOutPlayer().getName() + " ran out of time!");
if (ex.getTimeOutPlayer().equals(player1))
{
return new GameResult(0, 0, player1, player2,false,false,true,false);
}
else if (ex.getTimeOutPlayer().equals(player2))
{
return new GameResult(0,0,player1,player2,false,false,false,true);
}
else
{
return new GameResult(0,0,player1,player2,false,false,false,false);
}
}
}
/**
* Plays a single round of the game.
* @param maximizer The player with the goal to maximize the number of crossings.
* @param minimizer The player with the goal to minimize the number of crossings
* @return The number of crossings yielded in the final drawing.
* @throws InvalidMoveException An exception caused by cheating.
*/
private int playRound(Player maximizer, Player minimizer) throws InvalidMoveException, TimeOutException
{
int turn = 0;
GameState gs = new GameState(g,width,height); | LinkedList<GameMove> gameMoves = new LinkedList<>(); | 1 | 2023-10-18 12:11:38+00:00 | 8k |
instrumental-id/iiq-common-public | src/com/identityworksllc/iiq/common/ThingAccessUtils.java | [
{
"identifier": "AccessCheckInput",
"path": "src/com/identityworksllc/iiq/common/access/AccessCheckInput.java",
"snippet": "public final class AccessCheckInput {\n /**\n * Configuration\n */\n private CommonSecurityConfig configuration;\n\n /**\n * The plugin resource\n */\n ... | import com.identityworksllc.iiq.common.access.AccessCheckInput;
import com.identityworksllc.iiq.common.access.AccessCheckResponse;
import com.identityworksllc.iiq.common.auth.DummyPluginResource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import sailpoint.api.DynamicScopeMatchmaker;
import sailpoint.api.Matchmaker;
import sailpoint.api.SailPointContext;
import sailpoint.object.Capability;
import sailpoint.object.CustomGlobal;
import sailpoint.object.DynamicScope;
import sailpoint.object.Filter;
import sailpoint.object.Identity;
import sailpoint.object.IdentitySelector;
import sailpoint.object.Script;
import sailpoint.rest.plugin.BasePluginResource;
import sailpoint.server.Environment;
import sailpoint.tools.GeneralException;
import sailpoint.tools.Util;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Supplier; | 5,868 | if (Util.isNotNullOrEmpty(quicklinkPopulation)) {
DynamicScopeMatchmaker dynamicScopeMatchmaker = new DynamicScopeMatchmaker(pluginContext.getContext());
DynamicScope dynamicScope = pluginContext.getContext().getObject(DynamicScope.class, quicklinkPopulation);
boolean matchesDynamicScope = dynamicScopeMatchmaker.isMatch(dynamicScope, currentUser);
if (matchesDynamicScope) {
result.addMessage("Subject user matches DynamicScope " + quicklinkPopulation);
DynamicScope.PopulationRequestAuthority populationRequestAuthority = dynamicScope.getPopulationRequestAuthority();
if (populationRequestAuthority != null && !populationRequestAuthority.isAllowAll()) {
matchesDynamicScope = dynamicScopeMatchmaker.isMember(currentUser, target, populationRequestAuthority);
}
}
if (!matchesDynamicScope) {
result.denyMessage("Access denied to " + thingName + " because QuickLink population " + quicklinkPopulation + " does not match the subject and target");
}
}
}
if (result.isAllowed() && !Util.isEmpty(config.getValidTargetExcludedRights())) {
boolean userAllowed = true;
List<String> rights = config.getValidTargetExcludedRights();
Collection<String> userRights = target.getCapabilityManager().getEffectiveFlattenedRights();
if (userRights != null) {
for(String right : Util.safeIterable(userRights)) {
if (rights.contains(right)) {
result.addMessage("Excluded right matched: " + right);
userAllowed = false;
break;
}
}
}
if (!userAllowed) {
result.denyMessage("Access denied to " + thingName + " because target user " + target.getName() + " matches one or more of the excluded rights " + rights);
}
}
if (result.isAllowed() && !Util.isEmpty(config.getValidTargetExcludedCapabilities())) {
boolean userAllowed = true;
List<String> rights = config.getValidTargetExcludedCapabilities();
List<Capability> capabilities = target.getCapabilityManager().getEffectiveCapabilities();
if (capabilities != null) {
for(Capability capability : Util.safeIterable(capabilities)) {
if (rights.contains(capability.getName())) {
result.addMessage("Excluded capability matched: " + capability.getName());
userAllowed = false;
break;
}
}
}
if (!userAllowed) {
result.denyMessage("Access denied to " + thingName + " because target user " + target.getName() + " matches one or more of the excluded capabilities " + rights);
}
}
if (result.isAllowed() && Util.isNotNullOrEmpty(config.getInvalidTargetFilter())) {
String filterString = config.getValidTargetFilter();
Filter compiledFilter = Filter.compile(filterString);
HybridObjectMatcher hom = new HybridObjectMatcher(pluginContext.getContext(), compiledFilter);
if (hom.matches(target)) {
result.denyMessage("Access denied to " + thingName + " because target user " + target.getName() + " matches the invalid target filter");
}
}
if (result.isAllowed() && !Util.isEmpty(config.getValidTargetWorkgroups())) {
List<String> workgroups = config.getValidTargetWorkgroups();
boolean userAllowed = matchesAnyWorkgroup(target, workgroups);
if (!userAllowed) {
result.denyMessage("Access denied to " + thingName + " because target user " + target.getName() + " does not match any of the required workgroups " + workgroups);
}
}
if (result.isAllowed() && !Util.isEmpty(config.getValidTargetCapabilities())) {
boolean userAllowed = false;
List<String> rights = config.getValidTargetCapabilities();
List<Capability> capabilities = target.getCapabilityManager().getEffectiveCapabilities();
if (capabilities != null) {
for(Capability capability : Util.safeIterable(capabilities)) {
if (rights.contains(capability.getName())) {
userAllowed = true;
}
}
}
if (!userAllowed) {
result.denyMessage("Access denied to " + thingName + " because target user " + target.getName() + " does not match one or more of the included capabilities " + rights);
}
}
if (result.isAllowed() && config.getValidTargetSelector() != null) {
IdentitySelector selector = config.getValidTargetSelector();
Matchmaker matchmaker = new Matchmaker(pluginContext.getContext());
if (!matchmaker.isMatch(selector, target)) {
result.denyMessage("Access denied to " + thingName + " because target user " + target.getName() + " does not match the valid target selector");
}
}
if (result.isAllowed() && Util.isNotNullOrEmpty(config.getValidTargetFilter())) {
String filterString = config.getValidTargetFilter();
Filter compiledFilter = Filter.compile(filterString);
HybridObjectMatcher hom = new HybridObjectMatcher(pluginContext.getContext(), compiledFilter);
if (!hom.matches(target)) {
result.denyMessage("Access denied to " + thingName + " because target user " + target.getName() + " does not match the valid target filter");
}
}
return result;
}
/**
* An optional clear-cache method that can be used by plugin code
*/
public static void clearCachedResults() {
ConcurrentHashMap<SecurityCacheToken, SecurityResult> cacheMap = getCacheMap();
cacheMap.clear();
}
/**
* Creates a fake plugin context for use with {@link ThingAccessUtils#checkThingAccess(BasePluginResource, Identity, String, Map)} outside of a plugin. This constructs a new instance of a dummy BasePluginResource web service endpoint class.
* @param context The SailPointContext to return from {@link BasePluginResource#getContext()}
* @param loggedInUser The Identity to return from various getLoggedIn... methods
* @param pluginName The name of the plugin to include in the fake plugin context
* @return The fake plugin resource
*/
public static BasePluginResource createFakePluginContext(final SailPointContext context, final Identity loggedInUser, String pluginName) { | package com.identityworksllc.iiq.common;
/**
* Implements the "Common Security" protocol that was originally part of the
* UPE plugin. This allows more detailed authorization to check access to
* various objects within IIQ.
*
* There are two users involved in thing access: an subject Identity and a target
* Identity. The subject is the one doing the thing while the target is the one
* the thing is being done to. Some actions may be 'self' actions, where both the
* subject and the target are the same. Other actions don't have a 'target' concept
* and are treated as 'self' actions.
*/
@SuppressWarnings("unused")
public class ThingAccessUtils {
/**
* The container object to hold the cached ThingAccessUtil results
*/
private static final class SecurityResult implements Supplier<Optional<AccessCheckResponse>> {
/**
* The epoch millisecond timestamp when this object expires, one minute after creation
*/
private final long expiration;
/**
* The actual cached result
*/
private final Object result;
/**
* Store the result with an expiration time
* @param result The result to cache
*/
public SecurityResult(AccessCheckResponse result) {
this.result = result;
this.expiration = System.currentTimeMillis() + (1000L * 60);
}
/**
* Returns the cached result
* @return The cached result
*/
public Optional<AccessCheckResponse> get() {
if (this.result instanceof AccessCheckResponse && !this.isExpired()) {
return Optional.of((AccessCheckResponse) this.result);
} else {
return Optional.empty();
}
}
/**
* Returns true if the current epoch timestamp is later than the expiration date
* @return True if expired
*/
private boolean isExpired() {
return System.currentTimeMillis() >= expiration;
}
}
/**
* The container object to identify the cached ThingAccessUtil inputs.
*
* NOTE: It is very important that this work properly across plugin
* classloader contexts, even if the plugin has its own version of
* ThingAccessUtils.
*/
public static final class SecurityCacheToken {
/**
* The CommonSecurityConfig object associated with the cached result
*/
private final Map<String, Object> commonSecurityConfig;
/**
* The version of the plugin cache to invalidate records whenever
* a new plugin is installed. This will prevent wacky class cast
* problems.
*/
private final int pluginVersion;
/**
* The name of the source identity
*/
private final String source;
/**
* The optional state map
*/
private final Map<String, Object> state;
/**
* The name of the target identity
*/
private final String target;
/**
* Constructs a new cache entry
* @param csc The security config
* @param source The source identity name
* @param target The target identity name
*/
public SecurityCacheToken(CommonSecurityConfig csc, String source, String target, Map<String, Object> state) {
this.commonSecurityConfig = csc.toMap();
this.target = target;
this.source = source;
this.state = new HashMap<>();
if (state != null) {
this.state.putAll(state);
}
this.pluginVersion = Environment.getEnvironment().getPluginsCache().getVersion();
}
/**
* Constructs a new cache entry based on the input
* @param input The input object
* @throws GeneralException the errors
*/
public SecurityCacheToken(AccessCheckInput input) throws GeneralException {
this(
input.getConfiguration(),
input.getPluginResource().getLoggedInUserName(),
(input.getTarget() == null || input.getTarget().getName() == null) ? "null" : input.getTarget().getName(),
input.getState()
);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SecurityCacheToken that = (SecurityCacheToken) o;
return this.pluginVersion == that.pluginVersion && Objects.equals(commonSecurityConfig, that.commonSecurityConfig) && Objects.equals(target, that.target) && Objects.equals(source, that.source) && Objects.equals(state, that.state);
}
@Override
public int hashCode() {
return Objects.hash(pluginVersion, commonSecurityConfig, target, source, state);
}
}
private static final String CACHE_KEY = "idw.ThingAccessUtils.cache";
/**
* The logger
*/
private static final Log log = LogFactory.getLog(ThingAccessUtils.class);
/**
* Returns true if the logged in user can access the item based on the Common Security configuration parameters.
*
* @param pluginContext The plugin context, which provides user details
* @param configuration The configuration for the field or button or other object
* @return True if the user has access to the thing based on the configuration
* @throws GeneralException if any check failures occur (this should be interpreted as "no access")
*/
public static boolean checkThingAccess(BasePluginResource pluginContext, Map<String, Object> configuration) throws GeneralException {
return checkThingAccess(pluginContext, null, "anonymous", configuration);
}
/**
* Returns true if the logged in user can access the item based on the CommonSecurityConfig object
*
* @param pluginContext The plugin context, which provides user details
* @param config the CommonSecurityConfig object
* @return True if the user has access to the thing based on the configuration
* @throws GeneralException if any check failures occur (this should be interpreted as "no access")
*/
public static boolean checkThingAccess(BasePluginResource pluginContext, CommonSecurityConfig config) throws GeneralException {
return checkThingAccess(pluginContext, null, "anonymous", config);
}
/**
* Returns true if the logged in user can access the item based on the common configuration parameters.
*
* @param pluginContext The plugin context, which provides user details
* @param targetIdentity The target identity for the action (as opposed to the actor)
* @param configuration The configuration for the field or button or other object
* @return True if the user has access to the thing based on the configuration
* @throws GeneralException if any check failures occur (this should be interpreted as "no access")
*/
public static boolean checkThingAccess(BasePluginResource pluginContext, Identity targetIdentity, Map<String, Object> configuration) throws GeneralException {
return checkThingAccess(pluginContext, targetIdentity, "anonymous", configuration);
}
/**
* Returns true if the logged in user can access the item based on the common configuration parameters.
*
* @param pluginContext A plugin REST API resource (or fake equivalent) used to get some details and settings. This must not be null.
* @param targetIdentity The target identity
* @param thingName The thing being checked
* @param configuration The configuration for the field or button or other object
* @return True if the user has access to the thing based on the configuration
* @throws GeneralException if any check failures occur (this should be interpreted as "no access")
*/
public static boolean checkThingAccess(BasePluginResource pluginContext, Identity targetIdentity, String thingName, Map<String, Object> configuration) throws GeneralException {
Identity currentUser = pluginContext.getLoggedInUser();
Identity target = targetIdentity;
if (target == null) {
target = currentUser;
}
if (configuration == null || configuration.isEmpty()) {
log.debug("Configuration for " + thingName + " is empty; assuming that access is allowed");
return true;
}
CommonSecurityConfig config = CommonSecurityConfig.decode(configuration);
return checkThingAccess(pluginContext, target, thingName, config);
}
/**
* Returns true if the logged in user can access the item based on the common configuration parameters.
*
* Results for the same CommonSecurityConfig, source, and target user will be cached for up to one minute
* unless the CommonSecurityConfig object has noCache set to true.
*
* @param pluginContext A plugin REST API resource (or fake equivalent) used to get some details and settings. This must not be null.
* @param target The target identity
* @param thingName The thing being checked, entirely for logging purposes
* @param config The configuration specifying security rights
* @return True if the user has access to the thing based on the configuration
* @throws GeneralException if any check failures occur (this should be interpreted as "no access")
*/
public static boolean checkThingAccess(BasePluginResource pluginContext, Identity target, String thingName, CommonSecurityConfig config) throws GeneralException {
AccessCheckInput input = new AccessCheckInput(pluginContext, target, thingName, config);
return checkThingAccess(input).isAllowed();
}
/**
* Returns an 'allowed' response if the logged in user can access the item based on the
* common configuration parameters.
*
* Results for the same CommonSecurityConfig, source, and target user will be cached for up to one minute
* unless the CommonSecurityConfig object has noCache set to true.
*
* @param input The input containing the configuration for the checkThingAccess utility
* @return True if the user has access to the thing based on the configuration
* @throws GeneralException if any check failures occur (this should be interpreted as "no access")
*/
public static AccessCheckResponse checkThingAccess(AccessCheckInput input) throws GeneralException {
if (input.getConfiguration() == null) {
throw new IllegalArgumentException("An access check must contain a CommonSecurityConfig");
}
if (input.getPluginResource() == null) {
throw new IllegalArgumentException("An access check must contain a plugin context for accessing the IIQ context and the logged in user");
}
AccessCheckResponse result;
try {
if (!input.getConfiguration().isNoCache()) {
SecurityCacheToken cacheToken = new SecurityCacheToken(input);
Optional<AccessCheckResponse> cachedResult = getCachedResult(cacheToken);
if (cachedResult.isPresent()) {
return cachedResult.get();
}
result = checkThingAccessImpl(input, null);
getCacheMap().put(cacheToken, new SecurityResult(result));
} else {
result = checkThingAccessImpl(input, null);
}
} catch(Exception e) {
result = new AccessCheckResponse();
result.denyMessage("Caught an exception evaluating criteria: " + e.getMessage());
log.error("Caught an exception evaluating access criteria", e);
}
return result;
}
/**
* Returns an allowed response if the logged in user can access the item based on
* the common configuration parameters.
*
* @param input The inputs to the access check
* @return True if the user has access to the thing based on the configuration
* @throws GeneralException if any check failures occur (this should be interpreted as "no access")
*/
private static AccessCheckResponse checkThingAccessImpl(final AccessCheckInput input, AccessCheckResponse result) throws GeneralException {
if (result == null) {
result = new AccessCheckResponse();
}
BasePluginResource pluginContext = input.getPluginResource();
final Identity currentUser = pluginContext.getLoggedInUser();
final Identity target = (input.getTarget() != null) ? input.getTarget() : currentUser;
final String currentUserName = pluginContext.getLoggedInUserName();
final CommonSecurityConfig config = input.getConfiguration();
final String thingName = input.getThingName();
if (config.isDisabled()) {
result.denyMessage("Access denied to " + thingName + " because the configuration is marked disabled");
}
if (result.isAllowed() && Utilities.isNotEmpty(config.getOneOf())) {
boolean anyMatch = false;
for(CommonSecurityConfig sub : config.getOneOf()) {
AccessCheckInput child = new AccessCheckInput(input, sub);
AccessCheckResponse childResponse = checkThingAccessImpl(child, null);
if (childResponse.isAllowed()) {
anyMatch = true;
break;
}
}
if (!anyMatch) {
result.denyMessage("Access denied to " + thingName + " because none of the items in the 'oneOf' list resolved to true");
}
}
if (result.isAllowed() && Utilities.isNotEmpty(config.getAllOf())) {
boolean allMatch = true;
for(CommonSecurityConfig sub : config.getAllOf()) {
AccessCheckInput child = new AccessCheckInput(input, sub);
AccessCheckResponse childResponse = checkThingAccessImpl(child, null);
if (!childResponse.isAllowed()) {
allMatch = false;
break;
}
}
if (!allMatch) {
result.denyMessage("Access denied to " + thingName + " because at least one of the items in the 'allOf' list resolved to 'deny'");
}
}
if (result.isAllowed() && Utilities.isNotEmpty(config.getNot())) {
boolean anyMatch = false;
for(CommonSecurityConfig sub : config.getNot()) {
AccessCheckInput child = new AccessCheckInput(input, sub);
AccessCheckResponse childResponse = checkThingAccessImpl(child, null);
if (childResponse.isAllowed()) {
anyMatch = true;
break;
}
}
if (anyMatch) {
result.denyMessage("Access denied to " + thingName + " because at least one of the items in the 'not' list resolved to 'allow'");
}
}
if (result.isAllowed() && Util.isNotNullOrEmpty(config.getSettingOffSwitch())) {
boolean isDisabled = pluginContext.getSettingBool(config.getSettingOffSwitch());
if (isDisabled) {
result.denyMessage("Access denied to " + thingName + " because the feature " + config.getSettingOffSwitch() + " is disabled in plugin settings");
}
}
if (result.isAllowed() && config.getAccessCheckScript() != null) {
Script script = Utilities.getAsScript(config.getAccessCheckScript());
Map<String, Object> scriptArguments = new HashMap<>();
scriptArguments.put("subject", currentUser);
scriptArguments.put("target", target);
scriptArguments.put("requester", currentUser);
scriptArguments.put("identity", target);
scriptArguments.put("identityName", target.getName());
scriptArguments.put("manager", target.getManager());
scriptArguments.put("context", pluginContext.getContext());
scriptArguments.put("log", LogFactory.getLog(pluginContext.getClass()));
scriptArguments.put("state", input.getState());
Object output = pluginContext.getContext().runScript(script, scriptArguments);
// If the script returns a non-null value, it will be considered the authoritative
// response. No further checks will be done. If the output is null, the access
// checks will defer farther down.
if (output != null) {
boolean userAllowed = Util.otob(output);
if (!userAllowed) {
result.denyMessage("Access denied to " + thingName + " because access check script returned false for subject user " + currentUserName);
}
return result;
}
}
if (result.isAllowed() && config.getAccessCheckRule() != null) {
Map<String, Object> scriptArguments = new HashMap<>();
scriptArguments.put("subject", currentUser);
scriptArguments.put("target", target);
scriptArguments.put("requester", currentUser);
scriptArguments.put("identity", target);
scriptArguments.put("identityName", target.getName());
scriptArguments.put("manager", target.getManager());
scriptArguments.put("context", pluginContext.getContext());
scriptArguments.put("log", LogFactory.getLog(pluginContext.getClass()));
scriptArguments.put("state", input.getState());
Object output = pluginContext.getContext().runRule(config.getAccessCheckRule(), scriptArguments);
// If the script returns a non-null value, it will be considered the authoritative
// response. No further checks will be done. If the output is null, the access
// checks will defer farther down.
if (output != null) {
boolean userAllowed = Util.otob(output);
if (!userAllowed) {
result.denyMessage("Access denied to " + thingName + " because access check rule returned false for subject user " + currentUserName);
}
return result;
}
}
if (result.isAllowed() && !Util.isEmpty(config.getRequiredRights())) {
boolean userAllowed = false;
List<String> rights = config.getRequiredRights();
Collection<String> userRights = pluginContext.getLoggedInUserRights();
if (userRights != null) {
for(String right : Util.safeIterable(userRights)) {
if (rights.contains(right)) {
result.addMessage("Matching SPRight: " + right);
userAllowed = true;
break;
}
}
}
if (!userAllowed) {
result.denyMessage("Access denied to " + thingName + " because subject user " + currentUserName + " does not match any of the required rights " + rights);
}
}
if (result.isAllowed() && !Util.isEmpty(config.getRequiredCapabilities())) {
boolean userAllowed = false;
List<String> capabilities = config.getRequiredCapabilities();
List<Capability> loggedInUserCapabilities = pluginContext.getLoggedInUserCapabilities();
for(Capability cap : Util.safeIterable(loggedInUserCapabilities)) {
if (capabilities.contains(cap.getName())) {
result.addMessage("Matching Capability: " + cap.getName());
userAllowed = true;
break;
}
}
if (!userAllowed) {
result.denyMessage("Access denied to " + thingName + " because subject user " + currentUserName + " does not match any of these required capabilities " + capabilities);
}
}
if (result.isAllowed() && !Util.isEmpty(config.getExcludedRights())) {
boolean userAllowed = true;
List<String> rights = config.getRequiredRights();
Collection<String> userRights = pluginContext.getLoggedInUserRights();
if (userRights != null) {
for(String right : Util.safeIterable(userRights)) {
if (rights.contains(right)) {
result.addMessage("Matching excluded SPRight: " + right);
userAllowed = false;
break;
}
}
}
if (!userAllowed) {
result.denyMessage("Access denied to " + thingName + " because subject user " + currentUserName + " matches one of these excluded SPRights: " + rights);
}
}
if (result.isAllowed() && !Util.isEmpty(config.getExcludedCapabilities())) {
boolean userAllowed = true;
List<String> capabilities = config.getRequiredCapabilities();
List<Capability> loggedInUserCapabilities = pluginContext.getLoggedInUserCapabilities();
for(Capability cap : Util.safeIterable(loggedInUserCapabilities)) {
if (capabilities.contains(cap.getName())) {
result.addMessage("Matching excluded Capability: " + cap.getName());
userAllowed = false;
break;
}
}
if (!userAllowed) {
result.denyMessage("Access denied to " + thingName + " because subject user " + currentUserName + " matches one of these excluded capabilities: " + capabilities);
}
}
if (result.isAllowed() && !Util.isEmpty(config.getExcludedWorkgroups())) {
List<String> workgroups = config.getExcludedWorkgroups();
boolean matchesWorkgroup = matchesAnyWorkgroup(currentUser, workgroups);
if (matchesWorkgroup) {
result.denyMessage("Access denied to " + thingName + " because subject user " + currentUserName + " is a member of an excluded workgroup in " + workgroups);
}
}
if (result.isAllowed() && !Util.isEmpty(config.getRequiredWorkgroups())) {
List<String> workgroups = config.getRequiredWorkgroups();
boolean userAllowed = matchesAnyWorkgroup(currentUser, workgroups);
if (!userAllowed) {
result.denyMessage("Access denied to " + thingName + " because subject user " + currentUserName + " does not match any of the required workgroups " + workgroups);
}
}
if (result.isAllowed() && Util.isNotNullOrEmpty(config.getAccessCheckFilter())) {
String filterString = config.getValidTargetFilter();
Filter compiledFilter = Filter.compile(filterString);
HybridObjectMatcher hom = new HybridObjectMatcher(pluginContext.getContext(), compiledFilter);
if (!hom.matches(currentUser)) {
result.denyMessage("Access denied to " + thingName + " because subject user " + currentUserName + " does not match the access check filter");
}
}
if (result.isAllowed() && config.getAccessCheckSelector() != null) {
IdentitySelector selector = config.getAccessCheckSelector();
Matchmaker matchmaker = new Matchmaker(pluginContext.getContext());
if (!matchmaker.isMatch(selector, currentUser)) {
result.denyMessage("Access denied to " + thingName + " because subject user " + currentUserName + " does not match the access check selector");
}
}
if (result.isAllowed() && Util.isNotNullOrEmpty(config.getMirrorQuicklinkPopulation())) {
String quicklinkPopulation = config.getMirrorQuicklinkPopulation();
if (Util.isNotNullOrEmpty(quicklinkPopulation)) {
DynamicScopeMatchmaker dynamicScopeMatchmaker = new DynamicScopeMatchmaker(pluginContext.getContext());
DynamicScope dynamicScope = pluginContext.getContext().getObject(DynamicScope.class, quicklinkPopulation);
boolean matchesDynamicScope = dynamicScopeMatchmaker.isMatch(dynamicScope, currentUser);
if (matchesDynamicScope) {
result.addMessage("Subject user matches DynamicScope " + quicklinkPopulation);
DynamicScope.PopulationRequestAuthority populationRequestAuthority = dynamicScope.getPopulationRequestAuthority();
if (populationRequestAuthority != null && !populationRequestAuthority.isAllowAll()) {
matchesDynamicScope = dynamicScopeMatchmaker.isMember(currentUser, target, populationRequestAuthority);
}
}
if (!matchesDynamicScope) {
result.denyMessage("Access denied to " + thingName + " because QuickLink population " + quicklinkPopulation + " does not match the subject and target");
}
}
}
if (result.isAllowed() && !Util.isEmpty(config.getValidTargetExcludedRights())) {
boolean userAllowed = true;
List<String> rights = config.getValidTargetExcludedRights();
Collection<String> userRights = target.getCapabilityManager().getEffectiveFlattenedRights();
if (userRights != null) {
for(String right : Util.safeIterable(userRights)) {
if (rights.contains(right)) {
result.addMessage("Excluded right matched: " + right);
userAllowed = false;
break;
}
}
}
if (!userAllowed) {
result.denyMessage("Access denied to " + thingName + " because target user " + target.getName() + " matches one or more of the excluded rights " + rights);
}
}
if (result.isAllowed() && !Util.isEmpty(config.getValidTargetExcludedCapabilities())) {
boolean userAllowed = true;
List<String> rights = config.getValidTargetExcludedCapabilities();
List<Capability> capabilities = target.getCapabilityManager().getEffectiveCapabilities();
if (capabilities != null) {
for(Capability capability : Util.safeIterable(capabilities)) {
if (rights.contains(capability.getName())) {
result.addMessage("Excluded capability matched: " + capability.getName());
userAllowed = false;
break;
}
}
}
if (!userAllowed) {
result.denyMessage("Access denied to " + thingName + " because target user " + target.getName() + " matches one or more of the excluded capabilities " + rights);
}
}
if (result.isAllowed() && Util.isNotNullOrEmpty(config.getInvalidTargetFilter())) {
String filterString = config.getValidTargetFilter();
Filter compiledFilter = Filter.compile(filterString);
HybridObjectMatcher hom = new HybridObjectMatcher(pluginContext.getContext(), compiledFilter);
if (hom.matches(target)) {
result.denyMessage("Access denied to " + thingName + " because target user " + target.getName() + " matches the invalid target filter");
}
}
if (result.isAllowed() && !Util.isEmpty(config.getValidTargetWorkgroups())) {
List<String> workgroups = config.getValidTargetWorkgroups();
boolean userAllowed = matchesAnyWorkgroup(target, workgroups);
if (!userAllowed) {
result.denyMessage("Access denied to " + thingName + " because target user " + target.getName() + " does not match any of the required workgroups " + workgroups);
}
}
if (result.isAllowed() && !Util.isEmpty(config.getValidTargetCapabilities())) {
boolean userAllowed = false;
List<String> rights = config.getValidTargetCapabilities();
List<Capability> capabilities = target.getCapabilityManager().getEffectiveCapabilities();
if (capabilities != null) {
for(Capability capability : Util.safeIterable(capabilities)) {
if (rights.contains(capability.getName())) {
userAllowed = true;
}
}
}
if (!userAllowed) {
result.denyMessage("Access denied to " + thingName + " because target user " + target.getName() + " does not match one or more of the included capabilities " + rights);
}
}
if (result.isAllowed() && config.getValidTargetSelector() != null) {
IdentitySelector selector = config.getValidTargetSelector();
Matchmaker matchmaker = new Matchmaker(pluginContext.getContext());
if (!matchmaker.isMatch(selector, target)) {
result.denyMessage("Access denied to " + thingName + " because target user " + target.getName() + " does not match the valid target selector");
}
}
if (result.isAllowed() && Util.isNotNullOrEmpty(config.getValidTargetFilter())) {
String filterString = config.getValidTargetFilter();
Filter compiledFilter = Filter.compile(filterString);
HybridObjectMatcher hom = new HybridObjectMatcher(pluginContext.getContext(), compiledFilter);
if (!hom.matches(target)) {
result.denyMessage("Access denied to " + thingName + " because target user " + target.getName() + " does not match the valid target filter");
}
}
return result;
}
/**
* An optional clear-cache method that can be used by plugin code
*/
public static void clearCachedResults() {
ConcurrentHashMap<SecurityCacheToken, SecurityResult> cacheMap = getCacheMap();
cacheMap.clear();
}
/**
* Creates a fake plugin context for use with {@link ThingAccessUtils#checkThingAccess(BasePluginResource, Identity, String, Map)} outside of a plugin. This constructs a new instance of a dummy BasePluginResource web service endpoint class.
* @param context The SailPointContext to return from {@link BasePluginResource#getContext()}
* @param loggedInUser The Identity to return from various getLoggedIn... methods
* @param pluginName The name of the plugin to include in the fake plugin context
* @return The fake plugin resource
*/
public static BasePluginResource createFakePluginContext(final SailPointContext context, final Identity loggedInUser, String pluginName) { | return new DummyPluginResource(context, loggedInUser, pluginName); | 2 | 2023-10-20 15:20:16+00:00 | 8k |
mosaic-addons/traffic-state-estimation | src/main/java/com/dcaiti/mosaic/app/tse/config/CFxdReceiverApp.java | [
{
"identifier": "FxdRecord",
"path": "src/main/java/com/dcaiti/mosaic/app/fxd/data/FxdRecord.java",
"snippet": "public abstract class FxdRecord implements Serializable {\n\n /**\n * Time at record creation. [ns]\n */\n protected final long timeStamp;\n /**\n * Position at record cre... | import com.dcaiti.mosaic.app.fxd.data.FxdRecord;
import com.dcaiti.mosaic.app.fxd.data.FxdTraversal;
import com.dcaiti.mosaic.app.fxd.messages.FxdUpdateMessage;
import com.dcaiti.mosaic.app.tse.FxdKernel;
import com.dcaiti.mosaic.app.tse.processors.MessageBasedProcessor;
import com.dcaiti.mosaic.app.tse.processors.TimeBasedProcessor;
import com.dcaiti.mosaic.app.tse.processors.TraversalBasedProcessor;
import org.eclipse.mosaic.lib.util.gson.TimeFieldAdapter;
import org.eclipse.mosaic.rti.TIME;
import com.google.gson.annotations.JsonAdapter;
import java.util.List; | 5,927 | /*
* Copyright (c) 2023 Fraunhofer FOKUS and others. All rights reserved.
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*
* Contact: mosaic@fokus.fraunhofer.de
*/
package com.dcaiti.mosaic.app.tse.config;
public class CFxdReceiverApp<
RecordT extends FxdRecord, | /*
* Copyright (c) 2023 Fraunhofer FOKUS and others. All rights reserved.
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*
* Contact: mosaic@fokus.fraunhofer.de
*/
package com.dcaiti.mosaic.app.tse.config;
public class CFxdReceiverApp<
RecordT extends FxdRecord, | TraversalT extends FxdTraversal<RecordT, TraversalT>, | 1 | 2023-10-23 16:39:40+00:00 | 8k |
Primogem-Craft-Development/Primogem-Craft-Fabric | src/main/java/com/primogemstudio/primogemcraft/blocks/PrimogemCraftBlocks.java | [
{
"identifier": "AgnidusAgateBlock",
"path": "src/main/java/com/primogemstudio/primogemcraft/blocks/instances/materials/agnidus/AgnidusAgateBlock.java",
"snippet": "public class AgnidusAgateBlock extends Block {\n public AgnidusAgateBlock() {\n super(BlockBehaviour.Properties.of().sound(SoundT... | import com.primogemstudio.primogemcraft.blocks.instances.*;
import com.primogemstudio.primogemcraft.blocks.instances.dendrocore.*;
import com.primogemstudio.primogemcraft.blocks.instances.materials.agnidus.AgnidusAgateBlock;
import com.primogemstudio.primogemcraft.blocks.instances.materials.agnidus.AgnidusAgateOreBlock;
import com.primogemstudio.primogemcraft.blocks.instances.materials.nagadus.NagadusEmeraldBlock;
import com.primogemstudio.primogemcraft.blocks.instances.materials.nagadus.NagadusEmeraldOreBlock;
import com.primogemstudio.primogemcraft.blocks.instances.materials.prithva.PrithvaTopazBlock;
import com.primogemstudio.primogemcraft.blocks.instances.materials.prithva.PrithvaTopazOreBlock;
import com.primogemstudio.primogemcraft.blocks.instances.materials.vajrada.VajradaAmethystBlock;
import com.primogemstudio.primogemcraft.blocks.instances.materials.vajrada.VajradaAmethystOre;
import com.primogemstudio.primogemcraft.blocks.instances.materials.vayuda.VayudaTurquoiseGemstoneBlock;
import com.primogemstudio.primogemcraft.blocks.instances.materials.vayuda.VayudaTurquoiseGemstoneOre;
import com.primogemstudio.primogemcraft.blocks.instances.mora.*;
import com.primogemstudio.primogemcraft.blocks.instances.planks.*;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.fabricmc.fabric.api.blockrenderlayer.v1.BlockRenderLayerMap;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.core.Registry;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.BlockItem;
import net.minecraft.world.item.Item;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.SoundType;
import net.minecraft.world.level.block.state.BlockBehaviour;
import net.minecraft.world.level.block.state.properties.NoteBlockInstrument;
import static com.primogemstudio.primogemcraft.PrimogemCraftFabric.MOD_ID; | 4,392 | package com.primogemstudio.primogemcraft.blocks;
public class PrimogemCraftBlocks {
public static final DendroCoreBlock DENDRO_CORE_BLOCK = registerWithItem("dendro_core_block", new DendroCoreBlock());
public static final PrimogemBlock PRIMOGEM_BLOCK = registerWithItem("primogem_block", new PrimogemBlock());
public static final PrimogemOre PRIMOGEM_ORE = registerWithItem("primogem_ore", new PrimogemOre());
public static final Block DEEP_SLATE_PRIMOGEM_ORE = registerWithItem("deep_slate_primogem_ore", new Block(BlockBehaviour.Properties.of().instrument(NoteBlockInstrument.BASEDRUM).sound(SoundType.POLISHED_DEEPSLATE).strength(5f, 10f).lightLevel(s -> 1).requiresCorrectToolForDrops()));
public static final IntertwinedFateBlock INTERTWINED_FATE_BLOCK = registerWithItem("intertwined_fate_block", new IntertwinedFateBlock());
public static final MoraBunchBlock MORA_BUNCH_BLOCK = registerWithItem("mora_bunch_block", new MoraBunchBlock());
public static final MoraBlock MORA_BLOCK = registerWithItem("mora_block", new MoraBlock());
public static final ExquisiteMoraBlock EXQUISITE_MORA_BLOCK = registerWithItem("exquisite_mora_block", new ExquisiteMoraBlock());
public static final CheapMoraBlock CHEAP_MORA_BLOCK = registerWithItem("cheap_mora_block", new CheapMoraBlock());
public static final CheapMoraSlabBlock CHEAP_MORA_SLAB_BLOCK = registerWithItem("cheap_mora_slab", new CheapMoraSlabBlock());
public static final CheapMoraStairBlock CHEAP_MORA_STAIR_BLOCK = registerWithItem("cheap_mora_stair", new CheapMoraStairBlock());
public static final CheapMoraWallBlock CHEAP_MORA_WALL_BLOCK = registerWithItem("cheap_mora_wall", new CheapMoraWallBlock());
public static final TeyvatPlanksBlock TEYVAT_PLANKS_BLOCK = registerWithItem("teyvat_planks", new TeyvatPlanksBlock());
public static final TeyvatPlankSlabBlock TEYVAT_PLANK_SLAB_BLOCK = registerWithItem("teyvat_plank_slab", new TeyvatPlankSlabBlock());
public static final TeyvatPlankStairBlock TEYVAT_PLANK_STAIR_BLOCK = registerWithItem("teyvat_plank_stair", new TeyvatPlankStairBlock());
public static final TeyvatPlankFenceBlock TEYVAT_PLANK_FENCE_BLOCK = registerWithItem("teyvat_plank_fence", new TeyvatPlankFenceBlock());
public static final TeyvatPlankFenceGateBlock TEYVAT_PLANK_FENCE_GATE_BLOCK = registerWithItem("teyvat_plank_fence_gate", new TeyvatPlankFenceGateBlock());
public static final BlueTeyvatPlanksBlock BLUE_TEYVAT_PLANKS_BLOCK = registerWithItem("blue_teyvat_planks", new BlueTeyvatPlanksBlock());
public static final TeyvatPlankSlabBlock BLUE_TEYVAT_PLANK_SLAB_BLOCK = registerWithItem("blue_teyvat_plank_slab", new TeyvatPlankSlabBlock());
public static final TeyvatPlankStairBlock BLUE_TEYVAT_PLANK_STAIR_BLOCK = registerWithItem("blue_teyvat_plank_stair", new TeyvatPlankStairBlock());
public static final TeyvatPlankFenceBlock BLUE_TEYVAT_PLANK_FENCE_BLOCK = registerWithItem("blue_teyvat_plank_fence", new TeyvatPlankFenceBlock());
public static final TeyvatPlankFenceGateBlock BLUE_TEYVAT_PLANK_FENCE_GATE_BLOCK = registerWithItem("blue_teyvat_plank_fence_gate", new TeyvatPlankFenceGateBlock());
public static final PinkTeyvatPlanksBlock PINK_TEYVAT_PLANKS_BLOCK = registerWithItem("pink_teyvat_planks", new PinkTeyvatPlanksBlock());
public static final TeyvatPlankSlabBlock PINK_TEYVAT_PLANK_SLAB_BLOCK = registerWithItem("pink_teyvat_plank_slab", new TeyvatPlankSlabBlock());
public static final TeyvatPlankStairBlock PINK_TEYVAT_PLANK_STAIR_BLOCK = registerWithItem("pink_teyvat_plank_stair", new TeyvatPlankStairBlock());
public static final TeyvatPlankFenceBlock PINK_TEYVAT_PLANK_FENCE_BLOCK = registerWithItem("pink_teyvat_plank_fence", new TeyvatPlankFenceBlock());
public static final TeyvatPlankFenceGateBlock PINK_TEYVAT_PLANK_FENCE_GATE_BLOCK = registerWithItem("pink_teyvat_plank_fence_gate", new TeyvatPlankFenceGateBlock());
public static final CharCoalBlock CHAR_COAL_BLOCK = registerWithItem("charcoal_block", new CharCoalBlock());
public static final RustedPlankBlock RUSTED_PLANK_BLOCK = registerWithItem("rusted_plank", new RustedPlankBlock());
public static final RustedPlankStairsBlock RUSTED_PLANK_STAIR_BLOCK = registerWithItem("rusted_plank_stairs", new RustedPlankStairsBlock());
public static final RustIronBarBlock RUST_IRON_BAR_BLOCK = registerWithItem("rust_iron_bar", new RustIronBarBlock());
public static final DendroCorePlanksBlock DENDRO_CORE_PLANKS_BLOCK = registerWithItem("dendro_core_planks", new DendroCorePlanksBlock());
public static final DendroCorePlankSlabBlock DENDRO_CORE_PLANK_SLAB_BLOCK = registerWithItem("dendro_core_plank_slab", new DendroCorePlankSlabBlock());
public static final DendroCorePlankStairsBlock DENDRO_CORE_PLANK_STAIRS_BLOCK = registerWithItem("dendro_core_plank_stairs", new DendroCorePlankStairsBlock());
public static final DendroCorePlankPressurePlateBlock DENDRO_CORE_PLANK_PRESSURE_PLATE_BLOCK = registerWithItem("dendro_core_plank_pressure_plate", new DendroCorePlankPressurePlateBlock());
public static final DendroCodePlankButtonBlock DENDRO_CORE_PLANK_BUTTON_BLOCK = registerWithItem("dendro_core_plank_button", new DendroCodePlankButtonBlock());
public static final DendroCorePlanksFenceGateBlock DENDRO_CORE_PLANK_FENCE_GATE_BLOCK = registerWithItem("dendro_core_plank_fence_gate", new DendroCorePlanksFenceGateBlock());
public static final DendroCorePlankFenceBlock DENDRO_CORE_PLANK_FENCE_BLOCK = registerWithItem("dendro_core_plank_fence", new DendroCorePlankFenceBlock());
public static final VayudaTurquoiseGemstoneOre VAYUDA_TURQUOISE_GEMSTONE_ORE_BLOCK = registerWithItem("vayuda_turquoise_gemstone_ore", new VayudaTurquoiseGemstoneOre());
public static final VayudaTurquoiseGemstoneBlock VAYUDA_TURQUOISE_GEMSTONE_BLOCK = registerWithItem("vayuda_turquoise_gemstone_block", new VayudaTurquoiseGemstoneBlock());
public static final VajradaAmethystOre VAJRADA_AMETHYST_ORE_BLOCK = registerWithItem("vajrada_amethyst_ore", new VajradaAmethystOre()); | package com.primogemstudio.primogemcraft.blocks;
public class PrimogemCraftBlocks {
public static final DendroCoreBlock DENDRO_CORE_BLOCK = registerWithItem("dendro_core_block", new DendroCoreBlock());
public static final PrimogemBlock PRIMOGEM_BLOCK = registerWithItem("primogem_block", new PrimogemBlock());
public static final PrimogemOre PRIMOGEM_ORE = registerWithItem("primogem_ore", new PrimogemOre());
public static final Block DEEP_SLATE_PRIMOGEM_ORE = registerWithItem("deep_slate_primogem_ore", new Block(BlockBehaviour.Properties.of().instrument(NoteBlockInstrument.BASEDRUM).sound(SoundType.POLISHED_DEEPSLATE).strength(5f, 10f).lightLevel(s -> 1).requiresCorrectToolForDrops()));
public static final IntertwinedFateBlock INTERTWINED_FATE_BLOCK = registerWithItem("intertwined_fate_block", new IntertwinedFateBlock());
public static final MoraBunchBlock MORA_BUNCH_BLOCK = registerWithItem("mora_bunch_block", new MoraBunchBlock());
public static final MoraBlock MORA_BLOCK = registerWithItem("mora_block", new MoraBlock());
public static final ExquisiteMoraBlock EXQUISITE_MORA_BLOCK = registerWithItem("exquisite_mora_block", new ExquisiteMoraBlock());
public static final CheapMoraBlock CHEAP_MORA_BLOCK = registerWithItem("cheap_mora_block", new CheapMoraBlock());
public static final CheapMoraSlabBlock CHEAP_MORA_SLAB_BLOCK = registerWithItem("cheap_mora_slab", new CheapMoraSlabBlock());
public static final CheapMoraStairBlock CHEAP_MORA_STAIR_BLOCK = registerWithItem("cheap_mora_stair", new CheapMoraStairBlock());
public static final CheapMoraWallBlock CHEAP_MORA_WALL_BLOCK = registerWithItem("cheap_mora_wall", new CheapMoraWallBlock());
public static final TeyvatPlanksBlock TEYVAT_PLANKS_BLOCK = registerWithItem("teyvat_planks", new TeyvatPlanksBlock());
public static final TeyvatPlankSlabBlock TEYVAT_PLANK_SLAB_BLOCK = registerWithItem("teyvat_plank_slab", new TeyvatPlankSlabBlock());
public static final TeyvatPlankStairBlock TEYVAT_PLANK_STAIR_BLOCK = registerWithItem("teyvat_plank_stair", new TeyvatPlankStairBlock());
public static final TeyvatPlankFenceBlock TEYVAT_PLANK_FENCE_BLOCK = registerWithItem("teyvat_plank_fence", new TeyvatPlankFenceBlock());
public static final TeyvatPlankFenceGateBlock TEYVAT_PLANK_FENCE_GATE_BLOCK = registerWithItem("teyvat_plank_fence_gate", new TeyvatPlankFenceGateBlock());
public static final BlueTeyvatPlanksBlock BLUE_TEYVAT_PLANKS_BLOCK = registerWithItem("blue_teyvat_planks", new BlueTeyvatPlanksBlock());
public static final TeyvatPlankSlabBlock BLUE_TEYVAT_PLANK_SLAB_BLOCK = registerWithItem("blue_teyvat_plank_slab", new TeyvatPlankSlabBlock());
public static final TeyvatPlankStairBlock BLUE_TEYVAT_PLANK_STAIR_BLOCK = registerWithItem("blue_teyvat_plank_stair", new TeyvatPlankStairBlock());
public static final TeyvatPlankFenceBlock BLUE_TEYVAT_PLANK_FENCE_BLOCK = registerWithItem("blue_teyvat_plank_fence", new TeyvatPlankFenceBlock());
public static final TeyvatPlankFenceGateBlock BLUE_TEYVAT_PLANK_FENCE_GATE_BLOCK = registerWithItem("blue_teyvat_plank_fence_gate", new TeyvatPlankFenceGateBlock());
public static final PinkTeyvatPlanksBlock PINK_TEYVAT_PLANKS_BLOCK = registerWithItem("pink_teyvat_planks", new PinkTeyvatPlanksBlock());
public static final TeyvatPlankSlabBlock PINK_TEYVAT_PLANK_SLAB_BLOCK = registerWithItem("pink_teyvat_plank_slab", new TeyvatPlankSlabBlock());
public static final TeyvatPlankStairBlock PINK_TEYVAT_PLANK_STAIR_BLOCK = registerWithItem("pink_teyvat_plank_stair", new TeyvatPlankStairBlock());
public static final TeyvatPlankFenceBlock PINK_TEYVAT_PLANK_FENCE_BLOCK = registerWithItem("pink_teyvat_plank_fence", new TeyvatPlankFenceBlock());
public static final TeyvatPlankFenceGateBlock PINK_TEYVAT_PLANK_FENCE_GATE_BLOCK = registerWithItem("pink_teyvat_plank_fence_gate", new TeyvatPlankFenceGateBlock());
public static final CharCoalBlock CHAR_COAL_BLOCK = registerWithItem("charcoal_block", new CharCoalBlock());
public static final RustedPlankBlock RUSTED_PLANK_BLOCK = registerWithItem("rusted_plank", new RustedPlankBlock());
public static final RustedPlankStairsBlock RUSTED_PLANK_STAIR_BLOCK = registerWithItem("rusted_plank_stairs", new RustedPlankStairsBlock());
public static final RustIronBarBlock RUST_IRON_BAR_BLOCK = registerWithItem("rust_iron_bar", new RustIronBarBlock());
public static final DendroCorePlanksBlock DENDRO_CORE_PLANKS_BLOCK = registerWithItem("dendro_core_planks", new DendroCorePlanksBlock());
public static final DendroCorePlankSlabBlock DENDRO_CORE_PLANK_SLAB_BLOCK = registerWithItem("dendro_core_plank_slab", new DendroCorePlankSlabBlock());
public static final DendroCorePlankStairsBlock DENDRO_CORE_PLANK_STAIRS_BLOCK = registerWithItem("dendro_core_plank_stairs", new DendroCorePlankStairsBlock());
public static final DendroCorePlankPressurePlateBlock DENDRO_CORE_PLANK_PRESSURE_PLATE_BLOCK = registerWithItem("dendro_core_plank_pressure_plate", new DendroCorePlankPressurePlateBlock());
public static final DendroCodePlankButtonBlock DENDRO_CORE_PLANK_BUTTON_BLOCK = registerWithItem("dendro_core_plank_button", new DendroCodePlankButtonBlock());
public static final DendroCorePlanksFenceGateBlock DENDRO_CORE_PLANK_FENCE_GATE_BLOCK = registerWithItem("dendro_core_plank_fence_gate", new DendroCorePlanksFenceGateBlock());
public static final DendroCorePlankFenceBlock DENDRO_CORE_PLANK_FENCE_BLOCK = registerWithItem("dendro_core_plank_fence", new DendroCorePlankFenceBlock());
public static final VayudaTurquoiseGemstoneOre VAYUDA_TURQUOISE_GEMSTONE_ORE_BLOCK = registerWithItem("vayuda_turquoise_gemstone_ore", new VayudaTurquoiseGemstoneOre());
public static final VayudaTurquoiseGemstoneBlock VAYUDA_TURQUOISE_GEMSTONE_BLOCK = registerWithItem("vayuda_turquoise_gemstone_block", new VayudaTurquoiseGemstoneBlock());
public static final VajradaAmethystOre VAJRADA_AMETHYST_ORE_BLOCK = registerWithItem("vajrada_amethyst_ore", new VajradaAmethystOre()); | public static final VajradaAmethystBlock VAJRADA_AMETHYST_BLOCK = registerWithItem("vajrada_amethyst_block", new VajradaAmethystBlock()); | 6 | 2023-10-15 08:07:06+00:00 | 8k |
turtleisaac/PokEditor | src/main/java/io/github/turtleisaac/pokeditor/gui/sheets/tables/formats/MovesTable.java | [
{
"identifier": "CellTypes",
"path": "src/main/java/io/github/turtleisaac/pokeditor/gui/sheets/tables/cells/CellTypes.java",
"snippet": "public enum CellTypes\n{\n INTEGER,\n STRING,\n COMBO_BOX,\n COLORED_COMBO_BOX,\n BITFIELD_COMBO_BOX,\n CHECKBOX,\n CUSTOM;\n\n\n public interf... | import io.github.turtleisaac.pokeditor.formats.moves.MoveData;
import io.github.turtleisaac.pokeditor.formats.text.TextBankData;
import io.github.turtleisaac.pokeditor.gamedata.TextFiles;
import io.github.turtleisaac.pokeditor.gui.sheets.tables.cells.CellTypes;
import io.github.turtleisaac.pokeditor.gui.sheets.tables.DefaultTable;
import io.github.turtleisaac.pokeditor.gui.sheets.tables.FormatModel;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue; | 4,229 | package io.github.turtleisaac.pokeditor.gui.sheets.tables.formats;
public class MovesTable extends DefaultTable<MoveData, MovesTable.MovesColumn>
{
public static final int[] columnWidths = new int[] {40, 100, 500, 100, 65, 100, 65, 65, 120, 160, 65, 65, 80, 80, 80, 80, 80, 80, 80, 80, 65, 65};
private static final String[] categoryKeys = new String[] {"category.physical", "category.special", "category.status"};
private static final String[] targetKeys = new String[] {"target.selected", "target.automatic", "target.random", "target.bothFoes", "target.allExceptUser", "target.user", "target.userSide", "target.entireField", "target.foeSide", "target.ally", "target.userOrAlly", "target.MOVE_TARGET_ME_FIRST"};
public MovesTable(List<MoveData> data, List<TextBankData> textData)
{
super(new MovesModel(data, textData), textData, columnWidths, null);
}
@Override
public Queue<String[]> obtainTextSources(List<TextBankData> textData)
{
Queue<String[]> textSources = new LinkedList<>();
String[] categories = DefaultTable.loadStringsFromKeys(categoryKeys);
String[] typeNames = textData.get(TextFiles.TYPE_NAMES.getValue()).getStringList().toArray(String[]::new);
String[] targets = DefaultTable.loadStringsFromKeys(targetKeys);
// String[] arr = new String[500];
// Arrays.fill(arr, "Moo");
textSources.add(categories);
textSources.add(typeNames);
textSources.add(targets);
// textSources.add(arr);
return textSources;
}
@Override
public Class<MoveData> getDataClass()
{
return MoveData.class;
}
| package io.github.turtleisaac.pokeditor.gui.sheets.tables.formats;
public class MovesTable extends DefaultTable<MoveData, MovesTable.MovesColumn>
{
public static final int[] columnWidths = new int[] {40, 100, 500, 100, 65, 100, 65, 65, 120, 160, 65, 65, 80, 80, 80, 80, 80, 80, 80, 80, 65, 65};
private static final String[] categoryKeys = new String[] {"category.physical", "category.special", "category.status"};
private static final String[] targetKeys = new String[] {"target.selected", "target.automatic", "target.random", "target.bothFoes", "target.allExceptUser", "target.user", "target.userSide", "target.entireField", "target.foeSide", "target.ally", "target.userOrAlly", "target.MOVE_TARGET_ME_FIRST"};
public MovesTable(List<MoveData> data, List<TextBankData> textData)
{
super(new MovesModel(data, textData), textData, columnWidths, null);
}
@Override
public Queue<String[]> obtainTextSources(List<TextBankData> textData)
{
Queue<String[]> textSources = new LinkedList<>();
String[] categories = DefaultTable.loadStringsFromKeys(categoryKeys);
String[] typeNames = textData.get(TextFiles.TYPE_NAMES.getValue()).getStringList().toArray(String[]::new);
String[] targets = DefaultTable.loadStringsFromKeys(targetKeys);
// String[] arr = new String[500];
// Arrays.fill(arr, "Moo");
textSources.add(categories);
textSources.add(typeNames);
textSources.add(targets);
// textSources.add(arr);
return textSources;
}
@Override
public Class<MoveData> getDataClass()
{
return MoveData.class;
}
| static class MovesModel extends FormatModel<MoveData, MovesColumn> | 2 | 2023-10-15 05:00:57+00:00 | 8k |
xiezhihui98/GAT1400 | src/main/java/com/cz/viid/framework/service/impl/VIIDSubscribeServiceImpl.java | [
{
"identifier": "Constants",
"path": "src/main/java/com/cz/viid/framework/config/Constants.java",
"snippet": "public class Constants {\n public static class KAFKA_CONSUMER {\n public static final String APP_DEFAULT_GROUP = \"GA1400_BACKEND\";\n\n //消费失败重试topic\n public static fin... | import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cz.viid.fe.domain.VIIDSubscribeRequest;
import com.cz.viid.framework.config.Constants;
import com.cz.viid.framework.config.RedisConfig;
import com.cz.viid.framework.domain.dto.ResponseStatusObject;
import com.cz.viid.framework.domain.dto.SubscribeObject;
import com.cz.viid.framework.domain.entity.VIIDServer;
import com.cz.viid.framework.domain.entity.VIIDSubscribe;
import com.cz.viid.framework.domain.vo.SubscribesRequest;
import com.cz.viid.framework.domain.vo.VIIDSubscribesResponse;
import com.cz.viid.framework.mapper.VIIDSubscribeMapper;
import com.cz.viid.framework.service.VIIDServerService;
import com.cz.viid.framework.service.VIIDSubscribeService;
import com.cz.viid.rpc.VIIDServerClient;
import com.cz.viid.utils.StructCodec;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.net.URI;
import java.util.Collections;
import java.util.List;
import java.util.Objects; | 6,545 | package com.cz.viid.framework.service.impl;
@Service
public class VIIDSubscribeServiceImpl extends ServiceImpl<VIIDSubscribeMapper, VIIDSubscribe>
implements VIIDSubscribeService {
@Resource
VIIDServerService viidServerService;
@Resource
VIIDServerClient viidServerClient;
@Cacheable(cacheNames = RedisConfig.CACHE_15MIN,
key = "'SubscribeEntityService::getCacheById::' + #subscribeId",
unless = "#result == null")
@Override
public VIIDSubscribe getCacheById(String subscribeId) {
return getById(subscribeId);
}
@Override
public VIIDSubscribesResponse subscribes(VIIDSubscribeRequest request) {
VIIDServer setting = viidServerService.getCurrentServer();
VIIDServer domain = viidServerService.getById(request.getServerId());
String resourceUri = assembleResourceUri(request);
SubscribeObject subscribe = StructCodec.inputSubscribeBuilder(resourceUri, request.getTitle(),
request.getSubscribeDetail(), domain);
subscribe.setResourceClass(request.getResourceClass());
//发送订阅请求
URI uri = URI.create(domain.httpUrlBuilder());
VIIDSubscribesResponse response = viidServerClient.addSubscribes(uri,
SubscribesRequest.create(subscribe), setting.getServerId());
VIIDSubscribe entity = StructCodec.castSubscribe(subscribe);
entity.setSubscribeDetail(request.getSubscribeDetail());
entity.setServerId(request.getServerId());
this.save(entity);
return VIIDSubscribesResponse.create(response.getResponseStatusListObject().getResponseStatusObject());
}
@Override
public VIIDSubscribesResponse unSubscribes(VIIDSubscribeRequest request) {
VIIDServer setting = viidServerService.getCurrentServer();
VIIDSubscribe subscribe = this.getById(request.getSubscribeId());
if (Objects.isNull(subscribe))
return VIIDSubscribesResponse.create( | package com.cz.viid.framework.service.impl;
@Service
public class VIIDSubscribeServiceImpl extends ServiceImpl<VIIDSubscribeMapper, VIIDSubscribe>
implements VIIDSubscribeService {
@Resource
VIIDServerService viidServerService;
@Resource
VIIDServerClient viidServerClient;
@Cacheable(cacheNames = RedisConfig.CACHE_15MIN,
key = "'SubscribeEntityService::getCacheById::' + #subscribeId",
unless = "#result == null")
@Override
public VIIDSubscribe getCacheById(String subscribeId) {
return getById(subscribeId);
}
@Override
public VIIDSubscribesResponse subscribes(VIIDSubscribeRequest request) {
VIIDServer setting = viidServerService.getCurrentServer();
VIIDServer domain = viidServerService.getById(request.getServerId());
String resourceUri = assembleResourceUri(request);
SubscribeObject subscribe = StructCodec.inputSubscribeBuilder(resourceUri, request.getTitle(),
request.getSubscribeDetail(), domain);
subscribe.setResourceClass(request.getResourceClass());
//发送订阅请求
URI uri = URI.create(domain.httpUrlBuilder());
VIIDSubscribesResponse response = viidServerClient.addSubscribes(uri,
SubscribesRequest.create(subscribe), setting.getServerId());
VIIDSubscribe entity = StructCodec.castSubscribe(subscribe);
entity.setSubscribeDetail(request.getSubscribeDetail());
entity.setServerId(request.getServerId());
this.save(entity);
return VIIDSubscribesResponse.create(response.getResponseStatusListObject().getResponseStatusObject());
}
@Override
public VIIDSubscribesResponse unSubscribes(VIIDSubscribeRequest request) {
VIIDServer setting = viidServerService.getCurrentServer();
VIIDSubscribe subscribe = this.getById(request.getSubscribeId());
if (Objects.isNull(subscribe))
return VIIDSubscribesResponse.create( | Collections.singletonList(new ResponseStatusObject("", "500", "订阅不存在")) | 2 | 2023-10-23 11:25:43+00:00 | 8k |
eclipse-egit/egit | org.eclipse.egit.gitflow.test/src/org/eclipse/egit/gitflow/op/FeatureFinishOperationTest.java | [
{
"identifier": "BranchOperation",
"path": "org.eclipse.egit.core/src/org/eclipse/egit/core/op/BranchOperation.java",
"snippet": "public class BranchOperation implements IEGitOperation {\n\n\tprivate final String target;\n\n\tprivate Repository[] repositories;\n\n\tprivate @NonNull Map<Repository, Check... | import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.io.File;
import org.eclipse.egit.core.op.BranchOperation;
import org.eclipse.egit.gitflow.GitFlowRepository;
import org.eclipse.egit.gitflow.WrongGitFlowStateException;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.Status;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevCommit;
import org.junit.Test; | 5,095 | /*******************************************************************************
* Copyright (C) 2015, Max Hohenegger <eclipse@hohenegger.eu>
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License 2.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*******************************************************************************/
package org.eclipse.egit.gitflow.op;
public class FeatureFinishOperationTest extends AbstractFeatureOperationTest {
@Test
public void testFeatureFinishFastForward() throws Exception {
String fileName = "theFirstFile.txt";
Repository repository = testRepository.getRepository(); | /*******************************************************************************
* Copyright (C) 2015, Max Hohenegger <eclipse@hohenegger.eu>
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License 2.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*******************************************************************************/
package org.eclipse.egit.gitflow.op;
public class FeatureFinishOperationTest extends AbstractFeatureOperationTest {
@Test
public void testFeatureFinishFastForward() throws Exception {
String fileName = "theFirstFile.txt";
Repository repository = testRepository.getRepository(); | GitFlowRepository gfRepo = init("testFeatureFinish\n\nfirst commit\n"); | 1 | 2023-10-20 15:17:51+00:00 | 8k |
leforero4-ui/unico_proyecto_con_todos_los_patrones_de_diseno_en_java | src/main/application/driver/adapter/usecase/Game.java | [
{
"identifier": "BigBoard",
"path": "src/main/application/driver/adapter/usecase/board/BigBoard.java",
"snippet": "public class BigBoard implements BoardCollection<Enemy> {\n private final Enemy[][] squares;\n private final PatternsIterator<Enemy> iterator;\n private static final int ROWS = 8;\... | import java.util.ArrayList;
import java.util.List;
import main.application.driver.adapter.usecase.board.BigBoard;
import main.application.driver.adapter.usecase.expression.ConjunctionExpression;
import main.application.driver.adapter.usecase.expression.Context;
import main.application.driver.adapter.usecase.expression.AlternativeExpression;
import main.application.driver.adapter.usecase.expression.EnemyExpression;
import main.application.driver.adapter.usecase.factory_enemies.EnemyBasicMethod;
import main.application.driver.adapter.usecase.factory_enemies.EnemyHighMethod;
import main.application.driver.adapter.usecase.factory_enemies.EnemyMiddleMethod;
import main.application.driver.adapter.usecase.mission.BasicMission;
import main.application.driver.adapter.usecase.mission.HighMission;
import main.application.driver.adapter.usecase.mission.MiddleMission;
import main.application.driver.port.usecase.EnemyMethod;
import main.application.driver.port.usecase.Expression;
import main.application.driver.port.usecase.GameableUseCase;
import main.application.driver.port.usecase.iterator.BoardCollection;
import main.application.driver.port.usecase.iterator.PatternsIterator;
import main.domain.model.ArmyFactory;
import main.domain.model.CaretakerPlayer;
import main.domain.model.Command;
import main.domain.model.Enemy;
import main.domain.model.FavorableEnvironment;
import main.domain.model.Healable;
import main.domain.model.Mission;
import main.domain.model.Player;
import main.domain.model.Player.MementoPlayer;
import main.domain.model.command.Attack;
import main.domain.model.command.HealingPlayer;
import main.domain.model.Visitor; | 7,160 | package main.application.driver.adapter.usecase;
public class Game implements GameableUseCase {
private final ArmyFactory armyFactory;
private EnemyMethod enemyMethod; | package main.application.driver.adapter.usecase;
public class Game implements GameableUseCase {
private final ArmyFactory armyFactory;
private EnemyMethod enemyMethod; | private final Player player; | 23 | 2023-10-20 18:36:47+00:00 | 8k |
greatwqs/finance-manager | src/main/java/com/github/greatwqs/app/service/impl/UserServiceImpl.java | [
{
"identifier": "AppException",
"path": "src/main/java/com/github/greatwqs/app/common/exception/AppException.java",
"snippet": "public class AppException extends RuntimeException {\n\n private ErrorCode errorCode;\n\n // rewrite default msg in i18n/message.properties\n private String errorMsg;\... | import com.github.greatwqs.app.common.exception.AppException;
import com.github.greatwqs.app.common.exception.ErrorCode;
import com.github.greatwqs.app.domain.po.UserLoginHistoryPo;
import com.github.greatwqs.app.domain.vo.UserVo;
import com.github.greatwqs.app.manager.UserManager;
import com.github.greatwqs.app.mapper.UserlistLoginHistoryMapper;
import com.github.greatwqs.app.mapper.UserlistMapper;
import com.github.greatwqs.app.utils.PublicUtils;
import com.github.greatwqs.app.utils.collection.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.github.greatwqs.app.domain.po.UserPo;
import com.github.greatwqs.app.service.UserService;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import static com.github.greatwqs.app.common.AppConstants.*; | 5,122 | package com.github.greatwqs.app.service.impl;
/**
* @author greatwqs
* Create on 2020/6/25
*/
@Slf4j
@Service
public class UserServiceImpl implements UserService {
@Autowired
private ModelMapper modelMapper;
@Autowired
private UserlistMapper userlistMapper;
@Autowired
private UserlistLoginHistoryMapper userlistLoginHistoryMapper;
@Autowired
private UserManager userManager;
@Override
@Transactional
public String login(String username, String password, String loginIp) {
UserPo userPo = this.userManager.getPoByName(username);
if (userPo == null || !StringUtils.equals(userPo.getPassword(), password)) {
log.warn("user login not ok, username: " + username + ", password: " + password);
return StringUtils.EMPTY;
}
final String loginToken = PublicUtils.getUuid();
log.info("user login ok, username: " + username + ", password: " + password);
this.insertLoginHistory(userPo, loginToken, loginIp);
return loginToken;
}
private void insertLoginHistory(UserPo userPo, String loginToken, String loginIp) {
UserLoginHistoryPo history = new UserLoginHistoryPo();
history.setId(null);
history.setUserid(userPo.getId());
history.setLoginip(loginIp);
history.setLogintoken(loginToken);
history.setExpiretime(new Date(System.currentTimeMillis() + USER_LOGIN_SESSION_EXPIRE_TIME));
history.setIsvalid(true);
history.setCreatetime(new Date());
history.setUpdatetime(new Date());
userlistLoginHistoryMapper.insertSelective(history);
}
@Override
@Transactional
public void logout(UserPo userPo, String loginToken) {
userlistLoginHistoryMapper.updateIsValid(loginToken, userPo.getId());
}
@Override
public List<UserVo> allUsers(UserPo userPo) {
if (!userPo.getIssuperadmin()) { | package com.github.greatwqs.app.service.impl;
/**
* @author greatwqs
* Create on 2020/6/25
*/
@Slf4j
@Service
public class UserServiceImpl implements UserService {
@Autowired
private ModelMapper modelMapper;
@Autowired
private UserlistMapper userlistMapper;
@Autowired
private UserlistLoginHistoryMapper userlistLoginHistoryMapper;
@Autowired
private UserManager userManager;
@Override
@Transactional
public String login(String username, String password, String loginIp) {
UserPo userPo = this.userManager.getPoByName(username);
if (userPo == null || !StringUtils.equals(userPo.getPassword(), password)) {
log.warn("user login not ok, username: " + username + ", password: " + password);
return StringUtils.EMPTY;
}
final String loginToken = PublicUtils.getUuid();
log.info("user login ok, username: " + username + ", password: " + password);
this.insertLoginHistory(userPo, loginToken, loginIp);
return loginToken;
}
private void insertLoginHistory(UserPo userPo, String loginToken, String loginIp) {
UserLoginHistoryPo history = new UserLoginHistoryPo();
history.setId(null);
history.setUserid(userPo.getId());
history.setLoginip(loginIp);
history.setLogintoken(loginToken);
history.setExpiretime(new Date(System.currentTimeMillis() + USER_LOGIN_SESSION_EXPIRE_TIME));
history.setIsvalid(true);
history.setCreatetime(new Date());
history.setUpdatetime(new Date());
userlistLoginHistoryMapper.insertSelective(history);
}
@Override
@Transactional
public void logout(UserPo userPo, String loginToken) {
userlistLoginHistoryMapper.updateIsValid(loginToken, userPo.getId());
}
@Override
public List<UserVo> allUsers(UserPo userPo) {
if (!userPo.getIssuperadmin()) { | return Lists.newLinkedList(); | 8 | 2023-10-16 12:45:57+00:00 | 8k |
Wind-Gone/Vodka | code/src/main/java/utils/common/TableInfoCollector.java | [
{
"identifier": "OLAPTerminal",
"path": "code/src/main/java/benchmark/olap/OLAPTerminal.java",
"snippet": "public class OLAPTerminal implements Runnable {\n // public static AtomicInteger DeliveryBG=new AtomicInteger(0);\n public static AtomicLong oorderTableSize = new AtomicLong(benchmark.olap.qu... | import benchmark.olap.OLAPTerminal;
import config.CommonConfig;
import org.apache.log4j.Logger;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong; | 4,995 | package utils.common;
public class TableInfoCollector implements Runnable {
private static org.apache.log4j.Logger log = Logger.getLogger(TableInfoCollector.class);
int timeInterval;
String sConn;
Properties dbprop;
Connection conn_tableStaticsCollect = null;
int dbType;
int sys_Tps_Limit;
double neworderWeight;
double paymentWeight;
double deliveryWeight;
double receiveGoodsWeight;
SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //将毫秒级long值转换成日期格式
public TableInfoCollector(String iConn, Properties idbProps, int testTimeInterval, int dbType, int tps_limit, double ineworderWeight, double ipaymentWeight, double ideliveryWeight, double ireceiveGoodsWeight) {
this.sConn = iConn;
this.dbprop = idbProps;
this.timeInterval = testTimeInterval;
this.dbType = dbType;
this.sys_Tps_Limit = tps_limit;
this.neworderWeight = ineworderWeight;
this.paymentWeight = ipaymentWeight;
this.deliveryWeight = ideliveryWeight;
this.receiveGoodsWeight = ireceiveGoodsWeight;
}
public TableInfoCollector(String iConn, Properties dbProps, int dbType, int tps_limit, double ineworderWeight, double ipaymentWeight, double ideliveryWeight, double ireceiveGoodsWeight) {
this(iConn, dbProps, 5, dbType, tps_limit, ineworderWeight, ipaymentWeight, ideliveryWeight, ireceiveGoodsWeight);
}
@Override
public void run() {
// 执行信息收集任务的代码,定期收集两个表的数据
long startTimestamp = System.currentTimeMillis();
long currentTimestamp = startTimestamp;
boolean systemNotStopRunning = true;
// log.info("startTimestamp: " + dateformat.format(new Timestamp(startTimestamp).getTime()));
// log.info("currentTimestamp: " + dateformat.format(new Timestamp(currentTimestamp).getTime()));
try {
long delta;
do {
// log.info("开始执行信息收集任务...");
conn_tableStaticsCollect = DriverManager.getConnection(sConn, dbprop);
updateTableStaticsStatusLine(conn_tableStaticsCollect);
conn_tableStaticsCollect.close();
// log.info("信息收集任务执行完成。开始更新状态信息。。");
startTimestamp = currentTimestamp;
if (benchmark.oltp.OLTPClient.getSignalTerminalsRequestEndSent())
systemNotStopRunning = false;
do {
currentTimestamp = System.currentTimeMillis();
delta = currentTimestamp - startTimestamp;
} while ((delta < 5000) && (systemNotStopRunning));
} while ((delta >= 5000) && (systemNotStopRunning));
} catch (SQLException e) {
e.printStackTrace();
}
}
synchronized public void updateTableStaticsStatusLine(Connection dconn) throws SQLException {
//may be can be changed
int mode = 1; //mode=0 use select count table-real ,mode=1 use tps plus time count table-estimate
if (mode == 0) {
String sql1, sql2;
if (dbType == CommonConfig.DB_TIDB) {
sql1 = "SELECT /*+ read_from_storage(tiflash[vodka_oorder]) */ count(*) AS oorderTableSize FROM vodka_oorder";
sql2 = "SELECT /*+ read_from_storage(tiflash[vodka_order_line]) */ count(*) AS OrderlineTableSize FROM vodka_order_line";
} else {
sql1 = "SELECT count(*) AS oorderTableSize FROM vodka_oorder";
sql2 = "SELECT count(*) AS OrderlineTableSize FROM vodka_order_line";
}
PreparedStatement stmt1 = dconn.prepareStatement(sql1);
ResultSet rs1 = stmt1.executeQuery();
if (!rs1.next())
throw new SQLException("get oorder table size error!"); | package utils.common;
public class TableInfoCollector implements Runnable {
private static org.apache.log4j.Logger log = Logger.getLogger(TableInfoCollector.class);
int timeInterval;
String sConn;
Properties dbprop;
Connection conn_tableStaticsCollect = null;
int dbType;
int sys_Tps_Limit;
double neworderWeight;
double paymentWeight;
double deliveryWeight;
double receiveGoodsWeight;
SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //将毫秒级long值转换成日期格式
public TableInfoCollector(String iConn, Properties idbProps, int testTimeInterval, int dbType, int tps_limit, double ineworderWeight, double ipaymentWeight, double ideliveryWeight, double ireceiveGoodsWeight) {
this.sConn = iConn;
this.dbprop = idbProps;
this.timeInterval = testTimeInterval;
this.dbType = dbType;
this.sys_Tps_Limit = tps_limit;
this.neworderWeight = ineworderWeight;
this.paymentWeight = ipaymentWeight;
this.deliveryWeight = ideliveryWeight;
this.receiveGoodsWeight = ireceiveGoodsWeight;
}
public TableInfoCollector(String iConn, Properties dbProps, int dbType, int tps_limit, double ineworderWeight, double ipaymentWeight, double ideliveryWeight, double ireceiveGoodsWeight) {
this(iConn, dbProps, 5, dbType, tps_limit, ineworderWeight, ipaymentWeight, ideliveryWeight, ireceiveGoodsWeight);
}
@Override
public void run() {
// 执行信息收集任务的代码,定期收集两个表的数据
long startTimestamp = System.currentTimeMillis();
long currentTimestamp = startTimestamp;
boolean systemNotStopRunning = true;
// log.info("startTimestamp: " + dateformat.format(new Timestamp(startTimestamp).getTime()));
// log.info("currentTimestamp: " + dateformat.format(new Timestamp(currentTimestamp).getTime()));
try {
long delta;
do {
// log.info("开始执行信息收集任务...");
conn_tableStaticsCollect = DriverManager.getConnection(sConn, dbprop);
updateTableStaticsStatusLine(conn_tableStaticsCollect);
conn_tableStaticsCollect.close();
// log.info("信息收集任务执行完成。开始更新状态信息。。");
startTimestamp = currentTimestamp;
if (benchmark.oltp.OLTPClient.getSignalTerminalsRequestEndSent())
systemNotStopRunning = false;
do {
currentTimestamp = System.currentTimeMillis();
delta = currentTimestamp - startTimestamp;
} while ((delta < 5000) && (systemNotStopRunning));
} while ((delta >= 5000) && (systemNotStopRunning));
} catch (SQLException e) {
e.printStackTrace();
}
}
synchronized public void updateTableStaticsStatusLine(Connection dconn) throws SQLException {
//may be can be changed
int mode = 1; //mode=0 use select count table-real ,mode=1 use tps plus time count table-estimate
if (mode == 0) {
String sql1, sql2;
if (dbType == CommonConfig.DB_TIDB) {
sql1 = "SELECT /*+ read_from_storage(tiflash[vodka_oorder]) */ count(*) AS oorderTableSize FROM vodka_oorder";
sql2 = "SELECT /*+ read_from_storage(tiflash[vodka_order_line]) */ count(*) AS OrderlineTableSize FROM vodka_order_line";
} else {
sql1 = "SELECT count(*) AS oorderTableSize FROM vodka_oorder";
sql2 = "SELECT count(*) AS OrderlineTableSize FROM vodka_order_line";
}
PreparedStatement stmt1 = dconn.prepareStatement(sql1);
ResultSet rs1 = stmt1.executeQuery();
if (!rs1.next())
throw new SQLException("get oorder table size error!"); | OLAPTerminal.oorderTableSize = new AtomicLong(rs1.getInt("oorderTableSize")); | 0 | 2023-10-22 11:22:32+00:00 | 8k |
Onuraktasj/stock-tracking-system | src/main/java/com/onuraktas/stocktrackingsystem/impl/ProductServiceImpl.java | [
{
"identifier": "ProductProducer",
"path": "src/main/java/com/onuraktas/stocktrackingsystem/amqp/producer/ProductProducer.java",
"snippet": "@Component\npublic class ProductProducer {\n\n private final RabbitTemplate rabbitTemplate;\n\n public ProductProducer(RabbitTemplate rabbitTemplate) {\n ... | import com.onuraktas.stocktrackingsystem.amqp.producer.ProductProducer;
import com.onuraktas.stocktrackingsystem.constant.QueueName;
import com.onuraktas.stocktrackingsystem.dto.amqp.DeletedProductMessage;
import com.onuraktas.stocktrackingsystem.dto.entity.ProductDto;
import com.onuraktas.stocktrackingsystem.dto.general.SimpleCategory;
import com.onuraktas.stocktrackingsystem.dto.request.CreateProductRequest;
import com.onuraktas.stocktrackingsystem.dto.request.UpdateProductAmountRequest;
import com.onuraktas.stocktrackingsystem.dto.response.CreateProductResponse;
import com.onuraktas.stocktrackingsystem.dto.response.DeleteProductByIdResponse;
import com.onuraktas.stocktrackingsystem.entity.Category;
import com.onuraktas.stocktrackingsystem.entity.CategoryProductRel;
import com.onuraktas.stocktrackingsystem.entity.Product;
import com.onuraktas.stocktrackingsystem.entity.enums.Status;
import com.onuraktas.stocktrackingsystem.exception.ProductBadRequestException;
import com.onuraktas.stocktrackingsystem.exception.ProductNotFoundException;
import com.onuraktas.stocktrackingsystem.helper.GeneralValues;
import com.onuraktas.stocktrackingsystem.mapper.ProductMapper;
import com.onuraktas.stocktrackingsystem.message.ExceptionMessages;
import com.onuraktas.stocktrackingsystem.message.ProductMessages;
import com.onuraktas.stocktrackingsystem.repository.CategoryProductRelRepository;
import com.onuraktas.stocktrackingsystem.repository.CategoryRepository;
import com.onuraktas.stocktrackingsystem.repository.ProductRepository;
import com.onuraktas.stocktrackingsystem.service.ProductService;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.*; | 3,870 | package com.onuraktas.stocktrackingsystem.impl;
@Service
public class ProductServiceImpl implements ProductService {
private final ProductRepository productRepository;
private final CategoryProductRelRepository categoryProductRelRepository;
private final CategoryRepository categoryRepository;
private final ProductProducer productProducer;
public ProductServiceImpl (ProductRepository productRepository, CategoryProductRelRepository categoryProductRelRepository, CategoryRepository categoryRepository, ProductProducer productProducer){
this.productRepository = productRepository;
this.categoryProductRelRepository = categoryProductRelRepository;
this.categoryRepository = categoryRepository;
this.productProducer = productProducer;
}
@Override
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public CreateProductResponse createProduct(CreateProductRequest createProductRequest) {
this.validateCreateProductRequest(createProductRequest);
List<Category> categoryList = this.categoryRepository.findAllByCategoryIdInAndIsActive(createProductRequest.getCategoryList().stream().map(SimpleCategory::getCategoryId).toList(), Boolean.TRUE);
if (categoryList.isEmpty())
throw new ProductBadRequestException(ProductMessages.CATEGORY_NOT_FOUND);
List<UUID> categoryIdList = categoryList.stream().map(Category::getCategoryId).toList();
Product product = this.productRepository.save(ProductMapper.toEntity(createProductRequest));
CreateProductResponse createProductResponse = ProductMapper.toCreateProductResponse(product);
createProductResponse.setStatus(Status.OK.getStatus());
List<CategoryProductRel> categoryProductRelList = new ArrayList<>();
for (UUID categoryId : categoryIdList) {
categoryProductRelList.add(CategoryProductRel.builder().categoryId(categoryId).productId(product.getProductId()).build());
}
this.categoryProductRelRepository.saveAll(categoryProductRelList);
return createProductResponse;
}
@Override
public List<ProductDto> getAllProduct() {
return ProductMapper.toDtoList(productRepository.findAll());
}
@Override
public ProductDto getProduct(UUID productId) {
return ProductMapper.toDto(productRepository.findById(productId).orElseThrow(()-> new NoSuchElementException(ProductMessages.PRODUCT_NOT_FOUND)));
}
@Override
public ResponseEntity<ProductDto> updateProduct(UUID productId, ProductDto productDto) {
if (Objects.isNull(productId) || Objects.isNull(productDto.getProductId()) || !Objects.equals(productId,productDto.getProductId()))
return ResponseEntity.badRequest().build();
Optional<Product> existProduct = productRepository.findById(productId);
if (existProduct.isEmpty())
return ResponseEntity.notFound().build();
final ProductDto updateProduct = this.save(productDto);
if (Objects.nonNull(updateProduct))
return ResponseEntity.ok(updateProduct);
return ResponseEntity.internalServerError().build();
}
@Override
public ProductDto updateProductAmount(UUID productId, UpdateProductAmountRequest request) {
Product product = productRepository.findById(productId).orElseThrow(()-> new NoSuchElementException(ProductMessages.PRODUCT_NOT_FOUND));
product.setAmount(request.getAmount());
productRepository.save(product);
return ProductMapper.toDto(productRepository.save(product));
}
@Override
public DeleteProductByIdResponse deleteProductById(UUID productId) {
Product deletedProduct = this.productRepository.findByProductIdAndIsActive(productId, Boolean.TRUE).orElseThrow(()-> new ProductNotFoundException(ProductMessages.PRODUCT_NOT_FOUND));
deletedProduct.setIsActive(Boolean.FALSE);
this.productRepository.save(deletedProduct);
List<CategoryProductRel> categoryProductRelList = this.categoryProductRelRepository.findAllByProductIdAndIsActive(productId, Boolean.TRUE);
categoryProductRelList.forEach(categoryProductRel -> {
categoryProductRel.setIsActive(Boolean.FALSE);
});
this.categoryProductRelRepository.saveAll(categoryProductRelList);
return DeleteProductByIdResponse.builder().productId(productId).isActive(Boolean.FALSE).build();
}
@Override
public List<ProductDto> getProductListByCategory(UUID categoryId) {
List<UUID> productIdList = this.categoryProductRelRepository.findAllByCategoryIdAndIsActive(categoryId, Boolean.TRUE).stream().map(CategoryProductRel::getProductId).toList();
if (productIdList.isEmpty())
throw new ProductNotFoundException(ProductMessages.PRODUCT_NOT_FOUND);
List<ProductDto> productDtoList = ProductMapper.toDtoList(this.productRepository.findAllByProductIdInAndIsActive(productIdList, Boolean.TRUE));
if (productDtoList.isEmpty())
throw new ProductNotFoundException(ProductMessages.PRODUCT_NOT_FOUND);
return productDtoList;
}
@Override
public void deleteProductListByProductListIdList(List<UUID> productIdList) {
List<Product> productList = this.productRepository.findAllByProductIdInAndIsActive(productIdList, Boolean.TRUE);
productList.forEach(product -> product.setIsActive(Boolean.FALSE));
this.productRepository.saveAll(productList);
List<DeletedProductMessage> deletedProductMessageList = new ArrayList<>();
productList.stream().map(Product::getProductId).forEach(productId -> deletedProductMessageList.add(DeletedProductMessage.builder().productId(productId).build()));
this.productProducer.sendToQueue(QueueName.DELETED_PRODUCT_QUEUE, deletedProductMessageList);
}
private ProductDto save (ProductDto productDto){
Product product = ProductMapper.toEntity(productDto);
product = productRepository.save(product);
return ProductMapper.toDto(product);
}
private void validateCreateProductRequest(CreateProductRequest createProductRequest) {
if (Objects.isNull(createProductRequest))
throw new ProductBadRequestException(ExceptionMessages.BAD_REQUEST);
if (Objects.isNull(createProductRequest.getCategoryList()) || createProductRequest.getCategoryList().isEmpty())
throw new ProductBadRequestException(ProductMessages.CATEGORY_LIST_EMPTY);
| package com.onuraktas.stocktrackingsystem.impl;
@Service
public class ProductServiceImpl implements ProductService {
private final ProductRepository productRepository;
private final CategoryProductRelRepository categoryProductRelRepository;
private final CategoryRepository categoryRepository;
private final ProductProducer productProducer;
public ProductServiceImpl (ProductRepository productRepository, CategoryProductRelRepository categoryProductRelRepository, CategoryRepository categoryRepository, ProductProducer productProducer){
this.productRepository = productRepository;
this.categoryProductRelRepository = categoryProductRelRepository;
this.categoryRepository = categoryRepository;
this.productProducer = productProducer;
}
@Override
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public CreateProductResponse createProduct(CreateProductRequest createProductRequest) {
this.validateCreateProductRequest(createProductRequest);
List<Category> categoryList = this.categoryRepository.findAllByCategoryIdInAndIsActive(createProductRequest.getCategoryList().stream().map(SimpleCategory::getCategoryId).toList(), Boolean.TRUE);
if (categoryList.isEmpty())
throw new ProductBadRequestException(ProductMessages.CATEGORY_NOT_FOUND);
List<UUID> categoryIdList = categoryList.stream().map(Category::getCategoryId).toList();
Product product = this.productRepository.save(ProductMapper.toEntity(createProductRequest));
CreateProductResponse createProductResponse = ProductMapper.toCreateProductResponse(product);
createProductResponse.setStatus(Status.OK.getStatus());
List<CategoryProductRel> categoryProductRelList = new ArrayList<>();
for (UUID categoryId : categoryIdList) {
categoryProductRelList.add(CategoryProductRel.builder().categoryId(categoryId).productId(product.getProductId()).build());
}
this.categoryProductRelRepository.saveAll(categoryProductRelList);
return createProductResponse;
}
@Override
public List<ProductDto> getAllProduct() {
return ProductMapper.toDtoList(productRepository.findAll());
}
@Override
public ProductDto getProduct(UUID productId) {
return ProductMapper.toDto(productRepository.findById(productId).orElseThrow(()-> new NoSuchElementException(ProductMessages.PRODUCT_NOT_FOUND)));
}
@Override
public ResponseEntity<ProductDto> updateProduct(UUID productId, ProductDto productDto) {
if (Objects.isNull(productId) || Objects.isNull(productDto.getProductId()) || !Objects.equals(productId,productDto.getProductId()))
return ResponseEntity.badRequest().build();
Optional<Product> existProduct = productRepository.findById(productId);
if (existProduct.isEmpty())
return ResponseEntity.notFound().build();
final ProductDto updateProduct = this.save(productDto);
if (Objects.nonNull(updateProduct))
return ResponseEntity.ok(updateProduct);
return ResponseEntity.internalServerError().build();
}
@Override
public ProductDto updateProductAmount(UUID productId, UpdateProductAmountRequest request) {
Product product = productRepository.findById(productId).orElseThrow(()-> new NoSuchElementException(ProductMessages.PRODUCT_NOT_FOUND));
product.setAmount(request.getAmount());
productRepository.save(product);
return ProductMapper.toDto(productRepository.save(product));
}
@Override
public DeleteProductByIdResponse deleteProductById(UUID productId) {
Product deletedProduct = this.productRepository.findByProductIdAndIsActive(productId, Boolean.TRUE).orElseThrow(()-> new ProductNotFoundException(ProductMessages.PRODUCT_NOT_FOUND));
deletedProduct.setIsActive(Boolean.FALSE);
this.productRepository.save(deletedProduct);
List<CategoryProductRel> categoryProductRelList = this.categoryProductRelRepository.findAllByProductIdAndIsActive(productId, Boolean.TRUE);
categoryProductRelList.forEach(categoryProductRel -> {
categoryProductRel.setIsActive(Boolean.FALSE);
});
this.categoryProductRelRepository.saveAll(categoryProductRelList);
return DeleteProductByIdResponse.builder().productId(productId).isActive(Boolean.FALSE).build();
}
@Override
public List<ProductDto> getProductListByCategory(UUID categoryId) {
List<UUID> productIdList = this.categoryProductRelRepository.findAllByCategoryIdAndIsActive(categoryId, Boolean.TRUE).stream().map(CategoryProductRel::getProductId).toList();
if (productIdList.isEmpty())
throw new ProductNotFoundException(ProductMessages.PRODUCT_NOT_FOUND);
List<ProductDto> productDtoList = ProductMapper.toDtoList(this.productRepository.findAllByProductIdInAndIsActive(productIdList, Boolean.TRUE));
if (productDtoList.isEmpty())
throw new ProductNotFoundException(ProductMessages.PRODUCT_NOT_FOUND);
return productDtoList;
}
@Override
public void deleteProductListByProductListIdList(List<UUID> productIdList) {
List<Product> productList = this.productRepository.findAllByProductIdInAndIsActive(productIdList, Boolean.TRUE);
productList.forEach(product -> product.setIsActive(Boolean.FALSE));
this.productRepository.saveAll(productList);
List<DeletedProductMessage> deletedProductMessageList = new ArrayList<>();
productList.stream().map(Product::getProductId).forEach(productId -> deletedProductMessageList.add(DeletedProductMessage.builder().productId(productId).build()));
this.productProducer.sendToQueue(QueueName.DELETED_PRODUCT_QUEUE, deletedProductMessageList);
}
private ProductDto save (ProductDto productDto){
Product product = ProductMapper.toEntity(productDto);
product = productRepository.save(product);
return ProductMapper.toDto(product);
}
private void validateCreateProductRequest(CreateProductRequest createProductRequest) {
if (Objects.isNull(createProductRequest))
throw new ProductBadRequestException(ExceptionMessages.BAD_REQUEST);
if (Objects.isNull(createProductRequest.getCategoryList()) || createProductRequest.getCategoryList().isEmpty())
throw new ProductBadRequestException(ProductMessages.CATEGORY_LIST_EMPTY);
| if (createProductRequest.getCategoryList().size() > GeneralValues.CATEGORY_MAX_SIZE) | 15 | 2023-10-23 19:00:09+00:00 | 8k |
ushh789/FinancialCalculator | src/main/java/com/netrunners/financialcalculator/LogicalInstrumnts/FileInstruments/OpenFile.java | [
{
"identifier": "Credit",
"path": "src/main/java/com/netrunners/financialcalculator/LogicalInstrumnts/TypesOfFinancialOpearation/Credit/Credit.java",
"snippet": "public class Credit implements Savable {\n protected float loan;\n protected String currency;\n protected float annualPercent;\n p... | import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.netrunners.financialcalculator.LogicalInstrumnts.TypesOfFinancialOpearation.Credit.Credit;
import com.netrunners.financialcalculator.LogicalInstrumnts.TypesOfFinancialOpearation.Credit.CreditWithHolidays;
import com.netrunners.financialcalculator.LogicalInstrumnts.TypesOfFinancialOpearation.Credit.CreditWithoutHolidays;
import com.netrunners.financialcalculator.LogicalInstrumnts.TypesOfFinancialOpearation.Deposit.CapitalisedDeposit;
import com.netrunners.financialcalculator.LogicalInstrumnts.TypesOfFinancialOpearation.Deposit.Deposit;
import com.netrunners.financialcalculator.LogicalInstrumnts.TypesOfFinancialOpearation.Deposit.UncapitalisedDeposit;
import com.netrunners.financialcalculator.VisualInstruments.MenuActions.LanguageManager;
import javafx.scene.image.Image;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.time.LocalDate;
import java.util.logging.Level;
import static com.netrunners.financialcalculator.StartMenu.startMenuScene; | 4,950 | package com.netrunners.financialcalculator.LogicalInstrumnts.FileInstruments;
public class OpenFile {
public static void openFromSave() {
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle(LanguageManager.getInstance().getStringBinding("ChooseOpenFile").get());
fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("JSON files (*.json)", "*.json"));
File initialDirectory = new File("saves/");
fileChooser.setInitialDirectory(initialDirectory);
File selectedFile = fileChooser.showOpenDialog(null);
if (selectedFile != null) {
try (FileReader reader = new FileReader(selectedFile)) {
Gson gson = new Gson();
JsonObject jsonObject = gson.fromJson(reader, JsonObject.class);
String operationType = jsonObject.get("operation").getAsString();
switch (operationType) {
case "Credit" -> {
Credit credit = createCredit(jsonObject);
credit.sendCreditToResultTable();
}
case "Deposit" -> {
Deposit deposit = createDeposit(jsonObject);
deposit.sendDepositToResultTable();
}
default -> LogHelper.log(Level.WARNING, "Can't open file with operation type: " + operationType, null);
}
} catch (IOException | JsonParseException e) {
LogHelper.log(Level.SEVERE, "Error while opening file", e);
}
}
}
private static Credit createCredit(JsonObject jsonObject) {
Credit credit = null;
try {
float loan = jsonObject.get("loan").getAsFloat();
float annualPercent = jsonObject.get("annualPercent").getAsFloat();
int paymentType = jsonObject.get("paymentType").getAsInt();
String currency = jsonObject.get("currency").getAsString();
String startDateString = jsonObject.get("startDate").getAsString();
LocalDate startDate = LocalDate.parse(startDateString);
String endDateString = jsonObject.get("endDate").getAsString();
LocalDate endDate = LocalDate.parse(endDateString);
if (jsonObject.get("type").getAsString().equals("WithHolidays")) {
String holidaysStartString = jsonObject.get("holidaysStart").getAsString();
LocalDate holidaysStart = LocalDate.parse(holidaysStartString);
String holidaysEndString = jsonObject.get("holidaysEnd").getAsString();
LocalDate holidaysEnd = LocalDate.parse(holidaysEndString); | package com.netrunners.financialcalculator.LogicalInstrumnts.FileInstruments;
public class OpenFile {
public static void openFromSave() {
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle(LanguageManager.getInstance().getStringBinding("ChooseOpenFile").get());
fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("JSON files (*.json)", "*.json"));
File initialDirectory = new File("saves/");
fileChooser.setInitialDirectory(initialDirectory);
File selectedFile = fileChooser.showOpenDialog(null);
if (selectedFile != null) {
try (FileReader reader = new FileReader(selectedFile)) {
Gson gson = new Gson();
JsonObject jsonObject = gson.fromJson(reader, JsonObject.class);
String operationType = jsonObject.get("operation").getAsString();
switch (operationType) {
case "Credit" -> {
Credit credit = createCredit(jsonObject);
credit.sendCreditToResultTable();
}
case "Deposit" -> {
Deposit deposit = createDeposit(jsonObject);
deposit.sendDepositToResultTable();
}
default -> LogHelper.log(Level.WARNING, "Can't open file with operation type: " + operationType, null);
}
} catch (IOException | JsonParseException e) {
LogHelper.log(Level.SEVERE, "Error while opening file", e);
}
}
}
private static Credit createCredit(JsonObject jsonObject) {
Credit credit = null;
try {
float loan = jsonObject.get("loan").getAsFloat();
float annualPercent = jsonObject.get("annualPercent").getAsFloat();
int paymentType = jsonObject.get("paymentType").getAsInt();
String currency = jsonObject.get("currency").getAsString();
String startDateString = jsonObject.get("startDate").getAsString();
LocalDate startDate = LocalDate.parse(startDateString);
String endDateString = jsonObject.get("endDate").getAsString();
LocalDate endDate = LocalDate.parse(endDateString);
if (jsonObject.get("type").getAsString().equals("WithHolidays")) {
String holidaysStartString = jsonObject.get("holidaysStart").getAsString();
LocalDate holidaysStart = LocalDate.parse(holidaysStartString);
String holidaysEndString = jsonObject.get("holidaysEnd").getAsString();
LocalDate holidaysEnd = LocalDate.parse(holidaysEndString); | credit = new CreditWithHolidays(loan, currency, annualPercent, startDate, endDate, paymentType, holidaysStart, holidaysEnd); | 1 | 2023-10-18 16:03:09+00:00 | 8k |
bowbahdoe/java-audio-stack | mp3spi/src/main/java/dev/mccue/mp3spi/mpeg/sampled/convert/MpegFormatConversionProvider.java | [
{
"identifier": "TDebug",
"path": "tritonus-share/src/main/java/dev/mccue/tritonus/share/TDebug.java",
"snippet": "public class TDebug\r\n{\r\n\tpublic static boolean\t\tSHOW_ACCESS_CONTROL_EXCEPTIONS = false;\r\n\tprivate static final String\tPROPERTY_PREFIX = \"tritonus.\";\r\n\t// The stream we outpu... | import dev.mccue.mp3spi.mpeg.sampled.file.MpegEncoding;
import dev.mccue.tritonus.share.TDebug;
import dev.mccue.tritonus.share.sampled.Encodings;
import dev.mccue.tritonus.share.sampled.convert.TEncodingFormatConversionProvider;
import java.util.Arrays;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
| 4,299 | /*
* MpegFormatConversionProvider.
*
* JavaZOOM : mp3spi@javazoom.net
* http://www.javazoom.net
*
* ---------------------------------------------------------------------------
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as published
* by the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
* --------------------------------------------------------------------------
*/
package dev.mccue.mp3spi.mpeg.sampled.convert;
/**
* ConversionProvider for MPEG files.
*/
public class MpegFormatConversionProvider extends TEncodingFormatConversionProvider
{
private static final AudioFormat.Encoding MP3 = Encodings.getEncoding("MP3");
private static final AudioFormat.Encoding PCM_SIGNED = Encodings.getEncoding("PCM_SIGNED");
private static final AudioFormat[] INPUT_FORMATS =
{
// mono
new AudioFormat(MP3, -1.0F, -1, 1, -1, -1.0F, false),
new AudioFormat(MP3, -1.0F, -1, 1, -1, -1.0F, true),
// stereo
new AudioFormat(MP3, -1.0F, -1, 2, -1, -1.0F, false),
new AudioFormat(MP3, -1.0F, -1, 2, -1, -1.0F, true),
};
private static final AudioFormat[] OUTPUT_FORMATS =
{
// mono, 16 bit signed
new AudioFormat(PCM_SIGNED, -1.0F, 16, 1, 2, -1.0F, false),
new AudioFormat(PCM_SIGNED, -1.0F, 16, 1, 2, -1.0F, true),
// stereo, 16 bit signed
new AudioFormat(PCM_SIGNED, -1.0F, 16, 2, 4, -1.0F, false),
new AudioFormat(PCM_SIGNED, -1.0F, 16, 2, 4, -1.0F, true),
};
/**
* Constructor.
*/
public MpegFormatConversionProvider()
{
super(Arrays.asList(INPUT_FORMATS), Arrays.asList(OUTPUT_FORMATS));
| /*
* MpegFormatConversionProvider.
*
* JavaZOOM : mp3spi@javazoom.net
* http://www.javazoom.net
*
* ---------------------------------------------------------------------------
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as published
* by the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
* --------------------------------------------------------------------------
*/
package dev.mccue.mp3spi.mpeg.sampled.convert;
/**
* ConversionProvider for MPEG files.
*/
public class MpegFormatConversionProvider extends TEncodingFormatConversionProvider
{
private static final AudioFormat.Encoding MP3 = Encodings.getEncoding("MP3");
private static final AudioFormat.Encoding PCM_SIGNED = Encodings.getEncoding("PCM_SIGNED");
private static final AudioFormat[] INPUT_FORMATS =
{
// mono
new AudioFormat(MP3, -1.0F, -1, 1, -1, -1.0F, false),
new AudioFormat(MP3, -1.0F, -1, 1, -1, -1.0F, true),
// stereo
new AudioFormat(MP3, -1.0F, -1, 2, -1, -1.0F, false),
new AudioFormat(MP3, -1.0F, -1, 2, -1, -1.0F, true),
};
private static final AudioFormat[] OUTPUT_FORMATS =
{
// mono, 16 bit signed
new AudioFormat(PCM_SIGNED, -1.0F, 16, 1, 2, -1.0F, false),
new AudioFormat(PCM_SIGNED, -1.0F, 16, 1, 2, -1.0F, true),
// stereo, 16 bit signed
new AudioFormat(PCM_SIGNED, -1.0F, 16, 2, 4, -1.0F, false),
new AudioFormat(PCM_SIGNED, -1.0F, 16, 2, 4, -1.0F, true),
};
/**
* Constructor.
*/
public MpegFormatConversionProvider()
{
super(Arrays.asList(INPUT_FORMATS), Arrays.asList(OUTPUT_FORMATS));
| if (TDebug.TraceAudioConverter)
| 0 | 2023-10-19 14:09:37+00:00 | 8k |
dvillavicencio/Riven-of-a-Thousand-Servers | src/test/java/com/danielvm/destiny2bot/integration/InteractionControllerTest.java | [
{
"identifier": "BungieConfiguration",
"path": "src/main/java/com/danielvm/destiny2bot/config/BungieConfiguration.java",
"snippet": "@Data\n@Configuration\n@ConfigurationProperties(prefix = \"bungie.api\")\npublic class BungieConfiguration implements OAuth2Configuration {\n\n /**\n * The name of the ... | import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching;
import static org.assertj.core.api.Assertions.assertThat;
import com.danielvm.destiny2bot.config.BungieConfiguration;
import com.danielvm.destiny2bot.config.DiscordConfiguration;
import com.danielvm.destiny2bot.dao.UserDetailsReactiveDao;
import com.danielvm.destiny2bot.dto.destiny.GenericResponse;
import com.danielvm.destiny2bot.dto.destiny.milestone.MilestoneEntry;
import com.danielvm.destiny2bot.dto.discord.DiscordUser;
import com.danielvm.destiny2bot.dto.discord.Interaction;
import com.danielvm.destiny2bot.dto.discord.InteractionData;
import com.danielvm.destiny2bot.dto.discord.Member;
import com.danielvm.destiny2bot.entity.UserDetails;
import com.danielvm.destiny2bot.enums.InteractionType;
import com.danielvm.destiny2bot.enums.ManifestEntity;
import com.danielvm.destiny2bot.util.MessageUtil;
import com.danielvm.destiny2bot.util.OAuth2Util;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.KeyPair;
import java.security.PublicKey;
import java.time.Instant;
import java.util.Map;
import java.util.Objects;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.test.web.reactive.server.WebTestClient.ResponseSpec;
import org.springframework.web.reactive.function.BodyInserters;
import software.pando.crypto.nacl.Crypto; | 4,738 | package com.danielvm.destiny2bot.integration;
public class InteractionControllerTest extends BaseIntegrationTest {
private static final String VALID_PRIVATE_KEY = "F0EA3A0516695324C03ED552CD5A08A58CA1248172E8816C3BF235E52E75A7BF";
private static final String MALICIOUS_PRIVATE_KEY = "CE4517095255B0C92D586AF9EEC27B998D68775363F9FE74341483FB3A657CEC";
// Static mapper to be used on the @BeforeAll static method
private static final ObjectMapper OBJECT_MAPPER = new JsonMapper.Builder(new JsonMapper())
.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false)
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.build()
.registerModule(new JavaTimeModule());
@Autowired
BungieConfiguration bungieConfiguration;
@Autowired
DiscordConfiguration discordConfiguration;
@Autowired
UserDetailsReactiveDao userDetailsReactiveDao;
/**
* This method replaces all the placeholder values in the milestones-response.json file The reason
* for this is that the /weekly_raid and /weekly_dungeon responses will be weird if the dates are
* not dynamic, therefore this method
*
* @throws IOException in case we are not able to write back to the file (in-place)
*/
@BeforeAll
public static void before() throws IOException {
File milestoneFile = new File("src/test/resources/__files/bungie/milestone-response.json");
TypeReference<GenericResponse<Map<String, MilestoneEntry>>> typeReference = new TypeReference<>() {
};
var milestoneResponse = OBJECT_MAPPER.readValue(milestoneFile, typeReference);
replaceDates(milestoneResponse, "526718853");
replaceDates(milestoneResponse, "2712317338");
OBJECT_MAPPER.writeValue(milestoneFile, milestoneResponse);
}
private static void replaceDates(GenericResponse<Map<String, MilestoneEntry>> response,
String hash) {
response.getResponse().entrySet().stream()
.filter(entry -> Objects.equals(entry.getKey(), hash))
.forEach(entry -> {
var startDate = entry.getValue().getStartDate();
var endDate = entry.getValue().getEndDate();
if (Objects.nonNull(startDate)) {
entry.getValue().setStartDate(MessageUtil.PREVIOUS_TUESDAY);
}
if (Objects.nonNull(endDate)) {
entry.getValue().setEndDate(MessageUtil.NEXT_TUESDAY);
}
});
}
| package com.danielvm.destiny2bot.integration;
public class InteractionControllerTest extends BaseIntegrationTest {
private static final String VALID_PRIVATE_KEY = "F0EA3A0516695324C03ED552CD5A08A58CA1248172E8816C3BF235E52E75A7BF";
private static final String MALICIOUS_PRIVATE_KEY = "CE4517095255B0C92D586AF9EEC27B998D68775363F9FE74341483FB3A657CEC";
// Static mapper to be used on the @BeforeAll static method
private static final ObjectMapper OBJECT_MAPPER = new JsonMapper.Builder(new JsonMapper())
.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false)
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.build()
.registerModule(new JavaTimeModule());
@Autowired
BungieConfiguration bungieConfiguration;
@Autowired
DiscordConfiguration discordConfiguration;
@Autowired
UserDetailsReactiveDao userDetailsReactiveDao;
/**
* This method replaces all the placeholder values in the milestones-response.json file The reason
* for this is that the /weekly_raid and /weekly_dungeon responses will be weird if the dates are
* not dynamic, therefore this method
*
* @throws IOException in case we are not able to write back to the file (in-place)
*/
@BeforeAll
public static void before() throws IOException {
File milestoneFile = new File("src/test/resources/__files/bungie/milestone-response.json");
TypeReference<GenericResponse<Map<String, MilestoneEntry>>> typeReference = new TypeReference<>() {
};
var milestoneResponse = OBJECT_MAPPER.readValue(milestoneFile, typeReference);
replaceDates(milestoneResponse, "526718853");
replaceDates(milestoneResponse, "2712317338");
OBJECT_MAPPER.writeValue(milestoneFile, milestoneResponse);
}
private static void replaceDates(GenericResponse<Map<String, MilestoneEntry>> response,
String hash) {
response.getResponse().entrySet().stream()
.filter(entry -> Objects.equals(entry.getKey(), hash))
.forEach(entry -> {
var startDate = entry.getValue().getStartDate();
var endDate = entry.getValue().getEndDate();
if (Objects.nonNull(startDate)) {
entry.getValue().setStartDate(MessageUtil.PREVIOUS_TUESDAY);
}
if (Objects.nonNull(endDate)) {
entry.getValue().setEndDate(MessageUtil.NEXT_TUESDAY);
}
});
}
| private String createValidSignature(Interaction body, String timestamp) | 6 | 2023-10-20 05:53:03+00:00 | 8k |
MinecraftForge/ModLauncher | ml-test/src/test/java/net/minecraftforge/modlauncher/test/TransformationServiceDecoratorTests.java | [
{
"identifier": "TransformList",
"path": "src/main/java/cpw/mods/modlauncher/TransformList.java",
"snippet": "@SuppressWarnings(\"WeakerAccess\")\npublic class TransformList<T> {\n private final Map<TransformTargetLabel, List<ITransformer<T>>> transformers = new ConcurrentHashMap<>();\n private fi... | import cpw.mods.modlauncher.TransformList;
import cpw.mods.modlauncher.TransformStore;
import cpw.mods.modlauncher.TransformTargetLabel;
import cpw.mods.modlauncher.TransformationServiceDecorator;
import cpw.mods.modlauncher.api.ITransformer;
import cpw.mods.modlauncher.api.ITransformerVotingContext;
import cpw.mods.modlauncher.api.TransformerVoteResult;
import net.minecraftforge.unsafe.UnsafeHacks;
import org.jetbrains.annotations.NotNull;
import org.junit.jupiter.api.Test;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodNode;
import org.powermock.reflect.Whitebox;
import java.lang.reflect.Method;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertTrue; | 5,341 | /*
* Copyright (c) Forge Development LLC
* SPDX-License-Identifier: LGPL-3.0-only
*/
package net.minecraftforge.modlauncher.test;
class TransformationServiceDecoratorTests {
private final ClassNodeTransformer classNodeTransformer = new ClassNodeTransformer();
private final MethodNodeTransformer methodNodeTransformer = new MethodNodeTransformer();
@Test
void testGatherTransformersNormally() throws Exception {
UnsafeHacksUtil.hackPowermock();
MockTransformerService mockTransformerService = new MockTransformerService() {
@NotNull
@Override
public List<ITransformer> transformers() {
return Stream.of(classNodeTransformer, methodNodeTransformer).collect(Collectors.toList());
}
}; | /*
* Copyright (c) Forge Development LLC
* SPDX-License-Identifier: LGPL-3.0-only
*/
package net.minecraftforge.modlauncher.test;
class TransformationServiceDecoratorTests {
private final ClassNodeTransformer classNodeTransformer = new ClassNodeTransformer();
private final MethodNodeTransformer methodNodeTransformer = new MethodNodeTransformer();
@Test
void testGatherTransformersNormally() throws Exception {
UnsafeHacksUtil.hackPowermock();
MockTransformerService mockTransformerService = new MockTransformerService() {
@NotNull
@Override
public List<ITransformer> transformers() {
return Stream.of(classNodeTransformer, methodNodeTransformer).collect(Collectors.toList());
}
}; | TransformStore store = new TransformStore(); | 1 | 2023-10-18 17:56:01+00:00 | 8k |
Kyrotechnic/KyroClient | Client/src/main/java/me/kyroclient/modules/combat/AutoBlock.java | [
{
"identifier": "KyroClient",
"path": "Client/src/main/java/me/kyroclient/KyroClient.java",
"snippet": "public class KyroClient {\n //Vars\n public static final String MOD_ID = \"dankers\";\n public static String VERSION = \"0.2-b3\";\n public static List<String> changelog;\n public stati... | import me.kyroclient.KyroClient;
import me.kyroclient.events.MotionUpdateEvent;
import me.kyroclient.modules.Module;
import me.kyroclient.settings.BooleanSetting;
import me.kyroclient.settings.ModeSetting;
import me.kyroclient.settings.NumberSetting;
import me.kyroclient.util.MilliTimer;
import me.kyroclient.util.MovementUtils;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemSword;
import net.minecraft.network.Packet;
import net.minecraft.network.play.client.C07PacketPlayerDigging;
import net.minecraft.network.play.client.C08PacketPlayerBlockPlacement;
import net.minecraft.util.BlockPos;
import net.minecraft.util.EnumFacing;
import net.minecraftforge.event.entity.player.AttackEntityEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; | 6,618 | package me.kyroclient.modules.combat;
public class AutoBlock extends Module
{ | package me.kyroclient.modules.combat;
public class AutoBlock extends Module
{ | public ModeSetting mode; | 4 | 2023-10-15 16:24:51+00:00 | 8k |
AstroDev2023/2023-studio-1-but-better | source/core/src/test/com/csse3200/game/components/items/ItemComponentTest.java | [
{
"identifier": "GameExtension",
"path": "source/core/src/test/com/csse3200/game/extensions/GameExtension.java",
"snippet": "public class GameExtension implements AfterEachCallback, BeforeAllCallback {\n\tprivate Application game;\n\n\t@Override\n\tpublic void beforeAll(ExtensionContext context) {\n\t\t... | import com.badlogic.gdx.graphics.Texture;
import com.csse3200.game.extensions.GameExtension;
import com.csse3200.game.services.ResourceService;
import com.csse3200.game.services.ServiceLocator;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import static org.junit.jupiter.api.Assertions.*; | 3,936 | package com.csse3200.game.components.items;
@ExtendWith(GameExtension.class)
class ItemComponentTest {
@BeforeEach
void setup() { | package com.csse3200.game.components.items;
@ExtendWith(GameExtension.class)
class ItemComponentTest {
@BeforeEach
void setup() { | ServiceLocator.registerResourceService(new ResourceService()); | 1 | 2023-10-17 22:34:04+00:00 | 8k |
moeinfatehi/PassiveDigger | src/PassiveDigger/Passive_optionsPanel.java | [
{
"identifier": "BurpExtender",
"path": "src/burp/BurpExtender.java",
"snippet": "public class BurpExtender extends JPanel implements IBurpExtender\r\n{\r\n \r\n public static IBurpExtenderCallbacks callbacks;\r\n static JScrollPane frame;\r\n public static PrintWriter output;\r\n public ... | import burp.BurpExtender;
import burp.IHttpRequestResponse;
import burp.IRequestInfo;
import burp.IResponseInfo;
import java.awt.Color;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.table.DefaultTableModel; | 4,978 | .addComponent(options_UpdateButton)
.addComponent(options_UpdateLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel10, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 273, Short.MAX_VALUE)
.addContainerGap())
);
}// </editor-fold>//GEN-END:initComponents
private void baseReqRespTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_baseReqRespTableMouseClicked
if(evt.getClickCount()==2){
try {
int ind=baseReqRespTable.getSelectedRow();
reqRespForm.setReqResp(getBaseReqRespList().get(ind));
reqRespForm rrf = new reqRespForm();
rrf.setLocationRelativeTo(null);
rrf.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
rrf.setVisible(true);
} catch (Exception e) {
BurpExtender.output.println("*******"+e.toString());
}
}
}//GEN-LAST:event_baseReqRespTableMouseClicked
private void options_clearButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_options_clearButtonActionPerformed
DefaultTableModel baseReqRespModel=(DefaultTableModel)baseReqRespTable.getModel();
for (int i = 0; i < baseReqRespModel.getRowCount(); i++) {
removeRowFromBaseReqRespTable(i);
}
}//GEN-LAST:event_options_clearButtonActionPerformed
private void options_removeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_options_removeButtonActionPerformed
int[]rows=baseReqRespTable.getSelectedRows();
BurpExtender.output.println(rows.length);
for(int i=rows.length-1;i>=0;i--){
int thisInd=baseReqRespTable.convertRowIndexToModel(rows[i]); //to delete correctly in a sorted table
removeRowFromBaseReqRespTable(thisInd);
}
}//GEN-LAST:event_options_removeButtonActionPerformed
private void options_UpdateButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_options_UpdateButtonActionPerformed
//Remove Analyser extra datas
for (int i = PassiveAnalyzer.vulnerabilityList.size()-1; i>=0;i--) {
if(!PassiveAnalyzer.requestIsInScope(PassiveAnalyzer.vulnerabilityList.get(i).reqResp)){
PassiveAnalyzer.removeAnalyzerTableRow(i);
}
}
//Remove Headers extra datas
for (int i = Passive_Headers.getHeadersReqRespList().size()-1; i>=0;i--) {
if(!PassiveAnalyzer.requestIsInScope(Passive_Headers.getHeadersReqRespList().get(i))){
Passive_Headers.removeHeadersTableRow(i);
}
}
options_UpdateButton.setEnabled(false);
options_UpdateLabel.setForeground(new Color(43, 112, 61));
options_UpdateLabel.setText("Updated.");
}//GEN-LAST:event_options_UpdateButtonActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
List<String> codeslist=getDisabledRulesList();
RemoveFromAnalyzerBasedOnCodeList(codeslist);
}//GEN-LAST:event_jButton1ActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
public static javax.swing.JTable baseReqRespTable;
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel9;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane18;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JSeparator jSeparator2;
private javax.swing.JTabbedPane jTabbedPane1;
private javax.swing.JButton options_UpdateButton;
private javax.swing.JLabel options_UpdateLabel;
private javax.swing.JButton options_clearButton;
private javax.swing.JButton options_removeButton;
public static javax.swing.JTable options_request_table;
public static javax.swing.JTable options_response_table;
// End of variables declaration//GEN-END:variables
public static List<IHttpRequestResponse> getBaseReqRespList(){
return baseReqRespList;
}
public static void AddToBaseReqResp(IHttpRequestResponse reqResp){
BurpExtender.output.println("Adding "+reqResp.getHttpService().getHost()+":"+reqResp.getHttpService().getPort());
try {
if(targetIsUnique(reqResp)){
BurpExtender.output.println(" "+reqResp.getHttpService().getHost()+":"+reqResp.getHttpService().getPort()+" is unique => Added");
baseReqRespList.add(reqResp);
updateBaseReqRespTable(reqResp);
Passive_Headers.addToHeadersTable(reqResp);
mainPanel.firstLevelTabs.setSelectedIndex(mainPanel.passive_index);
updateOptionsTabTitle();
BurpExtender.output.println("New Target size: "+baseReqRespList.size()+" => "+printTargets());
BurpExtender.output.println("##########");
}
else{
BurpExtender.output.println(" "+reqResp.getHttpService().getHost()+":"+reqResp.getHttpService().getPort()+" is Repetetive => Not Added!"+" => "+printTargets());
BurpExtender.output.println("##########");
}
} catch (Exception e) {
BurpExtender.output.print("AddToBaseReqResp Exception");
}
}
private static void updateBaseReqRespTable(IHttpRequestResponse reqResp) {
DefaultTableModel model=(DefaultTableModel)baseReqRespTable.getModel();
String host=reqResp.getHttpService().getHost();
int port=reqResp.getHttpService().getPort(); | package PassiveDigger;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author "Moein Fatehi moein.fatehi@gmail.com"
*/
public class Passive_optionsPanel extends javax.swing.JPanel {
private static String extension_name="Options";
private static boolean updateRequired=false;
private static List<IHttpRequestResponse> baseReqRespList=new ArrayList<>();
private static boolean targetIsUnique(IHttpRequestResponse reqResp) {
BurpExtender.output.println("Target size: "+baseReqRespList.size()+" => "+printTargets());
for (IHttpRequestResponse rr : baseReqRespList) {
BurpExtender.output.println("**Testing if "+rr.getHttpService().getHost()+":"+rr.getHttpService().getPort()+" Equals to "+reqResp.getHttpService().getHost()+":"+reqResp.getHttpService().getPort());
if(reqResp.getHttpService().getHost().equals(rr.getHttpService().getHost())){
if(reqResp.getHttpService().getPort()==rr.getHttpService().getPort()){
return false;
}
}
}
return true;
}
private static String printTargets() {
String tar="[";
for (IHttpRequestResponse rr : baseReqRespList) {
tar=tar+rr.getHttpService().getHost()+":"+rr.getHttpService().getPort()+",";
}
tar+="]";
return tar;
}
/**
* Creates new form HeadersPanel
*/
public Passive_optionsPanel() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jScrollPane18 = new javax.swing.JScrollPane();
baseReqRespTable = new javax.swing.JTable();
jLabel9 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jSeparator2 = new javax.swing.JSeparator();
options_removeButton = new javax.swing.JButton();
options_clearButton = new javax.swing.JButton();
options_UpdateButton = new javax.swing.JButton();
options_UpdateLabel = new javax.swing.JLabel();
jTabbedPane1 = new javax.swing.JTabbedPane();
jScrollPane1 = new javax.swing.JScrollPane();
options_request_table = new javax.swing.JTable();
jScrollPane2 = new javax.swing.JScrollPane();
options_response_table = new javax.swing.JTable();
jLabel10 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
baseReqRespTable.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"#", "Host", "Port"
}
) {
Class[] types = new Class [] {
java.lang.Integer.class, java.lang.String.class, java.lang.Integer.class
};
boolean[] canEdit = new boolean [] {
false, false, false
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
baseReqRespTable.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
baseReqRespTableMouseClicked(evt);
}
});
jScrollPane18.setViewportView(baseReqRespTable);
if (baseReqRespTable.getColumnModel().getColumnCount() > 0) {
baseReqRespTable.getColumnModel().getColumn(0).setPreferredWidth(45);
baseReqRespTable.getColumnModel().getColumn(0).setMaxWidth(55);
baseReqRespTable.getColumnModel().getColumn(1).setPreferredWidth(150);
baseReqRespTable.getColumnModel().getColumn(1).setMaxWidth(400);
baseReqRespTable.getColumnModel().getColumn(2).setPreferredWidth(60);
baseReqRespTable.getColumnModel().getColumn(2).setMaxWidth(80);
}
jLabel9.setFont(new java.awt.Font("Ubuntu", 1, 14)); // NOI18N
jLabel9.setForeground(new java.awt.Color(255, 147, 0));
jLabel9.setText("Targets");
jLabel2.setText("(Double click for details)");
options_removeButton.setText("Remove");
options_removeButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
options_removeButtonActionPerformed(evt);
}
});
options_clearButton.setText("Clear");
options_clearButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
options_clearButtonActionPerformed(evt);
}
});
options_UpdateButton.setText("Update Other Tabs");
options_UpdateButton.setEnabled(false);
options_UpdateButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
options_UpdateButtonActionPerformed(evt);
}
});
options_request_table.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{ new Boolean(true), "Req_01", "Find file upload functionalities"},
{ new Boolean(true), "Req_02", "Find serialized data in request"},
{ new Boolean(true), "Req_03", "Find base64-Encoded data in request"}
},
new String [] {
"Enabled", "Code", "Title"
}
) {
Class[] types = new Class [] {
java.lang.Boolean.class, java.lang.String.class, java.lang.String.class
};
boolean[] canEdit = new boolean [] {
true, false, true
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jScrollPane1.setViewportView(options_request_table);
if (options_request_table.getColumnModel().getColumnCount() > 0) {
options_request_table.getColumnModel().getColumn(0).setPreferredWidth(100);
options_request_table.getColumnModel().getColumn(0).setMaxWidth(100);
options_request_table.getColumnModel().getColumn(1).setPreferredWidth(100);
options_request_table.getColumnModel().getColumn(1).setMaxWidth(100);
}
jTabbedPane1.addTab("Request", jScrollPane1);
options_response_table.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{ new Boolean(true), "Resp_01", "Find SQL errors in resposne for SQL injection"},
{ new Boolean(true), "Resp_02", "Find Reflected params (Possible XSS or HTML injection)"},
{ new Boolean(true), "Resp_03", "Find possible LFI vulnerabilities"},
{ new Boolean(true), "Resp_04", "Find sensitive files"},
{ new Boolean(true), "Resp_05", "Fingerprint web server/application"},
{ new Boolean(true), "Resp_06", "Find directory indexing/browsing"},
{ new Boolean(true), "Resp_07", "Find possible Execution After Redirection (EAR)"},
{ new Boolean(true), "Resp_08", "Find sensitive data in errors"},
{ new Boolean(true), "Resp_09", "Find misconfiguration in Cookie flags"},
{ new Boolean(false), "Resp_10", "Find Base64-encoded data in response"},
{ new Boolean(true), "Resp_11", "Extract email addresses"},
{ new Boolean(false), "Resp_12", "Extract phone numbers"}
},
new String [] {
"Enabled", "Code", "Title"
}
) {
Class[] types = new Class [] {
java.lang.Boolean.class, java.lang.String.class, java.lang.String.class
};
boolean[] canEdit = new boolean [] {
true, false, false
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jScrollPane2.setViewportView(options_response_table);
if (options_response_table.getColumnModel().getColumnCount() > 0) {
options_response_table.getColumnModel().getColumn(0).setPreferredWidth(100);
options_response_table.getColumnModel().getColumn(0).setMaxWidth(100);
options_response_table.getColumnModel().getColumn(1).setPreferredWidth(100);
options_response_table.getColumnModel().getColumn(1).setMaxWidth(100);
}
jTabbedPane1.addTab("Response", jScrollPane2);
jLabel10.setFont(new java.awt.Font("Ubuntu", 1, 14)); // NOI18N
jLabel10.setForeground(new java.awt.Color(255, 147, 0));
jLabel10.setText("Analyzer Configuration");
jButton1.setText("Update Analyzer Tab");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSeparator2)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTabbedPane1)
.addGroup(layout.createSequentialGroup()
.addComponent(options_UpdateButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(options_UpdateLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(options_removeButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(options_clearButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane18, javax.swing.GroupLayout.PREFERRED_SIZE, 428, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 481, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(0, 117, Short.MAX_VALUE)))
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel10)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton1)
.addGap(0, 0, Short.MAX_VALUE))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel9)
.addComponent(jLabel2))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane18, javax.swing.GroupLayout.PREFERRED_SIZE, 191, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addComponent(options_removeButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(options_clearButton)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(options_UpdateButton)
.addComponent(options_UpdateLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel10, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 273, Short.MAX_VALUE)
.addContainerGap())
);
}// </editor-fold>//GEN-END:initComponents
private void baseReqRespTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_baseReqRespTableMouseClicked
if(evt.getClickCount()==2){
try {
int ind=baseReqRespTable.getSelectedRow();
reqRespForm.setReqResp(getBaseReqRespList().get(ind));
reqRespForm rrf = new reqRespForm();
rrf.setLocationRelativeTo(null);
rrf.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
rrf.setVisible(true);
} catch (Exception e) {
BurpExtender.output.println("*******"+e.toString());
}
}
}//GEN-LAST:event_baseReqRespTableMouseClicked
private void options_clearButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_options_clearButtonActionPerformed
DefaultTableModel baseReqRespModel=(DefaultTableModel)baseReqRespTable.getModel();
for (int i = 0; i < baseReqRespModel.getRowCount(); i++) {
removeRowFromBaseReqRespTable(i);
}
}//GEN-LAST:event_options_clearButtonActionPerformed
private void options_removeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_options_removeButtonActionPerformed
int[]rows=baseReqRespTable.getSelectedRows();
BurpExtender.output.println(rows.length);
for(int i=rows.length-1;i>=0;i--){
int thisInd=baseReqRespTable.convertRowIndexToModel(rows[i]); //to delete correctly in a sorted table
removeRowFromBaseReqRespTable(thisInd);
}
}//GEN-LAST:event_options_removeButtonActionPerformed
private void options_UpdateButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_options_UpdateButtonActionPerformed
//Remove Analyser extra datas
for (int i = PassiveAnalyzer.vulnerabilityList.size()-1; i>=0;i--) {
if(!PassiveAnalyzer.requestIsInScope(PassiveAnalyzer.vulnerabilityList.get(i).reqResp)){
PassiveAnalyzer.removeAnalyzerTableRow(i);
}
}
//Remove Headers extra datas
for (int i = Passive_Headers.getHeadersReqRespList().size()-1; i>=0;i--) {
if(!PassiveAnalyzer.requestIsInScope(Passive_Headers.getHeadersReqRespList().get(i))){
Passive_Headers.removeHeadersTableRow(i);
}
}
options_UpdateButton.setEnabled(false);
options_UpdateLabel.setForeground(new Color(43, 112, 61));
options_UpdateLabel.setText("Updated.");
}//GEN-LAST:event_options_UpdateButtonActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
List<String> codeslist=getDisabledRulesList();
RemoveFromAnalyzerBasedOnCodeList(codeslist);
}//GEN-LAST:event_jButton1ActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
public static javax.swing.JTable baseReqRespTable;
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel9;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane18;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JSeparator jSeparator2;
private javax.swing.JTabbedPane jTabbedPane1;
private javax.swing.JButton options_UpdateButton;
private javax.swing.JLabel options_UpdateLabel;
private javax.swing.JButton options_clearButton;
private javax.swing.JButton options_removeButton;
public static javax.swing.JTable options_request_table;
public static javax.swing.JTable options_response_table;
// End of variables declaration//GEN-END:variables
public static List<IHttpRequestResponse> getBaseReqRespList(){
return baseReqRespList;
}
public static void AddToBaseReqResp(IHttpRequestResponse reqResp){
BurpExtender.output.println("Adding "+reqResp.getHttpService().getHost()+":"+reqResp.getHttpService().getPort());
try {
if(targetIsUnique(reqResp)){
BurpExtender.output.println(" "+reqResp.getHttpService().getHost()+":"+reqResp.getHttpService().getPort()+" is unique => Added");
baseReqRespList.add(reqResp);
updateBaseReqRespTable(reqResp);
Passive_Headers.addToHeadersTable(reqResp);
mainPanel.firstLevelTabs.setSelectedIndex(mainPanel.passive_index);
updateOptionsTabTitle();
BurpExtender.output.println("New Target size: "+baseReqRespList.size()+" => "+printTargets());
BurpExtender.output.println("##########");
}
else{
BurpExtender.output.println(" "+reqResp.getHttpService().getHost()+":"+reqResp.getHttpService().getPort()+" is Repetetive => Not Added!"+" => "+printTargets());
BurpExtender.output.println("##########");
}
} catch (Exception e) {
BurpExtender.output.print("AddToBaseReqResp Exception");
}
}
private static void updateBaseReqRespTable(IHttpRequestResponse reqResp) {
DefaultTableModel model=(DefaultTableModel)baseReqRespTable.getModel();
String host=reqResp.getHttpService().getHost();
int port=reqResp.getHttpService().getPort(); | IRequestInfo reqInfo=BurpExtender.callbacks.getHelpers().analyzeRequest(reqResp); | 2 | 2023-10-23 12:13:00+00:00 | 8k |
LuckPerms/rest-api-java-client | src/test/java/me/lucko/luckperms/rest/UserServiceTest.java | [
{
"identifier": "LuckPermsRestClient",
"path": "src/main/java/net/luckperms/rest/LuckPermsRestClient.java",
"snippet": "public interface LuckPermsRestClient extends AutoCloseable {\n\n /**\n * Creates a new client builder.\n *\n * @return the new builder\n */\n static Builder build... | import net.luckperms.rest.LuckPermsRestClient;
import net.luckperms.rest.model.Context;
import net.luckperms.rest.model.CreateGroupRequest;
import net.luckperms.rest.model.CreateTrackRequest;
import net.luckperms.rest.model.CreateUserRequest;
import net.luckperms.rest.model.DemotionResult;
import net.luckperms.rest.model.Group;
import net.luckperms.rest.model.Metadata;
import net.luckperms.rest.model.Node;
import net.luckperms.rest.model.NodeType;
import net.luckperms.rest.model.PermissionCheckRequest;
import net.luckperms.rest.model.PermissionCheckResult;
import net.luckperms.rest.model.PlayerSaveResult;
import net.luckperms.rest.model.PromotionResult;
import net.luckperms.rest.model.QueryOptions;
import net.luckperms.rest.model.TemporaryNodeMergeStrategy;
import net.luckperms.rest.model.TrackRequest;
import net.luckperms.rest.model.UpdateTrackRequest;
import net.luckperms.rest.model.UpdateUserRequest;
import net.luckperms.rest.model.User;
import net.luckperms.rest.model.UserLookupResult;
import net.luckperms.rest.model.UserSearchResult;
import org.junit.jupiter.api.Test;
import org.testcontainers.shaded.com.google.common.collect.ImmutableList;
import org.testcontainers.shaded.com.google.common.collect.ImmutableSet;
import retrofit2.Response;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue; | 5,847 | /*
* This file is part of LuckPerms, licensed under the MIT License.
*
* Copyright (c) lucko (Luck) <luck@lucko.me>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package me.lucko.luckperms.rest;
public class UserServiceTest extends AbstractIntegrationTest {
@Test
public void testUserCrud() throws IOException {
LuckPermsRestClient client = createClient();
UUID uuid = UUID.randomUUID();
String username = randomName();
// create
Response<PlayerSaveResult> createResp = client.users().create(new CreateUserRequest(uuid, username)).execute();
assertTrue(createResp.isSuccessful());
assertEquals(201, createResp.code());
PlayerSaveResult result = createResp.body();
assertNotNull(result);
// read
Response<User> readResp = client.users().get(uuid).execute();
assertTrue(readResp.isSuccessful());
User user = readResp.body();
assertNotNull(user);
assertEquals(uuid, user.uniqueId());
assertEquals(username, user.username());
// update
Response<Void> updateResp = client.users().update(uuid, new UpdateUserRequest(randomName())).execute();
assertTrue(updateResp.isSuccessful());
// delete
Response<Void> deleteResp = client.users().delete(uuid).execute();
assertTrue(deleteResp.isSuccessful());
}
@Test
public void testUserCreate() throws IOException {
LuckPermsRestClient client = createClient();
UUID uuid = UUID.randomUUID();
String username = randomName();
// create - clean insert
Response<PlayerSaveResult> createResp1 = client.users().create(new CreateUserRequest(uuid, username)).execute();
assertTrue(createResp1.isSuccessful());
assertEquals(201, createResp1.code());
PlayerSaveResult result1 = createResp1.body();
assertNotNull(result1);
assertEquals(ImmutableSet.of(PlayerSaveResult.Outcome.CLEAN_INSERT), result1.outcomes());
assertNull(result1.previousUsername());
assertNull(result1.otherUniqueIds());
// create - no change
Response<PlayerSaveResult> createResp2 = client.users().create(new CreateUserRequest(uuid, username)).execute();
assertTrue(createResp2.isSuccessful());
assertEquals(200, createResp2.code());
PlayerSaveResult result2 = createResp2.body();
assertNotNull(result2);
assertEquals(ImmutableSet.of(PlayerSaveResult.Outcome.NO_CHANGE), result2.outcomes());
assertNull(result2.previousUsername());
assertNull(result2.otherUniqueIds());
// create - changed username
String otherUsername = randomName();
Response<PlayerSaveResult> createResp3 = client.users().create(new CreateUserRequest(uuid, otherUsername)).execute();
assertTrue(createResp3.isSuccessful());
assertEquals(200, createResp3.code());
PlayerSaveResult result3 = createResp3.body();
assertNotNull(result3);
assertEquals(ImmutableSet.of(PlayerSaveResult.Outcome.USERNAME_UPDATED), result3.outcomes());
assertEquals(username, result3.previousUsername());
assertNull(result3.otherUniqueIds());
// create - changed uuid
UUID otherUuid = UUID.randomUUID();
Response<PlayerSaveResult> createResp4 = client.users().create(new CreateUserRequest(otherUuid, otherUsername)).execute();
assertTrue(createResp4.isSuccessful());
assertEquals(201, createResp4.code());
PlayerSaveResult result4 = createResp4.body();
assertNotNull(result4);
assertEquals(ImmutableSet.of(PlayerSaveResult.Outcome.CLEAN_INSERT, PlayerSaveResult.Outcome.OTHER_UNIQUE_IDS_PRESENT_FOR_USERNAME), result4.outcomes());
assertNull(result4.previousUsername());
assertEquals(ImmutableSet.of(uuid), result4.otherUniqueIds());
}
@Test
public void testUserList() throws IOException {
LuckPermsRestClient client = createClient();
UUID uuid = UUID.randomUUID();
String username = randomName();
// create a user & give it a permission
assertTrue(client.users().create(new CreateUserRequest(uuid, username)).execute().isSuccessful());
assertTrue(client.users().nodesAdd(uuid, new Node("test.node", true, Collections.emptySet(), null)).execute().isSuccessful());
Response<Set<UUID>> resp = client.users().list().execute();
assertTrue(resp.isSuccessful());
assertNotNull(resp.body());
assertTrue(resp.body().contains(uuid));
}
@Test
public void testUserLookup() throws IOException {
LuckPermsRestClient client = createClient();
UUID uuid = UUID.randomUUID();
String username = randomName();
// create a user
assertTrue(client.users().create(new CreateUserRequest(uuid, username)).execute().isSuccessful());
// uuid to username
Response<UserLookupResult> uuidToUsername = client.users().lookup(uuid).execute();
assertTrue(uuidToUsername.isSuccessful());
assertNotNull(uuidToUsername.body());
assertEquals(username, uuidToUsername.body().username());
// username to uuid
Response<UserLookupResult> usernameToUuid = client.users().lookup(username).execute();
assertTrue(usernameToUuid.isSuccessful());
assertNotNull(usernameToUuid.body());
assertEquals(uuid, uuidToUsername.body().uniqueId());
// not found
assertEquals(404, client.users().lookup(UUID.randomUUID()).execute().code());
assertEquals(404, client.users().lookup(randomName()).execute().code());
}
@Test
public void testUserNodes() throws IOException {
LuckPermsRestClient client = createClient();
UUID uuid = UUID.randomUUID();
String username = randomName();
// create a user
assertTrue(client.users().create(new CreateUserRequest(uuid, username)).execute().isSuccessful());
// get user nodes and validate they are as expected
List<Node> nodes = client.users().nodes(uuid).execute().body();
assertNotNull(nodes);
assertEquals(ImmutableList.of(
new Node("group.default", true, Collections.emptySet(), null)
), nodes);
long expiryTime = (System.currentTimeMillis() / 1000L) + 60;
// add a node
assertTrue(client.users().nodesAdd(uuid, new Node("test.node.one", true, Collections.emptySet(), null)).execute().isSuccessful());
// add multiple nodes
assertTrue(client.users().nodesAdd(uuid, ImmutableList.of(
new Node("test.node.two", false, Collections.emptySet(), null), | /*
* This file is part of LuckPerms, licensed under the MIT License.
*
* Copyright (c) lucko (Luck) <luck@lucko.me>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package me.lucko.luckperms.rest;
public class UserServiceTest extends AbstractIntegrationTest {
@Test
public void testUserCrud() throws IOException {
LuckPermsRestClient client = createClient();
UUID uuid = UUID.randomUUID();
String username = randomName();
// create
Response<PlayerSaveResult> createResp = client.users().create(new CreateUserRequest(uuid, username)).execute();
assertTrue(createResp.isSuccessful());
assertEquals(201, createResp.code());
PlayerSaveResult result = createResp.body();
assertNotNull(result);
// read
Response<User> readResp = client.users().get(uuid).execute();
assertTrue(readResp.isSuccessful());
User user = readResp.body();
assertNotNull(user);
assertEquals(uuid, user.uniqueId());
assertEquals(username, user.username());
// update
Response<Void> updateResp = client.users().update(uuid, new UpdateUserRequest(randomName())).execute();
assertTrue(updateResp.isSuccessful());
// delete
Response<Void> deleteResp = client.users().delete(uuid).execute();
assertTrue(deleteResp.isSuccessful());
}
@Test
public void testUserCreate() throws IOException {
LuckPermsRestClient client = createClient();
UUID uuid = UUID.randomUUID();
String username = randomName();
// create - clean insert
Response<PlayerSaveResult> createResp1 = client.users().create(new CreateUserRequest(uuid, username)).execute();
assertTrue(createResp1.isSuccessful());
assertEquals(201, createResp1.code());
PlayerSaveResult result1 = createResp1.body();
assertNotNull(result1);
assertEquals(ImmutableSet.of(PlayerSaveResult.Outcome.CLEAN_INSERT), result1.outcomes());
assertNull(result1.previousUsername());
assertNull(result1.otherUniqueIds());
// create - no change
Response<PlayerSaveResult> createResp2 = client.users().create(new CreateUserRequest(uuid, username)).execute();
assertTrue(createResp2.isSuccessful());
assertEquals(200, createResp2.code());
PlayerSaveResult result2 = createResp2.body();
assertNotNull(result2);
assertEquals(ImmutableSet.of(PlayerSaveResult.Outcome.NO_CHANGE), result2.outcomes());
assertNull(result2.previousUsername());
assertNull(result2.otherUniqueIds());
// create - changed username
String otherUsername = randomName();
Response<PlayerSaveResult> createResp3 = client.users().create(new CreateUserRequest(uuid, otherUsername)).execute();
assertTrue(createResp3.isSuccessful());
assertEquals(200, createResp3.code());
PlayerSaveResult result3 = createResp3.body();
assertNotNull(result3);
assertEquals(ImmutableSet.of(PlayerSaveResult.Outcome.USERNAME_UPDATED), result3.outcomes());
assertEquals(username, result3.previousUsername());
assertNull(result3.otherUniqueIds());
// create - changed uuid
UUID otherUuid = UUID.randomUUID();
Response<PlayerSaveResult> createResp4 = client.users().create(new CreateUserRequest(otherUuid, otherUsername)).execute();
assertTrue(createResp4.isSuccessful());
assertEquals(201, createResp4.code());
PlayerSaveResult result4 = createResp4.body();
assertNotNull(result4);
assertEquals(ImmutableSet.of(PlayerSaveResult.Outcome.CLEAN_INSERT, PlayerSaveResult.Outcome.OTHER_UNIQUE_IDS_PRESENT_FOR_USERNAME), result4.outcomes());
assertNull(result4.previousUsername());
assertEquals(ImmutableSet.of(uuid), result4.otherUniqueIds());
}
@Test
public void testUserList() throws IOException {
LuckPermsRestClient client = createClient();
UUID uuid = UUID.randomUUID();
String username = randomName();
// create a user & give it a permission
assertTrue(client.users().create(new CreateUserRequest(uuid, username)).execute().isSuccessful());
assertTrue(client.users().nodesAdd(uuid, new Node("test.node", true, Collections.emptySet(), null)).execute().isSuccessful());
Response<Set<UUID>> resp = client.users().list().execute();
assertTrue(resp.isSuccessful());
assertNotNull(resp.body());
assertTrue(resp.body().contains(uuid));
}
@Test
public void testUserLookup() throws IOException {
LuckPermsRestClient client = createClient();
UUID uuid = UUID.randomUUID();
String username = randomName();
// create a user
assertTrue(client.users().create(new CreateUserRequest(uuid, username)).execute().isSuccessful());
// uuid to username
Response<UserLookupResult> uuidToUsername = client.users().lookup(uuid).execute();
assertTrue(uuidToUsername.isSuccessful());
assertNotNull(uuidToUsername.body());
assertEquals(username, uuidToUsername.body().username());
// username to uuid
Response<UserLookupResult> usernameToUuid = client.users().lookup(username).execute();
assertTrue(usernameToUuid.isSuccessful());
assertNotNull(usernameToUuid.body());
assertEquals(uuid, uuidToUsername.body().uniqueId());
// not found
assertEquals(404, client.users().lookup(UUID.randomUUID()).execute().code());
assertEquals(404, client.users().lookup(randomName()).execute().code());
}
@Test
public void testUserNodes() throws IOException {
LuckPermsRestClient client = createClient();
UUID uuid = UUID.randomUUID();
String username = randomName();
// create a user
assertTrue(client.users().create(new CreateUserRequest(uuid, username)).execute().isSuccessful());
// get user nodes and validate they are as expected
List<Node> nodes = client.users().nodes(uuid).execute().body();
assertNotNull(nodes);
assertEquals(ImmutableList.of(
new Node("group.default", true, Collections.emptySet(), null)
), nodes);
long expiryTime = (System.currentTimeMillis() / 1000L) + 60;
// add a node
assertTrue(client.users().nodesAdd(uuid, new Node("test.node.one", true, Collections.emptySet(), null)).execute().isSuccessful());
// add multiple nodes
assertTrue(client.users().nodesAdd(uuid, ImmutableList.of(
new Node("test.node.two", false, Collections.emptySet(), null), | new Node("test.node.three", true, Collections.singleton(new Context("server", "test")), null), | 1 | 2023-10-22 16:07:30+00:00 | 8k |
EvanAatrox/hubbo | hubbo-config/src/main/java/cn/hubbo/configuration/security/SpringSecurityConfig.java | [
{
"identifier": "JWTProperties",
"path": "hubbo-common/src/main/java/cn/hubbo/common/domain/to/properties/JWTProperties.java",
"snippet": "@Component\n@ConfigurationProperties(prefix = \"token\")\n@Data\npublic class JWTProperties {\n\n\n Map<String, Object> header = new HashMap<>();\n\n\n /* 类型 *... | import cn.hubbo.common.domain.to.properties.JWTProperties;
import cn.hubbo.security.filter.AccessDecisionManagerImpl;
import cn.hubbo.security.filter.CustomFilterInvocationSecurityMetadataSource;
import cn.hubbo.security.filter.DynamicFilter;
import cn.hubbo.security.filter.FormAndJsonLoginFilter;
import cn.hubbo.security.filter.JwtTokenFilter;
import cn.hubbo.security.handler.AccessDeniedHandlerImpl;
import cn.hubbo.security.handler.AuthenticationEntryPointImpl;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.filter.OncePerRequestFilter;
import java.util.List; | 4,727 | package cn.hubbo.configuration.security;
/**
* @author 张晓华
* @version V1.0
* @Package cn.hubbo.configuration.security
* @date 2023/10/20 23:51
* @Copyright © 2023-2025 版权所有,未经授权均为剽窃,作者保留一切权利
*/
@Configuration
@AllArgsConstructor
public class SpringSecurityConfig {
private UserDetailsService userDetailsService;
private AuthenticationConfiguration authenticationConfiguration;
private RedisTemplate<String, Object> redisTemplate;
private JWTProperties jwtProperties;
/**
* @return 密码加密工具
*/
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
/**
* @return 用户信息校验的工具
*/
@Bean
public AuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
daoAuthenticationProvider.setUserDetailsService(userDetailsService);
daoAuthenticationProvider.setPasswordEncoder(passwordEncoder());
return daoAuthenticationProvider;
}
@Bean
public AuthenticationManager authenticationManager() throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
List<String> ignorePathPatterns = List.of("/test/**", "/user/login");
httpSecurity.csrf(AbstractHttpConfigurer::disable)
.sessionManagement(AbstractHttpConfigurer::disable)
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.NEVER))
.passwordManagement(AbstractHttpConfigurer::disable)
.anonymous(AbstractHttpConfigurer::disable)
.rememberMe(AbstractHttpConfigurer::disable)
.headers(AbstractHttpConfigurer::disable)
.authenticationManager(authenticationManager())
.httpBasic(Customizer.withDefaults())
.authorizeHttpRequests(authorization -> authorization.requestMatchers(ignorePathPatterns.toArray(new String[]{}))
.permitAll()
.anyRequest()
.authenticated())
.authenticationProvider(authenticationProvider())
.exceptionHandling(web -> web
.accessDeniedHandler(accessDeniedHandler())
.authenticationEntryPoint(authenticationEntryPoint()))
//.addFilterBefore(dynamicFilter(), FilterSecurityInterceptor.class)
.addFilterBefore(oncePerRequestFilter(), UsernamePasswordAuthenticationFilter.class)
.addFilterBefore(loginFilter(authenticationManager()), UsernamePasswordAuthenticationFilter.class);
return httpSecurity.build();
}
/**
* @return 放行的资源
*/
@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
List<String> ignorePathPatterns = List.of("/test/**", "/user/login");
return web -> web.ignoring().requestMatchers(ignorePathPatterns.toArray(new String[]{}));
}
@Bean
public FormAndJsonLoginFilter loginFilter(AuthenticationManager authenticationManager) {
FormAndJsonLoginFilter loginFilter = new FormAndJsonLoginFilter(authenticationManager, redisTemplate, jwtProperties);
loginFilter.setPostOnly(true);
loginFilter.setFilterProcessesUrl("/user/login");
loginFilter.setAuthenticationManager(authenticationManager);
loginFilter.setAllowSessionCreation(false);
return loginFilter;
}
@Bean
public AccessDeniedHandler accessDeniedHandler() {
return new AccessDeniedHandlerImpl();
}
@Bean
public AuthenticationEntryPoint authenticationEntryPoint() { | package cn.hubbo.configuration.security;
/**
* @author 张晓华
* @version V1.0
* @Package cn.hubbo.configuration.security
* @date 2023/10/20 23:51
* @Copyright © 2023-2025 版权所有,未经授权均为剽窃,作者保留一切权利
*/
@Configuration
@AllArgsConstructor
public class SpringSecurityConfig {
private UserDetailsService userDetailsService;
private AuthenticationConfiguration authenticationConfiguration;
private RedisTemplate<String, Object> redisTemplate;
private JWTProperties jwtProperties;
/**
* @return 密码加密工具
*/
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
/**
* @return 用户信息校验的工具
*/
@Bean
public AuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
daoAuthenticationProvider.setUserDetailsService(userDetailsService);
daoAuthenticationProvider.setPasswordEncoder(passwordEncoder());
return daoAuthenticationProvider;
}
@Bean
public AuthenticationManager authenticationManager() throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
List<String> ignorePathPatterns = List.of("/test/**", "/user/login");
httpSecurity.csrf(AbstractHttpConfigurer::disable)
.sessionManagement(AbstractHttpConfigurer::disable)
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.NEVER))
.passwordManagement(AbstractHttpConfigurer::disable)
.anonymous(AbstractHttpConfigurer::disable)
.rememberMe(AbstractHttpConfigurer::disable)
.headers(AbstractHttpConfigurer::disable)
.authenticationManager(authenticationManager())
.httpBasic(Customizer.withDefaults())
.authorizeHttpRequests(authorization -> authorization.requestMatchers(ignorePathPatterns.toArray(new String[]{}))
.permitAll()
.anyRequest()
.authenticated())
.authenticationProvider(authenticationProvider())
.exceptionHandling(web -> web
.accessDeniedHandler(accessDeniedHandler())
.authenticationEntryPoint(authenticationEntryPoint()))
//.addFilterBefore(dynamicFilter(), FilterSecurityInterceptor.class)
.addFilterBefore(oncePerRequestFilter(), UsernamePasswordAuthenticationFilter.class)
.addFilterBefore(loginFilter(authenticationManager()), UsernamePasswordAuthenticationFilter.class);
return httpSecurity.build();
}
/**
* @return 放行的资源
*/
@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
List<String> ignorePathPatterns = List.of("/test/**", "/user/login");
return web -> web.ignoring().requestMatchers(ignorePathPatterns.toArray(new String[]{}));
}
@Bean
public FormAndJsonLoginFilter loginFilter(AuthenticationManager authenticationManager) {
FormAndJsonLoginFilter loginFilter = new FormAndJsonLoginFilter(authenticationManager, redisTemplate, jwtProperties);
loginFilter.setPostOnly(true);
loginFilter.setFilterProcessesUrl("/user/login");
loginFilter.setAuthenticationManager(authenticationManager);
loginFilter.setAllowSessionCreation(false);
return loginFilter;
}
@Bean
public AccessDeniedHandler accessDeniedHandler() {
return new AccessDeniedHandlerImpl();
}
@Bean
public AuthenticationEntryPoint authenticationEntryPoint() { | return new AuthenticationEntryPointImpl(); | 7 | 2023-10-18 09:38:29+00:00 | 8k |
RoessinghResearch/senseeact | ExampleSenSeeActService/src/main/java/nl/rrd/senseeact/exampleservice/ExampleApplicationInit.java | [
{
"identifier": "MobileAppRepository",
"path": "SenSeeActClient/src/main/java/nl/rrd/senseeact/client/MobileAppRepository.java",
"snippet": "@AppComponent\npublic abstract class MobileAppRepository {\n\tprotected abstract List<MobileApp> getMobileApps();\n\n\tpublic MobileApp forAndroidPackage(String pk... | import nl.rrd.senseeact.client.MobileAppRepository;
import nl.rrd.senseeact.client.project.ProjectRepository;
import nl.rrd.senseeact.dao.DatabaseFactory;
import nl.rrd.senseeact.exampleclient.ExampleMobileAppRepository;
import nl.rrd.senseeact.exampleclient.project.ExampleProjectRepository;
import nl.rrd.senseeact.service.ApplicationInit;
import nl.rrd.senseeact.service.Configuration;
import nl.rrd.senseeact.service.OAuthTableRepository;
import nl.rrd.senseeact.service.ProjectUserAccessControlRepository;
import nl.rrd.senseeact.service.export.DataExporterFactory;
import nl.rrd.senseeact.service.mail.EmailTemplateRepository;
import nl.rrd.senseeact.service.sso.SSOTokenRepository;
import nl.rrd.utils.exception.ParseException; | 4,848 | package nl.rrd.senseeact.exampleservice;
public class ExampleApplicationInit extends ApplicationInit {
public ExampleApplicationInit() throws Exception {
}
@Override
protected Configuration createConfiguration() {
return ExampleConfiguration.getInstance();
}
@Override
protected DatabaseFactory createDatabaseFactory() throws ParseException {
return createMySQLDatabaseFactory();
}
@Override
protected OAuthTableRepository createOAuthTableRepository() {
return new ExampleOauthTableRepository();
}
@Override
protected SSOTokenRepository createSSOTokenRepository() {
return new ExampleSSOTokenRepository();
}
@Override
protected EmailTemplateRepository
createResetPasswordTemplateRepository() {
return new ExampleEmailTemplateRepository();
}
@Override
protected ProjectRepository createProjectRepository() { | package nl.rrd.senseeact.exampleservice;
public class ExampleApplicationInit extends ApplicationInit {
public ExampleApplicationInit() throws Exception {
}
@Override
protected Configuration createConfiguration() {
return ExampleConfiguration.getInstance();
}
@Override
protected DatabaseFactory createDatabaseFactory() throws ParseException {
return createMySQLDatabaseFactory();
}
@Override
protected OAuthTableRepository createOAuthTableRepository() {
return new ExampleOauthTableRepository();
}
@Override
protected SSOTokenRepository createSSOTokenRepository() {
return new ExampleSSOTokenRepository();
}
@Override
protected EmailTemplateRepository
createResetPasswordTemplateRepository() {
return new ExampleEmailTemplateRepository();
}
@Override
protected ProjectRepository createProjectRepository() { | return new ExampleProjectRepository(); | 4 | 2023-10-24 09:36:50+00:00 | 8k |
Spectrum3847/SpectrumTraining | src/main/java/frc/robot/swerve/configs/NOTEBLOCK2023.java | [
{
"identifier": "DefaultConfig",
"path": "src/main/java/frc/spectrumLib/swerve/config/DefaultConfig.java",
"snippet": "public class DefaultConfig {\n\n // Angle Offsets\n private static final double kFrontLeftCANcoderOffset = 0;\n private static final double kFrontRightCANncoderOffset = 0;\n ... | import edu.wpi.first.math.util.Units;
import frc.spectrumLib.swerve.config.DefaultConfig;
import frc.spectrumLib.swerve.config.DefaultConfig.SlotGains;
import frc.spectrumLib.swerve.config.ModuleConfig;
import frc.spectrumLib.swerve.config.ModuleConfig.SwerveModuleSteerFeedbackType;
import frc.spectrumLib.swerve.config.SwerveConfig; | 4,932 | package frc.robot.swerve.configs;
public class NOTEBLOCK2023 {
// Angle Offsets
private static final double kFrontLeftCANcoderOffset = -0.407958984375;
private static final double kFrontRightCANncoderOffset = -0.181396484375;
private static final double kBackLeftCANcoderOffset = -0.8779296875;
private static final double kBackRightCANcoderOffset = -0.84130859375;
// Physical Config
private static final double wheelBaseInches = 21.5;
private static final double trackWidthInches = 18.5;
private static final double kDriveGearRatio = 6.746;
private static final double kSteerGearRatio = 21.428;
// Tuning Config
// Estimated at first, then fudge-factored to make odom match record
private static final double kWheelRadiusInches = 2;
private static final double speedAt12VoltsMps = 6;
private static final double slipCurrent = 800;
private static final SlotGains steerGains = new SlotGains(100, 0, 0.05, 0, 0);
private static final SlotGains driveGains = new SlotGains(0.4, 0, 0, 0, 0);
/*Rotation Controller*/
private static final double kPRotationController = 0.0;
private static final double kIRotationController = 0.0;
private static final double kDRotationController = 0.0;
/*Profiling Configs*/
private static final double maxVelocity = speedAt12VoltsMps;
private static final double maxAccel = maxVelocity * 1.5; // take 1/2 sec to get to max speed.
private static final double maxAngularVelocity =
maxVelocity
/ Units.inchesToMeters(
Math.hypot(wheelBaseInches / 2.0, trackWidthInches / 2.0));
private static final double maxAngularAcceleration = Math.pow(maxAngularVelocity, 2);
// Device Setup
private static final String kCANbusName = "3847";
private static final boolean supportsPro = true;
private static final SwerveModuleSteerFeedbackType steerFeedbackType =
SwerveModuleSteerFeedbackType.FusedCANcoder;
// Wheel Positions
private static final double kFrontLeftXPos = Units.inchesToMeters(wheelBaseInches / 2.0);
private static final double kFrontLeftYPos = Units.inchesToMeters(trackWidthInches / 2.0);
private static final double kFrontRightXPos = Units.inchesToMeters(wheelBaseInches / 2.0);
private static final double kFrontRightYPos = Units.inchesToMeters(-trackWidthInches / 2.0);
private static final double kBackLeftXPos = Units.inchesToMeters(-wheelBaseInches / 2.0);
private static final double kBackLeftYPos = Units.inchesToMeters(trackWidthInches / 2.0);
private static final double kBackRightXPos = Units.inchesToMeters(-wheelBaseInches / 2.0);
private static final double kBackRightYPos = Units.inchesToMeters(-trackWidthInches / 2.0);
| package frc.robot.swerve.configs;
public class NOTEBLOCK2023 {
// Angle Offsets
private static final double kFrontLeftCANcoderOffset = -0.407958984375;
private static final double kFrontRightCANncoderOffset = -0.181396484375;
private static final double kBackLeftCANcoderOffset = -0.8779296875;
private static final double kBackRightCANcoderOffset = -0.84130859375;
// Physical Config
private static final double wheelBaseInches = 21.5;
private static final double trackWidthInches = 18.5;
private static final double kDriveGearRatio = 6.746;
private static final double kSteerGearRatio = 21.428;
// Tuning Config
// Estimated at first, then fudge-factored to make odom match record
private static final double kWheelRadiusInches = 2;
private static final double speedAt12VoltsMps = 6;
private static final double slipCurrent = 800;
private static final SlotGains steerGains = new SlotGains(100, 0, 0.05, 0, 0);
private static final SlotGains driveGains = new SlotGains(0.4, 0, 0, 0, 0);
/*Rotation Controller*/
private static final double kPRotationController = 0.0;
private static final double kIRotationController = 0.0;
private static final double kDRotationController = 0.0;
/*Profiling Configs*/
private static final double maxVelocity = speedAt12VoltsMps;
private static final double maxAccel = maxVelocity * 1.5; // take 1/2 sec to get to max speed.
private static final double maxAngularVelocity =
maxVelocity
/ Units.inchesToMeters(
Math.hypot(wheelBaseInches / 2.0, trackWidthInches / 2.0));
private static final double maxAngularAcceleration = Math.pow(maxAngularVelocity, 2);
// Device Setup
private static final String kCANbusName = "3847";
private static final boolean supportsPro = true;
private static final SwerveModuleSteerFeedbackType steerFeedbackType =
SwerveModuleSteerFeedbackType.FusedCANcoder;
// Wheel Positions
private static final double kFrontLeftXPos = Units.inchesToMeters(wheelBaseInches / 2.0);
private static final double kFrontLeftYPos = Units.inchesToMeters(trackWidthInches / 2.0);
private static final double kFrontRightXPos = Units.inchesToMeters(wheelBaseInches / 2.0);
private static final double kFrontRightYPos = Units.inchesToMeters(-trackWidthInches / 2.0);
private static final double kBackLeftXPos = Units.inchesToMeters(-wheelBaseInches / 2.0);
private static final double kBackLeftYPos = Units.inchesToMeters(trackWidthInches / 2.0);
private static final double kBackRightXPos = Units.inchesToMeters(-wheelBaseInches / 2.0);
private static final double kBackRightYPos = Units.inchesToMeters(-trackWidthInches / 2.0);
| public static final ModuleConfig FrontLeft = | 2 | 2023-10-23 17:01:53+00:00 | 8k |
imart302/DulceNectar-BE | src/main/java/com/dulcenectar/java/services/ReviewServiceImpl.java | [
{
"identifier": "CreateReviewDto",
"path": "src/main/java/com/dulcenectar/java/dtos/review/CreateReviewDto.java",
"snippet": "public class CreateReviewDto implements RequestDto<Review>{\n\t\n\tString review;\n\tInteger rating;\n\tInteger productId;\n\t\n\tpublic CreateReviewDto(String review, Integer ra... | import java.util.ArrayList;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import com.dulcenectar.java.dtos.review.CreateReviewDto;
import com.dulcenectar.java.dtos.review.ResponseReviewDto;
import com.dulcenectar.java.dtos.review.UpdateReviewDto;
import com.dulcenectar.java.exceptions.ProductNotFoundException;
import com.dulcenectar.java.exceptions.ReviewNotFoundException;
import com.dulcenectar.java.models.Product;
import com.dulcenectar.java.models.Review;
import com.dulcenectar.java.repositories.ProductRepository;
import com.dulcenectar.java.repositories.ReviewRepository;
import com.dulcenectar.java.security.UserDetailsImpl;
import com.dulcenectar.java.services.interfaces.IReviewService; | 4,182 | package com.dulcenectar.java.services;
@Service
public class ReviewServiceImpl implements IReviewService {
@Autowired ReviewRepository reviewRepository;
@Autowired ProductRepository productRepository;
@Override
public ArrayList<ResponseReviewDto> getReviews() {
ArrayList<Review> reviewsList = (ArrayList<Review>)reviewRepository.findAll();
ArrayList<ResponseReviewDto> reviewsResponse = new ArrayList<>();
for(Review review: reviewsList) {
ResponseReviewDto reviewResponseDto = new ResponseReviewDto();
reviewsResponse.add(reviewResponseDto.fromEntity(review));
}
return reviewsResponse;
}
@Override
public ResponseReviewDto saveReview(CreateReviewDto review) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
UserDetailsImpl currentUser = (UserDetailsImpl)authentication.getPrincipal();
Optional<Product> product = productRepository.findById(review.getProductId());
if(product.isEmpty()) throw new ProductNotFoundException();
Review reviewEntity = review.toEntity();
reviewEntity.setProduct(product.get());
reviewEntity.setUser(currentUser);
reviewRepository.save(reviewEntity);
ResponseReviewDto response = new ResponseReviewDto();
return response.fromEntity(reviewEntity);
}
@Override
public ResponseReviewDto deleteReview(Integer id) {
Optional<Review> reviewCheck = reviewRepository.findById(id);
| package com.dulcenectar.java.services;
@Service
public class ReviewServiceImpl implements IReviewService {
@Autowired ReviewRepository reviewRepository;
@Autowired ProductRepository productRepository;
@Override
public ArrayList<ResponseReviewDto> getReviews() {
ArrayList<Review> reviewsList = (ArrayList<Review>)reviewRepository.findAll();
ArrayList<ResponseReviewDto> reviewsResponse = new ArrayList<>();
for(Review review: reviewsList) {
ResponseReviewDto reviewResponseDto = new ResponseReviewDto();
reviewsResponse.add(reviewResponseDto.fromEntity(review));
}
return reviewsResponse;
}
@Override
public ResponseReviewDto saveReview(CreateReviewDto review) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
UserDetailsImpl currentUser = (UserDetailsImpl)authentication.getPrincipal();
Optional<Product> product = productRepository.findById(review.getProductId());
if(product.isEmpty()) throw new ProductNotFoundException();
Review reviewEntity = review.toEntity();
reviewEntity.setProduct(product.get());
reviewEntity.setUser(currentUser);
reviewRepository.save(reviewEntity);
ResponseReviewDto response = new ResponseReviewDto();
return response.fromEntity(reviewEntity);
}
@Override
public ResponseReviewDto deleteReview(Integer id) {
Optional<Review> reviewCheck = reviewRepository.findById(id);
| if(reviewCheck.isEmpty()) throw new ReviewNotFoundException(); | 4 | 2023-10-24 00:07:39+00:00 | 8k |
DaveScott99/ToyStore-JSP | src/main/java/br/com/toyStore/servlet/Servlet.java | [
{
"identifier": "CategoryDAO",
"path": "src/main/java/br/com/toyStore/dao/CategoryDAO.java",
"snippet": "public class CategoryDAO {\n\tprivate Connection conn;\n\tprivate PreparedStatement ps;\n\tprivate ResultSet rs;\n\tprivate Category category;\n\n\tpublic CategoryDAO(Connection conn) {\n\t\tthis.con... | import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;
import br.com.toyStore.dao.CategoryDAO;
import br.com.toyStore.dao.ProductDAO;
import br.com.toyStore.dao.UserDAO;
import br.com.toyStore.exception.DbException;
import br.com.toyStore.model.Category;
import br.com.toyStore.model.Product;
import br.com.toyStore.model.User;
import br.com.toyStore.util.ConnectionFactory; | 6,423 | package br.com.toyStore.servlet;
@WebServlet(urlPatterns = { "/Servlet", "/home", "/catalog", "/categories",
"/selectProduct", "/selectCategory", "/insertProduct", "/insertCategory", "/login", "/admin",
"/updateProduct", "/selectProductUpdate", "/deleteProduct", "/newProduct"})
@MultipartConfig(
fileSizeThreshold = 1024 * 1024 * 1, // 1 MB
maxFileSize = 1024 * 1024 * 10, // 10 MB
maxRequestSize = 1024 * 1024 * 100 // 100 MB
)
public class Servlet extends HttpServlet {
private static final long serialVersionUID = 1L;
ProductDAO productDao = new ProductDAO(ConnectionFactory.getConnection());
CategoryDAO categoryDao = new CategoryDAO(ConnectionFactory.getConnection());
UserDAO userDao = new UserDAO(ConnectionFactory.getConnection());
Product product = new Product();
Category category = new Category();
final String IMAGES_PATH = "D:\\ARQUIVOS\\DevCompleto\\JAVA-WEB\\toy-store\\src\\main\\webapp\\assets\\";
public Servlet() throws Exception{
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String action = request.getServletPath();
if (action.equals("/home")) {
findAllProducts(request, response);
}
else if (action.equals("/categories")) {
findAllCategories(request, response);
}
else if (action.equals("/selectCategory")) {
findAllProductsByCategory(request, response);
}
else if (action.equals("/selectProduct")) {
selectProduct(request, response);
}
else if (action.equals("/insertProduct")) {
insertProduct(request, response);
}
else if (action.equals("/login")) {
login(request, response);
}
else if (action.equals("/admin")) {
admin(request, response);
}
else if (action.equals("/selectProductUpdate")) {
selectProductForUpdate(request, response);
}
else if (action.equals("/updateProduct")) {
updateProduct(request, response);
}
else if (action.equals("/deleteProduct")) {
deleteProduct(request, response);
}
else if (action.equals("/insertCategory")) {
insertCategory(request, response);
}
else if (action.equals("/newProduct")) {
newProduct(request, response);
}
}
protected void newProduct(HttpServletRequest request, HttpServletResponse response) {
try {
List<Category> categories = categoryDao.findAll();
request.setAttribute("categories", categories);
RequestDispatcher rd = request.getRequestDispatcher("newProduct.jsp");
rd.forward(request, response);
} catch (Exception e) { | package br.com.toyStore.servlet;
@WebServlet(urlPatterns = { "/Servlet", "/home", "/catalog", "/categories",
"/selectProduct", "/selectCategory", "/insertProduct", "/insertCategory", "/login", "/admin",
"/updateProduct", "/selectProductUpdate", "/deleteProduct", "/newProduct"})
@MultipartConfig(
fileSizeThreshold = 1024 * 1024 * 1, // 1 MB
maxFileSize = 1024 * 1024 * 10, // 10 MB
maxRequestSize = 1024 * 1024 * 100 // 100 MB
)
public class Servlet extends HttpServlet {
private static final long serialVersionUID = 1L;
ProductDAO productDao = new ProductDAO(ConnectionFactory.getConnection());
CategoryDAO categoryDao = new CategoryDAO(ConnectionFactory.getConnection());
UserDAO userDao = new UserDAO(ConnectionFactory.getConnection());
Product product = new Product();
Category category = new Category();
final String IMAGES_PATH = "D:\\ARQUIVOS\\DevCompleto\\JAVA-WEB\\toy-store\\src\\main\\webapp\\assets\\";
public Servlet() throws Exception{
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String action = request.getServletPath();
if (action.equals("/home")) {
findAllProducts(request, response);
}
else if (action.equals("/categories")) {
findAllCategories(request, response);
}
else if (action.equals("/selectCategory")) {
findAllProductsByCategory(request, response);
}
else if (action.equals("/selectProduct")) {
selectProduct(request, response);
}
else if (action.equals("/insertProduct")) {
insertProduct(request, response);
}
else if (action.equals("/login")) {
login(request, response);
}
else if (action.equals("/admin")) {
admin(request, response);
}
else if (action.equals("/selectProductUpdate")) {
selectProductForUpdate(request, response);
}
else if (action.equals("/updateProduct")) {
updateProduct(request, response);
}
else if (action.equals("/deleteProduct")) {
deleteProduct(request, response);
}
else if (action.equals("/insertCategory")) {
insertCategory(request, response);
}
else if (action.equals("/newProduct")) {
newProduct(request, response);
}
}
protected void newProduct(HttpServletRequest request, HttpServletResponse response) {
try {
List<Category> categories = categoryDao.findAll();
request.setAttribute("categories", categories);
RequestDispatcher rd = request.getRequestDispatcher("newProduct.jsp");
rd.forward(request, response);
} catch (Exception e) { | throw new DbException(e.getMessage()); | 3 | 2023-10-20 02:51:14+00:00 | 8k |
yallerocha/Estruturas-de-Dados-e-Algoritmos | src/main/java/com/dataStructures/avltree/AVLTreeImpl.java | [
{
"identifier": "BSTImpl",
"path": "src/main/java/com/dataStructures/binarySearchTree/BSTImpl.java",
"snippet": "public class BSTImpl<T extends Comparable<T>> implements BST<T> {\n\n\tprotected BSTNode<T> root;\n\n\tpublic BSTImpl() {\n\t\troot = new BSTNode<T>();\n\t\troot.setParent(new BSTNode<T>());\... | import com.dataStructures.binarySearchTree.BSTImpl;
import com.dataStructures.binarySearchTree.BSTNode;
import com.dataStructures.binarySearchTree.binaryTree.UtilRotation; | 3,820 | package com.dataStructures.avltree;
/**
*
* Implementacao de uma arvore AVL
* A CLASSE AVLTree herda de BSTImpl. VOCE PRECISA SOBRESCREVER A IMPLEMENTACAO
* DE BSTIMPL RECEBIDA COM SUA IMPLEMENTACAO "OU ENTAO" IMPLEMENTAR OS SEGUITNES
* METODOS QUE SERAO TESTADOS NA CLASSE AVLTREE:
* - insert
* - preOrder
* - postOrder
* - remove
* - height
* - size
*
* @author Claudio Campelo
*
* @param <T>
*/
public class AVLTreeImpl<T extends Comparable<T>> extends BSTImpl<T> implements AVLTree<T> {
// TODO Do not forget: you must override the methods insert and remove
// conveniently.
// AUXILIARY
public int calculateBalance (BSTNode<T> node) {
int resp = 0;
if (!node.isEmpty()) {
resp = this.heightRecursive((BSTNode<T>) node.getLeft())
- this.heightRecursive((BSTNode<T>) node.getRight());
}
return resp;
}
// AUXILIARY
protected void rebalance (BSTNode<T> node) {
BSTNode<T> newRoot = null;
int balance = this.calculateBalance(node);
if (Math.abs(balance) > 1) {
if (balance > 1) {
if (this.calculateBalance((BSTNode<T>) node.getLeft()) >= 0) { | package com.dataStructures.avltree;
/**
*
* Implementacao de uma arvore AVL
* A CLASSE AVLTree herda de BSTImpl. VOCE PRECISA SOBRESCREVER A IMPLEMENTACAO
* DE BSTIMPL RECEBIDA COM SUA IMPLEMENTACAO "OU ENTAO" IMPLEMENTAR OS SEGUITNES
* METODOS QUE SERAO TESTADOS NA CLASSE AVLTREE:
* - insert
* - preOrder
* - postOrder
* - remove
* - height
* - size
*
* @author Claudio Campelo
*
* @param <T>
*/
public class AVLTreeImpl<T extends Comparable<T>> extends BSTImpl<T> implements AVLTree<T> {
// TODO Do not forget: you must override the methods insert and remove
// conveniently.
// AUXILIARY
public int calculateBalance (BSTNode<T> node) {
int resp = 0;
if (!node.isEmpty()) {
resp = this.heightRecursive((BSTNode<T>) node.getLeft())
- this.heightRecursive((BSTNode<T>) node.getRight());
}
return resp;
}
// AUXILIARY
protected void rebalance (BSTNode<T> node) {
BSTNode<T> newRoot = null;
int balance = this.calculateBalance(node);
if (Math.abs(balance) > 1) {
if (balance > 1) {
if (this.calculateBalance((BSTNode<T>) node.getLeft()) >= 0) { | newRoot = UtilRotation.rightRotation(node); | 2 | 2023-10-21 21:39:25+00:00 | 8k |
MYSTD/BigDataApiTest | data-governance-assessment/src/main/java/com/std/dga/governance/service/impl/GovernanceAssessDetailServiceImpl.java | [
{
"identifier": "Assessor",
"path": "data-governance-assessment/src/main/java/com/std/dga/assessor/Assessor.java",
"snippet": "public abstract class Assessor {\n\n public final GovernanceAssessDetail doAssessor(AssessParam assessParam){\n\n// System.out.println(\"Assessor 管理流程\");\n Gov... | import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.std.dga.assessor.Assessor;
import com.std.dga.dolphinscheduler.bean.TDsTaskDefinition;
import com.std.dga.dolphinscheduler.bean.TDsTaskInstance;
import com.std.dga.dolphinscheduler.service.TDsTaskDefinitionService;
import com.std.dga.dolphinscheduler.service.TDsTaskInstanceService;
import com.std.dga.governance.bean.AssessParam;
import com.std.dga.governance.bean.GovernanceAssessDetail;
import com.std.dga.governance.bean.GovernanceAssessDetailVO;
import com.std.dga.governance.bean.GovernanceMetric;
import com.std.dga.governance.mapper.GovernanceAssessDetailMapper;
import com.std.dga.governance.service.GovernanceAssessDetailService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.std.dga.governance.service.GovernanceMetricService;
import com.std.dga.meta.bean.TableMetaInfo;
import com.std.dga.meta.mapper.TableMetaInfoMapper;
import com.std.dga.util.SpringBeanProvider;
import com.sun.codemodel.internal.JForEach;
import org.apache.tomcat.util.threads.ThreadPoolExecutor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors; | 5,259 | package com.std.dga.governance.service.impl;
/**
* <p>
* 治理考评结果明细 服务实现类
* </p>
*
* @author std
* @since 2023-10-10
*/
@Service
@DS("dga")
public class GovernanceAssessDetailServiceImpl extends ServiceImpl<GovernanceAssessDetailMapper, GovernanceAssessDetail> implements GovernanceAssessDetailService {
@Autowired
TableMetaInfoMapper tableMetaInfoMapper;
@Autowired | package com.std.dga.governance.service.impl;
/**
* <p>
* 治理考评结果明细 服务实现类
* </p>
*
* @author std
* @since 2023-10-10
*/
@Service
@DS("dga")
public class GovernanceAssessDetailServiceImpl extends ServiceImpl<GovernanceAssessDetailMapper, GovernanceAssessDetail> implements GovernanceAssessDetailService {
@Autowired
TableMetaInfoMapper tableMetaInfoMapper;
@Autowired | GovernanceMetricService governanceMetricService; | 11 | 2023-10-20 10:13:43+00:00 | 8k |
RaulGB88/MOD-034-Microservicios-con-Java | REM20231023/catalogo/src/main/java/com/example/application/services/CatalogoServiceImpl.java | [
{
"identifier": "FilmResource",
"path": "REM20231023/catalogo/src/main/java/com/example/application/resources/FilmResource.java",
"snippet": "@RestController\n@Tag(name = \"peliculas-service\", description = \"Mantenimiento de peliculas\")\n@RequestMapping(path = \"/peliculas/v1\")\npublic class FilmRes... | import java.sql.Timestamp;
import java.time.Instant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.application.resources.FilmResource;
import com.example.application.resources.LanguageResource;
import com.example.domains.contracts.services.ActorService;
import com.example.domains.contracts.services.CategoryService;
import com.example.domains.contracts.services.FilmService;
import com.example.domains.entities.dtos.ActorDTO;
import com.example.domains.entities.dtos.FilmEditDTO;
import com.example.domains.entities.dtos.NovedadesDTO; | 4,792 | package com.example.application.services;
@Service
public class CatalogoServiceImpl implements CatalogoService {
@Autowired
private FilmService filmSrv;
@Autowired | package com.example.application.services;
@Service
public class CatalogoServiceImpl implements CatalogoService {
@Autowired
private FilmService filmSrv;
@Autowired | private ActorService artorSrv; | 2 | 2023-10-24 14:35:15+00:00 | 8k |
Amir-UL-Islam/eTBManager3-Backend | src/main/java/org/msh/etbm/web/api/admin/TagsREST.java | [
{
"identifier": "ServiceResult",
"path": "src/main/java/org/msh/etbm/commons/entities/ServiceResult.java",
"snippet": "public class ServiceResult {\n\n private UUID id;\n private String entityName;\n private Class entityClass;\n private Diffs logDiffs;\n private ObjectValues logValues;\n ... | import org.msh.etbm.commons.entities.ServiceResult;
import org.msh.etbm.commons.entities.query.QueryResult;
import org.msh.etbm.services.admin.tags.TagData;
import org.msh.etbm.services.admin.tags.TagFormData;
import org.msh.etbm.services.admin.tags.TagQueryParams;
import org.msh.etbm.services.admin.tags.TagService;
import org.msh.etbm.services.security.permissions.Permissions;
import org.msh.etbm.web.api.StandardResult;
import org.msh.etbm.web.api.authentication.Authenticated;
import org.msh.etbm.web.api.authentication.InstanceType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.UUID; | 5,528 | package org.msh.etbm.web.api.admin;
/**
* Created by rmemoria on 6/1/16.
*/
@RestController
@RequestMapping("/api/tbl")
@Authenticated(permissions = {Permissions.TABLE_TAGS_EDT}, instanceType = InstanceType.SERVER_MODE)
public class TagsREST {
@Autowired
TagService service;
@RequestMapping(value = "/tag/{id}", method = RequestMethod.GET)
public TagData get(@PathVariable UUID id) {
return service.findOne(id, TagData.class);
}
@RequestMapping(value = "/tag", method = RequestMethod.POST) | package org.msh.etbm.web.api.admin;
/**
* Created by rmemoria on 6/1/16.
*/
@RestController
@RequestMapping("/api/tbl")
@Authenticated(permissions = {Permissions.TABLE_TAGS_EDT}, instanceType = InstanceType.SERVER_MODE)
public class TagsREST {
@Autowired
TagService service;
@RequestMapping(value = "/tag/{id}", method = RequestMethod.GET)
public TagData get(@PathVariable UUID id) {
return service.findOne(id, TagData.class);
}
@RequestMapping(value = "/tag", method = RequestMethod.POST) | public StandardResult create(@Valid @NotNull @RequestBody TagFormData req) { | 3 | 2023-10-23 13:47:54+00:00 | 8k |
exagonsoft/drones-management-board-backend | src/main/java/exagonsoft/drones/service/impl/DroneServiceImpl.java | [
{
"identifier": "BatteryLevelDto",
"path": "src/main/java/exagonsoft/drones/dto/BatteryLevelDto.java",
"snippet": "@Getter\n@Setter\n@NoArgsConstructor\n@AllArgsConstructor\npublic class BatteryLevelDto {\n private int batteryLevel;\n}"
},
{
"identifier": "DroneDto",
"path": "src/main/jav... | import java.util.List;
import java.util.stream.Collectors;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service;
import exagonsoft.drones.dto.BatteryLevelDto;
import exagonsoft.drones.dto.DroneDto;
import exagonsoft.drones.dto.MedicationDto;
import exagonsoft.drones.entity.Drone;
import exagonsoft.drones.entity.DroneMedications;
import exagonsoft.drones.entity.Medication;
import exagonsoft.drones.entity.Drone.StateType;
import exagonsoft.drones.exception.DuplicateSerialNumberException;
import exagonsoft.drones.exception.ResourceNotFoundException;
import exagonsoft.drones.mapper.DroneMapper;
import exagonsoft.drones.repository.DroneRepository;
import exagonsoft.drones.service.DroneMedicationService;
import exagonsoft.drones.service.DroneService;
import exagonsoft.drones.service.MedicationService;
import exagonsoft.drones.utils.UtilFunctions;
import lombok.AllArgsConstructor; | 3,774 | package exagonsoft.drones.service.impl;
@Service
@AllArgsConstructor
public class DroneServiceImpl implements DroneService {
private DroneRepository droneRepository;
private DroneMedicationService droneMedicationService;
private MedicationService medicationService;
@Override
public DroneDto createDrone(DroneDto droneDto) {
try {
// *Validate the Drone Data*/
UtilFunctions.validateDrone(droneDto);
Drone drone = DroneMapper.mapToDrone(droneDto);
Drone savedDrone = droneRepository.save(drone);
return DroneMapper.mapToDroneDto(savedDrone);
} catch (DataIntegrityViolationException e) {
throw new DuplicateSerialNumberException("Serial Number already exists!");
}
}
@Override
public DroneDto getDroneByID(Long droneID) {
Drone drone = droneRepository.findById(droneID)
.orElseThrow(() -> new ResourceNotFoundException("Drone not found with given id: " + droneID));
return DroneMapper.mapToDroneDto(drone);
}
@Override
public List<DroneDto> listAllDrones() {
try {
List<Drone> drones = droneRepository.findAll();
return drones.stream().map((drone) -> DroneMapper.mapToDroneDto(drone))
.collect(Collectors.toList());
} catch (Exception e) {
throw new RuntimeException("Something went wrong!");
}
}
@Override
public DroneDto updateDrone(Long droneId, DroneDto updatedDrone) {
try {
// *Validate the Drone Data*/
UtilFunctions.validateDrone(updatedDrone);
UtilFunctions.validateDroneManagement(updatedDrone);
Drone drone = droneRepository.findById(droneId)
.orElseThrow(() -> new ResourceNotFoundException("Drone not found with given id: " + droneId));
drone.setMax_weight(updatedDrone.getMax_weight());
drone.setModel(updatedDrone.getModel());
drone.setBattery_capacity(updatedDrone.getBattery_capacity());
drone.setState(updatedDrone.getState());
Drone updatedDroneObj = droneRepository.save(drone);
return DroneMapper.mapToDroneDto(updatedDroneObj);
} catch (Exception e) {
throw e;
}
}
@Override
public List<DroneDto> listAvailableDrones() {
try {
List<Drone> drones = droneRepository.findAvailableDrones();
return drones.stream().map((drone) -> DroneMapper.mapToDroneDto(drone))
.collect(Collectors.toList());
} catch (Exception e) {
throw new RuntimeException("Something went wrong!");
}
}
@Override | package exagonsoft.drones.service.impl;
@Service
@AllArgsConstructor
public class DroneServiceImpl implements DroneService {
private DroneRepository droneRepository;
private DroneMedicationService droneMedicationService;
private MedicationService medicationService;
@Override
public DroneDto createDrone(DroneDto droneDto) {
try {
// *Validate the Drone Data*/
UtilFunctions.validateDrone(droneDto);
Drone drone = DroneMapper.mapToDrone(droneDto);
Drone savedDrone = droneRepository.save(drone);
return DroneMapper.mapToDroneDto(savedDrone);
} catch (DataIntegrityViolationException e) {
throw new DuplicateSerialNumberException("Serial Number already exists!");
}
}
@Override
public DroneDto getDroneByID(Long droneID) {
Drone drone = droneRepository.findById(droneID)
.orElseThrow(() -> new ResourceNotFoundException("Drone not found with given id: " + droneID));
return DroneMapper.mapToDroneDto(drone);
}
@Override
public List<DroneDto> listAllDrones() {
try {
List<Drone> drones = droneRepository.findAll();
return drones.stream().map((drone) -> DroneMapper.mapToDroneDto(drone))
.collect(Collectors.toList());
} catch (Exception e) {
throw new RuntimeException("Something went wrong!");
}
}
@Override
public DroneDto updateDrone(Long droneId, DroneDto updatedDrone) {
try {
// *Validate the Drone Data*/
UtilFunctions.validateDrone(updatedDrone);
UtilFunctions.validateDroneManagement(updatedDrone);
Drone drone = droneRepository.findById(droneId)
.orElseThrow(() -> new ResourceNotFoundException("Drone not found with given id: " + droneId));
drone.setMax_weight(updatedDrone.getMax_weight());
drone.setModel(updatedDrone.getModel());
drone.setBattery_capacity(updatedDrone.getBattery_capacity());
drone.setState(updatedDrone.getState());
Drone updatedDroneObj = droneRepository.save(drone);
return DroneMapper.mapToDroneDto(updatedDroneObj);
} catch (Exception e) {
throw e;
}
}
@Override
public List<DroneDto> listAvailableDrones() {
try {
List<Drone> drones = droneRepository.findAvailableDrones();
return drones.stream().map((drone) -> DroneMapper.mapToDroneDto(drone))
.collect(Collectors.toList());
} catch (Exception e) {
throw new RuntimeException("Something went wrong!");
}
}
@Override | public BatteryLevelDto checkDroneBatteryLevel(Long droneID) { | 0 | 2023-10-16 08:32:39+00:00 | 8k |
weibocom/rill-flow | rill-flow-service/src/main/java/com/weibo/rill/flow/service/statistic/DAGSubmitChecker.java | [
{
"identifier": "TaskException",
"path": "rill-flow-common/src/main/java/com/weibo/rill/flow/common/exception/TaskException.java",
"snippet": "@ResponseStatus(HttpStatus.BAD_REQUEST)\npublic class TaskException extends RuntimeException {\n private final int errorCode;\n private final String execut... | import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.weibo.rill.flow.common.exception.TaskException;
import com.weibo.rill.flow.common.function.ResourceCheckConfig;
import com.weibo.rill.flow.common.function.ResourceStatus;
import com.weibo.rill.flow.common.model.BizError;
import com.weibo.rill.flow.common.util.SerializerUtil;
import com.weibo.rill.flow.service.configuration.BeanConfig;
import com.weibo.rill.flow.service.dconfs.BizDConfs;
import com.weibo.rill.flow.service.dconfs.DynamicClientConfs;
import com.weibo.rill.flow.olympicene.core.switcher.SwitcherManager;
import com.weibo.rill.flow.service.util.ExecutionIdUtil;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.RoundingMode;
import java.nio.charset.StandardCharsets;
import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors; | 4,018 | /*
* Copyright 2021-2023 Weibo, Inc.
*
* 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.weibo.rill.flow.service.statistic;
@Slf4j
@Service
public class DAGSubmitChecker {
@Autowired
private BizDConfs bizDConfs;
@Autowired
private DAGResourceStatistic dagResourceStatistic;
@Autowired
private TrafficRateLimiter trafficRateLimiter;
@Autowired
private SystemMonitorStatistic systemMonitorStatistic;
@Autowired
private DynamicClientConfs dynamicClientConfs;
@Autowired
private SwitcherManager switcherManagerImpl;
public ResourceCheckConfig getCheckConfig(String resourceCheck) {
if (StringUtils.isBlank(resourceCheck)) {
return null;
}
try { | /*
* Copyright 2021-2023 Weibo, Inc.
*
* 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.weibo.rill.flow.service.statistic;
@Slf4j
@Service
public class DAGSubmitChecker {
@Autowired
private BizDConfs bizDConfs;
@Autowired
private DAGResourceStatistic dagResourceStatistic;
@Autowired
private TrafficRateLimiter trafficRateLimiter;
@Autowired
private SystemMonitorStatistic systemMonitorStatistic;
@Autowired
private DynamicClientConfs dynamicClientConfs;
@Autowired
private SwitcherManager switcherManagerImpl;
public ResourceCheckConfig getCheckConfig(String resourceCheck) {
if (StringUtils.isBlank(resourceCheck)) {
return null;
}
try { | return SerializerUtil.deserialize(resourceCheck.getBytes(StandardCharsets.UTF_8), ResourceCheckConfig.class); | 4 | 2023-11-03 03:46:01+00:00 | 8k |
aliyun/alibabacloud-compute-nest-saas-boost | boost.server/src/test/java/org/example/service/impl/ServiceInstanceLifecycleServiceImplTest.java | [
{
"identifier": "BaseResult",
"path": "boost.common/src/main/java/org/example/common/BaseResult.java",
"snippet": "@Data\npublic class BaseResult<T> implements Serializable {\n private static final long serialVersionUID = 5680133981298179266L;\n\n /**\n * Status code.\n */\n protected S... | import com.aliyun.computenestsupplier20210521.models.CreateServiceInstanceRequest;
import com.aliyun.computenestsupplier20210521.models.CreateServiceInstanceResponse;
import com.aliyun.computenestsupplier20210521.models.GetServiceInstanceRequest;
import com.aliyun.computenestsupplier20210521.models.GetServiceInstanceResponse;
import com.aliyun.computenestsupplier20210521.models.GetServiceInstanceResponseBody;
import com.aliyun.computenestsupplier20210521.models.ListServiceInstancesRequest;
import com.aliyun.computenestsupplier20210521.models.ListServiceInstancesRequest.ListServiceInstancesRequestFilter;
import com.aliyun.computenestsupplier20210521.models.ListServiceInstancesResponse;
import com.aliyun.computenestsupplier20210521.models.ListServiceInstancesResponseBody;
import com.aliyun.computenestsupplier20210521.models.ListServiceInstancesResponseBody.ListServiceInstancesResponseBodyServiceInstances;
import com.aliyun.computenestsupplier20210521.models.ListServiceInstancesResponseBody.ListServiceInstancesResponseBodyServiceInstancesService;
import com.aliyun.computenestsupplier20210521.models.ListServiceInstancesResponseBody.ListServiceInstancesResponseBodyServiceInstancesServiceServiceInfos;
import mockit.Expectations;
import mockit.Injectable;
import mockit.Tested;
import mockit.Verifications;
import org.example.common.BaseResult;
import org.example.common.ListResult;
import org.example.common.adapter.ComputeNestSupplierClient;
import org.example.common.constant.CallSource;
import org.example.common.errorinfo.ErrorInfo;
import org.example.common.exception.BizException;
import org.example.common.helper.ServiceInstanceLifeStyleHelper;
import org.example.common.model.ListServiceInstancesModel;
import org.example.common.model.ServiceInstanceModel;
import org.example.common.model.UserInfoModel;
import org.example.common.param.GetServiceInstanceParam;
import org.example.common.param.ListServiceInstancesParam;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpStatus;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals; | 4,313 | /*
*Copyright (c) Alibaba Group;
*Licensed under the Apache License, Version 2.0 (the "License");
*you may not use this file except in compliance with the License.
*You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*Unless required by applicable law or agreed to in writing, software
*distributed under the License is distributed on an "AS IS" BASIS,
*WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*See the License for the specific language governing permissions and
*limitations under the License.
*/
package org.example.service.impl;
class ServiceInstanceLifecycleServiceImplTest {
@Tested
private ServiceInstanceLifecycleServiceImpl serviceInstanceLifecycleService;
@Injectable
private ServiceInstanceLifeStyleHelper serviceInstanceLifeStyleHelper;
@Injectable
private ComputeNestSupplierClient computeNestSupplierClient;
private ListServiceInstancesResponseBody createListServiceInstancesResponseBody() {
ListServiceInstancesResponseBodyServiceInstancesServiceServiceInfos serviceInfos = new ListServiceInstancesResponseBodyServiceInstancesServiceServiceInfos().setName("serviceInfoName-2").setShortDescription("description");
ListServiceInstancesResponseBodyServiceInstancesService service = new ListServiceInstancesResponseBodyServiceInstancesService().setServiceInfos(Arrays.asList(serviceInfos));
ListServiceInstancesResponseBodyServiceInstances deployedServiceInstance = new ListServiceInstancesResponseBodyServiceInstances().setServiceInstanceId("si-serviceInstanceId-1")
.setStatus("deployed").setService(service);
ListServiceInstancesResponseBody responseBody = new ListServiceInstancesResponseBody().setMaxResults(20)
.setServiceInstances(Arrays.asList(deployedServiceInstance, deployedServiceInstance));
responseBody.setTotalCount(2);
return responseBody;
}
@Test
void listServiceInstances() throws Exception {
UserInfoModel userInfoModel = new UserInfoModel();
userInfoModel.setAid("aliYunId");
ListServiceInstancesParam listServiceInstancesParam = new ListServiceInstancesParam();
listServiceInstancesParam.setMaxResults(20);
listServiceInstancesParam.setStatus("deployed");
listServiceInstancesParam.setServiceInstanceId("si-serviceInstanceId");
listServiceInstancesParam.setServiceInstanceName("serviceInfoName-2");
ListServiceInstancesRequestFilter listServiceInstancesRequestFilter = new ListServiceInstancesRequestFilter();
listServiceInstancesRequestFilter.setName("ServiceType");
List<String> list = new ArrayList<>();
list.add("managed");
listServiceInstancesRequestFilter.setValue(list);
new Expectations() {{
serviceInstanceLifeStyleHelper.createFilter(anyString, withAny(new ArrayList<>()));
result = listServiceInstancesRequestFilter;
ListServiceInstancesResponse response = new ListServiceInstancesResponse();
response.setBody(createListServiceInstancesResponseBody());
computeNestSupplierClient.listServiceInstances(withAny(new ListServiceInstancesRequest()));
result = response;
}};
| /*
*Copyright (c) Alibaba Group;
*Licensed under the Apache License, Version 2.0 (the "License");
*you may not use this file except in compliance with the License.
*You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*Unless required by applicable law or agreed to in writing, software
*distributed under the License is distributed on an "AS IS" BASIS,
*WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*See the License for the specific language governing permissions and
*limitations under the License.
*/
package org.example.service.impl;
class ServiceInstanceLifecycleServiceImplTest {
@Tested
private ServiceInstanceLifecycleServiceImpl serviceInstanceLifecycleService;
@Injectable
private ServiceInstanceLifeStyleHelper serviceInstanceLifeStyleHelper;
@Injectable
private ComputeNestSupplierClient computeNestSupplierClient;
private ListServiceInstancesResponseBody createListServiceInstancesResponseBody() {
ListServiceInstancesResponseBodyServiceInstancesServiceServiceInfos serviceInfos = new ListServiceInstancesResponseBodyServiceInstancesServiceServiceInfos().setName("serviceInfoName-2").setShortDescription("description");
ListServiceInstancesResponseBodyServiceInstancesService service = new ListServiceInstancesResponseBodyServiceInstancesService().setServiceInfos(Arrays.asList(serviceInfos));
ListServiceInstancesResponseBodyServiceInstances deployedServiceInstance = new ListServiceInstancesResponseBodyServiceInstances().setServiceInstanceId("si-serviceInstanceId-1")
.setStatus("deployed").setService(service);
ListServiceInstancesResponseBody responseBody = new ListServiceInstancesResponseBody().setMaxResults(20)
.setServiceInstances(Arrays.asList(deployedServiceInstance, deployedServiceInstance));
responseBody.setTotalCount(2);
return responseBody;
}
@Test
void listServiceInstances() throws Exception {
UserInfoModel userInfoModel = new UserInfoModel();
userInfoModel.setAid("aliYunId");
ListServiceInstancesParam listServiceInstancesParam = new ListServiceInstancesParam();
listServiceInstancesParam.setMaxResults(20);
listServiceInstancesParam.setStatus("deployed");
listServiceInstancesParam.setServiceInstanceId("si-serviceInstanceId");
listServiceInstancesParam.setServiceInstanceName("serviceInfoName-2");
ListServiceInstancesRequestFilter listServiceInstancesRequestFilter = new ListServiceInstancesRequestFilter();
listServiceInstancesRequestFilter.setName("ServiceType");
List<String> list = new ArrayList<>();
list.add("managed");
listServiceInstancesRequestFilter.setValue(list);
new Expectations() {{
serviceInstanceLifeStyleHelper.createFilter(anyString, withAny(new ArrayList<>()));
result = listServiceInstancesRequestFilter;
ListServiceInstancesResponse response = new ListServiceInstancesResponse();
response.setBody(createListServiceInstancesResponseBody());
computeNestSupplierClient.listServiceInstances(withAny(new ListServiceInstancesRequest()));
result = response;
}};
| ListResult<ServiceInstanceModel> result = serviceInstanceLifecycleService.listServiceInstances(userInfoModel, listServiceInstancesParam); | 1 | 2023-11-01 08:19:34+00:00 | 8k |
mioclient/oyvey-ported | src/main/java/me/alpha432/oyvey/manager/ModuleManager.java | [
{
"identifier": "Render2DEvent",
"path": "src/main/java/me/alpha432/oyvey/event/impl/Render2DEvent.java",
"snippet": "public class Render2DEvent extends Event {\n private final DrawContext context;\n private final float delta;\n\n public Render2DEvent(DrawContext context, float delta) {\n ... | import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import me.alpha432.oyvey.event.impl.Render2DEvent;
import me.alpha432.oyvey.event.impl.Render3DEvent;
import me.alpha432.oyvey.features.Feature;
import me.alpha432.oyvey.features.modules.Module;
import me.alpha432.oyvey.features.modules.client.ClickGui;
import me.alpha432.oyvey.features.modules.client.HudModule;
import me.alpha432.oyvey.features.modules.combat.Criticals;
import me.alpha432.oyvey.features.modules.misc.MCF;
import me.alpha432.oyvey.features.modules.movement.ReverseStep;
import me.alpha432.oyvey.features.modules.movement.Step;
import me.alpha432.oyvey.features.modules.player.FastPlace;
import me.alpha432.oyvey.features.modules.player.Velocity;
import me.alpha432.oyvey.util.traits.Jsonable;
import me.alpha432.oyvey.util.traits.Util;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors; | 4,762 | package me.alpha432.oyvey.manager;
public class ModuleManager implements Jsonable, Util {
public List<Module> modules = new ArrayList<>();
public List<Module> sortedModules = new ArrayList<>();
public List<String> sortedModulesABC = new ArrayList<>();
public void init() {
modules.add(new HudModule());
modules.add(new ClickGui());
modules.add(new Criticals()); | package me.alpha432.oyvey.manager;
public class ModuleManager implements Jsonable, Util {
public List<Module> modules = new ArrayList<>();
public List<Module> sortedModules = new ArrayList<>();
public List<String> sortedModulesABC = new ArrayList<>();
public void init() {
modules.add(new HudModule());
modules.add(new ClickGui());
modules.add(new Criticals()); | modules.add(new MCF()); | 7 | 2023-11-05 18:10:28+00:00 | 8k |
EB-wilson/TooManyItems | src/main/java/tmi/recipe/parser/ThermalGeneratorParser.java | [
{
"identifier": "Recipe",
"path": "src/main/java/tmi/recipe/Recipe.java",
"snippet": "public class Recipe {\n private static final EffFunc ONE_BASE = getDefaultEff(1);\n private static final EffFunc ZERO_BASE = getDefaultEff(0);\n\n /**该配方的类型,请参阅{@link RecipeType}*/\n public final RecipeType recipeT... | import arc.math.Mathf;
import arc.struct.Seq;
import mindustry.Vars;
import mindustry.content.Blocks;
import mindustry.world.Block;
import mindustry.world.blocks.environment.Floor;
import mindustry.world.blocks.power.ThermalGenerator;
import tmi.recipe.Recipe;
import tmi.recipe.RecipeItemStack;
import tmi.recipe.RecipeType;
import tmi.recipe.types.PowerMark; | 4,649 | package tmi.recipe.parser;
public class ThermalGeneratorParser extends ConsumerParser<ThermalGenerator>{
{excludes.add(GeneratorParser.class);}
@Override
public boolean isTarget(Block content) {
return content instanceof ThermalGenerator;
}
@Override | package tmi.recipe.parser;
public class ThermalGeneratorParser extends ConsumerParser<ThermalGenerator>{
{excludes.add(GeneratorParser.class);}
@Override
public boolean isTarget(Block content) {
return content instanceof ThermalGenerator;
}
@Override | public Seq<Recipe> parse(ThermalGenerator content) { | 0 | 2023-11-05 11:39:21+00:00 | 8k |
dulaiduwang003/DeepSee | microservices/ts-drawing/src/main/java/com/cn/service/impl/DallServiceImpl.java | [
{
"identifier": "DallCommon",
"path": "microservices/ts-drawing/src/main/java/com/cn/common/DallCommon.java",
"snippet": "@Component\n@RequiredArgsConstructor\npublic class DallCommon {\n\n\n private final DallDefaultConfiguration configuration;\n public static final DallStructure STRUCTURE = new ... | import com.alibaba.fastjson.JSONObject;
import com.cn.common.DallCommon;
import com.cn.constant.DrawingConstant;
import com.cn.constant.DrawingStatusConstant;
import com.cn.dto.DallTaskDto;
import com.cn.dto.DialogueImageDto;
import com.cn.entity.TsDialogueDrawing;
import com.cn.entity.TsGenerateDrawing;
import com.cn.enums.DrawingTypeEnum;
import com.cn.enums.FileEnum;
import com.cn.exception.DallException;
import com.cn.mapper.TsDialogueDrawingMapper;
import com.cn.mapper.TsGenerateDrawingMapper;
import com.cn.model.DallModel;
import com.cn.model.DialogueGenerateModel;
import com.cn.service.DallService;
import com.cn.structure.TaskStructure;
import com.cn.utils.BaiduTranslationUtil;
import com.cn.utils.DrawingUtils;
import com.cn.utils.RedisUtils;
import com.cn.utils.UploadUtil;
import com.cn.vo.DialogueImageVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
import java.util.UUID; | 5,914 | package com.cn.service.impl;
@Service
@Slf4j
@RequiredArgsConstructor
public class DallServiceImpl implements DallService {
private final BaiduTranslationUtil baiduTranslationUtil;
private final TsDialogueDrawingMapper tsDialogueDrawingMapper;
private final TsGenerateDrawingMapper tsGenerateDrawingMapper;
private final UploadUtil uploadUtil;
private final DrawingUtils drawingUtils;
private final RedisUtils redisUtils;
private final RedisTemplate<String, Object> redisTemplate;
@Override
@Transactional(rollbackFor = Exception.class)
public DialogueImageVo dialogGenerationImg(final DialogueImageDto dto) {
final String block = WebClient.builder().baseUrl(DallCommon.STRUCTURE.getRequestUrl()).defaultHeader(HttpHeaders.AUTHORIZATION, "Bearer " + DallCommon.pollGetKey()).codecs(item -> item.defaultCodecs().maxInMemorySize(20 * 1024 * 1024)).build().post().uri("/images/generations").body(BodyInserters.fromValue(new DialogueGenerateModel().setPrompt(dto.getPrompt()))).retrieve().onStatus(status -> status.is4xxClientError() || status.is5xxServerError(), response -> response.bodyToMono(String.class).flatMap(errorBody -> {
final String errorCode = JSONObject.parseObject(errorBody).getString("error");
final JSONObject jsonObject = JSONObject.parseObject(errorCode);
final String code = jsonObject.getString("code");
if ("rate_limit_exceeded".equals(code)) {
log.warn("DALL-3 已经超过官方限制速率");
return Mono.error(new DallException("🥲 Sorry! 当前绘图人数过多,请稍后重试~"));
}
return Mono.error(new DallException("🥲 Sorry! 当前对话绘图服务可能出了点问题,请联系管理员解决~"));
})).bodyToMono(String.class).block();
//解析JSON
final JSONObject jsonObject = JSONObject.parseObject(block);
final JSONObject data = jsonObject.getJSONArray("data").getJSONObject(0);
String revisedPrompt = data.getString("revised_prompt");
//上传数据到阿里云OSS 不然回显过慢
final String url = uploadUtil.uploadImageFromUrl(data.getString("url"), FileEnum.DRAWING.getDec());
tsDialogueDrawingMapper.insert(new TsDialogueDrawing().setUrl(url));
synchronized (this) {
try {
//百度翻译API 单 1秒qs
revisedPrompt = baiduTranslationUtil.chineseTranslation(revisedPrompt);
} catch (Exception e) {
log.warn("调取百度翻译API失败 信息:{} 位置:{}", e.getMessage(), e.getClass());
}
}
return new DialogueImageVo().setRevisedPrompt(revisedPrompt).setUrl(url);
}
@Override | package com.cn.service.impl;
@Service
@Slf4j
@RequiredArgsConstructor
public class DallServiceImpl implements DallService {
private final BaiduTranslationUtil baiduTranslationUtil;
private final TsDialogueDrawingMapper tsDialogueDrawingMapper;
private final TsGenerateDrawingMapper tsGenerateDrawingMapper;
private final UploadUtil uploadUtil;
private final DrawingUtils drawingUtils;
private final RedisUtils redisUtils;
private final RedisTemplate<String, Object> redisTemplate;
@Override
@Transactional(rollbackFor = Exception.class)
public DialogueImageVo dialogGenerationImg(final DialogueImageDto dto) {
final String block = WebClient.builder().baseUrl(DallCommon.STRUCTURE.getRequestUrl()).defaultHeader(HttpHeaders.AUTHORIZATION, "Bearer " + DallCommon.pollGetKey()).codecs(item -> item.defaultCodecs().maxInMemorySize(20 * 1024 * 1024)).build().post().uri("/images/generations").body(BodyInserters.fromValue(new DialogueGenerateModel().setPrompt(dto.getPrompt()))).retrieve().onStatus(status -> status.is4xxClientError() || status.is5xxServerError(), response -> response.bodyToMono(String.class).flatMap(errorBody -> {
final String errorCode = JSONObject.parseObject(errorBody).getString("error");
final JSONObject jsonObject = JSONObject.parseObject(errorCode);
final String code = jsonObject.getString("code");
if ("rate_limit_exceeded".equals(code)) {
log.warn("DALL-3 已经超过官方限制速率");
return Mono.error(new DallException("🥲 Sorry! 当前绘图人数过多,请稍后重试~"));
}
return Mono.error(new DallException("🥲 Sorry! 当前对话绘图服务可能出了点问题,请联系管理员解决~"));
})).bodyToMono(String.class).block();
//解析JSON
final JSONObject jsonObject = JSONObject.parseObject(block);
final JSONObject data = jsonObject.getJSONArray("data").getJSONObject(0);
String revisedPrompt = data.getString("revised_prompt");
//上传数据到阿里云OSS 不然回显过慢
final String url = uploadUtil.uploadImageFromUrl(data.getString("url"), FileEnum.DRAWING.getDec());
tsDialogueDrawingMapper.insert(new TsDialogueDrawing().setUrl(url));
synchronized (this) {
try {
//百度翻译API 单 1秒qs
revisedPrompt = baiduTranslationUtil.chineseTranslation(revisedPrompt);
} catch (Exception e) {
log.warn("调取百度翻译API失败 信息:{} 位置:{}", e.getMessage(), e.getClass());
}
}
return new DialogueImageVo().setRevisedPrompt(revisedPrompt).setUrl(url);
}
@Override | public String addDallTask(final DallTaskDto dto) { | 3 | 2023-11-05 16:26:39+00:00 | 8k |
373675032/xw-fast | xw-fast-crud/src/main/java/world/xuewei/fast/crud/controller/BaseController.java | [
{
"identifier": "BusinessRunTimeException",
"path": "xw-fast-core/src/main/java/world/xuewei/fast/core/exception/BusinessRunTimeException.java",
"snippet": "@Setter\n@Getter\npublic class BusinessRunTimeException extends RuntimeException {\n\n private static final long serialVersionUID = -48796772838... | import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import world.xuewei.fast.core.exception.BusinessRunTimeException;
import world.xuewei.fast.core.exception.ParamEmptyException;
import world.xuewei.fast.crud.dto.request.ReqBody;
import world.xuewei.fast.crud.query.QueryBody;
import world.xuewei.fast.crud.query.ResultPage;
import world.xuewei.fast.crud.service.BaseDBService;
import world.xuewei.fast.web.dto.response.RespResult;
import java.io.Serializable;
import java.util.List; | 7,159 | package world.xuewei.fast.crud.controller;
/**
* 基础控制器
*
* @author XUEW
* @since 2023/11/1 18:02
*/
public class BaseController<T> {
protected final BaseDBService<T> baseService;
public BaseController(BaseDBService<T> baseService) {
this.baseService = baseService;
}
/**
* 保存实体
*
* @param reqBody 通用请求体
* @return 实体对象
*/
@PostMapping("/saveData")
@ResponseBody
public RespResult saveData(@RequestBody ReqBody<T> reqBody) {
T obj = Assert.notNull(reqBody.getObj(), () -> ParamEmptyException.build("实体[obj]"));
return RespResult.success("新增成功", baseService.saveData(obj));
}
/**
* 批量保存实体
*
* @param reqBody 通用请求体
* @return 实体对象列表
*/
@PostMapping("/saveBatchData")
@ResponseBody
public RespResult saveBatchData(@RequestBody ReqBody<T> reqBody) {
List<T> objs = Assert.notEmpty(reqBody.getObjs(), () -> ParamEmptyException.build("实体数组[objs]"));
return RespResult.success("新增成功", baseService.saveBatchData(objs));
}
/**
* 通过主键删除数据
*
* @param reqBody 通用请求体
* @return 删除条数
*/
@PostMapping("/delete")
@ResponseBody
public RespResult delete(@RequestBody ReqBody<T> reqBody) {
Serializable id = Assert.notNull(reqBody.getId(), () -> ParamEmptyException.build("ID[id]"));
int deleted = baseService.delete(id);
return deleted == 0 ? RespResult.notFound("目标") : RespResult.success("删除成功", deleted);
}
/**
* 通过主键删除数据
*
* @param reqBody 通用请求体
* @return 删除条数
*/
@PostMapping("/deleteBatch")
@ResponseBody
public RespResult deleteBatch(@RequestBody ReqBody<T> reqBody) {
List<Serializable> ids = Assert.notEmpty(reqBody.getIds(), () -> ParamEmptyException.build("ID数组[ids]"));
int deleted = baseService.deleteBatch(ids);
return deleted == 0 ? RespResult.notFound("目标") : RespResult.success("删除成功", deleted);
}
/**
* 通过指定字段及对应值删除数据
*
* @param reqBody 通用请求体
* @return 删除条数
*/
@PostMapping("/deleteByField")
@ResponseBody
public RespResult deleteByField(@RequestBody ReqBody<T> reqBody) {
String field = Assert.notNull(reqBody.getField(), () -> ParamEmptyException.build("字段[field]"));
Object value = Assert.notNull(reqBody.getValue(), () -> ParamEmptyException.build("值[value]"));
int deleted = baseService.deleteByField(field, value);
return deleted == 0 ? RespResult.notFound("目标") : RespResult.success("删除成功", deleted);
}
/**
* 通过指定字段及对应值删除数据
*
* @param reqBody 通用请求体
* @return 出参
*/
@PostMapping("/deleteBatchByField")
@ResponseBody
public RespResult deleteBatchByField(@RequestBody ReqBody<T> reqBody) {
String field = Assert.notNull(reqBody.getField(), () -> ParamEmptyException.build("字段[field]"));
List<Object> values = Assert.notEmpty(reqBody.getValues(), () -> ParamEmptyException.build("值数组[values]"));
int deleted = baseService.deleteBatchByField(field, values);
return deleted == 0 ? RespResult.notFound("目标") : RespResult.success("删除成功", deleted);
}
/**
* 通过主键查询
*
* @param reqBody 通用请求体
* @return 出参
*/
@PostMapping("/getById")
@ResponseBody
public RespResult getById(@RequestBody ReqBody<T> reqBody) {
Serializable id = Assert.notNull(reqBody.getId(), () -> ParamEmptyException.build("ID[id]"));
T t = baseService.getById(id);
return ObjectUtil.isEmpty(t) ? RespResult.notFound("目标") : RespResult.success("查询成功", t);
}
/**
* 通过主键查询
*
* @param reqBody 通用请求体
* @return 出参
*/
@PostMapping("/getByIds")
@ResponseBody
public RespResult getByIds(@RequestBody ReqBody<T> reqBody) {
List<Serializable> ids = Assert.notEmpty(reqBody.getIds(), () -> ParamEmptyException.build("ID数组[ids]"));
return RespResult.success("查询成功", baseService.getByIds(ids));
}
/**
* 通过实体查询数据集合
*
* @param reqBody 通用请求体
* @return 出参
*/
@PostMapping("/getByObj")
@ResponseBody
public RespResult getByObj(@RequestBody ReqBody<T> reqBody) {
T obj = Assert.notNull(reqBody.getObj(), () -> ParamEmptyException.build("实体[obj]"));
return RespResult.success("查询成功", baseService.getByObj(obj));
}
/**
* 通过指定字段和值查询
*
* @param reqBody 通用请求体
* @return 出参
*/
@PostMapping("/getByField")
@ResponseBody
public RespResult getByField(@RequestBody ReqBody<T> reqBody) {
String field = Assert.notNull(reqBody.getField(), () -> ParamEmptyException.build("字段[field]"));
Object value = Assert.notNull(reqBody.getValue(), () -> ParamEmptyException.build("值[value]"));
return RespResult.success("查询成功", baseService.getByField(field, value));
}
/**
* 通过指定字段及对应值查询数据
*
* @param reqBody 通用请求体
* @return 出参
*/
@PostMapping("/getBatchByField")
@ResponseBody
public RespResult getBatchByField(@RequestBody ReqBody<T> reqBody) {
String field = Assert.notNull(reqBody.getField(), () -> ParamEmptyException.build("字段[field]"));
List<Object> values = Assert.notEmpty(reqBody.getValues(), () -> ParamEmptyException.build("值数组[values]"));
return RespResult.success("查询成功", baseService.getBatchByField(field, values));
}
/**
* 查询全部
*
* @return 出参
*/
@PostMapping("/getAll")
@ResponseBody
public RespResult getAll() {
return RespResult.success("查询成功", baseService.getAll());
}
/**
* 自定义查询
*
* @param reqBody 通用请求体
* @return 出参
*/
@PostMapping("/customQuery")
@ResponseBody
public RespResult customQuery(@RequestBody ReqBody<T> reqBody) {
QueryBody<T> queryBody = Assert.notNull(reqBody.getQueryBody(), () -> ParamEmptyException.build("查询策略[queryBody]"));
// 参数合法性检查
queryBody.check();
QueryWrapper<T> queryWrapper = queryBody.buildWrapper();
IPage<T> page = queryBody.buildPage();
try {
if (ObjectUtil.isNotEmpty(page)) {
IPage<T> wrapperPage = baseService.getByWrapperPage(queryWrapper, page); | package world.xuewei.fast.crud.controller;
/**
* 基础控制器
*
* @author XUEW
* @since 2023/11/1 18:02
*/
public class BaseController<T> {
protected final BaseDBService<T> baseService;
public BaseController(BaseDBService<T> baseService) {
this.baseService = baseService;
}
/**
* 保存实体
*
* @param reqBody 通用请求体
* @return 实体对象
*/
@PostMapping("/saveData")
@ResponseBody
public RespResult saveData(@RequestBody ReqBody<T> reqBody) {
T obj = Assert.notNull(reqBody.getObj(), () -> ParamEmptyException.build("实体[obj]"));
return RespResult.success("新增成功", baseService.saveData(obj));
}
/**
* 批量保存实体
*
* @param reqBody 通用请求体
* @return 实体对象列表
*/
@PostMapping("/saveBatchData")
@ResponseBody
public RespResult saveBatchData(@RequestBody ReqBody<T> reqBody) {
List<T> objs = Assert.notEmpty(reqBody.getObjs(), () -> ParamEmptyException.build("实体数组[objs]"));
return RespResult.success("新增成功", baseService.saveBatchData(objs));
}
/**
* 通过主键删除数据
*
* @param reqBody 通用请求体
* @return 删除条数
*/
@PostMapping("/delete")
@ResponseBody
public RespResult delete(@RequestBody ReqBody<T> reqBody) {
Serializable id = Assert.notNull(reqBody.getId(), () -> ParamEmptyException.build("ID[id]"));
int deleted = baseService.delete(id);
return deleted == 0 ? RespResult.notFound("目标") : RespResult.success("删除成功", deleted);
}
/**
* 通过主键删除数据
*
* @param reqBody 通用请求体
* @return 删除条数
*/
@PostMapping("/deleteBatch")
@ResponseBody
public RespResult deleteBatch(@RequestBody ReqBody<T> reqBody) {
List<Serializable> ids = Assert.notEmpty(reqBody.getIds(), () -> ParamEmptyException.build("ID数组[ids]"));
int deleted = baseService.deleteBatch(ids);
return deleted == 0 ? RespResult.notFound("目标") : RespResult.success("删除成功", deleted);
}
/**
* 通过指定字段及对应值删除数据
*
* @param reqBody 通用请求体
* @return 删除条数
*/
@PostMapping("/deleteByField")
@ResponseBody
public RespResult deleteByField(@RequestBody ReqBody<T> reqBody) {
String field = Assert.notNull(reqBody.getField(), () -> ParamEmptyException.build("字段[field]"));
Object value = Assert.notNull(reqBody.getValue(), () -> ParamEmptyException.build("值[value]"));
int deleted = baseService.deleteByField(field, value);
return deleted == 0 ? RespResult.notFound("目标") : RespResult.success("删除成功", deleted);
}
/**
* 通过指定字段及对应值删除数据
*
* @param reqBody 通用请求体
* @return 出参
*/
@PostMapping("/deleteBatchByField")
@ResponseBody
public RespResult deleteBatchByField(@RequestBody ReqBody<T> reqBody) {
String field = Assert.notNull(reqBody.getField(), () -> ParamEmptyException.build("字段[field]"));
List<Object> values = Assert.notEmpty(reqBody.getValues(), () -> ParamEmptyException.build("值数组[values]"));
int deleted = baseService.deleteBatchByField(field, values);
return deleted == 0 ? RespResult.notFound("目标") : RespResult.success("删除成功", deleted);
}
/**
* 通过主键查询
*
* @param reqBody 通用请求体
* @return 出参
*/
@PostMapping("/getById")
@ResponseBody
public RespResult getById(@RequestBody ReqBody<T> reqBody) {
Serializable id = Assert.notNull(reqBody.getId(), () -> ParamEmptyException.build("ID[id]"));
T t = baseService.getById(id);
return ObjectUtil.isEmpty(t) ? RespResult.notFound("目标") : RespResult.success("查询成功", t);
}
/**
* 通过主键查询
*
* @param reqBody 通用请求体
* @return 出参
*/
@PostMapping("/getByIds")
@ResponseBody
public RespResult getByIds(@RequestBody ReqBody<T> reqBody) {
List<Serializable> ids = Assert.notEmpty(reqBody.getIds(), () -> ParamEmptyException.build("ID数组[ids]"));
return RespResult.success("查询成功", baseService.getByIds(ids));
}
/**
* 通过实体查询数据集合
*
* @param reqBody 通用请求体
* @return 出参
*/
@PostMapping("/getByObj")
@ResponseBody
public RespResult getByObj(@RequestBody ReqBody<T> reqBody) {
T obj = Assert.notNull(reqBody.getObj(), () -> ParamEmptyException.build("实体[obj]"));
return RespResult.success("查询成功", baseService.getByObj(obj));
}
/**
* 通过指定字段和值查询
*
* @param reqBody 通用请求体
* @return 出参
*/
@PostMapping("/getByField")
@ResponseBody
public RespResult getByField(@RequestBody ReqBody<T> reqBody) {
String field = Assert.notNull(reqBody.getField(), () -> ParamEmptyException.build("字段[field]"));
Object value = Assert.notNull(reqBody.getValue(), () -> ParamEmptyException.build("值[value]"));
return RespResult.success("查询成功", baseService.getByField(field, value));
}
/**
* 通过指定字段及对应值查询数据
*
* @param reqBody 通用请求体
* @return 出参
*/
@PostMapping("/getBatchByField")
@ResponseBody
public RespResult getBatchByField(@RequestBody ReqBody<T> reqBody) {
String field = Assert.notNull(reqBody.getField(), () -> ParamEmptyException.build("字段[field]"));
List<Object> values = Assert.notEmpty(reqBody.getValues(), () -> ParamEmptyException.build("值数组[values]"));
return RespResult.success("查询成功", baseService.getBatchByField(field, values));
}
/**
* 查询全部
*
* @return 出参
*/
@PostMapping("/getAll")
@ResponseBody
public RespResult getAll() {
return RespResult.success("查询成功", baseService.getAll());
}
/**
* 自定义查询
*
* @param reqBody 通用请求体
* @return 出参
*/
@PostMapping("/customQuery")
@ResponseBody
public RespResult customQuery(@RequestBody ReqBody<T> reqBody) {
QueryBody<T> queryBody = Assert.notNull(reqBody.getQueryBody(), () -> ParamEmptyException.build("查询策略[queryBody]"));
// 参数合法性检查
queryBody.check();
QueryWrapper<T> queryWrapper = queryBody.buildWrapper();
IPage<T> page = queryBody.buildPage();
try {
if (ObjectUtil.isNotEmpty(page)) {
IPage<T> wrapperPage = baseService.getByWrapperPage(queryWrapper, page); | ResultPage<T> resultPage = new ResultPage<>(wrapperPage); | 4 | 2023-11-07 11:45:40+00:00 | 8k |
daominh-studio/quick-mem | app/src/main/java/com/daominh/quickmem/ui/activities/auth/signup/SignUpActivity.java | [
{
"identifier": "UserDAO",
"path": "app/src/main/java/com/daominh/quickmem/data/dao/UserDAO.java",
"snippet": "public class UserDAO {\n\n private final QMDatabaseHelper qmDatabaseHelper;\n private SQLiteDatabase sqLiteDatabase;\n\n public UserDAO(Context context) {\n qmDatabaseHelper = n... | import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.util.Patterns;
import android.view.View;
import android.widget.Toast;
import androidx.activity.OnBackPressedCallback;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import androidx.appcompat.content.res.AppCompatResources;
import com.daominh.quickmem.R;
import com.daominh.quickmem.data.dao.UserDAO;
import com.daominh.quickmem.data.model.User;
import com.daominh.quickmem.databinding.ActivitySignupBinding;
import com.daominh.quickmem.preferen.UserSharePreferences;
import com.daominh.quickmem.ui.activities.MainActivity;
import com.daominh.quickmem.ui.activities.auth.AuthenticationActivity;
import com.daominh.quickmem.utils.PasswordHasher;
import com.swnishan.materialdatetimepicker.datepicker.MaterialDatePickerDialog;
import com.swnishan.materialdatetimepicker.datepicker.MaterialDatePickerView;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;
import java.util.UUID; | 7,004 | package com.daominh.quickmem.ui.activities.auth.signup;
public class SignUpActivity extends AppCompatActivity {
private UserDAO userDAO;
private static final int MAX_LENGTH = 30;
private static final String link = "https://avatar-nqm.koyeb.app/images";
ActivitySignupBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivitySignupBinding.inflate(getLayoutInflater());
View view = binding.getRoot();
setContentView(view);
setSupportActionBar(binding.toolbar);
setupToolbar();
setupSocialLoginButtons();
setupDateEditText();
setupEmailEditText();
setupPasswordEditText();
setupSignUpButton();
setupOnBackPressedCallback();
}
private void setupToolbar() {
binding.toolbar.setNavigationOnClickListener(v -> {
startActivity(new Intent(this, AuthenticationActivity.class));
finish();
});
}
private void setupSocialLoginButtons() {
binding.facebookBtn.setOnClickListener(v -> {
// intentToMain();
});
binding.googleBtn.setOnClickListener(v -> {
// intentToMain();
});
}
private void setupDateEditText() {
binding.dateEt.setOnClickListener(v -> openDialogDatePicker(binding.dateEt::setText));
binding.dateEt.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
handleDateTextChanged(s.toString(), binding);
}
@Override
public void afterTextChanged(Editable s) {
handleDateTextChanged(s.toString(), binding);
}
});
}
private void setupEmailEditText() {
binding.emailEt.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
handleEmailTextChanged(s.toString(), binding);
}
@Override
public void afterTextChanged(Editable s) {
handleEmailTextChanged(s.toString(), binding);
}
});
}
private void setupPasswordEditText() {
binding.passwordEt.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
handlePasswordTextChanged(s.toString(), binding);
}
@Override
public void afterTextChanged(Editable s) {
handlePasswordTextChanged(s.toString(), binding);
}
});
}
private void setupSignUpButton() {
binding.signUpBtn.setOnClickListener(v -> {
final String date = binding.dateEt.getText().toString();
final String email = binding.emailEt.getText().toString();
final String password = binding.passwordEt.getText().toString();
if (!handleDateTextChanged(date, binding)) return;
if (!handleEmailTextChanged(email, binding)) return;
if (!handlePasswordTextChanged(password, binding)) return;
int role = 2;
if (binding.radioYesNo.getCheckedRadioButtonId() == binding.radioYes.getId()) {
role = 1;
}
handleSignUp(date, email, password, role);
});
}
private void handleSignUp(String date, String email, String password, int role) {
// Create a new User object
User newUser = new User();
newUser.setId(UUID.randomUUID().toString());
newUser.setEmail(email);
newUser.setAvatar(randomAvatar());
newUser.setName("");
newUser.setUsername(userNameFromEmail(email));
newUser.setRole(role); | package com.daominh.quickmem.ui.activities.auth.signup;
public class SignUpActivity extends AppCompatActivity {
private UserDAO userDAO;
private static final int MAX_LENGTH = 30;
private static final String link = "https://avatar-nqm.koyeb.app/images";
ActivitySignupBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivitySignupBinding.inflate(getLayoutInflater());
View view = binding.getRoot();
setContentView(view);
setSupportActionBar(binding.toolbar);
setupToolbar();
setupSocialLoginButtons();
setupDateEditText();
setupEmailEditText();
setupPasswordEditText();
setupSignUpButton();
setupOnBackPressedCallback();
}
private void setupToolbar() {
binding.toolbar.setNavigationOnClickListener(v -> {
startActivity(new Intent(this, AuthenticationActivity.class));
finish();
});
}
private void setupSocialLoginButtons() {
binding.facebookBtn.setOnClickListener(v -> {
// intentToMain();
});
binding.googleBtn.setOnClickListener(v -> {
// intentToMain();
});
}
private void setupDateEditText() {
binding.dateEt.setOnClickListener(v -> openDialogDatePicker(binding.dateEt::setText));
binding.dateEt.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
handleDateTextChanged(s.toString(), binding);
}
@Override
public void afterTextChanged(Editable s) {
handleDateTextChanged(s.toString(), binding);
}
});
}
private void setupEmailEditText() {
binding.emailEt.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
handleEmailTextChanged(s.toString(), binding);
}
@Override
public void afterTextChanged(Editable s) {
handleEmailTextChanged(s.toString(), binding);
}
});
}
private void setupPasswordEditText() {
binding.passwordEt.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
handlePasswordTextChanged(s.toString(), binding);
}
@Override
public void afterTextChanged(Editable s) {
handlePasswordTextChanged(s.toString(), binding);
}
});
}
private void setupSignUpButton() {
binding.signUpBtn.setOnClickListener(v -> {
final String date = binding.dateEt.getText().toString();
final String email = binding.emailEt.getText().toString();
final String password = binding.passwordEt.getText().toString();
if (!handleDateTextChanged(date, binding)) return;
if (!handleEmailTextChanged(email, binding)) return;
if (!handlePasswordTextChanged(password, binding)) return;
int role = 2;
if (binding.radioYesNo.getCheckedRadioButtonId() == binding.radioYes.getId()) {
role = 1;
}
handleSignUp(date, email, password, role);
});
}
private void handleSignUp(String date, String email, String password, int role) {
// Create a new User object
User newUser = new User();
newUser.setId(UUID.randomUUID().toString());
newUser.setEmail(email);
newUser.setAvatar(randomAvatar());
newUser.setName("");
newUser.setUsername(userNameFromEmail(email));
newUser.setRole(role); | newUser.setPassword(PasswordHasher.hashPassword(password)); | 5 | 2023-11-07 16:56:39+00:00 | 8k |
FRCTeam2910/2023CompetitionRobot-Public | src/main/java/org/frcteam2910/c2023/Robot.java | [
{
"identifier": "RobotIdentity",
"path": "src/main/java/org/frcteam2910/c2023/config/RobotIdentity.java",
"snippet": "public enum RobotIdentity {\n LOKI_2023_ONE,\n PHANTOM_2023_TWO,\n ROBOT_2022,\n SIMULATION;\n\n public static RobotIdentity getIdentity() {\n if (Robot.isReal()) {... | import edu.wpi.first.math.filter.LinearFilter;
import edu.wpi.first.wpilibj.PowerDistribution;
import edu.wpi.first.wpilibj2.command.CommandScheduler;
import org.frcteam2910.c2023.config.RobotIdentity;
import org.frcteam2910.c2023.subsystems.led.LEDSubsystem;
import org.frcteam2910.c2023.util.DriverReadouts;
import org.frcteam2910.c2023.util.GamePiece;
import org.frcteam2910.c2023.util.MacAddressUtil;
import org.frcteam2910.c2023.util.constants.FieldConstants;
import org.littletonrobotics.junction.LogFileUtil;
import org.littletonrobotics.junction.LoggedRobot;
import org.littletonrobotics.junction.Logger;
import org.littletonrobotics.junction.networktables.NT4Publisher;
import org.littletonrobotics.junction.wpilog.WPILOGReader;
import org.littletonrobotics.junction.wpilog.WPILOGWriter; | 6,999 | // Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
package org.frcteam2910.c2023;
public class Robot extends LoggedRobot {
private RobotContainer robotContainer;
private final PowerDistribution powerDistribution = new PowerDistribution();
private final LinearFilter average = LinearFilter.movingAverage(50);
@Override
public void robotInit() {
Logger logger = Logger.getInstance();
// Record metadata
logger.recordMetadata("GitRevision", String.valueOf(BuildInfo.GIT_REVISION));
logger.recordMetadata("GitSHA", BuildInfo.GIT_SHA);
logger.recordMetadata("GitDate", BuildInfo.GIT_DATE);
logger.recordMetadata("GitBranch", BuildInfo.GIT_BRANCH);
logger.recordMetadata("BuildDate", BuildInfo.BUILD_DATE);
logger.recordMetadata("BuildUnixTime", String.valueOf(BuildInfo.BUILD_UNIX_TIME));
switch (BuildInfo.DIRTY) {
case 0:
logger.recordMetadata("GitDirty", "Clean");
break;
case 1:
logger.recordMetadata("GitDirty", "Dirty");
break;
default:
logger.recordMetadata("GitDirty", "Error");
break;
}
logger.recordMetadata("Robot Name", RobotIdentity.getIdentity().toString()); | // Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
package org.frcteam2910.c2023;
public class Robot extends LoggedRobot {
private RobotContainer robotContainer;
private final PowerDistribution powerDistribution = new PowerDistribution();
private final LinearFilter average = LinearFilter.movingAverage(50);
@Override
public void robotInit() {
Logger logger = Logger.getInstance();
// Record metadata
logger.recordMetadata("GitRevision", String.valueOf(BuildInfo.GIT_REVISION));
logger.recordMetadata("GitSHA", BuildInfo.GIT_SHA);
logger.recordMetadata("GitDate", BuildInfo.GIT_DATE);
logger.recordMetadata("GitBranch", BuildInfo.GIT_BRANCH);
logger.recordMetadata("BuildDate", BuildInfo.BUILD_DATE);
logger.recordMetadata("BuildUnixTime", String.valueOf(BuildInfo.BUILD_UNIX_TIME));
switch (BuildInfo.DIRTY) {
case 0:
logger.recordMetadata("GitDirty", "Clean");
break;
case 1:
logger.recordMetadata("GitDirty", "Dirty");
break;
default:
logger.recordMetadata("GitDirty", "Error");
break;
}
logger.recordMetadata("Robot Name", RobotIdentity.getIdentity().toString()); | logger.recordMetadata("Robot MAC Address", MacAddressUtil.getMACAddress()); | 4 | 2023-11-03 02:12:12+00:00 | 8k |
YunaBraska/type-map | src/main/java/berlin/yuna/typemap/model/ConcurrentTypeMap.java | [
{
"identifier": "ArgsDecoder",
"path": "src/main/java/berlin/yuna/typemap/logic/ArgsDecoder.java",
"snippet": "public class ArgsDecoder {\n\n public static Map<String, TypeSet> argsOf(final String input) {\n final Map<String, TypeSet> result = new HashMap<>();\n final List<Integer[]> ke... | import berlin.yuna.typemap.logic.ArgsDecoder;
import berlin.yuna.typemap.logic.JsonDecoder;
import berlin.yuna.typemap.logic.JsonEncoder;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.IntFunction;
import java.util.function.Supplier;
import static berlin.yuna.typemap.logic.TypeConverter.collectionOf;
import static berlin.yuna.typemap.logic.TypeConverter.convertObj;
import static berlin.yuna.typemap.model.TypeMap.convertAndMap;
import static berlin.yuna.typemap.model.TypeMap.treeGet;
import static java.util.Optional.ofNullable; | 5,117 | package berlin.yuna.typemap.model;
/**
* {@link ConcurrentTypeMap} is a specialized implementation of {@link ConcurrentHashMap} that offers enhanced
* functionality for type-safe data retrieval and manipulation. It is designed for
* high-performance type conversion while being native-ready for GraalVM. The {@link ConcurrentTypeMap}
* class provides methods to retrieve data in various forms (single objects, collections,
* arrays, or maps) while ensuring type safety without the need for reflection.
*/
public class ConcurrentTypeMap extends ConcurrentHashMap<Object, Object> implements TypeMapI<ConcurrentTypeMap> {
/**
* Default constructor for creating an empty TypeMap.
*/
public ConcurrentTypeMap() {
this((Map<?, ?>) null);
}
/**
* Constructs a new {@link ConcurrentTypeMap} of the specified json.
*/
public ConcurrentTypeMap(final String json) {
this(JsonDecoder.jsonMapOf(json));
}
/**
* Constructs a new {@link ConcurrentTypeMap} of the specified command line arguments.
*/
public ConcurrentTypeMap(final String[] cliArgs) { | package berlin.yuna.typemap.model;
/**
* {@link ConcurrentTypeMap} is a specialized implementation of {@link ConcurrentHashMap} that offers enhanced
* functionality for type-safe data retrieval and manipulation. It is designed for
* high-performance type conversion while being native-ready for GraalVM. The {@link ConcurrentTypeMap}
* class provides methods to retrieve data in various forms (single objects, collections,
* arrays, or maps) while ensuring type safety without the need for reflection.
*/
public class ConcurrentTypeMap extends ConcurrentHashMap<Object, Object> implements TypeMapI<ConcurrentTypeMap> {
/**
* Default constructor for creating an empty TypeMap.
*/
public ConcurrentTypeMap() {
this((Map<?, ?>) null);
}
/**
* Constructs a new {@link ConcurrentTypeMap} of the specified json.
*/
public ConcurrentTypeMap(final String json) {
this(JsonDecoder.jsonMapOf(json));
}
/**
* Constructs a new {@link ConcurrentTypeMap} of the specified command line arguments.
*/
public ConcurrentTypeMap(final String[] cliArgs) { | this(ArgsDecoder.argsOf(String.join(" ", cliArgs))); | 0 | 2023-11-09 14:40:13+00:00 | 8k |
estkme-group/InfiLPA | app/src/main/java/com/infineon/esim/lpa/lpa/task/ProfileActionTask.java | [
{
"identifier": "ProfileActionType",
"path": "core/src/main/java/com/infineon/esim/lpa/core/dtos/enums/ProfileActionType.java",
"snippet": "public enum ProfileActionType {\n PROFILE_ACTION_ENABLE,\n PROFILE_ACTION_DELETE,\n PROFILE_ACTION_DISABLE,\n PROFILE_ACTION_SET_NICKNAME,\n}"
},
{
... | import java.util.concurrent.Callable;
import com.infineon.esim.lpa.core.dtos.enums.ProfileActionType;
import com.infineon.esim.lpa.core.dtos.profile.ProfileMetadata;
import com.infineon.esim.lpa.core.dtos.result.local.EnableResult;
import com.infineon.esim.lpa.core.dtos.result.local.OperationResult;
import com.infineon.esim.lpa.core.dtos.result.remote.HandleNotificationsResult;
import com.infineon.esim.lpa.lpa.LocalProfileAssistant;
import com.infineon.esim.util.Log; | 5,956 | /*
* THE SOURCE CODE AND ITS RELATED DOCUMENTATION IS PROVIDED "AS IS". INFINEON
* TECHNOLOGIES MAKES NO OTHER WARRANTY OF ANY KIND,WHETHER EXPRESS,IMPLIED OR,
* STATUTORY AND DISCLAIMS ANY AND ALL IMPLIED WARRANTIES OF MERCHANTABILITY,
* SATISFACTORY QUALITY, NON INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE.
*
* THE SOURCE CODE AND DOCUMENTATION MAY INCLUDE ERRORS. INFINEON TECHNOLOGIES
* RESERVES THE RIGHT TO INCORPORATE MODIFICATIONS TO THE SOURCE CODE IN LATER
* REVISIONS OF IT, AND TO MAKE IMPROVEMENTS OR CHANGES IN THE DOCUMENTATION OR
* THE PRODUCTS OR TECHNOLOGIES DESCRIBED THEREIN AT ANY TIME.
*
* INFINEON TECHNOLOGIES SHALL NOT BE LIABLE FOR ANY DIRECT, INDIRECT OR
* CONSEQUENTIAL DAMAGE OR LIABILITY ARISING FROM YOUR USE OF THE SOURCE CODE OR
* ANY DOCUMENTATION, INCLUDING BUT NOT LIMITED TO, LOST REVENUES, DATA OR
* PROFITS, DAMAGES OF ANY SPECIAL, INCIDENTAL OR CONSEQUENTIAL NATURE, PUNITIVE
* DAMAGES, LOSS OF PROPERTY OR LOSS OF PROFITS ARISING OUT OF OR IN CONNECTION
* WITH THIS AGREEMENT, OR BEING UNUSABLE, EVEN IF ADVISED OF THE POSSIBILITY OR
* PROBABILITY OF SUCH DAMAGES AND WHETHER A CLAIM FOR SUCH DAMAGE IS BASED UPON
* WARRANTY, CONTRACT, TORT, NEGLIGENCE OR OTHERWISE.
*
* (C)Copyright INFINEON TECHNOLOGIES All rights reserved
*/
package com.infineon.esim.lpa.lpa.task;
public class ProfileActionTask implements Callable<Void> {
private static final String TAG = ProfileActionTask.class.getName();
private final LocalProfileAssistant lpa;
private final ProfileActionType profileActionType;
private final ProfileMetadata profile;
private OperationResult profileOperationResult = null;
public ProfileActionTask(LocalProfileAssistant lpa,
ProfileActionType profileActionType,
ProfileMetadata profile) {
this.lpa = lpa;
this.profileActionType = profileActionType;
this.profile = profile;
}
@Override
public Void call() throws Exception {
switch (profileActionType) {
case PROFILE_ACTION_ENABLE:
profileOperationResult = lpa.enableProfile(profile.getIccid(), true);
break;
case PROFILE_ACTION_DISABLE:
profileOperationResult = lpa.disableProfile(profile.getIccid());
break;
case PROFILE_ACTION_DELETE:
// If profile is currently enabled, disable it first
if (profile.isEnabled()) {
Log.info(TAG,"Profile that shall be deleted is enabled. First disable it.");
profileOperationResult = lpa.disableProfile(profile.getIccid());
handleProfileOperationResult(profileOperationResult);
performEuiccReset();
}
Log.info(TAG,"Deleting the profile.");
profileOperationResult = lpa.deleteProfile(profile.getIccid());
break;
case PROFILE_ACTION_SET_NICKNAME:
profileOperationResult = lpa.setNickname(profile.getIccid(), profile.getNickname());
break;
}
// Handle profile operation result
handleProfileOperationResult(profileOperationResult);
performEuiccReset();
// Send notification
try { | /*
* THE SOURCE CODE AND ITS RELATED DOCUMENTATION IS PROVIDED "AS IS". INFINEON
* TECHNOLOGIES MAKES NO OTHER WARRANTY OF ANY KIND,WHETHER EXPRESS,IMPLIED OR,
* STATUTORY AND DISCLAIMS ANY AND ALL IMPLIED WARRANTIES OF MERCHANTABILITY,
* SATISFACTORY QUALITY, NON INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE.
*
* THE SOURCE CODE AND DOCUMENTATION MAY INCLUDE ERRORS. INFINEON TECHNOLOGIES
* RESERVES THE RIGHT TO INCORPORATE MODIFICATIONS TO THE SOURCE CODE IN LATER
* REVISIONS OF IT, AND TO MAKE IMPROVEMENTS OR CHANGES IN THE DOCUMENTATION OR
* THE PRODUCTS OR TECHNOLOGIES DESCRIBED THEREIN AT ANY TIME.
*
* INFINEON TECHNOLOGIES SHALL NOT BE LIABLE FOR ANY DIRECT, INDIRECT OR
* CONSEQUENTIAL DAMAGE OR LIABILITY ARISING FROM YOUR USE OF THE SOURCE CODE OR
* ANY DOCUMENTATION, INCLUDING BUT NOT LIMITED TO, LOST REVENUES, DATA OR
* PROFITS, DAMAGES OF ANY SPECIAL, INCIDENTAL OR CONSEQUENTIAL NATURE, PUNITIVE
* DAMAGES, LOSS OF PROPERTY OR LOSS OF PROFITS ARISING OUT OF OR IN CONNECTION
* WITH THIS AGREEMENT, OR BEING UNUSABLE, EVEN IF ADVISED OF THE POSSIBILITY OR
* PROBABILITY OF SUCH DAMAGES AND WHETHER A CLAIM FOR SUCH DAMAGE IS BASED UPON
* WARRANTY, CONTRACT, TORT, NEGLIGENCE OR OTHERWISE.
*
* (C)Copyright INFINEON TECHNOLOGIES All rights reserved
*/
package com.infineon.esim.lpa.lpa.task;
public class ProfileActionTask implements Callable<Void> {
private static final String TAG = ProfileActionTask.class.getName();
private final LocalProfileAssistant lpa;
private final ProfileActionType profileActionType;
private final ProfileMetadata profile;
private OperationResult profileOperationResult = null;
public ProfileActionTask(LocalProfileAssistant lpa,
ProfileActionType profileActionType,
ProfileMetadata profile) {
this.lpa = lpa;
this.profileActionType = profileActionType;
this.profile = profile;
}
@Override
public Void call() throws Exception {
switch (profileActionType) {
case PROFILE_ACTION_ENABLE:
profileOperationResult = lpa.enableProfile(profile.getIccid(), true);
break;
case PROFILE_ACTION_DISABLE:
profileOperationResult = lpa.disableProfile(profile.getIccid());
break;
case PROFILE_ACTION_DELETE:
// If profile is currently enabled, disable it first
if (profile.isEnabled()) {
Log.info(TAG,"Profile that shall be deleted is enabled. First disable it.");
profileOperationResult = lpa.disableProfile(profile.getIccid());
handleProfileOperationResult(profileOperationResult);
performEuiccReset();
}
Log.info(TAG,"Deleting the profile.");
profileOperationResult = lpa.deleteProfile(profile.getIccid());
break;
case PROFILE_ACTION_SET_NICKNAME:
profileOperationResult = lpa.setNickname(profile.getIccid(), profile.getNickname());
break;
}
// Handle profile operation result
handleProfileOperationResult(profileOperationResult);
performEuiccReset();
// Send notification
try { | HandleNotificationsResult handleNotificationsResult = lpa.handleNotifications(); | 4 | 2023-11-06 02:41:13+00:00 | 8k |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.