hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
d27ada03e10c091a20b57dda91eda834a10c71da
406
package work.icql.java.designpattern.creational.singleton; /** * 单例:内部类-懒加载 */ public final class InnerClassSingleton { private InnerClassSingleton() { } private static class SingletonHolder { public static final InnerClassSingleton INSTANCE = new InnerClassSingleton(); } public static InnerClassSingleton getInstance() { return SingletonHolder.INSTANCE; } }
21.368421
85
0.714286
02d7e43040f54d0f2dcc671d07ea16337ce84c38
4,605
/* * Copyright 2016 higherfrequencytrading.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package net.openhft.chronicle.engine; import net.openhft.chronicle.core.Jvm; import net.openhft.chronicle.core.onoes.ExceptionKey; import net.openhft.chronicle.core.threads.ThreadDump; import net.openhft.chronicle.engine.server.ServerEndpoint; import net.openhft.chronicle.engine.tree.VanillaAssetTree; import net.openhft.chronicle.network.TCPRegistry; import net.openhft.chronicle.network.connection.TcpChannelHub; import net.openhft.chronicle.wire.WireType; import net.openhft.chronicle.wire.YamlLogging; import org.jetbrains.annotations.NotNull; import org.junit.*; import java.util.Map; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import static java.util.concurrent.TimeUnit.SECONDS; public class RestartClosedPublisherTest { public static final WireType WIRE_TYPE = WireType.TEXT; private static final String CONNECTION_1 = "Test1.host.port"; @Rule public ShutdownHooks hooks = new ShutdownHooks(); private ServerEndpoint _serverEndpoint1; private VanillaAssetTree _server; private VanillaAssetTree _remote; @NotNull private String _testMapUri = "/test/map"; private ThreadDump threadDump; private Map<ExceptionKey, Integer> exceptions; @Before public void threadDump() { threadDump = new ThreadDump(); } public void checkThreadDump() { threadDump.assertNoNewThreads(); } public void afterMethod() { ThreadMonitoringTest.filterExceptions(exceptions); if (Jvm.hasException(exceptions)) { Jvm.dumpException(exceptions); Assert.fail(); } } @Before public void setUp() throws Exception { exceptions = Jvm.recordExceptions(); TCPRegistry.createServerSocketChannelFor(CONNECTION_1); YamlLogging.setAll(false); _server = hooks.addCloseable(new VanillaAssetTree().forServer()); _serverEndpoint1 = hooks.addCloseable(new ServerEndpoint(CONNECTION_1, _server, "cluster")); } @After public void after() throws Exception { _serverEndpoint1.close(); _server.close(); TcpChannelHub.closeAllHubs(); TCPRegistry.reset(); threadDump.assertNoNewThreads(); ThreadMonitoringTest.filterExceptions(exceptions); if (Jvm.hasException(exceptions)) { Jvm.dumpException(exceptions); Assert.fail(); } } /** * Test that a client can connect to a server side map, register a subscriber and perform put. * Close the client, create new one and do the same. */ @Test public void testClientReconnectionOnMap() throws InterruptedException { @NotNull String testKey = "Key1"; for (int i = 0; i < 2; i++) { @NotNull String value = "Value1"; @NotNull BlockingQueue<String> eventQueue = new ArrayBlockingQueue<>(1); connectClientAndPerformPutGetTest(testKey, value, eventQueue); value = "Value2"; connectClientAndPerformPutGetTest(testKey, value, eventQueue); } } private void connectClientAndPerformPutGetTest(String testKey, String value, @NotNull BlockingQueue<String> eventQueue) throws InterruptedException { @NotNull VanillaAssetTree remote = new VanillaAssetTree().forRemoteAccess(CONNECTION_1, WIRE_TYPE); @NotNull String keySubUri = _testMapUri + "/" + testKey + "?bootstrap=false"; @NotNull Map<String, String> map = remote.acquireMap(_testMapUri, String.class, String.class); map.size(); remote.registerSubscriber(keySubUri + "?bootstrap=false", String.class, (e) -> eventQueue.add(e)); // wait for the subscription to be read by the server Jvm.pause(100); map.put(testKey, value); Assert.assertEquals(value, eventQueue.poll(2, SECONDS)); String getValue = map.get(testKey); Assert.assertEquals(value, getValue); remote.close(); } }
34.365672
153
0.699457
bf8b21998c63d3abe1f14831691ef986b4b21f91
6,643
package com.diego.hernando.orchestTest.business.worksign.service; import com.diego.hernando.orchestTest.business.DateOperationsService; import com.diego.hernando.orchestTest.business.worksign.WorkSignDto; import com.diego.hernando.orchestTest.model.WorkSignRecordType; import com.diego.hernando.orchestTest.model.WorkSignType; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; import java.util.Optional; import static com.diego.hernando.orchestTest.testUtils.DefaultDateTimeFormatter.parseDate; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; public class WorkSignReturnerByWeeksServiceTest { private final WorkSignReturnerByWeeksService workSignRetByWeekSrv = new WorkSignReturnerByWeeksService( null, null, new WorkSignOperationsService(), new DateOperationsService()); private final WorkSignDto.WorkSignDtoBuilder builderBaseDto = WorkSignDto.builder().type(WorkSignType.WORK).recordType(WorkSignRecordType.IN) .employeeId("01").businessId("1").serviceId("service").date(parseDate("08/07/2020 00:00:00")); @Test public void get_last_IN_work_day_wSign_expected_from_prepared_day_list_of_wSigns_getLastWorkInDayWsign () { List<WorkSignDto> dtos = new ArrayList<>(); dtos.add(builderBaseDto.build()); dtos.add(builderBaseDto.date(parseDate("08/07/2020 10:00:00")).build()); dtos.add(builderBaseDto.date(parseDate("08/07/2020 11:00:00")).type(WorkSignType.REST).build()); dtos.add(builderBaseDto.date(parseDate("08/07/2020 15:00:00")).type(WorkSignType.WORK) .recordType(WorkSignRecordType.OUT).build()); Optional<WorkSignDto> lastWorkInDayWsign = workSignRetByWeekSrv.getLastWorkInDayWsign(dtos); assertThat(lastWorkInDayWsign.isPresent(), is(true)); assertThat(lastWorkInDayWsign.get().getDate(), is(parseDate("08/07/2020 10:00:00"))); assertThat(lastWorkInDayWsign.get().getRecordType(), is(WorkSignRecordType.IN)); assertThat(lastWorkInDayWsign.get().getType(), is(WorkSignType.WORK)); } @Test public void test_get_list_empty_when_day_is_complete_getIncompleteWSignsOfDay () { List<WorkSignDto> dtos = new ArrayList<>(); dtos.add(builderBaseDto.build()); dtos.add(builderBaseDto.date(parseDate("08/07/2020 10:00:00")).build()); dtos.add(builderBaseDto.date(parseDate("08/07/2020 11:00:00")).type(WorkSignType.REST).build()); dtos.add(builderBaseDto.date(parseDate("08/07/2020 15:00:00")).type(WorkSignType.WORK) .recordType(WorkSignRecordType.OUT).build()); assertThat(workSignRetByWeekSrv.getIncompleteWSignsOfDay(dtos).size(), is(0)); } @Test public void test_get_list_empty_when_day_is_empty_getIncompleteWSignsOfDay () { List<WorkSignDto> dtos = new ArrayList<>(); assertThat(workSignRetByWeekSrv.getIncompleteWSignsOfDay(dtos).size(), is(0)); } @Test public void test_get_list_with_incomplete_wSigns_when_day_is_incomplete_getIncompleteWSignsOfDay () { List<WorkSignDto> dtos = new ArrayList<>(); dtos.add(builderBaseDto.build()); dtos.add(builderBaseDto.date(parseDate("08/07/2020 10:00:00")).build()); dtos.add(builderBaseDto.date(parseDate("08/07/2020 11:00:00")).type(WorkSignType.REST).build()); dtos.add(builderBaseDto.date(parseDate("08/07/2020 15:00:00")).type(WorkSignType.REST) .recordType(WorkSignRecordType.OUT).build()); assertThat(workSignRetByWeekSrv.getIncompleteWSignsOfDay(dtos).size(), is(3)); } @Test public void test_get_list_with_incomplete_wSigns_when_day_is_incomplete_getIncompleteWSignsOfDa () { List<WorkSignDto> dtos = new ArrayList<>(); dtos.add(builderBaseDto.build()); dtos.add(builderBaseDto.date(parseDate("08/07/2020 10:00:00")).build()); dtos.add(builderBaseDto.date(parseDate("08/07/2020 11:00:00")).type(WorkSignType.REST).build()); dtos.add(builderBaseDto.date(parseDate("08/07/2020 15:00:00")).type(WorkSignType.REST) .recordType(WorkSignRecordType.OUT).build()); assertThat(workSignRetByWeekSrv.getIncompleteWSignsOfDay(dtos).size(), is(3)); } @Test /* It is a strange case, but if it were true, it would cause the loss of info if the data from the previous day when they were incomplete. */ public void check_week_has_not_wSigns_its_init_not_free_work_isFreeWorkWeekInit () { List<WorkSignDto> dtos = new ArrayList<>(); assertThat(workSignRetByWeekSrv.isFreeWorkInitWeek(dtos), is(false)); } @Test public void check_when_first_wSign_ofWeek_is_IN_WORK_its_init_is_free_work_isFreeWorkWeekInit () { List<WorkSignDto> dtos = new ArrayList<>(); dtos.add(builderBaseDto.build()); assertThat(workSignRetByWeekSrv.isFreeWorkInitWeek(dtos), is(true)); } @Test public void check_when_first_wSign_ofWeek_is_OUT_WORK_its_init_is_not_free_work_isFreeWorkWeekInit () { List<WorkSignDto> dtos = new ArrayList<>(); dtos.add(builderBaseDto.recordType(WorkSignRecordType.OUT).build()); assertThat(workSignRetByWeekSrv.isFreeWorkInitWeek(dtos), is(false)); } @Test public void check_when_first_wSign_ofWeek_is_IN_REST_its_init_is_not_free_work_isFreeWorkWeekInit () { List<WorkSignDto> dtos = new ArrayList<>(); dtos.add(builderBaseDto.type(WorkSignType.REST).build()); assertThat(workSignRetByWeekSrv.isFreeWorkInitWeek(dtos), is(false)); } @Test public void check_when_first_wSign_ofWeek_is_OUT_REST_its_init_is_not_free_work_isFreeWorkWeekInit () { List<WorkSignDto> dtos = new ArrayList<>(); dtos.add(builderBaseDto.recordType(WorkSignRecordType.OUT).type(WorkSignType.REST).build()); assertThat(workSignRetByWeekSrv.isFreeWorkInitWeek(dtos), is(false)); } @Test public void test_get_list_last_day_getLastDayWeekWsigns(){ List<WorkSignDto> dtos = new ArrayList<>(); dtos.add(builderBaseDto.build()); dtos.add(builderBaseDto.date(parseDate("08/07/2020 10:00:00")).build()); dtos.add(builderBaseDto.date(parseDate("08/08/2020 11:00:00")).type(WorkSignType.REST).build()); dtos.add(builderBaseDto.date(parseDate("08/08/2020 15:00:00")).type(WorkSignType.WORK) .recordType(WorkSignRecordType.OUT).build()); assertThat(workSignRetByWeekSrv.getLastDayWeekWsigns(dtos, parseDate("08/08/2020 11:00:00")).size(), is(2)); } }
49.207407
145
0.72121
c30b4e205f4de5d36e550440047b8824c090127c
5,778
package com.pega.api2swagger.schemagen.json; import java.io.IOException; import java.util.Iterator; import org.apache.commons.lang3.StringUtils; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.JsonNodeType; import com.fasterxml.jackson.databind.node.ObjectNode; import com.pega.api2swagger.utils.JsonUtils; public class JsonSchemaGeneratorUtils { private static final String EXAMPLE = "example"; private static final String INTEGER = "integer"; private static final String NUMBER = "number"; private static final String STRING = "string"; private static final String BOOLEAN = "boolean"; private static final String UNKNOWN = "unknown"; private static final String PROPERTIES = "properties"; private static final String ARRAY = "array"; private static final String OBJECT = "object"; private static final String TYPE = "type"; private static final String ITEMS = "items"; static ObjectMapper mapper = new ObjectMapper(); public static String generateSchema(String json) { if(StringUtils.isBlank(json)) return ""; ObjectNode rootNode = mapper.getNodeFactory().objectNode(); JsonNode node = null; try { node = mapper.readValue(json, JsonNode.class); } catch (IOException e) { throw new RuntimeException(e); } rootNode = createSchemaByJsonNode(node); return JsonUtils.prettyPrint(rootNode.toString()); } private static ObjectNode createSchemaByJsonNode(JsonNode node) { ObjectNode resultNodeNew = mapper.getNodeFactory().objectNode(); if (node.getNodeType() == JsonNodeType.OBJECT) { ObjectNode objResult = leafNodes(node); resultNodeNew.put(TYPE, OBJECT); resultNodeNew.set(PROPERTIES, objResult); } else if (node.getNodeType() == JsonNodeType.ARRAY) { ObjectNode items = identifyAndProcessArrayNode(node); resultNodeNew = items; } return resultNodeNew; } private static ObjectNode identifyAndProcessArrayNode(JsonNode node) { ObjectNode arrayProperties = mapper.getNodeFactory().objectNode(); String arrayType = findArrayType(node); ObjectNode items; if (arrayType.equals(OBJECT)) { arrayProperties = traverseArray(((ArrayNode) node)); items = createArraySchemaOfObjectType(arrayProperties); } else if (arrayType.equals(UNKNOWN)) { throw new RuntimeException( "unknown array type as the array is empty, cannot proceed please have some type in array"); } else { items = scalarArray(arrayType); } return items; } private static ObjectNode traverseArray(ArrayNode aNode) { ObjectNode resultNode = traverseArrayNodes(aNode.elements()); return resultNode; } private static ObjectNode leafNodes(JsonNode intermediateNode) { Iterator<String> fieldNames = intermediateNode.fieldNames(); ObjectNode resultNode = traverseLeafNodes(intermediateNode, fieldNames); return resultNode; } private static ObjectNode traverseLeafNodes(JsonNode intermediateNode, Iterator<String> fieldNames) { ObjectNode resultNode = mapper.getNodeFactory().objectNode(); while (fieldNames.hasNext()) { String field = fieldNames.next(); JsonNode leafNode = intermediateNode.get(field); if (leafNode.getNodeType() == JsonNodeType.NUMBER) { ObjectNode child = mapper.getNodeFactory().objectNode(); if(leafNode.isInt() || leafNode.isLong()){ child.put(TYPE, INTEGER); child.put(EXAMPLE, leafNode.asInt() + ""); }else if(leafNode.isFloat() || leafNode.isDouble()){ child.put(TYPE, NUMBER); child.put(EXAMPLE, leafNode.asInt() + ""); } resultNode.set(field, child); } else if (leafNode.getNodeType() == JsonNodeType.BOOLEAN) { ObjectNode child = mapper.getNodeFactory().objectNode(); child.put(TYPE, BOOLEAN); child.put(EXAMPLE, leafNode.asBoolean() + ""); resultNode.set(field, child); } else if (leafNode.getNodeType() == JsonNodeType.STRING) { ObjectNode child = mapper.getNodeFactory().objectNode(); child.put(TYPE, STRING); child.put(EXAMPLE, leafNode.asText() ); resultNode.set(field, child); } else if (leafNode.getNodeType() == JsonNodeType.OBJECT) { ObjectNode child = mapper.getNodeFactory().objectNode(); child = createSchemaByJsonNode(leafNode); resultNode.set(field, child); }else if(leafNode.getNodeType() == JsonNodeType.ARRAY){ ObjectNode items = identifyAndProcessArrayNode(leafNode); resultNode.set(field, items); } } return resultNode; } private static ObjectNode createArraySchemaOfObjectType(ObjectNode arrayProperties) { ObjectNode items; ObjectNode properties = mapper.getNodeFactory().objectNode(); properties.put(TYPE, OBJECT); properties.set(PROPERTIES, arrayProperties); items = mapper.getNodeFactory().objectNode(); items.put(TYPE, ARRAY); items.set(ITEMS, properties); return items; } private static ObjectNode scalarArray(String arrayType) { ObjectNode items = mapper.getNodeFactory().objectNode(); items.put(TYPE, ARRAY); ObjectNode arrayTypeNode = mapper.getNodeFactory().objectNode(); arrayTypeNode.put(TYPE, arrayType); items.set(ITEMS, arrayTypeNode); return items; } private static String findArrayType(JsonNode leafNode) { Iterator<JsonNode> nodes = leafNode.elements(); while(nodes.hasNext()){ JsonNode node = nodes.next(); return node.getNodeType().name().toLowerCase(); } return UNKNOWN; } private static ObjectNode traverseArrayNodes(Iterator<JsonNode> fieldNames) { ObjectNode resultNode = mapper.getNodeFactory().objectNode(); while (fieldNames.hasNext()) { JsonNode field = fieldNames.next(); resultNode = leafNodes(field); } return resultNode; } }
33.206897
102
0.734683
5aa675a8d1ea853c3b2b9002a0cadf751c162bec
1,163
package bigtwo.game; public class Database { public static final String TABLE_GROUP = "gamegroup" , FIELD_GROUP_GROUPID = "groupid" , FIELD_GROUP_EASTEREGG = "easteregg" , FIELD_GROUP_LANG = "lang" , FIELD_GROUP_LINK = "link" , FIELD_GROUP_NCARD = "ncard" , FIELD_GROUP_ALLOWTRIPLE = "allowtriple", FIELD_GROUP_SVC_DATA = "svc_data" , FIELD_GROUP_CCTC_TYPE = "cctc_type" , FIELD_GROUP_SC_DATA = "sc_data" , FIELD_GROUP_FC_TYPE = "fc_type" ; public static final int FILED_INDEX_GROUP_GROUPID = 1, FILED_INDEX_GROUP_EASTEREGG = 2, FILED_INDEX_GROUP_LANG = 3, FILED_INDEX_GROUP_LINK = 4, FILED_INDEX_GROUP_NCARD = 5, FILED_INDEX_GROUP_ALLOWTRIPLE = 6, FILED_INDEX_GROUP_SVC_DATA = 7, FILED_INDEX_GROUP_CCTC_TYPE = 8, FILED_INDEX_GROUP_SC_DATA = 9, FILED_INDEX_GROUP_FC_TYPE = 10; public static final String TABLE_PLAYER = "player" , FIELD_PLAYER_PLAYERID = "playerid" , FIELD_PLAYER_GAME_PLAYED = "gameplayed", FIELD_PLAYER_GAME_WON = "gamewon" ; }
32.305556
43
0.649183
8f40a018dca0b8d349f6e63f82319096f1af7154
147
package framework.chef; import framework.order.Order; public interface ChefCommand { void showStock(); void processOrder(Order order); }
16.333333
35
0.748299
7a250748ed8d186559e70c5ec019df4fb3dda744
2,769
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.modules.php.api.queries; import java.io.File; import java.util.Collection; import java.util.Collections; import org.netbeans.api.annotations.common.NullAllowed; import org.netbeans.api.queries.VisibilityQuery; import org.netbeans.modules.php.api.phpmodule.PhpModule; import org.openide.filesystems.FileObject; /** * Factory for all queries. * @since 2.24 */ public final class Queries { private static final PhpVisibilityQuery DEFAULT_PHP_VISIBILITY_QUERY = new DefaultPhpVisibilityQuery(); private Queries() { } /** * Get PHP visibility query for the given PHP module. If the PHP module is {@code null}, * {@link VisibilityQuery#getDefault() default} visibility query is returned. * @param phpModule PHP module, can be {@code null} * @return PHP visibility query */ public static PhpVisibilityQuery getVisibilityQuery(@NullAllowed PhpModule phpModule) { if (phpModule == null) { return DEFAULT_PHP_VISIBILITY_QUERY; } PhpVisibilityQuery visibilityQuery = phpModule.getLookup().lookup(PhpVisibilityQuery.class); assert visibilityQuery != null : "No php visibility query for php module " + phpModule.getClass().getName(); return visibilityQuery; } //~ Inner classes private static final class DefaultPhpVisibilityQuery implements PhpVisibilityQuery { @Override public boolean isVisible(File file) { return VisibilityQuery.getDefault().isVisible(file); } @Override public boolean isVisible(FileObject file) { return VisibilityQuery.getDefault().isVisible(file); } @Override public Collection<FileObject> getIgnoredFiles() { return Collections.emptyList(); } @Override public Collection<FileObject> getCodeAnalysisExcludeFiles() { return Collections.emptyList(); } } }
33.361446
116
0.706392
ba725ee717bebb5f3b81886253c32daac9b206b5
4,511
package com.example.android.popularmovies; import android.content.Context; import android.os.AsyncTask; import android.support.annotation.NonNull; import com.example.android.popularmovies.model.MovieInfo; import com.example.android.popularmovies.model.Review; import com.example.android.popularmovies.model.Trailer; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.net.URL; import java.util.ArrayList; /** * Created by sakydpozrux on 25/04/2017. */ public class TrailersReviewsSource { private static final String RESULTS_JSON_KEY = "results"; public interface TrailersReviewsSourceDelegate { void trailersAndReviewsFetched(); void errorDuringTrailersAndReviewsFetch(String message); } final private Context mContext; final private TrailersReviewsSourceDelegate mDelegate; public TrailersReviewsSource(@NonNull Context context, @NonNull TrailersReviewsSourceDelegate delegate) { mContext = context; mDelegate = delegate; } public void makeQueryTrailersAndReviews(MovieInfo movie) { final String id = movie.tmdbId; new TrailersAndReviewsFetchTask().execute(id); } public ArrayList<Trailer> getTrailers() { return mFetchTaskArgument.trailers; } public ArrayList<Review> getReviews() { return mFetchTaskArgument.reviews; } private FetchTaskArgument mFetchTaskArgument; private class FetchTaskArgument { ArrayList<Trailer> trailers = new ArrayList<>(); ArrayList<Review> reviews = new ArrayList<>(); } private class TrailersAndReviewsFetchTask extends AsyncTask<String, Void, FetchTaskArgument> { @Override protected FetchTaskArgument doInBackground(String... params) { final String id = params[0]; final String key = mContext.getString(R.string.key); FetchTaskArgument args = new FetchTaskArgument(); try { args.trailers = fetchTrailers(id, key); args.reviews = fetchReviews(id, key); } catch (Exception e) { e.printStackTrace(); mDelegate.errorDuringTrailersAndReviewsFetch(e.getMessage()); } return args; } @NonNull private ArrayList<Review> fetchReviews(String id, String key) throws IOException, JSONException { URL reviewsUrl = MovieDbApiUtils.buildUrlReviews(key, id); String reviewsResponse = MovieDbApiUtils.getResponseFromHttpUrl(reviewsUrl); JSONArray jsonReviews = new JSONObject(reviewsResponse).getJSONArray(RESULTS_JSON_KEY); ArrayList<Review> reviews = new ArrayList<>(); for (int reviewIndex = 0; reviewIndex < jsonReviews.length(); ++reviewIndex) { final JSONObject jsonReview = (JSONObject) jsonReviews.get(reviewIndex); Review review = new Review(); review.tmdbId = jsonReview.getString("id"); review.author = jsonReview.getString("author"); review.content = jsonReview.getString("content"); reviews.add(review); } return reviews; } @NonNull private ArrayList<Trailer> fetchTrailers(String id, String key) throws IOException, JSONException { URL trailersUrl = MovieDbApiUtils.buildUrlVideos(key, id); String trailersResponse = MovieDbApiUtils.getResponseFromHttpUrl(trailersUrl); JSONArray jsonTrailers = new JSONObject(trailersResponse).getJSONArray(RESULTS_JSON_KEY); ArrayList<Trailer> trailers = new ArrayList<>(); for (int trailerIndex = 0; trailerIndex < jsonTrailers.length(); ++trailerIndex) { final JSONObject jsonTrailer = (JSONObject) jsonTrailers.get(trailerIndex); Trailer trailer = new Trailer(); trailer.tmdbId = jsonTrailer.getString("id"); trailer.key = jsonTrailer.getString("key"); trailer.name = jsonTrailer.getString("name"); trailers.add(trailer); } return trailers; } @Override protected void onPostExecute(FetchTaskArgument fetchTaskArgument) { mFetchTaskArgument = fetchTaskArgument; mDelegate.trailersAndReviewsFetched(); super.onPostExecute(fetchTaskArgument); } } }
38.555556
107
0.661937
55439b894fcfa45d49a66c7fdd73ca8f5d8b5202
1,685
/* * Copyright The OpenTelemetry 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 io.opentelemetry.auto.instrumentation.kafkastreams; import io.opentelemetry.OpenTelemetry; import io.opentelemetry.auto.bootstrap.instrumentation.decorator.ClientDecorator; import io.opentelemetry.trace.Span; import io.opentelemetry.trace.Tracer; import org.apache.kafka.streams.processor.internals.StampedRecord; public class KafkaStreamsDecorator extends ClientDecorator { public static final KafkaStreamsDecorator CONSUMER_DECORATE = new KafkaStreamsDecorator(); public static final Tracer TRACER = OpenTelemetry.getTracerProvider().get("io.opentelemetry.auto.kafka-streams-0.11"); public String spanNameForConsume(final StampedRecord record) { if (record == null) { return null; } final String topic = record.topic(); if (topic != null) { return topic; } else { return "destination"; } } public void onConsume(final Span span, final StampedRecord record) { if (record != null) { span.setAttribute("partition", record.partition()); span.setAttribute("offset", record.offset()); } } }
33.7
92
0.738872
d2da1354989c4f902b06454c51fae0a9199f723b
1,605
package ch.fridolins.fridowpi.sensors; import ch.fridolins.fridowpi.sensors.base.IUltrasonic; import edu.wpi.first.math.filter.LinearFilter; import edu.wpi.first.util.sendable.Sendable; import edu.wpi.first.util.sendable.SendableBuilder; import edu.wpi.first.util.sendable.SendableRegistry; import edu.wpi.first.wpilibj.AnalogInput; import edu.wpi.first.wpilibj.RobotController; public class AnalogUltrasonicSensor implements IUltrasonic, Sendable { private AnalogInput sensor; private LinearFilter filter; double scale; /*** / @param scale volts per mm / */ public AnalogUltrasonicSensor(int channel, double scale) { // this.sensor = new AnalogPotentiometer(channel); this.sensor = new AnalogInput(channel); this.scale = scale; filter = LinearFilter.movingAverage(16); filter.reset(); SendableRegistry.addLW(this, "AnalogUltrasonic", channel); } /*** / @return distance in mm / */ @Override public double getRawDistance() { return sensor.getValue() * scale * (5 / RobotController.getVoltage5V()); } /*** * @return filtered distance in mm * */ @Override public double getFilteredDistance() { return filter.calculate(this.getRawDistance()); } @Override public void initSendable(SendableBuilder builder) { builder.addDoubleProperty("RawSensorValue", this::getRawDistance, null); builder.addDoubleProperty("FilteredSensorValue", this::getFilteredDistance, null); builder.setSmartDashboardType("AnalogUltrasonic"); } }
30.283019
90
0.698442
8dab14dfacfc5d0d15b87df51d525de9bdb33550
9,478
package org.ggp.base.apps.benchmark; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.ggp.base.player.GamePlayer; import org.ggp.base.player.gamer.Gamer; import org.ggp.base.player.gamer.statemachine.random.RandomGamer; import org.ggp.base.server.GameServer; import org.ggp.base.server.event.ServerNewMovesEvent; import org.ggp.base.util.game.Game; import org.ggp.base.util.game.GameRepository; import org.ggp.base.util.gdl.grammar.Gdl; import org.ggp.base.util.gdl.grammar.GdlPool; import org.ggp.base.util.gdl.grammar.GdlRelation; import org.ggp.base.util.gdl.grammar.GdlRule; import org.ggp.base.util.match.Match; import org.ggp.base.util.observer.Event; import org.ggp.base.util.observer.Observer; import org.ggp.base.util.statemachine.Move; import org.ggp.base.util.statemachine.Role; import org.ggp.base.util.symbol.factory.SymbolFactory; import org.ggp.base.util.symbol.factory.exceptions.SymbolFormatException; import org.ggp.base.util.symbol.grammar.Symbol; import org.ggp.base.util.symbol.grammar.SymbolList; /** * PlayerTester is a benchmarking tool to evaluate the skill of a player. * It only requires one player to be running and uses only minimal extra * memory, so it can run on the same machine as the player. It run a set * of test cases, and computes a benchmark score for the player based on * how many of the tests the player passes. * * Tests consist of a game, a state in that game, a role that the player * will act as, and a set of "good" move choices. The player passes the * test if, when put into a match of the given game in the given state as * the given role, the player chooses one of the "good" move choices in a * reasonable amount of time. * * Mechanically, this is done by constructing an artificial game in which * the original game is modified to start in the chosen state, by adjusting * the set of "init" propositions. The player is put into a match playing * the game, with a suitable start clock, and runs through exactly one move. * Then the move is checked against the list of "good" moves, a "pass/fail" * verdict is issued, and the match is aborted. Repeat for all tests. * * The benchmark score is deterministic if the player is deterministic. * * @author Sam Schreiber */ public class PlayerTester { /** * TestCase is a test case for the PlayerTester. * * Each test case contains a game, a game state, a role, and a set of "good" * moves for that role to take in that game state when playing that game. The * PlayerTester will simulate this with an actual player, and determine if the * move the player chooses is one of the "good" moves. */ public static class TestCase { public final String suiteName; public final String gameKey; public final int nRole; public final int nStartClock; public final int nPlayClock; public final String theState; public final String[] goodMovesArr; public TestCase(String suiteName, String gameKey, int nRole, int nStartClock, int nPlayClock, String theState, String[] goodMovesArr) { this.suiteName = suiteName; this.gameKey = gameKey; this.nRole = nRole; this.nStartClock = nStartClock; this.nPlayClock = nPlayClock; this.theState = theState; this.goodMovesArr = goodMovesArr; } } /** * getMediasResGame takes a game and a desired initial state, and rewrites * the game rules so that the game begins in that initial state. To do this * it removes all of the "init" rules and substitutes in its own set. * @throws SymbolFormatException */ static Game getMediasResGame(String gameKey, String theState) throws SymbolFormatException { StringBuilder newRulesheet = new StringBuilder(); List<Gdl> theRules = GameRepository.getDefaultRepository().getGame(gameKey).getRules(); for (Gdl gdl : theRules) { if (gdl instanceof GdlRule) { // Capture and drop init statements of the form "( <= ( init ( pool ?piece ) ) ( piece ?piece ) )" GdlRule rule = (GdlRule)gdl; if (rule.getHead().getName().equals(GdlPool.INIT)) { ; } else { newRulesheet.append(gdl.toString() + "\n"); } } else if (gdl instanceof GdlRelation) { // Capture and drop init statements of the form "( init ( cell 4 4 empty ) )" GdlRelation rel = (GdlRelation)gdl; if (rel.getName().equals(GdlPool.INIT)) { ; } else { newRulesheet.append(gdl.toString() + "\n"); } } else { newRulesheet.append(gdl.toString() + "\n"); } } // Once all of the existing init lines have been removed, add new ones. SymbolList newInitialState = (SymbolList)SymbolFactory.create(theState); for (int i = 0; i < newInitialState.size(); i++) { Symbol anInit = newInitialState.get(i); newRulesheet.append("( INIT " + anInit + " )\n"); } return Game.createEphemeralGame("( " + newRulesheet.toString() + " )"); } public static boolean passesTest(String hostport, TestCase theCase) throws SymbolFormatException { final Game theGame = getMediasResGame(theCase.gameKey, theCase.theState); final Match theMatch = new Match("playerTester." + Match.getRandomString(5), -1, theCase.nStartClock, theCase.nPlayClock, theGame, ""); // Set up fake players to pretend to play the game alongside the real player List<String> theHosts = new ArrayList<String>(); List<Integer> thePorts = new ArrayList<Integer>(); for (int i = 0; i < Role.computeRoles(theGame.getRules()).size(); i++) { theHosts.add("SamplePlayer" + i); thePorts.add(9147+i); } theHosts.set(theCase.nRole, hostport.split(":")[0]); thePorts.set(theCase.nRole, Integer.parseInt(hostport.split(":")[1])); // Set up a game server to play through the game, with all players playing randomly // except the real player that we're testing final GameServer theServer = new GameServer(theMatch, theHosts, thePorts); for (int i = 0; i < theHosts.size(); i++) { if (i != theCase.nRole) { theServer.makePlayerPlayRandomly(i); } } final int theRole = theCase.nRole; final Move[] theChosenMoveArr = new Move[1]; theServer.addObserver(new Observer() { @Override public void observe(Event event) { if (event instanceof ServerNewMovesEvent) { theChosenMoveArr[0] = ((ServerNewMovesEvent)event).getMoves().get(theRole); theServer.abort(); } } }); theServer.start(); try { theServer.join(); } catch (InterruptedException e) { e.printStackTrace(); } final String theChosenMove = theChosenMoveArr[0].toString().toLowerCase(); Set<String> goodMoves = new HashSet<String>(Arrays.asList(theCase.goodMovesArr)); boolean passes = goodMoves.contains(theChosenMove); if (!passes) { System.out.println("Failure: player chose " + theChosenMove + "; acceptable moves are " + goodMoves); } else { System.out.println("Success: player chose " + theChosenMove + " which is an acceptable move."); } return passes; } public static Map<String, Double> getBenchmarkScores(String hostport) throws SymbolFormatException { Map<String, Integer> nTestsBySuite = new HashMap<String, Integer>(); Map<String, Integer> nPassesBySuite = new HashMap<String, Integer>(); for (TestCase aCase : PlayerTesterCases.TEST_CASES) { if (!nTestsBySuite.containsKey(aCase.suiteName)) nTestsBySuite.put(aCase.suiteName, 0); if (!nPassesBySuite.containsKey(aCase.suiteName)) nPassesBySuite.put(aCase.suiteName, 0); nTestsBySuite.put(aCase.suiteName, nTestsBySuite.get(aCase.suiteName) + 1); if (passesTest(hostport, aCase)) { nPassesBySuite.put(aCase.suiteName, nPassesBySuite.get(aCase.suiteName) + 1); } } Map<String, Double> benchmarkScores = new HashMap<String, Double>(); for (String key : nTestsBySuite.keySet()) { benchmarkScores.put(key, Math.floor(100 * (double)nPassesBySuite.get(key) / (double)nTestsBySuite.get(key))); } return benchmarkScores; } public static Map<String, Double> getBenchmarkScores(Gamer aGamer) throws IOException, SymbolFormatException { GamePlayer player = new GamePlayer(3141, aGamer); player.start(); Map<String, Double> theScores = getBenchmarkScores("127.0.0.1:3141"); player.shutdown(); return theScores; } public static void main(String[] args) throws InterruptedException, SymbolFormatException, IOException { System.out.println("Benchmark score for random player: " + getBenchmarkScores(new RandomGamer())); } }
44.083721
143
0.651087
30e13c6d0e90608e807d215799ee2a2f662b0ace
1,569
package com.hibegin.http.file.config; import com.hibegin.common.util.LoggerUtil; import com.hibegin.http.file.intercepter.FileInterceptor; import com.hibegin.http.file.server.SimpleWebServerCliOptions; import com.hibegin.http.server.config.AbstractServerConfig; import com.hibegin.http.server.config.RequestConfig; import com.hibegin.http.server.config.ResponseConfig; import com.hibegin.http.server.config.ServerConfig; import java.util.Objects; import java.util.logging.Logger; public class FileServerConfig extends AbstractServerConfig { private static final Logger LOGGER = LoggerUtil.getLogger(FileServerConfig.class); public final SimpleWebServerCliOptions options; public FileServerConfig(SimpleWebServerCliOptions options) { this.options = options; } public SimpleWebServerCliOptions getOptions() { return options; } @Override public ServerConfig getServerConfig() { ServerConfig serverConfig = new ServerConfig(); serverConfig.addInterceptor(FileInterceptor.class); serverConfig.setPort(Objects.requireNonNullElse(options.getPort(), SimpleWebServerCliOptions.DEFAULT_PORT)); serverConfig.setWelcomeFile(null); if (options.getPath() != null) { LOGGER.info("Current workPath " + options.getPath()); } return serverConfig; } @Override public RequestConfig getRequestConfig() { return new RequestConfig(); } @Override public ResponseConfig getResponseConfig() { return new ResponseConfig(); } }
32.020408
116
0.739962
d265626268ef21e6c6631cc0b45e9da3d3738b8f
1,656
/************************************************************************* * * ATOS CONFIDENTIAL * __________________ * * Copyright (2020) Atos Spain SA * All Rights Reserved. * * NOTICE: All information contained herein is, and remains * the property of Atos Spain SA and other companies of the Atos group. * The intellectual and technical concepts contained * herein are proprietary to Atos Spain SA * and other companies of the Atos group and may be covered by Spanish regulations * and are protected by copyright law. * Dissemination of this information or reproduction of this material * is strictly forbidden unless prior written permission is obtained * from Atos Spain SA. */ package eu.h2020.helios_social.modules.videocall.connection; import android.util.Log; import org.webrtc.SdpObserver; import org.webrtc.SessionDescription; public class CustomSdpObserver implements SdpObserver { private String tag; public CustomSdpObserver(String logTag) { tag = this.getClass().getCanonicalName(); this.tag = this.tag + " " + logTag; } @Override public void onCreateSuccess(SessionDescription sessionDescription) { Log.d(tag, "onCreateSuccess() called with: sessionDescription = [" + sessionDescription + "]"); } @Override public void onSetSuccess() { Log.d(tag, "onSetSuccess() called"); } @Override public void onCreateFailure(String s) { Log.d(tag, "onCreateFailure() called with: s = [" + s + "]"); } @Override public void onSetFailure(String s) { Log.d(tag, "onSetFailure() called with: s = [" + s + "]"); } }
28.551724
103
0.661836
48e1e1cdc276bb1cfd50dadaff983b702007a75f
1,693
package arrays; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.DisplayName; import java.lang.annotation.Documented; import java.util.*; /** * @author g1patil * You are given an integer array nums. In one move, you can pick an index i where 0 <= i < nums.length and increment nums[i] by 1. * Return the minimum number of moves to make every value in nums unique. * Leetcode : 945. Minimum Increment to Make Array Unique * * Algo : Sort the array first. * Run for loop * for each element, if the element is less than equal to the previous element , * then this element needs increment. The increment needed will be difference + 1 * At each step, keep incrementing the count. count will be difference + 1 + count */ public class MakeArrayUnique { /** * Returns the count of increment to make the array unique. * Att each step only, one increment is allowed. * @param nums int array of numbers * @return total count. * */ public int minIncrementForUnique(int[] nums) { Arrays.sort(nums); int count = 0 ; for (int i = 1; i < nums.length; i++) { if (nums[i] <= nums[i-1]){ count = count + nums[i-1] - nums[i] + 1; nums[i] = nums[i-1] + 1 ; } } return count; } @Test public void test_(){ System.out.println(minIncrementForUnique(new int[]{3,2,1,2,1,7})); } @Test @DisplayName("When all the elements are equal") public void test_2(){ Assertions.assertEquals(6 , minIncrementForUnique(new int[]{1,1,1,1})); } }
30.232143
131
0.61961
b5997d18a4ff9fd886806e8b12d25b4cd76f3e45
4,518
/** * Copyright (c) 2010, Ben Fortuna * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * o Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * o Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * o Neither the name of Ben Fortuna nor the names of any other contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package net.fortuna.ical4j.model.property; import net.fortuna.ical4j.model.*; import net.fortuna.ical4j.validate.ValidationException; import java.io.IOException; import java.net.URISyntaxException; import java.text.ParseException; /** * * Defines an POLL-PROPERTIES iCalendar component property. * <pre> * </pre> * @author benf * @author mike douglass */ public class PollProperties extends Property { private static final long serialVersionUID = -7769987073466681634L; private TextList properties; /** * Default constructor. */ public PollProperties() { super(POLL_PROPERTIES, new ParticipantType.Factory()); properties = new TextList(); } /** * @param aValue a value string for this component */ public PollProperties(final String aValue) { super(POLL_PROPERTIES, new ParticipantType.Factory()); setValue(aValue); } /** * @param aList a list of parameters for this component * @param aValue a value string for this component */ public PollProperties(final ParameterList aList, final String aValue) { super(POLL_PROPERTIES, aList, new ParticipantType.Factory()); setValue(aValue); } /** * @param cList a list of component names */ public PollProperties(final TextList cList) { super(POLL_PROPERTIES, new ParticipantType.Factory()); properties = cList; } /** * @param aList a list of parameters for this Property * @param val a list of Property names */ public PollProperties(final ParameterList aList, final TextList val) { super(POLL_PROPERTIES, aList, new ParticipantType.Factory()); properties = val; } /** * {@inheritDoc} */ public final void setValue(final String aValue) { properties = new TextList(aValue); } /** * {@inheritDoc} */ public final void validate() throws ValidationException { /* * ; the following is optional, ; and MAY occur more than once (";" xparam) */ } /** * @return Returns the Property names. */ public final TextList getPropertyNames() { return properties; } /** * {@inheritDoc} */ public final String getValue() { return getPropertyNames().toString(); } public static class Factory extends Content.Factory implements PropertyFactory<PollProperties> { private static final long serialVersionUID = 1L; public Factory() { super(POLL_PROPERTIES); } public PollProperties createProperty(final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new PollProperties(parameters, value); } public PollProperties createProperty() { return new PollProperties(); } } }
30.945205
96
0.682382
01f8b4600cf3b76c6bd3b776d2e381021a8af7bb
2,367
package org.develnext.jphp.ext.webcam.classes.event; import com.github.sarxos.webcam.Webcam; import com.github.sarxos.webcam.WebcamMotionEvent; import javafx.embed.swing.SwingFXUtils; import javafx.scene.image.Image; import org.develnext.jphp.ext.webcam.WebcamExtension; import php.runtime.Memory; import php.runtime.annotation.Reflection; import php.runtime.env.Environment; import php.runtime.lang.BaseWrapper; import php.runtime.memory.ArrayMemory; import php.runtime.reflection.ClassEntity; import java.awt.*; import java.awt.image.BufferedImage; import java.lang.reflect.Array; import java.util.ArrayList; @Reflection.Name("WebcamMotionEvent") @Reflection.Namespace(WebcamExtension.NS+"\\event") @Reflection.Abstract public class WebcamMotionEventWrapper extends BaseWrapper<WebcamMotionEvent> { public WebcamMotionEventWrapper(Environment env, WebcamMotionEvent wrappedObject) { super(env, wrappedObject); } public WebcamMotionEventWrapper(Environment env, ClassEntity clazz) { super(env, clazz); } interface WrappedInterface{ @Reflection.Getter Webcam getWebcam(); @Reflection.Getter double getArea(); } @Reflection.Getter public Memory getCog(){ Point cog = getWrappedObject().getCog(); ArrayMemory res = new ArrayMemory(); res.add(cog.getX()); res.add(cog.getY()); return res; } @Reflection.Getter public Memory getPoints(){ ArrayMemory result = new ArrayMemory(); ArrayList<Point> pointList = getWrappedObject().getPoints(); if(pointList == null){ return result; } for(Point point : pointList){ ArrayMemory pointInfo = new ArrayMemory(); pointInfo.add(point.getX()); pointInfo.add(point.getY()); result.add(pointInfo); } return result; } @Reflection.Getter public Image getCurrentImage(){ BufferedImage bufferedImage = getWrappedObject().getCurrentImage(); return bufferedImage == null ? null : SwingFXUtils.toFXImage(bufferedImage, null); } @Reflection.Getter public Image getPreviousImage(){ BufferedImage bufferedImage = getWrappedObject().getPreviousImage(); return bufferedImage == null ? null : SwingFXUtils.toFXImage(bufferedImage, null); } }
29.5875
90
0.697507
b744913dd217e398ea70398cdaf55d761f0bc3f6
184
/** * Components and Entities of the domain layer. * <p>It does not assume it that a component of the domain layer calls the UI layer and application layer. */ package sample.model;
36.8
106
0.744565
0fec76b1e6a8ef799a18ce616ff3301385881c57
760
package com.example.task.warrior; import com.example.task.Task; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectWriter; import org.junit.jupiter.api.Test; class TaskWarriorServiceTest { @Test void name() throws JsonProcessingException { final ObjectMapper objectMapper = new ObjectMapper(); final ObjectWriter objectWriter = objectMapper.writer() .withoutAttribute("entry"); final Task task = new Task(); task.description = "first task"; task.entry = "lol"; // assertEquals("{\"description\":\"first task\"}", // objectWriter.writeValueAsString(task)); } }
31.666667
63
0.689474
b6df8f5c84f8811cf511a37d5d1861e46c7899e2
1,277
/** * $Id$ * Copyright(C) 2012-2016 qiyun.com. All rights reserved. */ package com.configx.demo.bean; import com.configx.client.converter.ConfigBeanConverter; import org.simpleframework.xml.Serializer; import org.simpleframework.xml.convert.AnnotationStrategy; import org.simpleframework.xml.core.Persister; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.convert.TypeDescriptor; /** * 自定义配置转换器,将XML文件转换成Bean */ public class XmlConfigConverter implements ConfigBeanConverter { private static final Logger LOGGER = LoggerFactory.getLogger(XmlConfigConverter.class); @Override public boolean matches(String propertyName, String propertyValue, TypeDescriptor targetType) { return propertyName != null && propertyName.endsWith(".xml"); } @Override public Object convert(String propertyName, String propertyValue, TypeDescriptor targetType) { Class<?> targetClass = targetType.getType(); Serializer serializer = new Persister(new AnnotationStrategy()); try { return serializer.read(targetClass, propertyValue, false); } catch (Exception e) { LOGGER.error("Convert xml to " + targetClass + " error", e); } return null; } }
31.925
98
0.723571
1fcb839b217a00c0540e65c47bcd6e64b18281db
625
package examples; import java.io.File; import java.net.URL; import org.terifan.imageio.jpeg.JPEGImageIO; import examples.res.R; import org.terifan.imageio.jpeg.CompressionType; public class TranscodeJPEGDemo { public static void main(String... args) { try { URL input = R.class.getResource("Swallowtail.jpg"); File output = new File("d:\\Swallowtail-arithmetic.jpg"); new JPEGImageIO().setCompressionType(CompressionType.ArithmeticProgressive).transcode(input, output); _ImageWindow.show(output).setTitle("" + output.length()); } catch (Throwable e) { e.printStackTrace(System.out); } } }
20.833333
104
0.7312
bb2d426bbe74ed88a64b7bfe082377328af3b133
196
/* * Travis Ferguson - Apache 2.0 Licensed */ package com.overwrittenstack.raceday.service; /** * * @author Travis */ public class TimedRaceManager { //TODO make this work }
15.076923
46
0.637755
7d1a605580c67a557d1cc96a5c23eb4c45e4009d
3,059
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.taobao.adfs.database.tdhsocket.client.easy.impl; import com.taobao.adfs.database.tdhsocket.client.common.TDHSCommon; import com.taobao.adfs.database.tdhsocket.client.easy.Query; import com.taobao.adfs.database.tdhsocket.client.easy.Set; import com.taobao.adfs.database.tdhsocket.client.request.Get; import com.taobao.adfs.database.tdhsocket.client.request.Update; import org.jetbrains.annotations.Nullable; /** * @author <a href="mailto:wentong@taobao.com">文通</a> * @since 11-12-27 下午4:12 */ public class SetImpl implements Set { private String field = null; private final Get get; private final Update update; private final Query query; public SetImpl(Get get, Update update, Query query) { this.get = get; this.query = query; this.update = update; } public Set field(String field) { if (this.field != null) { throw new IllegalArgumentException("can't field twice!"); } this.field = field; return this; } private Query setIt(String value, TDHSCommon.UpdateFlag updateFlag) { if (this.field == null) { throw new IllegalArgumentException("no field!"); } this.get.getTableInfo().getFields().add(this.field); this.field = null; this.update.addEntry(updateFlag, value); return query; } public Query add(long value) { return setIt(String.valueOf(value), TDHSCommon.UpdateFlag.TDHS_UPDATE_ADD); } public Query sub(long value) { return setIt(String.valueOf(value), TDHSCommon.UpdateFlag.TDHS_UPDATE_SUB); } public Query set(@Nullable String value) { return setIt(value, TDHSCommon.UpdateFlag.TDHS_UPDATE_SET); } public Query set(long value) { return set(String.valueOf(value)); } public Query set(int value) { return set(String.valueOf(value)); } public Query set(short value) { return set(String.valueOf(value)); } public Query set(char value) { return set(String.valueOf(value)); } public Query setNow() { return setIt("", TDHSCommon.UpdateFlag.TDHS_UPDATE_NOW); } public Query setNull() { return set(null); } }
29.699029
83
0.680288
b7618bccaa60f723c503e4d352657168477d35ae
1,085
package frc.fangv.robot.subsystems; import edu.wpi.first.cameraserver.CameraServer; import edu.wpi.first.wpilibj2.command.Subsystem; public class CameraSubsystem implements Subsystem { /** * The Singleton instance of this CameraSubsystem. External classes should * use the {@link #getInstance()} method to get the instance. */ private final static CameraSubsystem INSTANCE = new CameraSubsystem(); /** * Creates a new instance of this CameraSubsystem. * This constructor is private since this class is a Singleton. External classes * should use the {@link #getInstance()} method to get the instance. */ private CameraSubsystem() { CameraServer.getInstance().startAutomaticCapture(); } /** * Returns the Singleton instance of this CameraSubsystem. This static method * should be used -- {@code CameraSubsystem.getInstance();} -- by external * classes, rather than the constructor to get the instance of this class. */ public static CameraSubsystem getInstance() { return INSTANCE; } }
32.878788
84
0.706912
935a4ddfe673e9ac8e893e1092aed004a8a5c9ea
6,422
/* * Copyright (c) 2020-2021 Heiko Bornholdt and Kevin Röbert * * 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 org.drasyl.channel; import io.netty.buffer.ByteBuf; import io.netty.channel.AbstractChannel; import io.netty.channel.Channel; import io.netty.channel.ChannelConfig; import io.netty.channel.ChannelMetadata; import io.netty.channel.ChannelOutboundBuffer; import io.netty.channel.ChannelPromise; import io.netty.channel.DefaultChannelConfig; import io.netty.channel.EventLoop; import io.netty.channel.nio.NioEventLoop; import io.netty.util.ReferenceCountUtil; import io.netty.util.internal.StringUtil; import org.drasyl.identity.DrasylAddress; import org.drasyl.identity.IdentityPublicKey; import java.net.SocketAddress; import java.nio.channels.AlreadyConnectedException; import java.nio.channels.ClosedChannelException; import java.nio.channels.NotYetConnectedException; /** * A virtual {@link Channel} for peer communication. * <p> * (Currently) only compatible with {@link io.netty.channel.nio.NioEventLoop}. * <p> * Inspired by {@link io.netty.channel.local.LocalChannel}. * * @see DrasylServerChannel */ public class DrasylChannel extends AbstractChannel { private static final String EXPECTED_TYPES = " (expected: " + StringUtil.simpleClassName(ByteBuf.class) + ')'; enum State {OPEN, BOUND, CONNECTED, CLOSED} private static final ChannelMetadata METADATA = new ChannelMetadata(false); private final ChannelConfig config = new DefaultChannelConfig(this); private volatile State state; volatile boolean pendingWrites; private volatile DrasylAddress localAddress; // NOSONAR private final DrasylAddress remoteAddress; public DrasylChannel(final Channel parent, final State state, final DrasylAddress localAddress, final DrasylAddress remoteAddress) { super(parent); this.state = state; this.localAddress = localAddress; this.remoteAddress = remoteAddress; } public DrasylChannel(final DrasylServerChannel parent, final IdentityPublicKey remoteAddress) { this(parent, null, parent.localAddress0(), remoteAddress); } @Override protected AbstractUnsafe newUnsafe() { return new DrasylChannelUnsafe(); } @Override protected boolean isCompatible(final EventLoop loop) { return loop instanceof NioEventLoop; } @Override protected SocketAddress localAddress0() { return localAddress; } @Override protected SocketAddress remoteAddress0() { return remoteAddress; } @Override protected void doRegister() { state = State.CONNECTED; } @Override protected void doBind(final SocketAddress localAddress) { state = State.BOUND; } @Override protected void doDisconnect() { doClose(); } @Override protected void doClose() { localAddress = null; state = State.CLOSED; } @Override protected void doBeginRead() { // NOOP // UdpServer, UdpMulticastServer, TcpServer are currently pushing their readings } @Override protected Object filterOutboundMessage(final Object msg) throws Exception { if (msg instanceof ByteBuf) { return super.filterOutboundMessage(msg); } throw new UnsupportedOperationException( "unsupported message type: " + StringUtil.simpleClassName(msg) + EXPECTED_TYPES); } @SuppressWarnings("java:S135") @Override protected void doWrite(final ChannelOutboundBuffer in) throws Exception { switch (state) { case OPEN: case BOUND: throw new NotYetConnectedException(); case CLOSED: throw new ClosedChannelException(); case CONNECTED: break; } pendingWrites = false; while (true) { final Object msg = in.current(); if (msg == null) { break; } if (!parent().isWritable()) { pendingWrites = true; break; } ReferenceCountUtil.retain(msg); parent().write(new AddressedMessage<>(msg, remoteAddress)); in.remove(); } parent().flush(); } @Override public ChannelConfig config() { return config; } @Override public boolean isOpen() { return state != State.CLOSED; } @Override public boolean isActive() { return state == State.CONNECTED; } @Override public ChannelMetadata metadata() { return METADATA; } private class DrasylChannelUnsafe extends AbstractUnsafe { @Override public void connect(final SocketAddress remoteAddress, final SocketAddress localAddress, final ChannelPromise promise) { if (!promise.setUncancellable() || !ensureOpen(promise)) { return; } if (state == State.CONNECTED) { final Exception cause = new AlreadyConnectedException(); safeSetFailure(promise, cause); pipeline().fireExceptionCaught(cause); } } } }
31.024155
99
0.65914
2bcdb1b932807d42b3db37231281a9f53380a347
210
package com.deer.wms.produce.manage.model; import com.deer.wms.project.seed.core.service.QueryParams; /** * Created by on 2019/10/08. */ public class MtAloneProcessMaterialsBomParams extends QueryParams { }
21
67
0.780952
e3f995f0dfcaed9b9793872429a68b594bc16b35
2,241
/** * Copyright 2018 Nelson Tavares de Sousa * * 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 de.gerdiproject.bookmark.backend.route; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; import org.bson.Document; import com.mongodb.BasicDBObject; import com.mongodb.client.FindIterable; import com.mongodb.client.MongoCollection; import de.gerdiproject.bookmark.backend.BookmarkCollection; import de.gerdiproject.bookmark.backend.BookmarkPersistenceConstants; import spark.Request; import spark.Response; /** * This class implements the handler for collection retrieval. * * @author Nelson Tavares de Sousa * */ public class GetCollections extends AbstractBookmarkRoute { /** * Initializes the get collections route. * * @param collection * A MongoDB collection on which the operations are performed. */ public GetCollections(final MongoCollection<Document> collection) { super(collection); } @Override public Object handle(final Request request, final Response response) { response.type(BookmarkPersistenceConstants.APPLICATION_JSON); final String userId = getProfileSubject(request, response); final BasicDBObject query = new BasicDBObject( BookmarkPersistenceConstants.DB_USER_ID_FIELD_NAME, userId); final FindIterable<Document> myCursor = collection.find(query); final List<BookmarkCollection> collectionsList = new ArrayList<>(); myCursor.forEach( (Consumer<Document>)(final Document doc) -> collectionsList .add(new BookmarkCollection(doc))); return GSON.toJson(collectionsList).toString(); } }
31.56338
77
0.729585
0bfc6000ee7427aabccef5c048e2678e68a1d806
12,505
package be.cytomine.client.abst; import be.cytomine.client.*; import java.util.*; import org.json.simple.*; import java.util.Date; import be.cytomine.client.Server; import be.cytomine.client.SoftwareParameter; import org.json.simple.JSONObject; /** * A parameter for a software. It's a template to create job parameter. When job is init, we create job parameter list based on software parameter list. * * @author ClientBuilder (Loïc Rollus) * @version 0.1 * * DO NOT EDIT THIS FILE. THIS IS CODE IS BUILD AUTOMATICALY. ALL CHANGE WILL BE LOST AFTER NEXT GENERATION. * * IF YOU WANT TO EDIT A DOMAIN FILE (change method, add property,...), JUST EDIT THE CHILD FILE “YourDomain.java” instead of this file “AbstractYourDomain.java”. I WON'T BE CLEAR IF IT ALREADY EXIST. * */ public abstract class AbstractSoftwareParameter extends AbstractDomain { /** * The full class name of the domain * */ protected String clazz; /** * The domain id * */ protected Long id; /** * The date of the domain creation * */ protected Date created; /** * The date of the domain modification * */ protected Date updated; /** * When domain was removed from Cytomine * */ protected Date deleted; /** * The parameter name * */ protected String name; /** * The parameter data type (Number, String, Date, Boolean, Domain (e.g: image instance id,...), ListDomain ) * */ protected String type; /** * Default value when creating job parameter * */ protected String defaultParamValue; /** * Flag if value is mandatory * */ protected Boolean required; /** * The software of the parameter * */ protected Long software; /** * Index for parameter position. When launching software, parameter will be send ordered by index (asc). * */ protected Integer index; /** * Used for UI. If parameter has '(List)Domain' type, the URI will provide a list of choice. E.g. if uri is 'api/project.json', the choice list will be cytomine project list * */ protected String uri; /** * Used for UI. JSON Fields to print in choice list. E.g. if uri is api/project.json and uriPrintAttribut is 'name', the choice list will contains project name * */ protected String uriPrintAttribut; /** * Used for UI. JSON Fields used to sort choice list. E.g. if uri is api/project.json and uriSortAttribut is 'id', projects will be sort by id (not by name) * */ protected String uriSortAttribut; /** * Indicated if the field is autofilled by the server * */ protected Boolean setByServer; /** * * @return * The full class name of the domain */ public String getClazz() throws Exception { return clazz; } /** * * @return * The domain id */ public Long getId() throws Exception { return id; } /** * * @return * The date of the domain creation */ public Date getCreated() throws Exception { return created; } /** * * @return * The date of the domain modification */ public Date getUpdated() throws Exception { return updated; } /** * * @return * When domain was removed from Cytomine */ public Date getDeleted() throws Exception { return deleted; } /** * * @return * The parameter name */ public String getName() throws Exception { return name; } /** * * @param name * The parameter name */ public void setName(String name) throws Exception { this.name = name; } /** * * @return * The parameter data type (Number, String, Date, Boolean, Domain (e.g: image instance id,...), ListDomain ) */ public String getType() throws Exception { return type; } /** * * @param type * The parameter data type (Number, String, Date, Boolean, Domain (e.g: image instance id,...), ListDomain ) */ public void setType(String type) throws Exception { this.type = type; } /** * * @return * Default value when creating job parameter */ public String getDefaultParamValue() throws Exception { return defaultParamValue; } /** * * @param defaultParamValue * Default value when creating job parameter */ public void setDefaultParamValue(String defaultParamValue) throws Exception { this.defaultParamValue = defaultParamValue; } /** * * @return * Flag if value is mandatory */ public Boolean getRequired() throws Exception { return required; } /** * * @param required * Flag if value is mandatory */ public void setRequired(Boolean required) throws Exception { this.required = required; } /** * * @return * The software of the parameter */ public Long getSoftware() throws Exception { return software; } /** * * @param software * The software of the parameter */ public void setSoftware(Long software) throws Exception { this.software = software; } /** * * @return * Index for parameter position. When launching software, parameter will be send ordered by index (asc). */ public Integer getIndex() throws Exception { return index; } /** * * @param index * Index for parameter position. When launching software, parameter will be send ordered by index (asc). */ public void setIndex(Integer index) throws Exception { this.index = index; } /** * * @return * Used for UI. If parameter has '(List)Domain' type, the URI will provide a list of choice. E.g. if uri is 'api/project.json', the choice list will be cytomine project list */ public String getUri() throws Exception { return uri; } /** * * @param uri * Used for UI. If parameter has '(List)Domain' type, the URI will provide a list of choice. E.g. if uri is 'api/project.json', the choice list will be cytomine project list */ public void setUri(String uri) throws Exception { this.uri = uri; } /** * * @return * Used for UI. JSON Fields to print in choice list. E.g. if uri is api/project.json and uriPrintAttribut is 'name', the choice list will contains project name */ public String getUriPrintAttribut() throws Exception { return uriPrintAttribut; } /** * * @param uriPrintAttribut * Used for UI. JSON Fields to print in choice list. E.g. if uri is api/project.json and uriPrintAttribut is 'name', the choice list will contains project name */ public void setUriPrintAttribut(String uriPrintAttribut) throws Exception { this.uriPrintAttribut = uriPrintAttribut; } /** * * @return * Used for UI. JSON Fields used to sort choice list. E.g. if uri is api/project.json and uriSortAttribut is 'id', projects will be sort by id (not by name) */ public String getUriSortAttribut() throws Exception { return uriSortAttribut; } /** * * @param uriSortAttribut * Used for UI. JSON Fields used to sort choice list. E.g. if uri is api/project.json and uriSortAttribut is 'id', projects will be sort by id (not by name) */ public void setUriSortAttribut(String uriSortAttribut) throws Exception { this.uriSortAttribut = uriSortAttribut; } /** * * @return * Indicated if the field is autofilled by the server */ public Boolean getSetByServer() throws Exception { return setByServer; } /** * * @param setByServer * Indicated if the field is autofilled by the server */ public void setSetByServer(Boolean setByServer) throws Exception { this.setByServer = setByServer; } public void build(String name, String type, Long software) throws Exception { this.name=name; this.type=type; this.software=software; } public void build(JSONObject json) throws Exception { this.clazz =JSONUtils.extractJSONString(json.get("class")); this.id =JSONUtils.extractJSONLong(json.get("id")); this.created =JSONUtils.extractJSONDate(json.get("created")); this.updated =JSONUtils.extractJSONDate(json.get("updated")); this.deleted =JSONUtils.extractJSONDate(json.get("deleted")); this.name =JSONUtils.extractJSONString(json.get("name")); this.type =JSONUtils.extractJSONString(json.get("type")); this.defaultParamValue =JSONUtils.extractJSONString(json.get("defaultParamValue")); this.required =JSONUtils.extractJSONBoolean(json.get("required")); this.software =JSONUtils.extractJSONLong(json.get("software")); this.index =JSONUtils.extractJSONInteger(json.get("index")); this.uri =JSONUtils.extractJSONString(json.get("uri")); this.uriPrintAttribut =JSONUtils.extractJSONString(json.get("uriPrintAttribut")); this.uriSortAttribut =JSONUtils.extractJSONString(json.get("uriSortAttribut")); this.setByServer =JSONUtils.extractJSONBoolean(json.get("setByServer")); } public JSONObject toJSON() throws Exception { JSONObject json=new JSONObject(); json.put("class",JSONUtils.formatJSON(this.clazz)); json.put("id",JSONUtils.formatJSON(this.id)); json.put("created",JSONUtils.formatJSON(this.created)); json.put("updated",JSONUtils.formatJSON(this.updated)); json.put("deleted",JSONUtils.formatJSON(this.deleted)); json.put("name",JSONUtils.formatJSON(this.name)); json.put("type",JSONUtils.formatJSON(this.type)); json.put("defaultParamValue",JSONUtils.formatJSON(this.defaultParamValue)); json.put("required",JSONUtils.formatJSON(this.required)); json.put("software",JSONUtils.formatJSON(this.software)); json.put("index",JSONUtils.formatJSON(this.index)); json.put("uri",JSONUtils.formatJSON(this.uri)); json.put("uriPrintAttribut",JSONUtils.formatJSON(this.uriPrintAttribut)); json.put("uriSortAttribut",JSONUtils.formatJSON(this.uriSortAttribut)); json.put("setByServer",JSONUtils.formatJSON(this.setByServer)); return json; } public static SoftwareParameter get(Server server, Long id) throws Exception { String path = "/api/softwareparameter/{id}.json?"; path = path.replace("{id}",id+""); JSONObject json = server.doGET(path); SoftwareParameter domain = new SoftwareParameter(); domain.build(json); return domain; } public static SoftwareParameter listBySoftware(Server server, Long id, Boolean setByServer, Integer max, Integer offset) throws Exception { throw new Exception("Not yet implemented"); } public void add(Server server) throws Exception { String path = "/api/softwareparameter.json?"; JSONObject json = server.doPOST(path,this.toJSON()); this.build((JSONObject)json.get("softwareparameter")); } public static SoftwareParameter list(Server server, Integer max, Integer offset) throws Exception { throw new Exception("Not yet implemented"); } public void delete(Server server) throws Exception { String path = "/api/softwareparameter/{id}.json?"; path = path.replace("{id}",getId()+""); server.doDELETE(path); build(new JSONObject()); } public void edit(Server server) throws Exception { String path = "/api/softwareparameter/{id}.json?"; path = path.replace("{id}",getId()+""); JSONObject json = server.doPUT(path,this.toJSON()); this.build((JSONObject)json.get("softwareparameter")); } }
24.471624
200
0.610956
da65e86d2bb1ea9512561c4b307d0f2198a15fc1
2,234
/* * * * Copyright 2019 Max Berkelmans * * * * 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 me.max.migrational; import me.max.migrational.testobjects.ClassObject; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import java.lang.reflect.InvocationTargetException; import java.util.HashMap; import java.util.Map; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** * This is test class and will check if migration is still working correctly * This was made to not need to manually test if it still works after making changes * * @author Max Berkelmans * @since 1.1.0 */ public class ClassMigrationTest { private static ClassObject testObject; @BeforeClass public static void setUp() throws IllegalAccessException, InstantiationException, InvocationTargetException { Map<String, Object> data = new HashMap<>(); data.put("name", "Stijn"); testObject = (ClassObject) new Migrator(ClassObject.class, data).migrateToClass(); } @AfterClass public static void tearDown() { testObject = null; } @Test public void migrate_Name_ReturnsStijn() { final String expected = "Stijn"; final String actual = testObject.getName(); assertEquals(expected, actual); } @Test public void migrate_Age_ReturnsTwentySeven() { final int expected = 27; final int actual = testObject.getAge(); assertEquals(expected, actual); } @Test public void migrate_IsCool_ReturnsTrue() { final boolean actual = testObject.isCool(); assertTrue(actual); } }
26.915663
113
0.692927
260f04f5c65ffdbd329914f341533291ebdf1d64
1,533
package com.example.restapi.controller; import com.example.restapi.dto.UserDto; import com.example.restapi.exception.UserNotFoundException; import com.example.restapi.model.User; import com.example.restapi.repository.UserRepository; import com.example.restapi.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import javax.validation.Valid; import java.net.URI; import java.util.List; @RestController public class UserController { @Autowired UserService userService; @GetMapping("/users") public List<User> getUsers(){ return this.userService.getAUsers(); } @PostMapping("/users") @Transactional public ResponseEntity<Object> creatUser(@Valid @RequestBody User user){ User savedUser = this.userService.CreateUser(user); URI location = ServletUriComponentsBuilder .fromCurrentRequest() .path("/{id}") .buildAndExpand(savedUser.getId()).toUri(); return ResponseEntity.created(location).build(); //create a User entiy object } @GetMapping("/users/{id}") public User getOneUser(@PathVariable int id){ User user = this.userService.getAsingleUser(id); return user; } }
22.880597
76
0.711676
f71f3b2d3b5752a14de05349ea22bf78df746e4d
238
package com.coolweather.android.gson; /** * 作者:陈俊伟 on 2018/4/22 0022 21:07 * <p> * 作用:xxx */ public class AQI { public AQICity city; public class AQICity { public String aqi; public String pm25; } }
11.333333
37
0.588235
e756487add637d0eebe24341800afb64304c1e01
1,056
/** * :软件实体应该对扩展开放,对修改关闭,其 * 含义是说一个软件实体应该通过扩展来实现变化,而不是通过修改已有的代码来实现变化。 * 软件实体包括以下几个部分:<br/> * <ol> * <li>项目或软件产品中按照一定的逻辑规则划分的模块。</li> * <li>抽象和类。</li> * <li>方法。</li> * </ol> * <br/> * 可以把变化归纳为以下三种类型: * <ol> * <li>逻辑变化 * 只变化一个逻辑,而不涉及其他模块,比如原有的一个算法是a*b+c,现在需要修改为 a*b*c,可以通过修改原有类中的方法的方式来完成,前提条件是所有依赖或关联类都按照 * 相同的逻辑处理。</li> * <li>子模块变化 * 一个模块变化,会对其他的模块产生影响,特别是一个低层次的模块变化必然引起高层 * 模块的变化,因此在通过扩展完成变化时,高层次的模块修改是必然的,刚刚的书籍打折处 * 理就是类似的处理模块,该部分的变化甚至会引起界面的变化。</li> * <li>可见视图变化可见视图是提供给客户使用的界面,如JSP程序、Swing界面等,该部分的变化一般会引 * 起连锁反应(特别是在国内做项目,做欧美的外包项目一般不会影响太大)。如果仅仅是界 * 面上按钮、文字的重新排布倒是简单,最司空见惯的是业务耦合变化,什么意思呢?一个展 示数据的列表,按照原有的需求是6列,突然有一天要增加1列,而且这一列要跨N张表,处 理M个逻辑才能展现出来,这样的变化是比较恐怖的,但还是可以通过扩展来完成变化,这 * 就要看我们原有的设计是否灵活。</li> * </ol> * 开闭原则的作用 * <ol> * <li> 开闭原则对测试的影响</li> * <li>开闭原则可以提高复用性</li> * <li>开闭原则可以提高可维护性</li> * <li>面向对象开发的要求</li> * </ol> * 应用方法 * <ol> * <li>抽象约束</li> * <li>元数据(metadata)控制模块行为</li> * <li> 制定项目章程</li> * <li>封装变化</li> * </ol> * @author MayZhou */ package principle.ocp;
25.756098
126
0.657197
6575869de2209f83cb44418fdf6ce7479cdbede4
6,201
package net.minecraft.client.renderer.block.model; import net.minecraft.client.renderer.*; import java.lang.reflect.*; import com.google.gson.*; public class ItemCameraTransforms { public static final ItemCameraTransforms DEFAULT; public static float field_181690_b; public static float field_181691_c; public static float field_181692_d; public static float field_181693_e; public static float field_181694_f; public static float field_181695_g; public static float field_181696_h; public static float field_181697_i; public static float field_181698_j; public final ItemTransformVec3f thirdPerson; public final ItemTransformVec3f firstPerson; public final ItemTransformVec3f head; public final ItemTransformVec3f gui; public final ItemTransformVec3f ground; public final ItemTransformVec3f fixed; private ItemCameraTransforms() { this(ItemTransformVec3f.DEFAULT, ItemTransformVec3f.DEFAULT, ItemTransformVec3f.DEFAULT, ItemTransformVec3f.DEFAULT, ItemTransformVec3f.DEFAULT, ItemTransformVec3f.DEFAULT); } public ItemCameraTransforms(final ItemCameraTransforms p_i46443_1_) { this.thirdPerson = p_i46443_1_.thirdPerson; this.firstPerson = p_i46443_1_.firstPerson; this.head = p_i46443_1_.head; this.gui = p_i46443_1_.gui; this.ground = p_i46443_1_.ground; this.fixed = p_i46443_1_.fixed; } public ItemCameraTransforms(final ItemTransformVec3f p_i46444_1_, final ItemTransformVec3f p_i46444_2_, final ItemTransformVec3f p_i46444_3_, final ItemTransformVec3f p_i46444_4_, final ItemTransformVec3f p_i46444_5_, final ItemTransformVec3f p_i46444_6_) { this.thirdPerson = p_i46444_1_; this.firstPerson = p_i46444_2_; this.head = p_i46444_3_; this.gui = p_i46444_4_; this.ground = p_i46444_5_; this.fixed = p_i46444_6_; } public void applyTransform(final TransformType p_181689_1_) { final ItemTransformVec3f itemtransformvec3f = this.getTransform(p_181689_1_); if (itemtransformvec3f != ItemTransformVec3f.DEFAULT) { GlStateManager.translate(itemtransformvec3f.translation.x + ItemCameraTransforms.field_181690_b, itemtransformvec3f.translation.y + ItemCameraTransforms.field_181691_c, itemtransformvec3f.translation.z + ItemCameraTransforms.field_181692_d); GlStateManager.rotate(itemtransformvec3f.rotation.y + ItemCameraTransforms.field_181694_f, 0.0f, 1.0f, 0.0f); GlStateManager.rotate(itemtransformvec3f.rotation.x + ItemCameraTransforms.field_181693_e, 1.0f, 0.0f, 0.0f); GlStateManager.rotate(itemtransformvec3f.rotation.z + ItemCameraTransforms.field_181695_g, 0.0f, 0.0f, 1.0f); GlStateManager.scale(itemtransformvec3f.scale.x + ItemCameraTransforms.field_181696_h, itemtransformvec3f.scale.y + ItemCameraTransforms.field_181697_i, itemtransformvec3f.scale.z + ItemCameraTransforms.field_181698_j); } } public ItemTransformVec3f getTransform(final TransformType p_181688_1_) { switch (p_181688_1_) { case THIRD_PERSON: { return this.thirdPerson; } case FIRST_PERSON: { return this.firstPerson; } case HEAD: { return this.head; } case GUI: { return this.gui; } case GROUND: { return this.ground; } case FIXED: { return this.fixed; } default: { return ItemTransformVec3f.DEFAULT; } } } public boolean func_181687_c(final TransformType p_181687_1_) { return !this.getTransform(p_181687_1_).equals(ItemTransformVec3f.DEFAULT); } static { DEFAULT = new ItemCameraTransforms(); ItemCameraTransforms.field_181690_b = 0.0f; ItemCameraTransforms.field_181691_c = 0.0f; ItemCameraTransforms.field_181692_d = 0.0f; ItemCameraTransforms.field_181693_e = 0.0f; ItemCameraTransforms.field_181694_f = 0.0f; ItemCameraTransforms.field_181695_g = 0.0f; ItemCameraTransforms.field_181696_h = 0.0f; ItemCameraTransforms.field_181697_i = 0.0f; ItemCameraTransforms.field_181698_j = 0.0f; } static class Deserializer implements JsonDeserializer<ItemCameraTransforms> { public ItemCameraTransforms deserialize(final JsonElement p_deserialize_1_, final Type p_deserialize_2_, final JsonDeserializationContext p_deserialize_3_) throws JsonParseException { final JsonObject jsonobject = p_deserialize_1_.getAsJsonObject(); final ItemTransformVec3f itemtransformvec3f = this.func_181683_a(p_deserialize_3_, jsonobject, "thirdperson"); final ItemTransformVec3f itemtransformvec3f2 = this.func_181683_a(p_deserialize_3_, jsonobject, "firstperson"); final ItemTransformVec3f itemtransformvec3f3 = this.func_181683_a(p_deserialize_3_, jsonobject, "head"); final ItemTransformVec3f itemtransformvec3f4 = this.func_181683_a(p_deserialize_3_, jsonobject, "gui"); final ItemTransformVec3f itemtransformvec3f5 = this.func_181683_a(p_deserialize_3_, jsonobject, "ground"); final ItemTransformVec3f itemtransformvec3f6 = this.func_181683_a(p_deserialize_3_, jsonobject, "fixed"); return new ItemCameraTransforms(itemtransformvec3f, itemtransformvec3f2, itemtransformvec3f3, itemtransformvec3f4, itemtransformvec3f5, itemtransformvec3f6); } private ItemTransformVec3f func_181683_a(final JsonDeserializationContext p_181683_1_, final JsonObject p_181683_2_, final String p_181683_3_) { return (ItemTransformVec3f)(p_181683_2_.has(p_181683_3_) ? p_181683_1_.deserialize(p_181683_2_.get(p_181683_3_), (Type)ItemTransformVec3f.class) : ItemTransformVec3f.DEFAULT); } } public enum TransformType { NONE, THIRD_PERSON, FIRST_PERSON, HEAD, GUI, GROUND, FIXED; } }
47.335878
261
0.709563
f4318fe029ad09ba86e6944c8eec41448aa0cf87
12,391
package org.hswebframework.payment.payment.channel.alipay.substitute; import com.alipay.api.AlipayApiException; import com.alipay.api.AlipayClient; import com.alipay.api.DefaultAlipayClient; import com.alipay.api.domain.*; import com.alipay.api.internal.util.AlipaySignature; import com.alipay.api.request.AlipayFundBatchDetailQueryRequest; import com.alipay.api.request.AlipayFundBatchTransferRequest; import com.alipay.api.response.AlipayFundBatchDetailQueryResponse; import com.alipay.api.response.AlipayFundBatchTransferResponse; import org.hswebframework.payment.api.enums.ErrorCode; import org.hswebframework.payment.api.enums.PayeeType; import org.hswebframework.payment.api.enums.TransType; import org.hswebframework.payment.api.payment.ActiveQuerySupportPaymentChannel; import org.hswebframework.payment.api.payment.ChannelProvider; import org.hswebframework.payment.api.payment.order.PaymentOrder; import org.hswebframework.payment.api.payment.payee.Payee; import org.hswebframework.payment.api.payment.substitute.SubstituteChannel; import org.hswebframework.payment.api.payment.substitute.SubstituteDetailCompleteEvent; import org.hswebframework.payment.api.payment.substitute.request.SubstituteRequest; import org.hswebframework.payment.api.utils.Money; import org.hswebframework.payment.payment.channel.AbstractPaymentChannel; import org.hswebframework.payment.payment.channel.alipay.AlipayConfig; import org.hswebframework.payment.payment.notify.ChannelNotificationResult; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import org.hswebframework.web.bean.FastBeanCopier; import org.springframework.http.MediaType; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.*; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicLong; import java.util.stream.Collectors; /** * 支付宝批量代付渠道 * * @author zhouhao * @since 1.0.0 */ @Slf4j @RestController public class AlipaySubstituteChannel extends AbstractPaymentChannel<AlipaySubstituteConfig, SubstituteRequest<Payee>, AlipaySubstituteResponse> implements SubstituteChannel<Payee, AlipaySubstituteResponse> , ActiveQuerySupportPaymentChannel { @Override public PayeeType getPayeeType() { return PayeeType.ALIPAY; } private AlipayClient createAlipayClient(AlipaySubstituteConfig config) { return new DefaultAlipayClient( config.getUrl(), config.getAppId(), config.getRsaPrivateKey(), "json", "utf-8", config.getPublicKey(), config.getSignType(), config.getProxyHost(), config.getProxyPort()); } @Override public TransType getTransType() { return TransType.SUBSTITUTE; } @PostMapping(value = "/alipay/batch-trans/notify/{paymentId}", produces = MediaType.TEXT_PLAIN_VALUE) @ResponseBody public String channelNotify(@PathVariable String paymentId, @RequestParam Map<String, String> params) { AlipayConfig config = getChannelConfig(paymentId); if (config == null) { log.error("收到支付宝异步通知,但是未获取到渠道配置[{}],通知内容:{}", paymentId, params); return "fail"; } try { boolean verifySuccess = AlipaySignature.rsaCheckV1(params, config.getPublicKey(), "utf-8", config.getSignType()); if (!verifySuccess) { log.warn("验证签名失败:channelId:[{}],data:{}", config.getId(), params); return "fail"; } //每条记录以“|”间隔 //格式为:流水号^收款方账号^收款账号姓名^付款金额^成功标识(S)^成功原因(null)^支付宝内部流水号^完成时间。 String successDetail = params.get("success_details"); AtomicLong successAmount = new AtomicLong(); if (StringUtils.hasText(successDetail)) { Arrays.stream(successDetail.split("[|]")) .map(str -> str.split("[\\^]")) .forEach(arr -> { log.debug("支付宝代付成功:{}", String.join(",", arr)); String id = arr[0]; String acc = arr[1]; String name = arr[2]; long amount = Money.amout(arr[3]).getCent(); String remark = arr[4]; successAmount.addAndGet(amount); eventPublisher.publishEvent(SubstituteDetailCompleteEvent.builder() .amount(amount) .detailId(id) .paymentId(paymentId) .memo("成功:" + remark) .success(true) .build()); }); } //格式为:流水号^收款方账号^收款账号姓名^付款金额^失败标识(F)^失败原因^支付宝内部流水号^完成时间。 String failedDetail = params.get("fail_details"); if (StringUtils.hasText(failedDetail)) { Arrays.stream(failedDetail.split("[|]")) .map(str -> str.split("[\\^]")) .forEach(arr -> { log.debug("支付宝代付成功:{}", String.join(",", arr)); String id = arr[0]; String acc = arr[1]; String name = arr[2]; String amount = arr[3]; String code = arr[4]; String remark = arr[6]; eventPublisher.publishEvent(SubstituteDetailCompleteEvent.builder() .amount(Money.amout(amount).getCent()) .detailId(id) .paymentId(paymentId) .memo(code + ":" + remark) .success(false) .build()); }); } afterHandleChannelNotify(ChannelNotificationResult.builder() .paymentId(paymentId) .success(successAmount.get() > 0) .amount(successAmount.get()) .resultObject(params) .build()); return "success"; } catch (Exception e) { log.warn("处理支付宝代付通知失败", e); } return "fail"; } @Override protected AlipaySubstituteResponse doRequestPay(AlipaySubstituteConfig config, SubstituteRequest<Payee> request) { AlipaySubstituteResponse response = FastBeanCopier.copy(request, new AlipaySubstituteResponse()); AlipayClient client = createAlipayClient(config); try { AtomicLong totalAmount = new AtomicLong(); List<AccTransDetail> details = request.getDetails().stream() .map(detail -> { AccPayeeInfo payeeInfo = new AccPayeeInfo(); payeeInfo.setPayeeAccount(detail.getPayee().getPayee()); payeeInfo.setPayeeName(detail.getPayee().getPayeeName()); totalAmount.addAndGet(detail.getAmount()); AccTransDetail accTransDetail = new AccTransDetail(); accTransDetail.setDetailNo(detail.getId()); accTransDetail.setPayeeInfo(payeeInfo); accTransDetail.setRemark(detail.getRemark()); accTransDetail.setTransAmount(Money.cent(detail.getAmount()).toString()); return accTransDetail; }).collect(Collectors.toList()); AlipayFundBatchTransferModel model = new AlipayFundBatchTransferModel(); model.setTotalCount(String.valueOf(request.getDetails().size())); model.setTotalTransAmount(Money.cent(totalAmount.get()).toString()); model.setAccDetailList(details); model.setBatchNo(request.getPaymentId()); model.setPayerAccountType(config.getAccountType()); model.setPayerAccount(config.getAccountName()); model.setBizCode("BATCH_TRANS_ACC"); model.setBizScene("LOCAL"); AlipayFundBatchTransferRequest transferRequest = new AlipayFundBatchTransferRequest(); transferRequest.setNotifyUrl(getNotifyLocation(config) + "alipay/batch-trans/notify/" + request.getPaymentId()); transferRequest.setBizModel(model); AlipayFundBatchTransferResponse channelResponse = client.execute(transferRequest); String batchNo = channelResponse.getBatchNo(); String batchTransId = channelResponse.getBatchTransId(); response.setBatchNo(batchNo); response.setBatchTransId(batchTransId); response.setSuccess(channelResponse.isSuccess()); response.setMessage(channelResponse.getSubMsg()); return response; } catch (AlipayApiException e) { log.error("发起支付宝代付失败:", e); response.setError(ErrorCode.CHANNEL_RETURN_ERROR.createException(e.getErrMsg())); } catch (Exception e) { log.error("发起支付宝代付失败:", e); response.setError(ErrorCode.SERVICE_ERROR); } return response; } @Override public String getChannel() { return "alipay-substitute"; } @Override public String getChannelName() { return "支付宝批量付款"; } @Override @SneakyThrows public void doActiveQueryOrderResult(PaymentOrder order) { AlipaySubstituteConfig config = getConfigurator().getPaymentConfigById(order.getChannelId()); AlipayClient client = createAlipayClient(config); OriginalRequestResponse requestResponse = getOriginalRequestResponse(order.getId()); AlipaySubstituteResponse substituteResponse = requestResponse.getResponse(); AlipayFundBatchDetailQueryModel model = new AlipayFundBatchDetailQueryModel(); model.setBatchNo(substituteResponse.getBatchNo()); model.setBizCode("BATCH_TRANS_ACC"); model.setBizScene("LOCAL"); AlipayFundBatchDetailQueryRequest request = new AlipayFundBatchDetailQueryRequest(); request.setBizModel(model); AlipayFundBatchDetailQueryResponse response = client.execute(request); if (response.isSuccess()) { List<AccDetailModel> models = response.getAccDetailList(); if (!CollectionUtils.isEmpty(models)) { //判断整个批次是否全部完成 for (AccDetailModel detailModel : models) { boolean processing = "INIT".equalsIgnoreCase(detailModel.getStatus()) || "APPLIED".equalsIgnoreCase(detailModel.getStatus()) || "DEALED".equalsIgnoreCase(detailModel.getStatus()); //有明细还在处理中则退出 if (processing) { return; } } long successAmount = 0; for (AccDetailModel detailModel : models) { boolean success = "SUCCESS".equalsIgnoreCase(detailModel.getStatus()); long amount = Money.amout(detailModel.getTransAmount()).getCent(); if (success) { successAmount += amount; } eventPublisher.publishEvent(SubstituteDetailCompleteEvent.builder() .amount(amount) .detailId(detailModel.getDetailNo()) .paymentId(order.getId()) .memo(detailModel.getErrorMsg()) .success(success) .build()); } afterHandleChannelNotify(ChannelNotificationResult.builder() .amount(successAmount) .success(successAmount > 0) .paymentId(order.getId()) .build()); } } } @Override public String getChannelProvider() { return ChannelProvider.officialAlipay; } @Override public String getChannelProviderName() { return "官方支付宝"; } }
44.571942
143
0.59406
71902fc529d08ed61f2a64d17fc7a3ca8704d165
15,980
/*- * See the file LICENSE for redistribution information. * * Copyright (c) 2002,2008 Oracle. All rights reserved. * * $Id: Transaction.java,v 1.59 2008/05/29 03:38:23 linda Exp $ */ package com.sleepycat.je; import com.sleepycat.je.dbi.EnvironmentImpl; import com.sleepycat.je.txn.Locker; import com.sleepycat.je.txn.Txn; import com.sleepycat.je.utilint.PropUtil; /** * The Transaction object is the handle for a transaction. Methods off the * transaction handle are used to configure, abort and commit the transaction. * Transaction handles are provided to other Berkeley DB methods in order to * transactionally protect those operations. * * <p>Transaction handles are free-threaded; transactions handles may be used * concurrently by multiple threads. Once the {@link * com.sleepycat.je.Transaction#abort Transaction.abort} or {@link * com.sleepycat.je.Transaction#commit Transaction.commit} methods are called, * the handle may not be accessed again, regardless of the success or failure * of the method.</p> * * <p>To obtain a transaction with default attributes:</p> * * <blockquote><pre> * Transaction txn = myEnvironment.beginTransaction(null, null); * </pre></blockquote> * * <p>To customize the attributes of a transaction:</p> * * <blockquote><pre> * TransactionConfig config = new TransactionConfig(); * config.setReadUncommitted(true); * Transaction txn = myEnvironment.beginTransaction(null, config); * </pre></blockquote> */ public class Transaction { private Txn txn; private Environment env; private long id; private String name; /** * Creates a transaction. */ Transaction(Environment env, Txn txn) { this.env = env; this.txn = txn; /* * Copy the id to this wrapper object so the id will be available * after the transaction is closed and the txn field is nulled. */ this.id = txn.getId(); } /** * Cause an abnormal termination of the transaction. * * <p>The log is played backward, and any necessary undo operations are * done. Before Transaction.abort returns, any locks held by the * transaction will have been released.</p> * * <p>In the case of nested transactions, aborting a parent transaction * causes all children (unresolved or not) of the parent transaction to be * aborted.</p> * * <p>All cursors opened within the transaction must be closed before the * transaction is aborted.</p> * * <p>After Transaction.abort has been called, regardless of its return, * the {@link com.sleepycat.je.Transaction Transaction} handle may not be * accessed again.</p> * * @throws DatabaseException if a failure occurs. */ public void abort() throws DatabaseException { try { checkEnv(); env.removeReferringHandle(this); txn.abort(false); // no sync required /* Remove reference to internal txn, so we can reclaim memory. */ txn = null; } catch (Error E) { DbInternal.envGetEnvironmentImpl(env).invalidate(E); throw E; } } /** * Return the transaction's unique ID. * * @return The transaction's unique ID. * * @throws DatabaseException if a failure occurs. */ public long getId() throws DatabaseException { return id; } /** * End the transaction. If the environment is configured for synchronous * commit, the transaction will be committed synchronously to stable * storage before the call returns. This means the transaction will * exhibit all of the ACID (atomicity, consistency, isolation, and * durability) properties. * * <p>If the environment is not configured for synchronous commit, the * commit will not necessarily have been committed to stable storage before * the call returns. This means the transaction will exhibit the ACI * (atomicity, consistency, and isolation) properties, but not D * (durability); that is, database integrity will be maintained, but it is * possible this transaction may be undone during recovery.</p> * * <p>All cursors opened within the transaction must be closed before the * transaction is committed.</p> * * <p>After this method returns the {@link com.sleepycat.je.Transaction * Transaction} handle may not be accessed again, regardless of the * method's success or failure. If the method encounters an error, the * transaction and all child transactions of the transaction will have been * aborted when the call returns.</p> * * @throws DatabaseException if a failure occurs. */ public void commit() throws DatabaseException { try { checkEnv(); env.removeReferringHandle(this); txn.commit(); /* Remove reference to internal txn, so we can reclaim memory. */ txn = null; } catch (Error E) { DbInternal.envGetEnvironmentImpl(env).invalidate(E); throw E; } } /** * * @hidden * Feature not yet available. * * End the transaction using the specified durability requirements. This * requirement overrides any default durability requirements associated * with the environment. If the durability requirements cannot be satisfied, * an exception is thrown to describe the problem. Please see * {@link Durability} for specific exceptions that could result when the * durability requirements cannot be satisfied. * * @param durability the durability requirements for this transaction * * @throws DatabaseException if a failure occurs. */ public void commit(Durability durability) throws DatabaseException { doCommit(durability, false /* explicitSync */); } /** * End the transaction, committing synchronously. This means the * transaction will exhibit all of the ACID (atomicity, consistency, * isolation, and durability) properties. * * <p>This behavior is the default for database environments unless * otherwise configured using the {@link * com.sleepycat.je.EnvironmentConfig#setTxnNoSync * EnvironmentConfig.setTxnNoSync} method. This behavior may also be set * for a single transaction using the {@link * com.sleepycat.je.Environment#beginTransaction * Environment.beginTransaction} method. Any value specified to this * method overrides both of those settings.</p> * * <p>All cursors opened within the transaction must be closed before the * transaction is committed.</p> * * <p>After this method returns the {@link com.sleepycat.je.Transaction * Transaction} handle may not be accessed again, regardless of the * method's success or failure. If the method encounters an error, the * transaction and all child transactions of the transaction will have been * aborted when the call returns.</p> * * @throws DatabaseException if a failure occurs. */ public void commitSync() throws DatabaseException { doCommit(TransactionConfig.SYNC, true /* explicitSync */); } /** * End the transaction, not committing synchronously. This means the * transaction will exhibit the ACI (atomicity, consistency, and isolation) * properties, but not D (durability); that is, database integrity will be * maintained, but it is possible this transaction may be undone during * recovery. * * <p>This behavior may be set for a database environment using the {@link * com.sleepycat.je.EnvironmentConfig#setTxnNoSync * EnvironmentConfig.setTxnNoSync} method or for a single transaction using * the {@link com.sleepycat.je.Environment#beginTransaction * Environment.beginTransaction} method. Any value specified to this * method overrides both of those settings.</p> * * <p>All cursors opened within the transaction must be closed before the * transaction is committed.</p> * * <p>After this method returns the {@link com.sleepycat.je.Transaction * Transaction} handle may not be accessed again, regardless of the * method's success or failure. If the method encounters an error, the * transaction and all child transactions of the transaction will have been * aborted when the call returns.</p> * * @throws DatabaseException if a failure occurs. */ public void commitNoSync() throws DatabaseException { doCommit(TransactionConfig.NO_SYNC, true /* explicitSync */); } /** * End the transaction, committing synchronously. This means the * transaction will exhibit all of the ACID (atomicity, consistency, * isolation, and durability) properties. * * <p>This behavior is the default for database environments unless * otherwise configured using the {@link * com.sleepycat.je.EnvironmentConfig#setTxnNoSync * EnvironmentConfig.setTxnNoSync} method. This behavior may also be set * for a single transaction using the {@link * com.sleepycat.je.Environment#beginTransaction * Environment.beginTransaction} method. Any value specified to this * method overrides both of those settings.</p> * * <p>All cursors opened within the transaction must be closed before the * transaction is committed.</p> * * <p>After this method returns the {@link com.sleepycat.je.Transaction * Transaction} handle may not be accessed again, regardless of the * method's success or failure. If the method encounters an error, the * transaction and all child transactions of the transaction will have been * aborted when the call returns.</p> * * @throws DatabaseException if a failure occurs. */ public void commitWriteNoSync() throws DatabaseException { doCommit(TransactionConfig.WRITE_NO_SYNC, true /* explicitSync */); } /** * @hidden * For internal use. */ public boolean getPrepared() { return txn.getPrepared(); } /** * Perform error checking and invoke the commit on Txn. * * @param durability the durability to use for the commit * @param explicitSync true if the method was invoked from one of the * sync-specific APIs, false if durability was used explicitly. This * parameter exists solely to support mixed mode api usage checks. * * @throws DatabaseException if a failure occurs. */ private void doCommit(Durability durability, boolean explicitSync) throws DatabaseException { try { checkEnv(); env.removeReferringHandle(this); if (explicitSync) { /* A sync-specific api was invoked. */ if (txn.getExplicitDurabilityConfigured()) { throw new IllegalArgumentException ("Mixed use of deprecated durability API for the " + "transaction commit with the new durability API for " + "TransactionConfig or MutableEnvironmentConfig"); } } else if (txn.getExplicitSyncConfigured()) { /* Durability was explicitly configured for commit */ throw new IllegalArgumentException ("Mixed use of new durability API for the " + "transaction commit with deprecated durability API for " + "TransactionConfig or MutableEnvironmentConfig"); } txn.commit(durability); /* Remove reference to internal txn, so we can reclaim memory. */ txn = null; } catch (Error E) { DbInternal.envGetEnvironmentImpl(env).invalidate(E); throw E; } } /** * Configure the timeout value for the transaction lifetime. * * <p>If the transaction runs longer than this time, the transaction may * throw {@link com.sleepycat.je.DatabaseException DatabaseException}.</p> * * <p>Timeouts are checked whenever a thread of control blocks on a lock or * when deadlock detection is performed. For this reason, the accuracy of * the timeout depends on how often deadlock detection is performed.</p> * * @param timeOut The timeout value for the transaction lifetime, in * microseconds. A value of 0 disables timeouts for the transaction. * * @throws IllegalArgumentException If the value of timeout is negative * @throws DatabaseException if a failure occurs. */ public void setTxnTimeout(long timeOut) throws IllegalArgumentException, DatabaseException { checkEnv(); txn.setTxnTimeout(PropUtil.microsToMillis(timeOut)); } /** * Configure the lock request timeout value for the transaction. * * <p>If a lock request cannot be granted in this time, the transaction may * throw {@link com.sleepycat.je.DatabaseException DatabaseException}.</p> * * <p>Timeouts are checked whenever a thread of control blocks on a lock or * when deadlock detection is performed. For this reason, the accuracy of * the timeout depends on how often deadlock detection is performed.</p> * * @param timeOut The lock request timeout value for the transaction, in * microseconds. A value of 0 disables timeouts for the transaction. * * <p>This method may be called at any time during the life of the * application.</p> * * @throws IllegalArgumentException If the value of timeout is negative. * * @throws DatabaseException if a failure occurs. */ public void setLockTimeout(long timeOut) throws IllegalArgumentException, DatabaseException { checkEnv(); txn.setLockTimeout(PropUtil.microsToMillis(timeOut)); } /** * Set the user visible name for the transaction. * * @param name The user visible name for the transaction. * */ public void setName(String name) { this.name = name; } /** * Get the user visible name for the transaction. * * @return The user visible name for the transaction. * */ public String getName() { return name; } /** * @hidden * For internal use. */ public int hashCode() { return (int) id; } /** * @hidden * For internal use. */ public boolean equals(Object o) { if (o == null) { return false; } if (!(o instanceof Transaction)) { return false; } if (((Transaction) o).id == id) { return true; } return false; } public String toString() { StringBuffer sb = new StringBuffer(); sb.append("<Transaction id=\""); sb.append(id).append("\""); if (name != null) { sb.append(" name=\""); sb.append(name).append("\""); } sb.append(">"); return sb.toString(); } /** * This method should only be called by the LockerFactory.getReadableLocker * and getWritableLocker methods. The locker returned does not enforce the * readCommitted isolation setting. */ Locker getLocker() throws DatabaseException { if (txn == null) { throw new DatabaseException("Transaction " + id + " has been closed and is no longer"+ " usable."); } else { return txn; } } /* * Helpers */ Txn getTxn() { return txn; } /** * @throws RunRecoveryException if the underlying environment is invalid. */ private void checkEnv() throws DatabaseException { EnvironmentImpl envImpl = env.getEnvironmentImpl(); if (envImpl == null) { throw new DatabaseException("The environment has been closed. " + " This transaction is no longer" + " usable."); } envImpl.checkIfInvalid(); } }
34.218415
80
0.657322
f104e8a8e2faae4d4782852cb036c01303ffdf72
3,159
/* * Copyright (c) 2007, Dennis M. Sosnoski All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following * disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of * JiBX nor the names of its contributors may be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jibx.schema.codegen; import org.eclipse.jdt.core.dom.Expression; import org.eclipse.jdt.core.dom.InfixExpression; /** * Abstract syntax tree infix expression builder. This adds convenience methods and control information to the base * builder. */ public class InfixExpressionBuilder extends ExpressionBuilderBase { /** Method invocation. */ private final InfixExpression m_expression; /** Number of operands added to expression. */ private int m_operandCount; /** * Constructor. * * @param source * @param expr */ public InfixExpressionBuilder(ClassBuilder source, InfixExpression expr) { super(source, expr); m_expression = expr; } /** * Constructor with left operand supplied. * * @param source * @param expr * @param operand */ public InfixExpressionBuilder(ClassBuilder source, InfixExpression expr, Expression operand) { super(source, expr); m_expression = expr; addOperand(operand); } /** * Add operand to expression. If the right operand has not yet been set this will set it; otherwise, it will add the * operand as an extended operand of the expression. * * @param operand */ protected void addOperand(Expression operand) { if (m_operandCount == 0) { m_expression.setLeftOperand(operand); } else if (m_operandCount == 1) { m_expression.setRightOperand(operand); } else { m_expression.extendedOperands().add(operand); } m_operandCount++; } }
39.987342
120
0.710351
d217f0daa170ed7f79e0c47966b6bd7334e1800b
683
package com.icfolson.aem.harbor.api.trees.construction; import com.google.common.base.Optional; import com.icfolson.aem.harbor.api.trees.TreeNode; /** * A Strategy used to construct a Tree of nodes * * @param <T> */ public interface TreeConstructionStrategy<T extends TreeNode> { /** * Construction produces a Parent object representing the rooted tree. If * construction does not result in a root then an absent Optional is * returned representing the absence of a list root. * * @return An optional Parent representing the rooted list or Optional.absent if no root can be produced by the * Strategy. */ Optional<T> construct(); }
28.458333
115
0.715959
d7f9405d0ddff990213787af2db55bcb15cea23d
3,620
package seedu.address.logic.commands; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static seedu.address.commons.core.Messages.MESSAGE_FIND_ORDERS_OVERVIEW; import static seedu.address.logic.commands.CommandTestUtil.assertOrderCommandSuccess; import static seedu.address.testutil.TypicalOrders.EMILY; import static seedu.address.testutil.TypicalOrders.SIMON; import static seedu.address.testutil.TypicalOrders.getTypicalAddressBookOrders; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.junit.jupiter.api.Test; import seedu.address.model.Model; import seedu.address.model.ModelManager; import seedu.address.model.UserPrefs; import seedu.address.model.order.OrderUuidContainsKeywordsPredicate; import seedu.address.model.person.NameContainsKeywordsPredicate; import seedu.address.model.person.Person; /** * Contains integration tests (interaction with the Model) for {@code FindOrderNameCommand}. */ public class FindOrderNameCommandTest { private Model model = new ModelManager(getTypicalAddressBookOrders(), new UserPrefs()); private Model expectedModel = new ModelManager(getTypicalAddressBookOrders(), new UserPrefs()); @Test public void equals() { NameContainsKeywordsPredicate firstPredicate = new NameContainsKeywordsPredicate(Collections.singletonList("first")); NameContainsKeywordsPredicate secondPredicate = new NameContainsKeywordsPredicate(Collections.singletonList("second")); FindOrderCommand findFirstCommand = new FindOrderNameCommand(firstPredicate); FindOrderCommand findSecondCommand = new FindOrderNameCommand(secondPredicate); // same object -> returns true assertTrue(findFirstCommand.equals(findFirstCommand)); // same values -> returns true FindOrderCommand findFirstCommandCopy = new FindOrderNameCommand(firstPredicate); assertTrue(findFirstCommand.equals(findFirstCommandCopy)); // different types -> returns false assertFalse(findFirstCommand.equals(1)); // null -> returns false assertFalse(findFirstCommand.equals(null)); // different person -> returns false assertFalse(findFirstCommand.equals(findSecondCommand)); } @Test public void execute_multipleKeywords_multipleOrdersFound() { String expectedMessage = String.format(MESSAGE_FIND_ORDERS_OVERVIEW, 2, "name", Arrays.asList("emily Simon".split(" "))); NameContainsKeywordsPredicate predicate = preparePredicate("emily Simon"); FindOrderCommand command = new FindOrderNameCommand(predicate); List<Person> filteredList = expectedModel.getFilteredPersonList().filtered(predicate); String[] uuidKeywords = filteredList.stream().map(person->person.getUuid().toString()).toArray(String[]::new); expectedModel.updateFilteredOrderList(new OrderUuidContainsKeywordsPredicate(Arrays.asList(uuidKeywords))); assertOrderCommandSuccess(command, model, expectedMessage, expectedModel); assertEquals(Arrays.asList(EMILY, SIMON), model.getFilteredOrderList()); } /** * Parses {@code userInput} into a {@code NameContainsKeywordsPredicate}. */ private NameContainsKeywordsPredicate preparePredicate(String userInput) { String[] nameKeywords = userInput.trim().split("\\s+"); return new NameContainsKeywordsPredicate(Arrays.asList(nameKeywords)); } }
44.146341
118
0.759392
3483a9fe6854f27bcb154c01c8d7b87356c127eb
748
package com.insightfullogic.java8.answers.chapter9; import com.insightfullogic.java8.answers.chapter9.BlockingArtistAnalyzer; import org.junit.Test; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public class BlockingArtistAnalyzerTest { private final com.insightfullogic.java8.answers.chapter9.BlockingArtistAnalyzer analyser = new BlockingArtistAnalyzer(new FakeLookupService()::lookupArtistName); @Test public void largerGroupsAreLarger() { assertTrue(analyser.isLargerGroup("The Beatles", "John Coltrane")); } @Test public void smallerGroupsArentLarger() { assertFalse(analyser.isLargerGroup("John Coltrane", "The Beatles")); } }
31.166667
166
0.748663
c9d8b88749aa98af79f2e8d91890c7df485e9bd2
359
package ada.adapters.cli.commands.enums; public enum EAuthType { USER("user"), ROLE("role"), WILDCARD("all"); private final String value; EAuthType(String value) { this.value = value; } public String getValue() { return value; } @Override public String toString() { return value; } }
14.36
40
0.576602
0899f59d9f45185ce7d7f178891676a5dec6522e
2,992
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.shardingsphere.sharding.merge.dql.groupby; import com.google.common.base.Preconditions; import lombok.RequiredArgsConstructor; import org.apache.shardingsphere.sharding.merge.dql.orderby.CompareUtil; import org.apache.shardingsphere.infra.binder.segment.select.orderby.OrderByItem; import org.apache.shardingsphere.infra.binder.statement.dml.SelectStatementContext; import org.apache.shardingsphere.infra.merge.result.impl.memory.MemoryQueryResultRow; import java.util.Collection; import java.util.Comparator; import java.util.List; /** * Group by row comparator. */ @RequiredArgsConstructor public final class GroupByRowComparator implements Comparator<MemoryQueryResultRow> { private final SelectStatementContext selectStatementContext; private final List<Boolean> valueCaseSensitive; @Override public int compare(final MemoryQueryResultRow o1, final MemoryQueryResultRow o2) { if (!selectStatementContext.getOrderByContext().getItems().isEmpty()) { return compare(o1, o2, selectStatementContext.getOrderByContext().getItems()); } return compare(o1, o2, selectStatementContext.getGroupByContext().getItems()); } @SuppressWarnings("rawtypes") private int compare(final MemoryQueryResultRow o1, final MemoryQueryResultRow o2, final Collection<OrderByItem> orderByItems) { for (OrderByItem each : orderByItems) { Object orderValue1 = o1.getCell(each.getIndex()); Preconditions.checkState(null == orderValue1 || orderValue1 instanceof Comparable, "Order by value must implements Comparable"); Object orderValue2 = o2.getCell(each.getIndex()); Preconditions.checkState(null == orderValue2 || orderValue2 instanceof Comparable, "Order by value must implements Comparable"); int result = CompareUtil.compareTo((Comparable) orderValue1, (Comparable) orderValue2, each.getSegment().getOrderDirection(), each.getSegment().getNullOrderDirection(), valueCaseSensitive.get(each.getIndex())); if (0 != result) { return result; } } return 0; } }
46.030769
140
0.737634
1b695ec34bc5eaee6f753da9096cf9a63406d079
1,261
package com.subrosagames.subrosa.domain.location.persistence; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.OneToMany; import javax.persistence.Table; import com.fasterxml.jackson.annotation.JsonIgnore; import com.subrosagames.subrosa.domain.location.Point; import com.subrosagames.subrosa.domain.location.Zone; /** * Persisted game zone. */ @Entity @Table(name = "zone") public class ZoneEntity implements Zone { @JsonIgnore @Id @Column(name = "zone_id") private Integer id; @OneToMany(fetch = FetchType.EAGER, targetEntity = PointEntity.class) @JoinTable( name = "zone_point", joinColumns = @JoinColumn(name = "zone_id"), inverseJoinColumns = @JoinColumn(name = "point_id") ) private List<Point> points; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public List<Point> getPoints() { return points; } public void setPoints(List<Point> points) { this.points = points; } }
23.792453
73
0.693894
d9c8c675a49f649742dfe4aa35fec20285800064
896
package lambda; public class LambdasAsArgumentDemo { static String stringOp(StringFunc sf, String s) { return sf.func(s); } public static void main(String [] args) { String inStr="Lambdas add power to Java"; String outStr; System.out.println("Here is input string: "+inStr); outStr=stringOp((str)-> str.toUpperCase(),inStr); System.out.println("The string in uppercase: "+outStr); outStr=stringOp((str)->{ String result=""; int i; for(i=0;i<str.length();i++) if(str.charAt(i)!=' ') result+=str.charAt(i); return result; },inStr); System.out.println("The string with spaces removed: "+outStr); StringFunc reverse=(str)->{ String result=""; int i; for(i=str.length()-1;i>=0;i--) result+=str.charAt(i); return result; }; System.out.println("The string reversed: "+stringOp(reverse,inStr)); } }
19.911111
70
0.628348
cb86eaf3563228d5622ae1f8dcc8627542968cc5
3,385
package cc.lixiaoyu.wanandroid.core.wechat; import cc.lixiaoyu.wanandroid.entity.Article; import cc.lixiaoyu.wanandroid.entity.WechatPage; import cc.lixiaoyu.wanandroid.util.Optional; import cc.lixiaoyu.wanandroid.util.ToastUtil; import io.reactivex.functions.Consumer; public class WechatDataPresenter extends WechatDataContract.Presenter { private WechatDataContract.Model mModel; //加载的当前页,默认为1 private int mCurrentPage = 1; public WechatDataPresenter() { mModel = new WechatDataModel(); } @Override public void openArticleDetail(Article article) { getView().showOpenArticleDetail(article); } @Override public void collectArticle(final int position, Article article) { mModel.collectArticle(article.getId()).subscribe(new Consumer<Optional<String>>() { @Override public void accept(Optional<String> s) throws Exception { getView().showCollectArticle(true, position); } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { getView().showCollectArticle(false, position); } }); } @Override public void cancelCollectArticle(final int position, Article article) { mModel.unCollectArticle(article.getId()).subscribe(new Consumer<Optional<String>>() { @Override public void accept(Optional<String> s) throws Exception { getView().showCancelCollectArticle(true, position); } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { getView().showCancelCollectArticle(false, position); } }); } @Override public void getWechatArticlesById(int id) { mCurrentPage = 1; mModel.getWechatArticlesById(mCurrentPage, id) .subscribe(new Consumer<Optional<WechatPage>>() { @Override public void accept(Optional<WechatPage> wechatPageOptional) throws Exception { getView().showWechatArticlesById(wechatPageOptional.getIncludeNull().getDataList()); } }, new Consumer<Throwable>() { @Override public void accept(Throwable t) throws Exception { ToastUtil.showToast("出错了"); t.printStackTrace(); } }); } @Override public void loadMoreWechatArticlesById(int id) { mCurrentPage++; mModel.getWechatArticlesById(mCurrentPage, id) .subscribe(new Consumer<Optional<WechatPage>>() { @Override public void accept(Optional<WechatPage> wechatPageOptional) throws Exception { getView().showLoadMoreWechatArticleById(wechatPageOptional.getIncludeNull().getDataList(),true); } }, new Consumer<Throwable>() { @Override public void accept(Throwable t) throws Exception { getView().showLoadMoreWechatArticleById(null,false); } }); } @Override public void start() { } }
35.260417
120
0.59291
80482ade310980c05a356e3835baea34e846ee9b
357
package me.androidbox.loginmvp.login; /** * Created by steve on 5/9/16. */ public interface LoginModelContract { interface OnLoginCompletedListener { void onUsernameError(); void onPasswordError(); void onSuccess(); } void login(String username, String password, OnLoginCompletedListener onLoginCompletedListener); }
23.8
100
0.711485
19a6c3ac76e51b472150d5773d5f3a9e2d354539
4,723
/*** Copyright (c) 2013-2014 CommonsWare, 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 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.commonsware.cwac.camera; import android.annotation.SuppressLint; import android.os.Build; import android.util.Log; import com.commonsware.cwac.camera.CameraHost.RecordingHint; import org.xmlpull.v1.XmlPullParser; public class SimpleDeviceProfile extends DeviceProfile { private boolean useTextureView = Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN && !isCyanogenMod(); private boolean portraitFFCFlipped = false; private int minPictureHeight = 0; private int maxPictureHeight = Integer.MAX_VALUE; private boolean doesZoomActuallyWork = true; private int defaultOrientation = -1; private boolean useDeviceOrientation = false; private int pictureDelay = 0; private RecordingHint recordingHint = RecordingHint.NONE; SimpleDeviceProfile load(XmlPullParser xpp) { StringBuilder buf = null; try { while (xpp.getEventType() != XmlPullParser.END_DOCUMENT) { switch (xpp.getEventType()) { case XmlPullParser.START_TAG: buf = new StringBuilder(); break; case XmlPullParser.TEXT: if (buf != null) { buf.append(xpp.getText()); } break; case XmlPullParser.END_TAG: if (buf != null) { set(xpp.getName(), buf.toString().trim()); } break; } xpp.next(); } } catch (Exception e) { Log.e("CWAC-Camera", String.format( "Exception parsing device profile for %s %s", Build.MANUFACTURER, Build.MODEL), e); } return (this); } @SuppressLint("DefaultLocale") private void set(String name, String value) { if ("useTextureView".equals(name)) { useTextureView = Boolean.parseBoolean(value); } else if ("portraitFFCFlipped".equals(name)) { portraitFFCFlipped = Boolean.parseBoolean(value); } else if ("doesZoomActuallyWork".equals(name)) { doesZoomActuallyWork = Boolean.parseBoolean(value); } else if ("useDeviceOrientation".equals(name)) { useDeviceOrientation = Boolean.parseBoolean(value); } else if ("minPictureHeight".equals(name)) { minPictureHeight = Integer.parseInt(value); } else if ("maxPictureHeight".equals(name)) { maxPictureHeight = Integer.parseInt(value); } // else if ("defaultOrientation".equals(name)) { // defaultOrientation=Integer.parseInt(value); // } else if ("pictureDelay".equals(name)) { pictureDelay = Integer.parseInt(value); } else if ("recordingHint".equals(name)) { String hint = value.toUpperCase(); if ("ANY".equals(hint)) { recordingHint = RecordingHint.ANY; } else if ("STILL_ONLY".equals(hint)) { recordingHint = RecordingHint.STILL_ONLY; } else if ("VIDEO_ONLY".equals(hint)) { recordingHint = RecordingHint.VIDEO_ONLY; } } } @Override public boolean useTextureView() { return (useTextureView); } @Override public boolean portraitFFCFlipped() { return (portraitFFCFlipped); } @Override public int getMinPictureHeight() { return (minPictureHeight); } @Override public int getMaxPictureHeight() { return (maxPictureHeight); } @Override public boolean doesZoomActuallyWork(boolean isFFC) { return (doesZoomActuallyWork); } // only needed if EXIF headers are mis-coded, such // as on Nexus 7 (2012) @Override public int getDefaultOrientation() { return (defaultOrientation); } // for devices like DROID Mini where setRotation() // goes BOOM @Override public boolean useDeviceOrientation() { return (useDeviceOrientation); } // for devices like Galaxy Nexus where delaying // taking a picture after modifying Camera.Parameters // seems to help @Override public int getPictureDelay() { return (pictureDelay); } @Override public RecordingHint getDefaultRecordingHint() { return (recordingHint); } // based on http://stackoverflow.com/a/9801191/115145 // and // https://github.com/commonsguy/cwac-camera/issues/43#issuecomment-23791446 private boolean isCyanogenMod() { return (System.getProperty("os.version").contains("cyanogenmod") || Build.HOST .contains("cyanogenmod")); } static class MotorolaRazrI extends SimpleDeviceProfile { public boolean doesZoomActuallyWork(boolean isFFC) { return (!isFFC); } } }
27.459302
89
0.720093
92812712d0dc321c178dfb0a8d961c5a83fcf133
12,183
/* RetroRPGCS: An RPG */ package com.puttysoftware.retrorpgcs.maze.effects; import com.puttysoftware.randomrange.RandomRange; import com.puttysoftware.retrorpgcs.maze.utilities.DirectionConstants; public class Dizzy extends MazeEffect { private static final int DIZZY_STATE_UDRL = 1; private static final int DIZZY_STATE_ULDR = 2; private static final int DIZZY_STATE_ULRD = 3; private static final int DIZZY_STATE_URDL = 4; private static final int DIZZY_STATE_URLD = 5; private static final int DIZZY_STATE_DULR = 6; private static final int DIZZY_STATE_DURL = 7; private static final int DIZZY_STATE_DLUR = 8; private static final int DIZZY_STATE_DLRU = 9; private static final int DIZZY_STATE_DRUL = 10; private static final int DIZZY_STATE_DRLU = 11; private static final int DIZZY_STATE_LDUR = 12; private static final int DIZZY_STATE_LDRU = 13; private static final int DIZZY_STATE_LUDR = 14; private static final int DIZZY_STATE_LURD = 15; private static final int DIZZY_STATE_LRDU = 16; private static final int DIZZY_STATE_LRUD = 17; private static final int DIZZY_STATE_RDLU = 18; private static final int DIZZY_STATE_RDUL = 19; private static final int DIZZY_STATE_RLDU = 20; private static final int DIZZY_STATE_RLUD = 21; private static final int DIZZY_STATE_RUDL = 22; private static final int DIZZY_STATE_RULD = 23; private static final int MIN_DIZZY_STATE = 1; private static final int MAX_DIZZY_STATE = 23; // Fields private int state; private final RandomRange r; // Constructor public Dizzy(final int newRounds) { super("Dizzy", newRounds); this.r = new RandomRange(Dizzy.MIN_DIZZY_STATE, Dizzy.MAX_DIZZY_STATE); } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (!super.equals(obj) || !(obj instanceof Dizzy)) { return false; } final var other = (Dizzy) obj; if (this.state != other.state) { return false; } return true; } @Override public int hashCode() { final var prime = 31; var result = super.hashCode(); return result = prime * result + this.state; } @Override public int modifyMove1(final int arg) { this.state = this.r.generate(); switch (arg) { case DirectionConstants.DIRECTION_NORTH: switch (this.state) { case DIZZY_STATE_UDRL: case DIZZY_STATE_ULDR: case DIZZY_STATE_ULRD: case DIZZY_STATE_URDL: case DIZZY_STATE_URLD: return DirectionConstants.DIRECTION_NORTH; case DIZZY_STATE_DULR: case DIZZY_STATE_DURL: case DIZZY_STATE_DLUR: case DIZZY_STATE_DLRU: case DIZZY_STATE_DRUL: case DIZZY_STATE_DRLU: return DirectionConstants.DIRECTION_SOUTH; case DIZZY_STATE_LDUR: case DIZZY_STATE_LDRU: case DIZZY_STATE_LUDR: case DIZZY_STATE_LURD: case DIZZY_STATE_LRDU: case DIZZY_STATE_LRUD: return DirectionConstants.DIRECTION_WEST; case DIZZY_STATE_RDLU: case DIZZY_STATE_RDUL: case DIZZY_STATE_RLDU: case DIZZY_STATE_RLUD: case DIZZY_STATE_RUDL: case DIZZY_STATE_RULD: return DirectionConstants.DIRECTION_EAST; default: break; } break; case DirectionConstants.DIRECTION_SOUTH: switch (this.state) { case DIZZY_STATE_DULR: case DIZZY_STATE_DURL: case DIZZY_STATE_LUDR: case DIZZY_STATE_LURD: case DIZZY_STATE_RUDL: case DIZZY_STATE_RULD: return DirectionConstants.DIRECTION_NORTH; case DIZZY_STATE_UDRL: case DIZZY_STATE_LDUR: case DIZZY_STATE_LDRU: case DIZZY_STATE_RDLU: case DIZZY_STATE_RDUL: return DirectionConstants.DIRECTION_SOUTH; case DIZZY_STATE_ULDR: case DIZZY_STATE_ULRD: case DIZZY_STATE_DLUR: case DIZZY_STATE_DLRU: case DIZZY_STATE_RLDU: case DIZZY_STATE_RLUD: return DirectionConstants.DIRECTION_WEST; case DIZZY_STATE_URDL: case DIZZY_STATE_URLD: case DIZZY_STATE_DRUL: case DIZZY_STATE_DRLU: case DIZZY_STATE_LRDU: case DIZZY_STATE_LRUD: return DirectionConstants.DIRECTION_EAST; default: break; } break; case DirectionConstants.DIRECTION_WEST: switch (this.state) { case DIZZY_STATE_DLUR: case DIZZY_STATE_DRUL: case DIZZY_STATE_LDUR: case DIZZY_STATE_LRUD: case DIZZY_STATE_RDUL: case DIZZY_STATE_RLUD: return DirectionConstants.DIRECTION_NORTH; case DIZZY_STATE_ULDR: case DIZZY_STATE_URDL: case DIZZY_STATE_LUDR: case DIZZY_STATE_LRDU: case DIZZY_STATE_RLDU: case DIZZY_STATE_RUDL: return DirectionConstants.DIRECTION_SOUTH; case DIZZY_STATE_URLD: case DIZZY_STATE_DULR: case DIZZY_STATE_DRLU: case DIZZY_STATE_RDLU: case DIZZY_STATE_RULD: return DirectionConstants.DIRECTION_WEST; case DIZZY_STATE_DURL: case DIZZY_STATE_DLRU: case DIZZY_STATE_UDRL: case DIZZY_STATE_ULRD: case DIZZY_STATE_LDRU: case DIZZY_STATE_LURD: return DirectionConstants.DIRECTION_EAST; default: break; } break; case DirectionConstants.DIRECTION_EAST: switch (this.state) { case DIZZY_STATE_DLRU: case DIZZY_STATE_DRLU: case DIZZY_STATE_LDRU: case DIZZY_STATE_LRDU: case DIZZY_STATE_RDLU: case DIZZY_STATE_RLDU: return DirectionConstants.DIRECTION_NORTH; case DIZZY_STATE_ULRD: case DIZZY_STATE_URLD: case DIZZY_STATE_LURD: case DIZZY_STATE_LRUD: case DIZZY_STATE_RLUD: case DIZZY_STATE_RULD: return DirectionConstants.DIRECTION_SOUTH; case DIZZY_STATE_UDRL: case DIZZY_STATE_URDL: case DIZZY_STATE_DURL: case DIZZY_STATE_DRUL: case DIZZY_STATE_RDUL: case DIZZY_STATE_RUDL: return DirectionConstants.DIRECTION_WEST; case DIZZY_STATE_ULDR: case DIZZY_STATE_DULR: case DIZZY_STATE_DLUR: case DIZZY_STATE_LDUR: case DIZZY_STATE_LUDR: return DirectionConstants.DIRECTION_EAST; default: break; } break; case DirectionConstants.DIRECTION_NORTHWEST: switch (this.state) { case DIZZY_STATE_UDRL: case DIZZY_STATE_ULDR: case DIZZY_STATE_ULRD: case DIZZY_STATE_URDL: case DIZZY_STATE_URLD: return DirectionConstants.DIRECTION_NORTHWEST; case DIZZY_STATE_DULR: case DIZZY_STATE_DURL: case DIZZY_STATE_DLUR: case DIZZY_STATE_DLRU: case DIZZY_STATE_DRUL: case DIZZY_STATE_DRLU: return DirectionConstants.DIRECTION_SOUTHEAST; case DIZZY_STATE_LDUR: case DIZZY_STATE_LDRU: case DIZZY_STATE_LUDR: case DIZZY_STATE_LURD: case DIZZY_STATE_LRDU: case DIZZY_STATE_LRUD: return DirectionConstants.DIRECTION_SOUTHWEST; case DIZZY_STATE_RDLU: case DIZZY_STATE_RDUL: case DIZZY_STATE_RLDU: case DIZZY_STATE_RLUD: case DIZZY_STATE_RUDL: case DIZZY_STATE_RULD: return DirectionConstants.DIRECTION_NORTHEAST; default: break; } break; case DirectionConstants.DIRECTION_NORTHEAST: switch (this.state) { case DIZZY_STATE_DULR: case DIZZY_STATE_DURL: case DIZZY_STATE_LUDR: case DIZZY_STATE_LURD: case DIZZY_STATE_RUDL: case DIZZY_STATE_RULD: return DirectionConstants.DIRECTION_NORTHWEST; case DIZZY_STATE_UDRL: case DIZZY_STATE_LDUR: case DIZZY_STATE_LDRU: case DIZZY_STATE_RDLU: case DIZZY_STATE_RDUL: return DirectionConstants.DIRECTION_SOUTHEAST; case DIZZY_STATE_ULDR: case DIZZY_STATE_ULRD: case DIZZY_STATE_DLUR: case DIZZY_STATE_DLRU: case DIZZY_STATE_RLDU: case DIZZY_STATE_RLUD: return DirectionConstants.DIRECTION_SOUTHWEST; case DIZZY_STATE_URDL: case DIZZY_STATE_URLD: case DIZZY_STATE_DRUL: case DIZZY_STATE_DRLU: case DIZZY_STATE_LRDU: case DIZZY_STATE_LRUD: return DirectionConstants.DIRECTION_NORTHEAST; default: break; } break; case DirectionConstants.DIRECTION_SOUTHWEST: switch (this.state) { case DIZZY_STATE_DLUR: case DIZZY_STATE_DRUL: case DIZZY_STATE_LDUR: case DIZZY_STATE_LRUD: case DIZZY_STATE_RDUL: case DIZZY_STATE_RLUD: return DirectionConstants.DIRECTION_NORTHWEST; case DIZZY_STATE_ULDR: case DIZZY_STATE_URDL: case DIZZY_STATE_LUDR: case DIZZY_STATE_LRDU: case DIZZY_STATE_RLDU: case DIZZY_STATE_RUDL: return DirectionConstants.DIRECTION_SOUTHEAST; case DIZZY_STATE_URLD: case DIZZY_STATE_DULR: case DIZZY_STATE_DRLU: case DIZZY_STATE_RDLU: case DIZZY_STATE_RULD: return DirectionConstants.DIRECTION_SOUTHWEST; case DIZZY_STATE_DURL: case DIZZY_STATE_DLRU: case DIZZY_STATE_UDRL: case DIZZY_STATE_ULRD: case DIZZY_STATE_LDRU: case DIZZY_STATE_LURD: return DirectionConstants.DIRECTION_NORTHEAST; default: break; } break; case DirectionConstants.DIRECTION_SOUTHEAST: switch (this.state) { case DIZZY_STATE_DLRU: case DIZZY_STATE_DRLU: case DIZZY_STATE_LDRU: case DIZZY_STATE_LRDU: case DIZZY_STATE_RDLU: case DIZZY_STATE_RLDU: return DirectionConstants.DIRECTION_NORTHWEST; case DIZZY_STATE_ULRD: case DIZZY_STATE_URLD: case DIZZY_STATE_LURD: case DIZZY_STATE_LRUD: case DIZZY_STATE_RLUD: case DIZZY_STATE_RULD: return DirectionConstants.DIRECTION_SOUTHEAST; case DIZZY_STATE_UDRL: case DIZZY_STATE_URDL: case DIZZY_STATE_DURL: case DIZZY_STATE_DRUL: case DIZZY_STATE_RDUL: case DIZZY_STATE_RUDL: return DirectionConstants.DIRECTION_SOUTHWEST; case DIZZY_STATE_ULDR: case DIZZY_STATE_DULR: case DIZZY_STATE_DLUR: case DIZZY_STATE_LDUR: case DIZZY_STATE_LUDR: return DirectionConstants.DIRECTION_NORTHEAST; default: break; } break; default: break; } return 0; } }
36.044379
79
0.593039
f09e02176ea8ca7a9696bef714b5d5348f11e85a
575
import static org.junit.jupiter.api.Assertions.assertArrayEquals; import org.junit.jupiter.api.Test; class SolutionTest { @Test void sample() { assertArrayEquals(new long[]{0, 0, 0}, Kata.NumbersWithDigitInside(5, 6)); assertArrayEquals(new long[]{1, 6, 6}, Kata.NumbersWithDigitInside(7, 6)); assertArrayEquals(new long[]{3, 22, 110}, Kata.NumbersWithDigitInside(11, 1)); assertArrayEquals(new long[]{2, 30, 200}, Kata.NumbersWithDigitInside(20, 0)); assertArrayEquals(new long[]{9, 286, 5955146588160L}, Kata.NumbersWithDigitInside(44, 4)); } }
38.333333
94
0.721739
1e663d7931a201cd050e7afd551839bc979e2064
3,368
/* * ARX: Powerful Data Anonymization * Copyright 2012 - 2017 Fabian Prasser, Florian Kohlmayer and contributors * * 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.deidentifier.arx.gui.view.impl.wizard; import org.deidentifier.arx.gui.view.impl.wizard.HierarchyWizard.HierarchyWizardView; import org.eclipse.jface.wizard.IWizardPage; import org.eclipse.jface.wizard.WizardPage; import org.eclipse.swt.widgets.Button; /** * An abstract base class for pages that allow configuring a builder. * * @author Fabian Prasser * @param <T> */ public abstract class HierarchyWizardPageBuilder<T> extends WizardPage implements HierarchyWizardView { /** Var. */ private final HierarchyWizardPageFinal<T> finalPage; /** Var. */ private final HierarchyWizardModelAbstract<T> model; /** Var. */ private final HierarchyWizard<T> wizard; /** * Creates a new base class. * * @param wizard * @param model * @param finalPage */ public HierarchyWizardPageBuilder(final HierarchyWizard<T> wizard, final HierarchyWizardModelAbstract<T> model, final HierarchyWizardPageFinal<T> finalPage){ super(""); //$NON-NLS-1$ this.wizard = wizard; this.model = model; this.finalPage = finalPage; this.model.setView(this); this.model.update(); } @Override public boolean canFlipToNextPage() { return isPageComplete(); } @Override public IWizardPage getNextPage() { return finalPage; } @Override public void setVisible(boolean value){ if (value) { this.model.update(); Button load = this.wizard.getLoadButton(); if (load != null) load.setEnabled(false); } super.setVisible(value); model.setVisible(value); } @Override public void update() { if (model.getError() != null) { this.setErrorMessage(model.getError()); finalPage.setGroups(null); finalPage.setHierarchy(null); this.setPageComplete(false); Button save = this.wizard.getSaveButton(); if (save != null) save.setEnabled(false); } else { this.setErrorMessage(null); finalPage.setGroups(model.getGroups()); finalPage.setHierarchy(model.getHierarchy()); this.setPageComplete(true); Button save = this.wizard.getSaveButton(); if (save != null) save.setEnabled(true); } } /** * Update the page when the model has changed. */ public abstract void updatePage(); }
31.773585
104
0.609264
a0a36bca0c398a4821e3c9beff164f6b4ffdb39d
24,683
/* * * Copyright (c) 2012-2015 VMware, Inc. All Rights Reserved. * * 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.vmware.identity.idm.server; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import javax.security.auth.login.LoginException; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import com.vmware.identity.idm.Attribute; import com.vmware.identity.idm.AttributeValuePair; import com.vmware.identity.idm.DomainType; import com.vmware.identity.idm.Group; import com.vmware.identity.idm.IdentityStoreType; import com.vmware.identity.idm.InvalidPrincipalException; import com.vmware.identity.idm.KnownSamlAttributes; import com.vmware.identity.idm.PersonUser; import com.vmware.identity.idm.PrincipalId; import com.vmware.identity.idm.UserAccountLockedException; import com.vmware.identity.idm.server.config.ServerIdentityStoreData; import com.vmware.identity.idm.server.performance.PerformanceMonitorFactory; import com.vmware.identity.idm.server.provider.IIdentityProvider; import com.vmware.identity.idm.server.provider.LdapConnectionPool; import com.vmware.identity.idm.server.provider.PrincipalGroupLookupInfo; import com.vmware.identity.idm.server.provider.activedirectory.ActiveDirectoryProvider; import com.vmware.identity.idm.server.provider.ldap.LdapWithAdMappingsProvider; public class LdapWithAdMappingsProviderTest { // bugzilla#1173915 - unable to create NativeAd due to changes. Need to adjust the tests .... //private static ServerIdentityStoreData realADProviderstoreData = null; private static ServerIdentityStoreData ldapADProviderstoreData = null; private static ServerIdentityStoreData ldapSADProviderstoreData = null; private static final String TENANT_NAME = "vsphere.local"; private static final String AD_DOMAIN_NAME = "ssolabs.eng.vmware.com"; private static final String AD_DOMAIN_ALIAS = "SSOLABS"; private static final String AD_DOMAIN_NAME_USER = AD_DOMAIN_NAME; private static final String AD_LDAPS_DOMAIN_NAME = "ssovcui.com"; private static final String AD_LDAPS_DOMAIN_ALIAS = "ssovcui"; private static String NESTED_GROUP_USER_NAME = "user_ngs"; private static String NESTED_GROUP01 = AD_DOMAIN_NAME + "\\NG01"; private static String NESTED_GROUP02 = AD_DOMAIN_NAME + "\\NG02"; private static String NESTED_GROUP03 = AD_DOMAIN_NAME + "\\NG03"; private static String NESTED_GROUP04 = AD_DOMAIN_NAME + "\\NG04"; private static String NESTED_GROUP05 = AD_DOMAIN_NAME + "\\NG05"; private static String NESTED_GROUP06 = AD_DOMAIN_NAME + "\\NG06"; private static String NESTED_GROUP07 = AD_DOMAIN_NAME + "\\NG07"; private static String NESTED_GROUP08 = AD_DOMAIN_NAME + "\\NG08"; private static String NESTED_GROUP09 = AD_DOMAIN_NAME + "\\NG09"; private static String NESTED_GROUP10 = AD_DOMAIN_NAME + "\\NG10"; private static String NESTED_GROUP11 = AD_DOMAIN_NAME + "\\NG11"; private static String NESTED_GROUP12 = AD_DOMAIN_NAME + "\\NG12"; private static String NESTED_GROUP14 = AD_DOMAIN_NAME + "\\NG14"; private static String NESTED_GROUP15 = AD_DOMAIN_NAME + "\\NG15"; private static String NESTED_GROUP16 = AD_DOMAIN_NAME + "\\NG16"; private static String NESTED_GROUP17 = AD_DOMAIN_NAME + "\\NG17"; private static String NESTED_GROUP18 = AD_DOMAIN_NAME + "\\NG18"; private static String DOMAIN_USERS_GROUP = AD_DOMAIN_NAME + "\\Domain Users"; private static String USERS_GROUP = AD_DOMAIN_NAME + "\\Users"; private static String BASE_GROUP_DN = "OU=GroupsOU,DC=ssolabs,DC=eng,DC=vmware,DC=com"; // domain groups: NG01, NG02, NG03, NG04, NG05, NG06, NG14, NG15, NG16 // OU groups: NG07, NG08, NG09, NG10, NG11, NG12, NG17, NG18 // membership: // NG01: NG02 // NG02: NG06; // NG03: user_ngs // NG04: NG10 // NG05: user_ngs // NG06: user_ngs // NG07 NG08; // NG08: NG12 // NG09: user_ngs // NG10: user_ngs // NG11: NG05; // NG12: user_ngs // NG14: user_ngs, NG16 // NG15: NG14 // NG16: NG15 // NG17: user_ngs, NG18 // NG18: NG17 private static Set<String> userNestedDomainGroups; private static Set<String> userNestedDomainGroupsOU; private static Set<String> userNestedDomainGroupsOUMTC; private static Set<String> userDirectDomainGroups; private static Set<String> userDirectDomainGroupsOU; static { //bugzilla#1173915 /* realADProviderstoreData = new ServerIdentityStoreData(DomainType.EXTERNAL_DOMAIN, AD_DOMAIN_NAME); realADProviderstoreData.setProviderType(IdentityStoreType.IDENTITY_STORE_TYPE_ACTIVE_DIRECTORY); realADProviderstoreData.setConnectionStrings(Arrays.asList("ldap://dc-1.ssolabs.eng.vmware.com")); realADProviderstoreData.setUserName("CN=Administrator,CN=Users,DC=SSOLABS,DC=ENG,DC=VMWARE,DC=COM"); realADProviderstoreData.setPassword("ca$hc0w"); realADProviderstoreData.setUserBaseDn( "DC=SSOLABS,DC=ENG,DC=VMWARE,DC=COM"); realADProviderstoreData.setGroupBaseDn("DC=SSOLABS,DC=ENG,DC=VMWARE,DC=COM"); realADProviderstoreData.setAlias(AD_DOMAIN_ALIAS); realADProviderstoreData.setAttributeMap(attrMap); */ Map<String, String> attrMap = getAttributes(); ldapADProviderstoreData = getLdapADData(attrMap); ldapSADProviderstoreData = getLdapsADData(attrMap); userNestedDomainGroups = new HashSet<String>(); userNestedDomainGroups.addAll( Arrays.asList( new String[] { NESTED_GROUP01, NESTED_GROUP02, NESTED_GROUP03, NESTED_GROUP04, NESTED_GROUP05, NESTED_GROUP06, NESTED_GROUP07, NESTED_GROUP08, NESTED_GROUP09, NESTED_GROUP10, NESTED_GROUP11, NESTED_GROUP12, NESTED_GROUP14, NESTED_GROUP15, NESTED_GROUP16, NESTED_GROUP17, NESTED_GROUP18, DOMAIN_USERS_GROUP, USERS_GROUP} ) ); userNestedDomainGroupsOU = new HashSet<String>(); userNestedDomainGroupsOU.addAll( Arrays.asList( new String[] { NESTED_GROUP07, NESTED_GROUP08, NESTED_GROUP09, NESTED_GROUP10, NESTED_GROUP12, NESTED_GROUP17, NESTED_GROUP18}) ); userNestedDomainGroupsOUMTC = new HashSet<String>(); userNestedDomainGroupsOUMTC.addAll( Arrays.asList( new String[] { NESTED_GROUP07, NESTED_GROUP08, NESTED_GROUP09, NESTED_GROUP10, NESTED_GROUP11, NESTED_GROUP12, NESTED_GROUP17, NESTED_GROUP18}) ); userDirectDomainGroups = new HashSet<String>(); userDirectDomainGroups.addAll( Arrays.asList( new String[] { NESTED_GROUP03, NESTED_GROUP05, NESTED_GROUP06, NESTED_GROUP09, NESTED_GROUP10, NESTED_GROUP12, DOMAIN_USERS_GROUP, NESTED_GROUP14, NESTED_GROUP17}) ); userDirectDomainGroupsOU = new HashSet<String>(); userDirectDomainGroupsOU.addAll( Arrays.asList( new String[] { NESTED_GROUP09, NESTED_GROUP10, NESTED_GROUP12, NESTED_GROUP17 } ) ); PerformanceMonitorFactory.setPerformanceMonitor(new TestPerfMonitor()); LdapConnectionPool.getInstance().createPool("vsphere.local"); } // bugzilla#1173915 //private static final IIdentityProvider realAdProvider = new ActiveDirectoryProvider(realADProviderstoreData); private static final IIdentityProvider ldapAdProvider = new LdapWithAdMappingsProvider(TENANT_NAME, ldapADProviderstoreData); private static final IIdentityProvider ldapsAdProvider = new LdapWithAdMappingsProvider(TENANT_NAME, ldapSADProviderstoreData); @BeforeClass public static void testSetup() { } @AfterClass public static void testTearDown() { //any cleanup here } @Test public void testAuthenticate() { testAuthenticate( ldapAdProvider ); } private static void testAuthenticate(IIdentityProvider provider) { Map<PrincipalId, String> validCreds = new HashMap<PrincipalId, String>(); validCreds.put(new PrincipalId("lookup", AD_DOMAIN_NAME_USER), "vmware123$"); validCreds.put(new PrincipalId("lookup", AD_DOMAIN_NAME_USER), "vmware123$"); for (PrincipalId user: validCreds.keySet()) { try { PrincipalId res = provider.authenticate(user, validCreds.get(user)); Assert.assertEquals(user, res); } catch (LoginException e) { Assert.fail(e.getMessage()); } } Map<PrincipalId, String> invalidCreds = new HashMap<PrincipalId, String>(); invalidCreds.put(new PrincipalId("nonExistant", AD_DOMAIN_NAME_USER), "invalidPwd"); invalidCreds.put(new PrincipalId("lookup", AD_DOMAIN_NAME_USER), "1xxxxxxxxxxxxxx"); for (PrincipalId invalidUser : invalidCreds.keySet()) { try { provider.authenticate(invalidUser, invalidCreds.get(invalidUser)); } catch (LoginException e) { //expected exception continue; } Assert.assertTrue("should not reach here", false); } try { provider.checkUserAccountFlags(new PrincipalId("locked_user", AD_DOMAIN_NAME_USER)); Assert.fail("checkUserAccountFlags for a locked user [locked_user] should throw."); } catch(UserAccountLockedException ex) { // expected exception } catch(Exception ex) { Assert.fail(String.format("Unexpected exception: [%s]. Expected UserAccountLockedException exception", ex.toString())); } } @Test public void testLdapsAuthenticate() { testAuthenticate(ldapsAdProvider); } @Ignore("bugzilla#1173915") @Test public void testGetAttributesMatches() throws Exception { /* List<Attribute> attrs = Arrays.asList( new Attribute(attrNameGivenName), new Attribute(attrNameSn), new Attribute(attrNameMemberOf), new Attribute(attrNameSubjectType), new Attribute(attrNameEmailAddress), new Attribute(attrNameUserPrincipalName) ); PrincipalId id = new PrincipalId("lookup", AD_DOMAIN_NAME_USER); Collection<AttributeValuePair> attrValsUnmapped = realAdProvider.getAttributes(id, attrs); Collection<AttributeValuePair> attrValsMapped = ldapAdProvider.getAttributes(id, attrs); Assert.assertEquals( attrValsUnmapped.size(), attrValsMapped.size() ); Iterator<AttributeValuePair> itr = attrValsUnmapped.iterator(); Iterator<AttributeValuePair> itrRes = attrValsMapped.iterator(); while (itr.hasNext() && itrRes.hasNext()) { AttributeValuePair adResult = itr.next(); AttributeValuePair ldapAdResult = itrRes.next(); List<String> result = adResult.getValues(); List<String> resultMapped = ldapAdResult.getValues(); Assert.assertEquals(result, resultMapped); } */ } @Test public void testGetAttributesInvalid() { testGetAttributesInvalid(ldapAdProvider); } private static void testGetAttributesInvalid(IIdentityProvider provider) { PrincipalId id = new PrincipalId("lookup", AD_DOMAIN_NAME_USER); List<Attribute> invalidList = Arrays.asList(new Attribute("unknownAttrName")); try { provider.getAttributes(id, invalidList); Assert.fail("getting invalid attributes should fail."); } catch (IllegalArgumentException e) { Assert.assertTrue(e.getMessage().contains("No attribute mapping found")); } catch(Exception ex) { Assert.fail(String.format("Unexpected exception: [%s].", ex.toString())); } } @Test public void testFindUser() throws Exception { testFindUser(ldapAdProvider); } private static void testFindUser(IIdentityProvider provider) throws Exception { PrincipalId user = new PrincipalId("lookup", AD_DOMAIN_NAME_USER); PersonUser result = provider.findUser(user); Assert.assertNotNull(result); Assert.assertEquals("", user.getName(), result.getId().getName()); PrincipalId nonExistant = new PrincipalId("nonExistant", AD_DOMAIN_NAME_USER); try { provider.findUser(nonExistant); } catch (InvalidPrincipalException e) { //expected exception return; } Assert.assertTrue("should not reach here", false); } @Ignore("bugzilla#1173915") @Test public void testFindMatches() throws Exception { /* Set<PersonUser> users = realAdProvider.findUsers("testuser", realADProviderstoreData.getName(), -1); Set<PersonUser> usersMapped = ldapAdProvider.findUsers("testuser", realADProviderstoreData.getName(), -1); Assert.assertEquals(users, usersMapped); for(PersonUser pu : users) { Boolean isActive = realAdProvider.IsActive(pu.getId());; Boolean isActiveMapped = ldapAdProvider.IsActive(pu.getId()); Assert.assertEquals(isActive, isActiveMapped); Set<Group> groups = realAdProvider.findDirectParentGroups(pu.getId()); Set<Group> groupsMapped = ldapAdProvider.findDirectParentGroups(pu.getId()); Assert.assertEquals(groups, groupsMapped); groups = realAdProvider.findNestedParentGroups(pu.getId()); groupsMapped = ldapAdProvider.findNestedParentGroups(pu.getId()); Assert.assertEquals(groups, groupsMapped); for(Group g : groups) { Set<PersonUser> users1 = null; users1 = realAdProvider.findUsersInGroup(g.getId(), "", -1); Set<PersonUser> usersMapped1 = ldapAdProvider.findUsersInGroup(g.getId(), "", -1); Assert.assertEquals(users1, usersMapped1); Set<Group> group1 = realAdProvider.findGroupsInGroup(g.getId(), "", -1); Set<Group> groupMapped1 = ldapAdProvider.findGroupsInGroup(g.getId(), "", -1); Assert.assertEquals(group1, groupMapped1); } } users = realAdProvider.findDisabledUsers("testuser", -1); usersMapped = ldapAdProvider.findDisabledUsers("testuser", -1); Assert.assertEquals(users, usersMapped); users = realAdProvider.findLockedUsers("locked", -1); usersMapped = ldapAdProvider.findLockedUsers("locked", -1); Assert.assertEquals(users, usersMapped); */ } @Ignore("bugzilla#1173915") @Test public void testFindGroupsMatches() throws Exception { /* Set<Group> groups = realAdProvider.findGroups("JohnGroup-482", realADProviderstoreData.getName(), -1); Set<Group> groupsMapped = ldapAdProvider.findGroups("JohnGroup-482", realADProviderstoreData.getName(), -1); Assert.assertEquals(groups, groupsMapped); for(Group g : groups) { Set<PersonUser> users1 = realAdProvider.findUsersInGroup(g.getId(), "", -1); Set<PersonUser> usersMapped1 = ldapAdProvider.findUsersInGroup(g.getId(), "", -1); Assert.assertEquals(users1, usersMapped1); Set<Group> group1 = realAdProvider.findGroupsInGroup(g.getId(), "", -1); Set<Group> groupMapped1 = ldapAdProvider.findGroupsInGroup(g.getId(), "", -1); Assert.assertEquals(group1, groupMapped1); } */ } @Ignore("bugzilla#1173915") @Test public void testFindPersonUserMatches() throws Exception { /* PrincipalId testUserId = new PrincipalId("lookup", AD_DOMAIN_NAME_USER); PersonUser user = realAdProvider.findUser(testUserId); PersonUser userMapped = ldapAdProvider.findUser(testUserId); verifyResult(user, userMapped); */ } @Test public void testFindGroupsByNameInGroup() throws Exception { testFindGroupsByNameInGroup(ldapAdProvider); } @Ignore("bugzilla#1173915") @Test public void testFindGroupsByNameInGroupAD() throws Exception { /* testFindGroupsByNameInGroup(realAdProvider); */ } private static void testFindGroupsByNameInGroup(IIdentityProvider provider) throws Exception { PrincipalId idGroup = new PrincipalId("Group1", AD_DOMAIN_NAME); Set<Group> findAnyGroup = provider.findGroupsByNameInGroup(idGroup, "", -1); Set<Group> findGroupByName = provider.findGroupsByNameInGroup(idGroup, "grpFgPwdPolicy", -1); Set<Group> findGroupByPrefix = provider.findGroupsByNameInGroup(idGroup, "grp", -1); Assert.assertTrue("Unexpected size", findAnyGroup.size() == 1); Assert.assertTrue("Unexpected size", findGroupByName.size() == 1); Assert.assertTrue("Unexpected size", findGroupByPrefix.size() == 1); Assert.assertArrayEquals(findAnyGroup.toArray(), findGroupByName.toArray()); Assert.assertArrayEquals(findAnyGroup.toArray(), findGroupByPrefix.toArray()); } @Test public void testFindUsersByNameInGroup() throws Exception { testFindUsersByNameInGroup(ldapAdProvider); } @Ignore("bugzilla#1173915") @Test public void testFindUsersByNameInGroupAD() throws Exception { /* testFindUsersByNameInGroup(realAdProvider); */ } @Test public void testNestedTokenGroups() throws Exception { ServerIdentityStoreData data = getLdapADData(getAttributes()); LdapWithAdMappingsProvider adOverLdap = null; // recursive domain scope data.setFlags(LdapWithAdMappingsProvider.FLAG_DO_NOT_USE_BASE_DN_FOR_NESTED_GROUPS); // should not take effect data.setGroupBaseDn(BASE_GROUP_DN); adOverLdap = new LdapWithAdMappingsProvider(TENANT_NAME, data); testGetGroupsAttribute( adOverLdap, userNestedDomainGroups ); // recusrive base dn data.setFlags( 0 ); data.setGroupBaseDn(BASE_GROUP_DN); adOverLdap = new LdapWithAdMappingsProvider(TENANT_NAME, data); testGetGroupsAttribute( adOverLdap, userNestedDomainGroupsOU ); // matching rule domain scope data.setFlags( LdapWithAdMappingsProvider.FLAG_AD_MATCHING_RULE_IN_CHAIN | LdapWithAdMappingsProvider.FLAG_DO_NOT_USE_BASE_DN_FOR_NESTED_GROUPS ); // should not take effect data.setGroupBaseDn(BASE_GROUP_DN); adOverLdap = new LdapWithAdMappingsProvider(TENANT_NAME, data); testGetGroupsAttribute( adOverLdap, userNestedDomainGroups ); // matching rule base dn data.setFlags( LdapWithAdMappingsProvider.FLAG_AD_MATCHING_RULE_IN_CHAIN ); data.setGroupBaseDn(BASE_GROUP_DN); adOverLdap = new LdapWithAdMappingsProvider(TENANT_NAME, data); testGetGroupsAttribute( adOverLdap, userNestedDomainGroupsOUMTC ); // direct group domain scope data.setFlags( LdapWithAdMappingsProvider.FLAG_DIRECT_GROUPS_ONLY | LdapWithAdMappingsProvider.FLAG_DO_NOT_USE_BASE_DN_FOR_NESTED_GROUPS ); // should not take effect data.setGroupBaseDn(BASE_GROUP_DN); adOverLdap = new LdapWithAdMappingsProvider(TENANT_NAME, data); testGetGroupsAttribute( adOverLdap, userDirectDomainGroups ); // direct group base dn data.setFlags( LdapWithAdMappingsProvider.FLAG_DIRECT_GROUPS_ONLY ); data.setGroupBaseDn(BASE_GROUP_DN); adOverLdap = new LdapWithAdMappingsProvider(TENANT_NAME, data); testGetGroupsAttribute( adOverLdap, userDirectDomainGroupsOU ); } private static void testGetGroupsAttribute( IIdentityProvider provider, Set<String> expectedGroups ) throws Exception { List<Attribute> attrs = Arrays.asList( new Attribute(KnownSamlAttributes.ATTRIBUTE_USER_GROUPS) ); PrincipalId id = new PrincipalId(NESTED_GROUP_USER_NAME, AD_DOMAIN_NAME); Collection<AttributeValuePair> attributeValues = provider.getAttributes(id, attrs); Assert.assertNotNull("attributeValues should not be null", attributeValues); Assert.assertTrue("attributeValues.size() > 0", attributeValues.size() > 0); HashSet<String> actual = new HashSet<String>(); Iterator<AttributeValuePair> itr = attributeValues.iterator(); while (itr.hasNext()) { AttributeValuePair cur = itr.next(); if ( KnownSamlAttributes.ATTRIBUTE_USER_GROUPS.equalsIgnoreCase(cur.getAttrDefinition().getName()) ) { actual.addAll(cur.getValues()); break; } } Assert.assertEquals("Group membership should match.", expectedGroups, actual); } private static void testFindUsersByNameInGroup(IIdentityProvider provider) throws Exception { Map<PrincipalId, Integer> sizeFromGroupId = new HashMap<PrincipalId, Integer>(); sizeFromGroupId.put(new PrincipalId("JohnGroup-482", AD_DOMAIN_NAME_USER), null); final String strJohn = "lookup"; final String strGivenNamePrefix = "givenName-John"; for (PrincipalId groupId : sizeFromGroupId.keySet()) { Set<PersonUser> resultByCN = provider.findUsersByNameInGroup(groupId, strJohn, -1); Set<PersonUser> resultByGivenNamePrefix = provider.findUsersByNameInGroup(groupId, strGivenNamePrefix, -1); Assert.assertArrayEquals(resultByCN.toArray(), resultByGivenNamePrefix.toArray()); } } public static void verifyResult(PersonUser userA, PersonUser userB) { Assert.assertEquals(userA.getObjectId(), userB.getObjectId()); Assert.assertEquals(userA.getAlias(), userB.getAlias()); Assert.assertEquals(userA.getId(), userB.getId()); Assert.assertEquals(userA.getDetail(), userB.getDetail()); Assert.assertEquals(userA.isLocked(), userB.isLocked()); Assert.assertEquals(userA.isDisabled(), userB.isDisabled()); } private static Map<String, String> getAttributes() { Map<String, String> attrMap = new HashMap<String, String>(); attrMap.put(KnownSamlAttributes.ATTRIBUTE_USER_FIRST_NAME, "givenName"); attrMap.put(KnownSamlAttributes.ATTRIBUTE_USER_LAST_NAME, "sn"); attrMap.put(KnownSamlAttributes.ATTRIBUTE_USER_GROUPS, "memberof"); attrMap.put(KnownSamlAttributes.ATTRIBUTE_USER_SUBJECT_TYPE, "subjectType"); attrMap.put("mail", "mail"); attrMap.put(KnownSamlAttributes.ATTRIBUTE_USER_PRINCIPAL_NAME, "userPrincipalName"); return attrMap; } private static ServerIdentityStoreData getLdapADData(Map<String, String> attributes) { ServerIdentityStoreData data = new ServerIdentityStoreData(DomainType.EXTERNAL_DOMAIN, AD_DOMAIN_NAME); data.setProviderType(IdentityStoreType.IDENTITY_STORE_TYPE_LDAP_WITH_AD_MAPPING); data.setConnectionStrings(Arrays.asList("ldap://dc-1.ssolabs.eng.vmware.com")); data.setUserName("CN=Administrator,CN=Users,DC=SSOLABS,DC=ENG,DC=VMWARE,DC=COM"); data.setPassword("ca$hc0w"); data.setUserBaseDn( "DC=SSOLABS,DC=ENG,DC=VMWARE,DC=COM"); data.setGroupBaseDn("DC=SSOLABS,DC=ENG,DC=VMWARE,DC=COM"); data.setAlias(AD_DOMAIN_ALIAS); data.setAttributeMap(attributes); return data; } private static ServerIdentityStoreData getLdapsADData(Map<String, String> attributes) { ServerIdentityStoreData data = new ServerIdentityStoreData(DomainType.EXTERNAL_DOMAIN, AD_DOMAIN_NAME); data.setProviderType(IdentityStoreType.IDENTITY_STORE_TYPE_LDAP_WITH_AD_MAPPING); data.setConnectionStrings(Arrays.asList("ldap://dc-1.ssolabs.eng.vmware.com")); data.setUserName("CN=Administrator,CN=Users,DC=SSOLABS,DC=ENG,DC=VMWARE,DC=COM"); data.setPassword("ca$hc0w"); data.setUserBaseDn( "DC=SSOLABS,DC=ENG,DC=VMWARE,DC=COM"); data.setGroupBaseDn("DC=SSOLABS,DC=ENG,DC=VMWARE,DC=COM"); data.setAlias(AD_DOMAIN_ALIAS); data.setAttributeMap(attributes); return data; } }
40.134959
153
0.701576
63d4be8f8d133f0862644e5592382967abb460be
1,313
package com.me.ui.sample; import android.app.Application; import android.content.Context; import com.alibaba.android.arouter.launcher.ARouter; import com.me.ui.sample.library.log.MLog; import com.me.ui.util.ProcessUtils; import com.me.ui.util.Utils; import com.tencent.bugly.Bugly; import com.tencent.bugly.crashreport.CrashReport.UserStrategy; /** * Description * Author: Kevin.Tang * Date: 17/9/21 下午9:23 */ public class SampleApplication extends Application { private static SampleApplication mApplication; @Override public void onCreate() { super.onCreate(); mApplication = this; Utils.init(this); // ARouter if (BuildConfig.DEBUG) { ARouter.openDebug(); ARouter.openLog(); } ARouter.init(this); // Logger MLog.config(); // Bugly UserStrategy strategy = new UserStrategy(getApplicationContext()); strategy.setUploadProcess(ProcessUtils.isMainProcess()); Bugly.init(getApplicationContext(), "dd620d6b4a", false, strategy); } public static Context getContext() { return mApplication; } @Override protected void attachBaseContext(Context base) { super.attachBaseContext(base); // MultiDex.install(this); } }
24.773585
75
0.662605
a84c750f624cc070ed8a8039e930004a321eddff
5,185
/******************************************************************************* * Copyright 2013 Sebastien Diot * * 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.blockwithme.lessobjects.beans; import javax.annotation.Nonnull; import javax.annotation.ParametersAreNonnullByDefault; import com.blockwithme.lessobjects.Field; import com.blockwithme.lessobjects.fields.global.ByteGlobalField; import com.blockwithme.lessobjects.fields.optional.ByteOptionalField; import com.blockwithme.lessobjects.fields.primitive.ByteField; import com.blockwithme.lessobjects.storage.Storage; /** The Byte Value Change holder * * @author tarung * * */ @ParametersAreNonnullByDefault public class ByteValueChange implements ValueChange<Byte> { /** The field. */ @Nonnull private Field<Byte, ? extends Field<Byte, ?>> field; /** The new value. */ private byte newValue; /** The old value. */ private byte oldValue; /** The struct index. */ private int structIndex; /** {@inheritDoc} */ @SuppressWarnings({ "null", "rawtypes" }) @Override public void applyChange(final Storage theStorage) { theStorage.selectStructure(structIndex); if (field.isOptional()) { theStorage.write((ByteOptionalField) field, newValue); } else if (field.global()) { theStorage.write((ByteGlobalField) field, newValue); } else { theStorage.write((ByteField) field, newValue); } } /** New value, use this method to avoid auto-boxing. */ public byte byteNewValue() { return newValue; } /** Old value, use this method to avoid auto-boxing. */ public byte byteOldValue() { return oldValue; } /** {@inheritDoc} */ @SuppressWarnings({ "null", "unchecked" }) @Override public <F extends Field<Byte, F>> F field() { return (F) field; } /** {@inheritDoc} */ @SuppressWarnings({ "boxing", "null" }) @Override public Byte newValue() { return newValue; } /** {@inheritDoc} */ @SuppressWarnings({ "boxing", "null" }) @Override public Byte oldValue() { return oldValue; } /** {@inheritDoc} */ @SuppressWarnings({ "null", "rawtypes" }) @Override public void reverseChange(final Storage theStorage) { theStorage.selectStructure(structIndex); if (field.isOptional()) { theStorage.write((ByteOptionalField) field, oldValue); } else if (field.global()) { theStorage.write((ByteGlobalField) field, oldValue); } else { theStorage.write((ByteField) field, oldValue); } } /** {@inheritDoc} */ @Override public int structureIndex() { return structIndex; } /** updates Byte Value Change holder. * * @param theStructIndex the struct index * @param theField the field * @param theOldValue the old value * @param theNewValue the new value */ @SuppressWarnings({ "unchecked", "rawtypes" }) public void update(final int theStructIndex, final ByteField theField, final byte theOldValue, final byte theNewValue) { structIndex = theStructIndex; field = theField; oldValue = theOldValue; newValue = theNewValue; } /** updates Byte Value Change holder. * * @param theStructIndex the struct index * @param theField the field * @param theOldValue the old value * @param theNewValue the new value */ @SuppressWarnings({ "rawtypes", "unchecked" }) public void update(final int theStructIndex, final ByteGlobalField theField, final byte theOldValue, final byte theNewValue) { structIndex = theStructIndex; field = theField; oldValue = theOldValue; newValue = theNewValue; } /** updates Byte Value Change holder. * * @param theStructIndex the struct index * @param theField the field * @param theOldValue the old value * @param theNewValue the new value */ @SuppressWarnings({ "rawtypes", "unchecked" }) public void update(final int theStructIndex, final ByteOptionalField theField, final byte theOldValue, final byte theNewValue) { structIndex = theStructIndex; field = theField; oldValue = theOldValue; newValue = theNewValue; } }
31.809816
83
0.607522
857df8a45ceec33b18c6b10c61b9db2bb7f4d759
8,607
/* * Copyright (c) 2008-2020, Hazelcast, Inc. All Rights Reserved. * * 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.hazelcast.client.cp.internal.datastructures.atomicref; import com.hazelcast.client.impl.ClientDelegatingFuture; import com.hazelcast.client.impl.protocol.ClientMessage; import com.hazelcast.client.impl.protocol.codec.AtomicRefApplyCodec; import com.hazelcast.client.impl.protocol.codec.AtomicRefCompareAndSetCodec; import com.hazelcast.client.impl.protocol.codec.AtomicRefContainsCodec; import com.hazelcast.client.impl.protocol.codec.AtomicRefGetCodec; import com.hazelcast.client.impl.protocol.codec.AtomicRefSetCodec; import com.hazelcast.client.impl.protocol.codec.CPGroupDestroyCPObjectCodec; import com.hazelcast.client.impl.spi.ClientContext; import com.hazelcast.client.impl.spi.ClientProxy; import com.hazelcast.client.impl.spi.impl.ClientInvocation; import com.hazelcast.client.impl.spi.impl.ClientInvocationFuture; import com.hazelcast.core.IFunction; import com.hazelcast.cp.CPGroupId; import com.hazelcast.cp.IAtomicReference; import com.hazelcast.cp.internal.RaftGroupId; import com.hazelcast.cp.internal.datastructures.atomicref.AtomicRefService; import com.hazelcast.cp.internal.datastructures.atomicref.operation.ApplyOp.ReturnValueType; import com.hazelcast.internal.serialization.Data; import com.hazelcast.spi.impl.InternalCompletableFuture; import static com.hazelcast.cp.internal.datastructures.atomicref.operation.ApplyOp.ReturnValueType.NO_RETURN_VALUE; import static com.hazelcast.cp.internal.datastructures.atomicref.operation.ApplyOp.ReturnValueType.RETURN_NEW_VALUE; import static com.hazelcast.cp.internal.datastructures.atomicref.operation.ApplyOp.ReturnValueType.RETURN_OLD_VALUE; import static com.hazelcast.internal.util.Preconditions.checkTrue; /** * Client-side Raft-based proxy implementation of {@link IAtomicReference} * * @param <T> the type of object referred to by this reference */ @SuppressWarnings("checkstyle:methodcount") public class AtomicRefProxy<T> extends ClientProxy implements IAtomicReference<T> { private final RaftGroupId groupId; private final String objectName; public AtomicRefProxy(ClientContext context, RaftGroupId groupId, String proxyName, String objectName) { super(AtomicRefService.SERVICE_NAME, proxyName, context); this.groupId = groupId; this.objectName = objectName; } @Override public boolean compareAndSet(T expect, T update) { return compareAndSetAsync(expect, update).joinInternal(); } @Override public T get() { return getAsync().joinInternal(); } @Override public void set(T newValue) { setAsync(newValue).joinInternal(); } @Override public T getAndSet(T newValue) { return getAndSetAsync(newValue).joinInternal(); } @Override public boolean isNull() { return isNullAsync().joinInternal(); } @Override public void clear() { clearAsync().joinInternal(); } @Override public boolean contains(T value) { return containsAsync(value).joinInternal(); } @Override public void alter(IFunction<T, T> function) { alterAsync(function).joinInternal(); } @Override public T alterAndGet(IFunction<T, T> function) { return alterAndGetAsync(function).joinInternal(); } @Override public T getAndAlter(IFunction<T, T> function) { return getAndAlterAsync(function).joinInternal(); } @Override public <R> R apply(IFunction<T, R> function) { return applyAsync(function).joinInternal(); } @Override public InternalCompletableFuture<Boolean> compareAndSetAsync(T expect, T update) { Data expectedData = getContext().getSerializationService().toData(expect); Data newData = getContext().getSerializationService().toData(update); ClientMessage request = AtomicRefCompareAndSetCodec.encodeRequest(groupId, objectName, expectedData, newData); ClientInvocationFuture future = new ClientInvocation(getClient(), request, name).invoke(); return new ClientDelegatingFuture<>(future, getSerializationService(), AtomicRefCompareAndSetCodec::decodeResponse); } @Override public InternalCompletableFuture<T> getAsync() { ClientMessage request = AtomicRefGetCodec.encodeRequest(groupId, objectName); ClientInvocationFuture future = new ClientInvocation(getClient(), request, name).invoke(); return new ClientDelegatingFuture<>(future, getSerializationService(), AtomicRefGetCodec::decodeResponse); } @Override public InternalCompletableFuture<Void> setAsync(T newValue) { Data data = getContext().getSerializationService().toData(newValue); ClientMessage request = AtomicRefSetCodec.encodeRequest(groupId, objectName, data, false); ClientInvocationFuture future = new ClientInvocation(getClient(), request, name).invoke(); return new ClientDelegatingFuture<>(future, getSerializationService(), AtomicRefGetCodec::decodeResponse); } @Override public InternalCompletableFuture<T> getAndSetAsync(T newValue) { Data data = getContext().getSerializationService().toData(newValue); ClientMessage request = AtomicRefSetCodec.encodeRequest(groupId, objectName, data, true); ClientInvocationFuture future = new ClientInvocation(getClient(), request, name).invoke(); return new ClientDelegatingFuture<>(future, getSerializationService(), AtomicRefGetCodec::decodeResponse); } @Override public InternalCompletableFuture<Boolean> isNullAsync() { return containsAsync(null); } @Override public InternalCompletableFuture<Void> clearAsync() { return setAsync(null); } @Override public InternalCompletableFuture<Boolean> containsAsync(T expected) { Data data = getContext().getSerializationService().toData(expected); ClientMessage request = AtomicRefContainsCodec.encodeRequest(groupId, objectName, data); ClientInvocationFuture future = new ClientInvocation(getClient(), request, name).invoke(); return new ClientDelegatingFuture<>(future, getSerializationService(), AtomicRefContainsCodec::decodeResponse); } @Override public InternalCompletableFuture<Void> alterAsync(IFunction<T, T> function) { return invokeApply(function, NO_RETURN_VALUE, true); } @Override public InternalCompletableFuture<T> alterAndGetAsync(IFunction<T, T> function) { return invokeApply(function, RETURN_NEW_VALUE, true); } @Override public InternalCompletableFuture<T> getAndAlterAsync(IFunction<T, T> function) { return invokeApply(function, RETURN_OLD_VALUE, true); } @Override public <R> InternalCompletableFuture<R> applyAsync(IFunction<T, R> function) { return invokeApply(function, RETURN_NEW_VALUE, false); } @Override public void onDestroy() { ClientMessage request = CPGroupDestroyCPObjectCodec.encodeRequest(groupId, getServiceName(), objectName); new ClientInvocation(getClient(), request, name).invoke().joinInternal(); } @Override public String getPartitionKey() { throw new UnsupportedOperationException(); } public CPGroupId getGroupId() { return groupId; } private <T2, T3> InternalCompletableFuture<T3> invokeApply(IFunction<T, T2> function, ReturnValueType returnValueType, boolean alter) { checkTrue(function != null, "Function cannot be null"); Data data = getContext().getSerializationService().toData(function); ClientMessage request = AtomicRefApplyCodec.encodeRequest(groupId, objectName, data, returnValueType.value(), alter); ClientInvocationFuture future = new ClientInvocation(getClient(), request, name).invoke(); return new ClientDelegatingFuture<>(future, getSerializationService(), AtomicRefApplyCodec::decodeResponse); } }
40.599057
125
0.738353
10be5582ec6d5ab12cb33218d3f73825789b42c4
18,004
package de.citec.sc.sampling; import de.citec.sc.learning.QueryConstructor; import de.citec.sc.utils.Performance; import de.citec.sc.variable.State; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import evaluation.TaggedTimer; import learning.AdvancedLearner.TrainingTriple; import learning.Learner; import learning.Model; import learning.ObjectiveFunction; import learning.scorer.Scorer; import sampling.Explorer; import sampling.IBeamSearchSampler; import sampling.samplingstrategies.AcceptStrategies; import sampling.samplingstrategies.AcceptStrategy; import sampling.samplingstrategies.BeamSearchSamplingStrategies; import sampling.samplingstrategies.BeamSearchSamplingStrategy; import sampling.samplingstrategies.BeamSearchSamplingStrategy.StatePair; import sampling.stoppingcriterion.BeamSearchStoppingCriterion; import utility.Utils; import variables.AbstractState; public class QABeamSearchSampler<InstanceT, StateT extends AbstractState<InstanceT>, ResultT> implements IBeamSearchSampler<StateT, ResultT> { public interface StepCallback { default <InstanceT, StateT extends AbstractState<InstanceT>> void onStartStep( QABeamSearchSampler<InstanceT, StateT, ?> sampler, int step, int e, int numberOfExplorers, List<StateT> initialStates) { } default <InstanceT, StateT extends AbstractState<InstanceT>> void onEndStep( QABeamSearchSampler<InstanceT, StateT, ?> sampler, int step, int e, int numberOfExplorers, List<StateT> initialStates, List<StateT> currentState) { } } protected static Logger log = LogManager.getFormatterLogger(); protected Model<InstanceT, StateT> model; protected Scorer scorer; protected ObjectiveFunction<StateT, ResultT> objective; protected List<Explorer<StateT>> explorers; protected BeamSearchStoppingCriterion<StateT> stoppingCriterion; protected static int DEFAULT_BEAM_SIZE = 10; protected final boolean multiThreaded = false; protected int stepsBetweenTraining = 1; /** * Defines the sampling strategy for the training phase. The test phase * currently always uses the greedy variant. */ private BeamSearchSamplingStrategy<StateT> trainSamplingStrategy = BeamSearchSamplingStrategies .greedyBeamSearchSamplingStrategyByObjective(DEFAULT_BEAM_SIZE, s -> s.getObjectiveScore()); private AcceptStrategy<StateT> trainAcceptStrategy = AcceptStrategies.objectiveAccept(); /** * Greedy sampling strategy for test phase. */ private BeamSearchSamplingStrategy<StateT> testSamplingStrategy = BeamSearchSamplingStrategies .greedyBeamSearchSamplingStrategyByModel(DEFAULT_BEAM_SIZE, s -> s.getModelScore()); /** * Strict accept strategy for test phase. */ private AcceptStrategy<StateT> testAcceptStrategy = AcceptStrategies.strictModelAccept(); private List<StepCallback> stepCallbacks = new ArrayList<>(); public List<StepCallback> getStepCallbacks() { return stepCallbacks; } public void addStepCallbacks(List<StepCallback> stepCallbacks) { this.stepCallbacks.addAll(stepCallbacks); } public void addStepCallback(StepCallback stepCallback) { this.stepCallbacks.add(stepCallback); } /** * The DefaultSampler implements the Sampler interface. This sampler divides * the sampling procedure in the exploration of the search space (using * Explorers) and the actual sampling that happens in this class. It is * designed to be flexible in the actual sampling strategy and the stopping * criterion. * * @param model * @param scorer * @param objective * @param explorers * @param stoppingCriterion */ public QABeamSearchSampler(Model<InstanceT, StateT> model, ObjectiveFunction<StateT, ResultT> objective, List<Explorer<StateT>> explorers, BeamSearchStoppingCriterion<StateT> stoppingCriterion) { super(); this.model = model; this.objective = objective; this.explorers = explorers; this.stoppingCriterion = stoppingCriterion; } @Override public List<List<StateT>> generateChain(List<StateT> initialStates, ResultT goldResult, Learner<StateT> learner) { List<List<StateT>> generatedChain = new ArrayList<>(); List<StateT> currentStates = new ArrayList<>(); currentStates.addAll(initialStates); int step = 0; do { log.info("---------------------------"); int e = 0; for (Explorer<StateT> explorer : explorers) { log.info("..............."); log.info("TRAINING Step: %s; Explorer: %s", step + 1, explorer.getClass().getSimpleName()); log.info("Current states : %s", currentStates.size()); for (StepCallback c : stepCallbacks) { c.onStartStep(this, step, e, explorers.size(), initialStates); } if (step % stepsBetweenTraining == 0) { currentStates = performTrainingStep(learner, explorer, goldResult, currentStates); } else { currentStates = performPredictionStep(explorer, currentStates); } generatedChain.add(currentStates); for (StepCallback c : stepCallbacks) { c.onEndStep(this, step, e, explorers.size(), initialStates, currentStates); } e++; } step++; } while (!stoppingCriterion.checkCondition(generatedChain, step)); log.info("\n\nStop sampling after step %s", step); //loop over generated chain and check if any state has 1.0 as objective score List<StateT> lastChain = generatedChain.get(generatedChain.size() - 1); //get the highest scoring state StateT finalState = lastChain.stream().max((s1, s2) -> Double.compare(s1.getObjectiveScore(), s2.getObjectiveScore())).get(); State s = (State) finalState; if (s.getObjectiveScore() == 1.0) { Performance.addParsed(s.getDocument().getQuestionString(), s.getDocument().getGoldQueryString()); } else { String q = s.toString() + "\n\nScore: " + s.getObjectiveScore() + "\n\nQuery:" + QueryConstructor.getSPARQLQuery(s) + "\n" + "================================================================================================================\n"; Performance.addUnParsed(s.getDocument().getQuestionString(), q); } return generatedChain; } @Override public List<List<StateT>> generateChain(List<StateT> initialStates) { List<List<StateT>> generatedChain = new ArrayList<>(); List<StateT> currentStates = new ArrayList<>(); currentStates.addAll(initialStates); int step = 0; do { log.info("---------------------------"); int e = 0; for (Explorer<StateT> explorer : explorers) { log.info("..............."); log.info("PREDICTION Step: %s; Explorer: %s", step + 1, explorer.getClass().getSimpleName()); for (StepCallback c : stepCallbacks) { c.onStartStep(this, step, e, explorers.size(), initialStates); } currentStates = performPredictionStep(explorer, currentStates); log.info("States# " + currentStates.size()); generatedChain.add(currentStates); for (StepCallback c : stepCallbacks) { c.onEndStep(this, step, e, explorers.size(), initialStates, currentStates); } e++; } step++; } while (!stoppingCriterion.checkCondition(generatedChain, step)); log.info("\n\nStop sampling after step %s", step); return generatedChain; } /** * Generates states, computes features, scores states, and updates the * model. After that a successor state is selected. * * @param learner * @param explorer * @param goldResult * @param currentState * @return */ protected List<StateT> performTrainingStep(Learner<StateT> learner, Explorer<StateT> explorer, ResultT goldResult, List<StateT> currentStates) { log.debug("TRAINING Step:"); Map<Integer, List<StateT>> mapStates = new HashMap<>(); int c = 0; List<StateT> allStates = new ArrayList<>(currentStates); List<StatePair<StateT>> allNextStatePairs = new ArrayList<>(); Map<StateT, List<StateT>> allStateWithParent = new HashMap<>(); for (StateT currentState : currentStates) { /** * Generate possible successor states. */ List<StateT> nextStates = explorer.getNextStates(currentState); mapStates.put(c, nextStates); allStateWithParent.put(currentState, nextStates); allStates.addAll(nextStates); allNextStatePairs.addAll( nextStates.stream().map(s -> new StatePair<>(currentState, s)).collect(Collectors.toList())); c++; } /** * Score all states with Objective/Model only if sampling strategy needs * that. If not, score only selected candidate and current. */ if (trainSamplingStrategy.usesObjective()) { /** * Compute objective function scores */ scoreWithObjective(allStates, goldResult); } if (trainSamplingStrategy.usesModel()) { /** * Apply templates to states and, thus generate factors and features */ for (StateT currentState : allStateWithParent.keySet()) { model.score(allStateWithParent.get(currentState), currentState.getInstance()); } // model.score(allStates, currentStates.get(0).getInstance()); } /** * Sample one possible successor */ List<StatePair<StateT>> candidateStatePairs = trainSamplingStrategy .sampleCandidate(new ArrayList<>(allNextStatePairs)); List<StateT> candidateStates = candidateStatePairs.stream().map(p -> p.getCandidateState()) .collect(Collectors.toList()); /** * If states were not scored before score only selected candidate and * current state. */ if (!trainSamplingStrategy.usesObjective()) { /** * Compute objective function scores */ scoreWithObjective(candidateStates, goldResult); } if (!trainSamplingStrategy.usesModel()) { /** * Apply templates to current and candidate state only */ List<StateT> scoredStates = new ArrayList<>(); scoredStates.addAll(currentStates); scoredStates.addAll(candidateStates); model.score(scoredStates, scoredStates.get(0).getInstance()); } /** * Update model with selected state */ // StatePair<StateT> best = candidateStatePairs.stream().max((s1, s2) -> // Double // .compare(s1.getCandidateState().getModelScore(), // s2.getCandidateState().getModelScore())).get(); // learner.update(best.getParentState(), best.getCandidateState()); List<TrainingTriple<StateT>> trainingTriples = candidateStatePairs.stream() .map(p -> new TrainingTriple<>(p.getParentState(), p.getCandidateState(), 1.0)) .collect(Collectors.toList()); // for (StatePair<StateT> candidateStatePair : candidateStatePairs) { // StateT candidateState = candidateStatePair.getCandidateState(); // StateT currentState = candidateStatePair.getParentState(); learner.update(trainingTriples); // } Set<StateT> acceptedStates = new HashSet<>(); for (StatePair<StateT> candidateStatePair : candidateStatePairs) { StateT candidateState = candidateStatePair.getCandidateState(); StateT currentState = candidateStatePair.getParentState(); StateT acceptedState = trainAcceptStrategy.isAccepted(candidateState, currentState) ? candidateState : currentState; acceptedStates.add(acceptedState); } if (acceptedStates.isEmpty()) { acceptedStates.add(currentStates.get(0)); } return new ArrayList<>(acceptedStates); } /** * Generates states, computes features and scores states. After that a * successor state is selected. * * @param explorer * @param currentState * @return */ protected List<StateT> performPredictionStep(Explorer<StateT> explorer, List<StateT> currentStates) { log.debug("PREDICTION:"); Map<Integer, List<StateT>> mapStates = new HashMap<>(); int c = 0; List<StateT> allStates = new ArrayList<>(currentStates); List<StatePair<StateT>> allNextStatePairs = new ArrayList<>(); Map<StateT, List<StateT>> allStateWithParent = new HashMap<>(); for (StateT currentState : currentStates) { /** * Generate possible successor states. */ List<StateT> nextStates = explorer.getNextStates(currentState); mapStates.put(c, nextStates); allStateWithParent.put(currentState, nextStates); allStates.addAll(nextStates); allNextStatePairs.addAll( nextStates.stream().map(s -> new StatePair<>(currentState, s)).collect(Collectors.toList())); c++; } /** * Score all states with Objective/Model only if sampling strategy needs * that. If not, score only selected candidate and current. */ /** * Apply templates to states and, thus generate factors and features */ for (StateT currentState : allStateWithParent.keySet()) { model.score(allStateWithParent.get(currentState), currentState.getInstance()); } // model.score(allStates, currentStates.get(0).getInstance()); /** * Sample one possible successor */ List<StatePair<StateT>> candidateStatePairs = testSamplingStrategy .sampleCandidate(new ArrayList<>(allNextStatePairs)); /** * Update model with selected state */ Set<StateT> acceptedStates = new HashSet<>(); for (StatePair<StateT> candidateStatePair : candidateStatePairs) { StateT candidateState = candidateStatePair.getCandidateState(); StateT currentState = candidateStatePair.getParentState(); StateT acceptedState = testAcceptStrategy.isAccepted(candidateState, currentState) ? candidateState : currentState; acceptedStates.add(acceptedState); } if (acceptedStates.isEmpty()) { acceptedStates.addAll(currentStates); } return new ArrayList<>(acceptedStates); } /** * Computes the objective scores for each of the given states. The * <i>multiThreaded</i> flag determines if the computation is performed in * parallel or sequentially. * * @param goldResult * @param currentState * @param nextStates */ protected void scoreWithObjective(List<StateT> allStates, ResultT goldResult) { long scID = TaggedTimer.start("OBJ-SCORE"); log.debug("Score %s states according to objective...", allStates.size() + 1); Stream<StateT> stream = Utils.getStream(allStates, multiThreaded); stream.forEach(s -> objective.score(s, goldResult)); TaggedTimer.stop(scID); } protected Model<?, StateT> getModel() { return model; } protected Scorer getScorer() { return scorer; } public BeamSearchStoppingCriterion<StateT> getStoppingCriterion() { return stoppingCriterion; } /** * Set the stopping criterion for the sampling chain. This function can be * used to change the stopping criterion for the test phase. * * @param stoppingCriterion */ public void setStoppingCriterion(BeamSearchStoppingCriterion<StateT> stoppingCriterion) { this.stoppingCriterion = stoppingCriterion; } /** * Sets the sampling strategy for the training phase. The candidate state * that is used for training is selected from all possible successor states * using this strategy. * * @param samplingStrategy */ public void setTrainSamplingStrategy(BeamSearchSamplingStrategy<StateT> samplingStrategy) { this.trainSamplingStrategy = samplingStrategy; } public void setTestSamplingStrategy(BeamSearchSamplingStrategy<StateT> samplingStrategy) { this.testSamplingStrategy = samplingStrategy; } /** * Sets the strategy for accepting a sampled candidate state as the next * state in the training phase. * * @return */ public void setTrainAcceptStrategy(AcceptStrategy<StateT> acceptStrategy) { this.trainAcceptStrategy = acceptStrategy; } public void setTestAcceptStrategy(AcceptStrategy<StateT> acceptStrategy) { this.testAcceptStrategy = acceptStrategy; } public List<Explorer<StateT>> getExplorers() { return explorers; } public void setExplorers(List<Explorer<StateT>> explorers) { this.explorers = explorers; } }
38.225053
139
0.63297
dbceb3d439f34e1d4c555d73406895c42b38812a
5,353
/* * Copyright 2016-2017 Davide Steduto * * 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 eu.davidea.flexibleadapter.items; import androidx.recyclerview.widget.RecyclerView; import android.view.View; import java.util.List; import eu.davidea.flexibleadapter.FlexibleAdapter; /** * Generic implementation of {@link IFlexible} interface with most useful methods to manage * selection and view holder methods. * * @param <VH> {@link RecyclerView.ViewHolder} * @author Davide Steduto * @since 20/01/2016 Created * <br>21/04/2017 ViewHolders methods are now abstract * <br>08/12/2017 New callback methods when view is attached/detached/recycled * <br>22/04/2018 Item is born with draggable and swipeable enabled */ @SuppressWarnings("WeakerAccess") public abstract class AbstractFlexibleItem<VH extends RecyclerView.ViewHolder> implements IFlexible<VH> { /* Item flags recognized by the FlexibleAdapter */ protected boolean mEnabled = true, mHidden = false, mSelectable = true, mDraggable = true, mSwipeable = true; /*---------------*/ /* BASIC METHODS */ /*---------------*/ /** * You <b>MUST</b> implement this method to compare items <b>unique</b> identifiers. * <p>Adapter needs this method to distinguish them and pick up correct items.</p> * See <a href="http://developer.android.com/reference/java/lang/Object.html#equals(java.lang.Object)"> * Writing a correct {@code equals} method</a> to implement your own {@code equals} method. * <p><b>Hint:</b> If you don't use unique IDs, reimplement with Basic Java implementation: * <pre> * public boolean equals(Object o) { * return this == o; * }</pre></p> * <p><b>Important Note:</b> When used with {@code Hash[Map,Set]}, the general contract for the * {@code equals} and {@link #hashCode()} methods is that if {@code equals} returns {@code true} * for any two objects, then {@code hashCode()} must return the same value for these objects. * This means that subclasses of {@code Object} usually override either both methods or neither * of them.</p> * * @param o instance to compare * @return true if items are equals, false otherwise. */ @Override public abstract boolean equals(Object o); @Override public boolean isEnabled() { return mEnabled; } @Override public void setEnabled(boolean enabled) { mEnabled = enabled; } @Override public boolean isHidden() { return mHidden; } @Override public void setHidden(boolean hidden) { mHidden = hidden; } @Override public int getSpanSize(int spanCount, int position) { return 1; } @Override public boolean shouldNotifyChange(IFlexible newItem) { return true; } /*--------------------*/ /* SELECTABLE METHODS */ /*--------------------*/ @Override public boolean isSelectable() { return mSelectable; } @Override public void setSelectable(boolean selectable) { this.mSelectable = selectable; } @Override public String getBubbleText(int position) { return String.valueOf(position + 1); } /*-------------------*/ /* TOUCHABLE METHODS */ /*-------------------*/ @Override public boolean isDraggable() { return mDraggable; } @Override public void setDraggable(boolean draggable) { mDraggable = draggable; } @Override public boolean isSwipeable() { return mSwipeable; } @Override public void setSwipeable(boolean swipeable) { mSwipeable = swipeable; } /*---------------------*/ /* VIEW HOLDER METHODS */ /*---------------------*/ /** * {@inheritDoc} * <p>If not overridden return value is the same of {@link #getLayoutRes()}.</p> */ @Override public int getItemViewType() { return getLayoutRes(); } /** * {@inheritDoc} */ @Override public abstract int getLayoutRes(); /** * {@inheritDoc} */ @Override public abstract VH createViewHolder(View view, FlexibleAdapter<IFlexible> adapter); /** * {@inheritDoc} */ @Override public abstract void bindViewHolder(FlexibleAdapter<IFlexible> adapter, VH holder, int position, List<Object> payloads); /** * {@inheritDoc} */ @Override public void unbindViewHolder(FlexibleAdapter<IFlexible> adapter, VH holder, int position) { } /** * {@inheritDoc} */ @Override public void onViewAttached(FlexibleAdapter<IFlexible> adapter, VH holder, int position) { } /** * {@inheritDoc} */ @Override public void onViewDetached(FlexibleAdapter<IFlexible> adapter, VH holder, int position) { } }
27.451282
124
0.634411
b0a68a1dad880bba9a8cabc1ceeed4a856d3c0d0
4,474
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.camel.test.jsonvalidator; import java.io.File; import java.nio.file.Paths; import org.apache.camel.CamelContext; import org.apache.camel.Exchange; import org.apache.camel.ProducerTemplate; import org.apache.camel.ValidationException; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.impl.DefaultCamelContext; import org.apache.camel.util.FileUtil; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.wildfly.camel.test.common.utils.FileUtils; import org.wildfly.extension.camel.CamelAware; @CamelAware @RunWith(Arquillian.class) public class JsonValidatorIntegrationTest { @Deployment public static JavaArchive deployment() { final JavaArchive archive = ShrinkWrap.create(JavaArchive.class, "json-validator-tests"); archive.addAsResource("jsonvalidator/schema.json"); archive.addClasses(FileUtils.class); return archive; } @Before public void setUp() throws Exception { FileUtils.deleteDirectory(Paths.get("target/validator")); } @Test public void testValidMessage() throws Exception { CamelContext camelctx = new DefaultCamelContext(); camelctx.addRoutes(new RouteBuilder() { public void configure() throws Exception { from("file:target/validator?noop=true") .to("json-validator:jsonvalidator/schema.json") .to("mock:valid"); } }); MockEndpoint mockValid = camelctx.getEndpoint("mock:valid", MockEndpoint.class); mockValid.expectedMessageCount(1); camelctx.start(); try { ProducerTemplate template = camelctx.createProducerTemplate(); template.sendBodyAndHeader("file:target/validator", "{ \"name\": \"Joe Doe\", \"id\": 1, \"price\": 12.5 }", Exchange.FILE_NAME, "valid.json"); mockValid.assertIsSatisfied(); Assert.assertTrue("Can delete the file", FileUtil.deleteFile(new File("target/validator/valid.json"))); } finally { camelctx.close(); } } @Test public void testInvalidMessage() throws Exception { CamelContext camelctx = new DefaultCamelContext(); camelctx.addRoutes(new RouteBuilder() { public void configure() throws Exception { from("file:target/validator?noop=true") .doTry() .to("json-validator:jsonvalidator/schema.json") .doCatch(ValidationException.class) .to("mock:invalid") .end(); } }); MockEndpoint mockInvalid = camelctx.getEndpoint("mock:invalid", MockEndpoint.class); mockInvalid.expectedMessageCount(1); camelctx.start(); try { ProducerTemplate template = camelctx.createProducerTemplate(); template.sendBodyAndHeader("file:target/validator", "{ \"name\": \"Joe Doe\", \"id\": \"AA1\", \"price\": 12.5 }", Exchange.FILE_NAME, "invalid.json"); mockInvalid.assertIsSatisfied(); Assert.assertTrue("Can delete the file", FileUtil.deleteFile(new File("target/validator/invalid.json"))); } finally { camelctx.close(); } } }
36.080645
117
0.662494
699da5bef0c1b20d9903b9358e1b97b7579eed48
5,340
/* * Copyright © 2018 Apple Inc. and the ServiceTalk project 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 io.servicetalk.http.api; import io.servicetalk.buffer.api.Buffer; /** * <a href="https://tools.ietf.org/html/rfc7231#section-6">Response Status Code</a>. */ public interface HttpResponseStatus { /** * Get the three digit <a href="https://tools.ietf.org/html/rfc7231#section-6">status-code</a> indicating status of the response. * @return the three digit <a href="https://tools.ietf.org/html/rfc7231#section-6">status-code</a> indicating status of the response. */ int getCode(); /** * Write the equivalent of {@link #getCode()} to a {@link Buffer}. * @param buffer The {@link Buffer} to write to. */ void writeCodeTo(Buffer buffer); /** * Write the <a href="https://tools.ietf.org/html/rfc7230.html#section-3.1.2">reason-phrase</a> portion of the * response to a {@link Buffer}. * <pre> * The reason-phrase element exists for the sole purpose of providing a * textual description associated with the numeric status code, mostly * out of deference to earlier Internet application protocols that were * more frequently used with interactive text clients. A client SHOULD * ignore the reason-phrase content. * </pre> * @param buffer The {@link Buffer} to write to. */ void writeReasonPhraseTo(Buffer buffer); /** * Get the {@link StatusClass} for this {@link HttpResponseStatus}. * @return the {@link StatusClass} for this {@link HttpResponseStatus}. */ StatusClass getStatusClass(); /** * The <a href="https://tools.ietf.org/html/rfc7231#section-6">class of response</a>. */ enum StatusClass { /** * <a href="https://tools.ietf.org/html/rfc7231#section-6.2">1xx Informational responses</a>. */ INFORMATIONAL_1XX(100, 199), /** * <a href="https://tools.ietf.org/html/rfc7231#section-6.3">2xx Success</a>. */ SUCCESS_2XX(200, 299), /** * <a href="https://tools.ietf.org/html/rfc7231#section-6.4">3xx Redirection</a>. */ REDIRECTION_3XX(300, 399), /** * <a href="https://tools.ietf.org/html/rfc7231#section-6.5">4xx Client errors</a>. */ CLIENT_ERROR_4XX(400, 499), /** * <a href="https://tools.ietf.org/html/rfc7231#section-6.6">5xx Server errors</a>. */ SERVER_ERROR_5XX(500, 599), /** * Unknown. Statuses outside of the <a href="https://tools.ietf.org/html/rfc7231#section-6">defined range of * response codes</a>. */ UNKNOWN(0, 0) { @Override public boolean contains(final int statusCode) { return statusCode < 100 || statusCode >= 600; } }; private final int minStatus; private final int maxStatus; StatusClass(final int minStatus, final int maxStatus) { this.minStatus = minStatus; this.maxStatus = maxStatus; } /** * Determine if {@code code} falls into this class. * @param statusCode the status code to test. * @return {@code true} if and only if the specified HTTP status code falls into this class. */ public boolean contains(final int statusCode) { return minStatus <= statusCode && statusCode <= maxStatus; } /** * Determine if {@code status} code falls into this class. * @param status the status to test. * @return {@code true} if and only if the specified HTTP status code falls into this class. */ public boolean contains(final HttpResponseStatus status) { return contains(status.getCode()); } /** * Determines the {@link StatusClass} from the {@code statusCode}. * * @param statusCode the status code to use for determining the {@link StatusClass}. * @return One of the {@link StatusClass} enum values. */ public static StatusClass toStatusClass(final int statusCode) { if (INFORMATIONAL_1XX.contains(statusCode)) { return INFORMATIONAL_1XX; } if (SUCCESS_2XX.contains(statusCode)) { return SUCCESS_2XX; } if (REDIRECTION_3XX.contains(statusCode)) { return REDIRECTION_3XX; } if (CLIENT_ERROR_4XX.contains(statusCode)) { return CLIENT_ERROR_4XX; } if (SERVER_ERROR_5XX.contains(statusCode)) { return SERVER_ERROR_5XX; } return UNKNOWN; } } }
36.081081
137
0.604494
db3a2a8a47bf0fd02fc7bde11a68851ff4cb2659
9,198
/* * AbstractClusterer.java * Copyright (C) 2009 University of Waikato, Hamilton, New Zealand * @author Albert Bifet (abifet@cs.waikato.ac.nz) * * 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 <http://www.gnu.org/licenses/>. * */ package moa.clusterers; import java.util.LinkedList; import java.util.List; import java.util.Random; import moa.cluster.Clustering; import com.yahoo.labs.samoa.instances.InstancesHeader; import moa.core.Measurement; import moa.core.ObjectRepository; import moa.core.StringUtils; import moa.gui.AWTRenderer; import moa.options.AbstractOptionHandler; import com.github.javacliparser.FlagOption; import com.github.javacliparser.IntOption; import moa.tasks.TaskMonitor; import com.yahoo.labs.samoa.instances.Instance; import com.yahoo.labs.samoa.instances.Instances; public abstract class AbstractClusterer extends AbstractOptionHandler implements Clusterer { @Override public String getPurposeString() { return "MOA Clusterer: " + getClass().getCanonicalName(); } protected InstancesHeader modelContext; protected double trainingWeightSeenByModel = 0.0; protected int randomSeed = 1; protected IntOption randomSeedOption; public FlagOption evaluateMicroClusteringOption; protected Random clustererRandom; protected Clustering clustering; public AbstractClusterer() { if (isRandomizable()) { this.randomSeedOption = new IntOption("randomSeed", 'r', "Seed for random behaviour of the Clusterer.", 1); } if( implementsMicroClusterer()){ this.evaluateMicroClusteringOption = new FlagOption("evaluateMicroClustering", 'M', "Evaluate the underlying microclustering instead of the macro clustering"); } } @Override public void prepareForUseImpl(TaskMonitor monitor, ObjectRepository repository) { if (this.randomSeedOption != null) { this.randomSeed = this.randomSeedOption.getValue(); } if (!trainingHasStarted()) { resetLearning(); } clustering = new Clustering(); } public void setModelContext(InstancesHeader ih) { if ((ih != null) && (ih.classIndex() < 0)) { throw new IllegalArgumentException( "Context for a Clusterer must include a class to learn"); } if (trainingHasStarted() && (this.modelContext != null) && ((ih == null) || !contextIsCompatible(this.modelContext, ih))) { throw new IllegalArgumentException( "New context is not compatible with existing model"); } this.modelContext = ih; } public InstancesHeader getModelContext() { return this.modelContext; } public void setRandomSeed(int s) { this.randomSeed = s; if (this.randomSeedOption != null) { // keep option consistent this.randomSeedOption.setValue(s); } } public boolean trainingHasStarted() { return this.trainingWeightSeenByModel > 0.0; } public double trainingWeightSeenByModel() { return this.trainingWeightSeenByModel; } public void resetLearning() { this.trainingWeightSeenByModel = 0.0; if (isRandomizable()) { this.clustererRandom = new Random(this.randomSeed); } resetLearningImpl(); } public void trainOnInstance(Instance inst) { if (inst.weight() > 0.0) { this.trainingWeightSeenByModel += inst.weight(); trainOnInstanceImpl(inst); } } public Measurement[] getModelMeasurements() { List<Measurement> measurementList = new LinkedList<Measurement>(); measurementList.add(new Measurement("model training instances", trainingWeightSeenByModel())); measurementList.add(new Measurement("model serialized size (bytes)", measureByteSize())); Measurement[] modelMeasurements = getModelMeasurementsImpl(); if (modelMeasurements != null) { for (Measurement measurement : modelMeasurements) { measurementList.add(measurement); } } // add average of sub-model measurements Clusterer[] subModels = getSubClusterers(); if ((subModels != null) && (subModels.length > 0)) { List<Measurement[]> subMeasurements = new LinkedList<Measurement[]>(); for (Clusterer subModel : subModels) { if (subModel != null) { subMeasurements.add(subModel.getModelMeasurements()); } } Measurement[] avgMeasurements = Measurement .averageMeasurements(subMeasurements .toArray(new Measurement[subMeasurements.size()][])); for (Measurement measurement : avgMeasurements) { measurementList.add(measurement); } } return measurementList.toArray(new Measurement[measurementList.size()]); } public void getDescription(StringBuilder out, int indent) { StringUtils.appendIndented(out, indent, "Model type: "); out.append(this.getClass().getName()); StringUtils.appendNewline(out); Measurement.getMeasurementsDescription(getModelMeasurements(), out, indent); StringUtils.appendNewlineIndented(out, indent, "Model description:"); StringUtils.appendNewline(out); if (trainingHasStarted()) { getModelDescription(out, indent); } else { StringUtils.appendIndented(out, indent, "Model has not been trained."); } } public Clusterer[] getSubClusterers() { return null; } @Override public Clusterer copy() { return (Clusterer) super.copy(); } // public boolean correctlyClassifies(Instance inst) { // return Utils.maxIndex(getVotesForInstance(inst)) == (int) inst // .classValue(); // } public String getClassNameString() { return InstancesHeader.getClassNameString(this.modelContext); } public String getClassLabelString(int classLabelIndex) { return InstancesHeader.getClassLabelString(this.modelContext, classLabelIndex); } public String getAttributeNameString(int attIndex) { return InstancesHeader.getAttributeNameString(this.modelContext, attIndex); } public String getNominalValueString(int attIndex, int valIndex) { return InstancesHeader.getNominalValueString(this.modelContext, attIndex, valIndex); } // originalContext notnull // newContext notnull public static boolean contextIsCompatible(InstancesHeader originalContext, InstancesHeader newContext) { // rule 1: num classes can increase but never decrease // rule 2: num attributes can increase but never decrease // rule 3: num nominal attribute values can increase but never decrease // rule 4: attribute types must stay in the same order (although class // can // move; is always skipped over) // attribute names are free to change, but should always still represent // the original attributes if (newContext.numClasses() < originalContext.numClasses()) { return false; // rule 1 } if (newContext.numAttributes() < originalContext.numAttributes()) { return false; // rule 2 } int oPos = 0; int nPos = 0; while (oPos < originalContext.numAttributes()) { if (oPos == originalContext.classIndex()) { oPos++; if (!(oPos < originalContext.numAttributes())) { break; } } if (nPos == newContext.classIndex()) { nPos++; } if (originalContext.attribute(oPos).isNominal()) { if (!newContext.attribute(nPos).isNominal()) { return false; // rule 4 } if (newContext.attribute(nPos).numValues() < originalContext .attribute(oPos).numValues()) { return false; // rule 3 } } else { assert (originalContext.attribute(oPos).isNumeric()); if (!newContext.attribute(nPos).isNumeric()) { return false; // rule 4 } } oPos++; nPos++; } return true; // all checks clear } public AWTRenderer getAWTRenderer() { // TODO should return a default renderer here // - or should null be interpreted as the default? return null; } // reason for ...Impl methods: // ease programmer burden by not requiring them to remember calls to super // in overridden methods & will produce compiler errors if not overridden public abstract void resetLearningImpl(); public abstract void trainOnInstanceImpl(Instance inst); protected abstract Measurement[] getModelMeasurementsImpl(); public abstract void getModelDescription(StringBuilder out, int indent); protected static int modelAttIndexToInstanceAttIndex(int index, Instance inst) { return inst.classIndex() > index ? index : index + 1; } protected static int modelAttIndexToInstanceAttIndex(int index, Instances insts) { return insts.classIndex() > index ? index : index + 1; } public boolean implementsMicroClusterer(){ return false; } public boolean keepClassLabel(){ return false; } public Clustering getMicroClusteringResult(){ return null; }; }
30.157377
95
0.713416
9c105d21102cf40bf6898c9bb22f195b2ac9c4a4
630
package tp.pr5.control; import java.util.Scanner; import tp.pr5.Resources.Counter; import tp.pr5.logic.Connect4Move; import tp.pr5.logic.Connect4Rules; import tp.pr5.logic.GameRules; import tp.pr5.logic.Move; public class Connect4Factory implements GameTypeFactory { public GameRules createRules() { return new Connect4Rules(); } public Move createMove(int col, int row, Counter colour) { return new Connect4Move(col, colour); } public Player createHumanPlayerAtConsole(Scanner in) { return new HumanPlayer(false, in, this); } public Player createRandomPlayer() { return new RandomConnect4Player(); } }
21
59
0.761905
ba8413d0fa35b79588ed695efc7d7faf967628ff
5,390
package Pokemons; import java.io.Serializable; import java.util.List; import Pokemons.Type.Types; public class Pokemon implements Serializable { private static final long serialVersionUID = -2280764990854534879L; public String name; public Species species; public int Health; public StatusEffects statuseffect; public List<Types> type; public List<Move> moves; public int level; public int HP = 0; public int EVHP = 0; public int IVHP; public int ATTACK = 0; public int XATT = 0; public int EVATT = 0; public int IVATT; public int DEFENCE = 0; public int XDEF = 0; public int EVDEF = 0; public int IVDEF; public int SATTACK = 0; public int XSATT = 0; public int EVSATT = 0; public int IVSATT; public int SDEFENCE = 0; public int XSDEF = 0; public int EVSDEF = 0; public int IVSDEF; public int SPEED = 0; public int XSPD = 0; public int EVSPD = 0; public int IVSPD; public int XACC = 0; public int XEVA = 0; public int XSTATPRCT = 0; public int XCRIT = 0; public int[] basestats; public Pokemon(Species species, int level) { this.name = species.toString(); this.species = species; this.type = Type.getPokemonTypes(species); this.level = level; setIVs(); setStats(); setXStats(); this.Health = this.HP; this.statuseffect = StatusEffects.None; moves = Move.getMoves(species, level); } public void setIVs() { IVHP = (int) (Math.random()*32); IVATT = (int) (Math.random()*32); IVDEF = (int) (Math.random()*32); IVSATT = (int) (Math.random()*32); IVSDEF = (int) (Math.random()*32); IVSPD = (int) (Math.random()*32); } public void setStats() { this.basestats = Stats.getBaseStats(species); this.HP += Stats.getHP(basestats[0],IVHP,HP,EVHP,level); this.ATTACK += Stats.getStat(basestats[1],IVATT,ATTACK,EVATT,level); this.DEFENCE += Stats.getStat(basestats[2],IVDEF,DEFENCE,EVDEF,level); this.SATTACK += Stats.getStat(basestats[3],IVSATT,SATTACK,EVSATT,level); this.SDEFENCE += Stats.getStat(basestats[4],IVSDEF,SDEFENCE,EVSDEF,level); this.SPEED += Stats.getStat(basestats[5],IVSPD,SPEED,EVSPD,level); } public void setXStats() { XATT = ATTACK; XDEF = DEFENCE; XSATT = SATTACK; XSDEF = SDEFENCE; XSPD = SPEED; XACC = 0; XEVA = 0; XCRIT = 0; XSTATPRCT = 0; } public void levelUp() { if (level < 100) { level++; evolve(null); setStats(); System.out.println(" HP ATK DEF SAT SDE SPD"); System.out.println("Stats: " + HP + " " + ATTACK + " " + DEFENCE + " " + SATTACK + " " + SDEFENCE + " " + SPEED); System.out.println("Basestats: " + basestats[0] + " " + basestats[1] + " " + basestats[2] + " " + basestats[3] + " " + basestats[4] + " " + basestats[5]); } } public void evolve(Items.MiscItem item) { Species species1 = species; species = Evolve.checkEvolve(species, level, item); this.type = Type.getPokemonTypes(species); if (name == species1.toString()) { name = species.toString(); } setStats(); } public enum Species { Bulbasaur(1), Ivysaur(2), Venusaur(3), Charmander(4), Charmeleon(5), Charizard(6), Squirtle(7), Wartortle(8), Blastiose(9), Caterpie(10), Metapod(11), Butterfree(12), Weedle(13), Kakuna(14), Beedrill(15), Pidgey(16), Pidgeotto(17), Pidgeot(18), Rattata(19), Raticate(20), Spearow(21), Fearow(22), Ekans(23), Arbok(24), Pikachu(25), Raichu(26), Sandshrew(27), Sandslash(28), NidoranFemale(29), Nidorina(30), Nidoqueen(31), NidoranMale(32), Nidorino(33), Nidoking(34), Clefairy(35), Clefable(36), Vulpix(37), Ninetales(38), Jigglypuff(39), Wigglytuff(40), Zubat(41), Golbat(42), Oddish(43), Gloom(44), Vileplume(45), Paras(46), Parasect(47), Venonat(48), Venomoth(49), Diglett(50), Dugtrio(51), Meowth(52), Persian(53), Psyduck(54), Golduck(55), Mankey(56), Primeape(57), Growlithe(58), Arcanine(59), Poliwag(60), Poliwhirl(61), Poliwrath(62), Abra(63), Kadabra(64), Alakazam(65), Machop(66), Machoke(67), Machamp(68), Bellsprout(69), Weepinbell(70), Victreebel(71), Tentacool(72), Tentacruel(73), Geodude(74), Graveler(75), Golem(76), Ponyta(77), Rapidash(78), Slowpoke(79), Slowbro(80), Magnemite(81), Magneton(82), Farfetchd(83), Doduo(84), Dodrio(85), Seel(86), Dewgong(87), Grimer(88), Muk(89), Shellder(90), Cloyster(91), Gastly(92), Haunter(93), Gengar(94), Onix(95), Drowzee(96), Hypno(97), Krabby(98), Kingler(99), Voltorb (100), Electrode(101), Exeggcute(102), Exeggutor(103), Cubone(104), Marowak(105), Hitmonlee(106), Hitmonchan(107), Lickitung(108), Koffing(109), Weezing(110), Rhyhorn(111), Rhydon(112), Chansey(113), Tangela(114), Kangaskhan(115), Horsea(116), Seadra(117), Goldeen(118), Seaking(119), Staryu(120), Starmie(121), MrMime(122), Scyther(123), Jynx(124), Electabuzz(125), Magmar(126), Pinsir(127), Tauros(128), Magikarp(129), Gyarados(130), Lapras(131), Ditto(132), Eevee(133), Vaporeon(134), Jolteon(135), Flareon(136), Porygon(137), Omanyte(138), Omastar(139), Kabuto(140), Kabutops(141), Aerodactyl(142), Snorlax(143), Articuno(144), Zapdos(145), Moltres(146), Dratini(147), Dragonair(148), Dragonite(149), Mewtwo(150), Mew(151); public int species; Species(int s) { species = s; } } public enum StatusEffects { Burned(1), Poisoned(2), Paralyzed(3), Asleep(4), Frozen(5), None(6), FullHeal(7); public int statuseffects; StatusEffects(int s){ statuseffects = s; } } }
36.418919
153
0.668831
9e112c2d727f2b244386072d0bf749e70fdd1069
3,301
package gcm.play.android.samples.com.gcmquickstart; import android.content.Context; import android.content.SharedPreferences; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.os.Build; import org.json.JSONArray; import org.json.JSONObject; import java.text.SimpleDateFormat; import java.util.Date; /** * Created by cloud on 10/19/15. */ public class Utils { public static String generateUDID (Context context) { SharedPreferences settings = context.getSharedPreferences("setting", 0); if (settings.getString("device_imei", "").equals("")) { String serial_number = ""; if (Build.VERSION.SDK_INT >= 9) { serial_number = android.os.Build.SERIAL; } String mac_address = ""; WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); if (wifiManager != null) { WifiInfo wifiInfo = wifiManager.getConnectionInfo(); if (wifiInfo != null) { mac_address = wifiInfo.getMacAddress(); } } if ((serial_number == null || serial_number.equals(""))) { int random_number = (int) (Math.random() * 1 + 1) + (int) (Math.random() * 10 + 1) + (int) (Math.random() * 100 + 1) + (int) (Math.random() * 1000 + 1) + (int) (Math.random() * 10000 + 1) + (int) (Math.random() * 100000 + 1) + (int) (Math.random() * 1000000 + 1) + (int) (Math.random() * 10000000 + 1); if (random_number < 10000000) { random_number = random_number + 10000000; } serial_number = String.valueOf(random_number); } if ((mac_address == null || mac_address.equals(""))) { SimpleDateFormat formatter = new SimpleDateFormat("yyyy:MM:dd:HH:mm:ss"); Date curDate = new Date(System.currentTimeMillis()); mac_address = formatter.format(curDate); } mac_address = mac_address.replace(":", ""); String[] new_mac_address = new String[2]; new_mac_address[0] = mac_address.substring(0, 6); new_mac_address[1] = mac_address.substring(6); String[] new_serial_number = new String[2]; new_serial_number[0] = serial_number.substring(0, 4); new_serial_number[1] = serial_number.substring(4); settings.edit().putString("device_imei", "AN" + new_mac_address[0] + new_serial_number[1] + new_mac_address[1] + new_serial_number[0]).apply(); return "AN" + new_mac_address[0] + new_serial_number[1] + new_mac_address[1] + new_serial_number[0]; } else { return settings.getString("device_imei", ""); } } public static String generateUIDJsonText(String[] UIDs) { String result = ""; JSONArray array = new JSONArray(); JSONObject json = new JSONObject(); try { for (int i = 0; i < UIDs.length; i++) { json.put("uid", UIDs[i]); json.put("interval", 3); array.put(json); } result = array.toString(); } catch (Exception e) { } return result; } }
38.383721
318
0.572857
b838db5ce864be238c1d76a84d4357d8f04bb066
2,821
package mage.cards.c; import mage.abilities.Ability; import mage.abilities.effects.OneShotEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.cards.Cards; import mage.cards.CardsImpl; import mage.constants.CardType; import mage.constants.ComparisonType; import mage.constants.Outcome; import mage.constants.Zone; import mage.filter.FilterCard; import mage.filter.predicate.mageobject.ManaValuePredicate; import mage.game.Game; import mage.players.Player; import mage.util.CardUtil; import java.util.UUID; /** * @author TheElk801 */ public final class CollectedConjuring extends CardImpl { public CollectedConjuring(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.SORCERY}, "{2}{U}{R}"); // Exile the top six cards of your library. You may cast up to two sorcery // cards with converted mana costs 3 or less from among them without paying // their mana cost. Put the exiled cards not cast this way on the bottom // of your library in a random order. this.getSpellAbility().addEffect(new CollectedConjuringEffect()); } private CollectedConjuring(final CollectedConjuring card) { super(card); } @Override public CollectedConjuring copy() { return new CollectedConjuring(this); } } class CollectedConjuringEffect extends OneShotEffect { private static final FilterCard filter = new FilterCard("sorcery cards with mana value 3 or less"); static { filter.add(CardType.SORCERY.getPredicate()); filter.add(new ManaValuePredicate(ComparisonType.FEWER_THAN, 4)); } CollectedConjuringEffect() { super(Outcome.PlayForFree); this.staticText = "exile the top six cards of your library. You may cast up to two sorcery spells " + "with mana value 3 or less from among them without paying their mana costs. " + "Put the exiled cards not cast this way on the bottom of your library in a random order"; } private CollectedConjuringEffect(final CollectedConjuringEffect effect) { super(effect); } @Override public CollectedConjuringEffect copy() { return new CollectedConjuringEffect(this); } @Override public boolean apply(Game game, Ability source) { Player controller = game.getPlayer(source.getControllerId()); if (controller == null) { return false; } Cards cards = new CardsImpl(controller.getLibrary().getTopCards(game, 6)); controller.moveCards(cards, Zone.EXILED, source, game); CardUtil.castMultipleWithAttributeForFree(controller, source, game, cards, filter, 2); controller.putCardsOnBottomOfLibrary(cards, game, source, false); return true; } }
33.583333
109
0.704006
14f0ed120d1a2727af3cc81e7d2e62039c4917f4
2,153
/* * Copyright 2016 Red Hat, Inc, and individual contributors. * * 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 eventbusbridge; import java.util.Collections; import java.util.List; import com.google.common.primitives.Chars; import io.vertx.core.Vertx; import io.vertx.core.eventbus.EventBus; import io.vertx.core.eventbus.Message; import io.vertx.core.json.JsonObject; import io.vertx.ext.bridge.BridgeOptions; import io.vertx.ext.bridge.PermittedOptions; import io.vertx.ext.eventbus.bridge.tcp.TcpEventBusBridge; public class Main { public static void main(String[] args) { final Vertx vertx = Vertx.vertx(); final EventBus eb = vertx.eventBus(); TcpEventBusBridge bridge = TcpEventBusBridge.create( vertx, new BridgeOptions() .addOutboundPermitted(new PermittedOptions().setAddressRegex("word.*")) .addInboundPermitted(new PermittedOptions().setAddressRegex("word.*"))); bridge.listen(7001, res -> { System.out.println("Vert.x bridge started on 7001"); vertx.eventBus().consumer("word.scramble", (Message<JsonObject> m) -> { String word = m.body().getString("word"); List<Character> chars = Chars.asList(word.toCharArray()); Collections.shuffle(chars); String scrambled = new String(Chars.toArray(chars)); JsonObject reply = new JsonObject(); reply.put("word", word); reply.put("scrambled", scrambled); m.reply(reply); }); }); } }
35.883333
96
0.655365
0a61876de0853c7466ba82e119404cc86e94f259
12,606
/* $This file is distributed under the terms of the license in LICENSE$ */ package edu.cornell.mannlib.semservices.service.impl; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.StringWriter; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.concurrent.TimeUnit; import javax.xml.parsers.ParserConfigurationException; import org.apache.commons.lang3.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.jena.query.Query; import org.apache.jena.query.QueryExecution; import org.apache.jena.query.QueryExecutionFactory; import org.apache.jena.query.QueryFactory; import org.apache.jena.query.QuerySolution; import org.apache.jena.query.ResultSet; import org.apache.jena.rdf.model.Literal; import org.apache.jena.rdf.model.RDFNode; import org.apache.jena.rdf.model.Resource; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import edu.cornell.mannlib.semservices.bo.Concept; import edu.cornell.mannlib.semservices.service.ExternalConceptService; import edu.cornell.mannlib.semservices.util.SKOSUtils; import edu.cornell.mannlib.semservices.util.XMLUtils; import edu.cornell.mannlib.vitro.webapp.utils.json.JacksonUtils; import edu.cornell.mannlib.vitro.webapp.web.URLEncoder; public class AgrovocService implements ExternalConceptService { protected final Log logger = LogFactory.getLog(getClass()); private final String schemeUri = "http://aims.fao.org/aos/agrovoc/agrovocScheme"; private final String ontologyName = "agrovoc"; private final String format = "SKOS"; private final String lang = "en"; private final String searchMode = "starts with";//Used to be Exact Match, or exact word or starts with protected final String dbpedia_endpoint = " http://dbpedia.org/sparql"; // URL to get all the information for a concept protected final String conceptSkosMosBase = "http://agrovoc.uniroma2.it/agrovoc/rest/v1/"; protected final String conceptsSkosMosSearch = conceptSkosMosBase + "search?"; protected final String conceptSkosMosURL = conceptSkosMosBase + "data?"; @Override public List<Concept> getConcepts(String term) throws Exception { List<Concept> conceptList = new ArrayList<>(); //For the RDF webservices mechanism, utilize the following /* String result = getTermExpansion(this.ontologyName, term, this.searchMode, this.format, this.lang); // return empty conceptList if conceptUri is empty if (StringUtils.isEmpty(result)) { return conceptList; } // Get the list of the concept URIs in the RDF List<String> conceptUris = getConceptURIsListFromRDF(result); */ //For the SKOSMos search mechanism, utilize this instead String result = getSKOSMosSearchResults(term, this.lang); List<String> conceptUris = getConceptURIsListFromSkosMosResult(result); if (conceptUris.size() == 0) return conceptList; int conceptCounter = 0; HashSet<String> encounteredURI = new HashSet<>(); // Loop through each of these URIs and load using the SKOSManager for (String conceptUri : conceptUris) { conceptCounter++; if (StringUtils.isEmpty(conceptUri)) { // If the conceptURI is empty, keep going continue; } if(encounteredURI.contains(conceptUri)) { //If we have already encountered this concept URI, do not redisplay or reprocess continue; } encounteredURI.add(conceptUri); // Test and see if the URI is valid URI uri = null; try { uri = new URI(conceptUri); } catch (URISyntaxException e) { logger.error("Error occurred with creating the URI ", e); continue; } // Returns concept information in the format specified, which is // currently XML // Utilizing Agrovoc's getConceptInfo returns alternate and // preferred labels but // none of the exact match or close match descriptions String bestMatch = "false"; //Assume the first result is considered the 'best match' //Although that is not something we are actually retrieving from the service itself explicitly if(conceptCounter == 1) { bestMatch = "true"; } Concept c = this.createConcept(bestMatch, conceptUri); if (c != null) { // Get definition from dbpedia references stored in the close // Match list List<String> closeMatches = c.getCloseMatchURIList(); for (String closeMatch : closeMatches) { if (closeMatch.startsWith("http://dbpedia.org")) { try { String description = getDbpediaDescription(closeMatch); c.setDefinition(description); } catch (Exception ex) { logger.error("An error occurred in the process of retrieving dbpedia description", ex); } } } conceptList.add(c); } } return conceptList; } public List<Concept> processResults(String term) throws Exception { return getConcepts(term); } public Concept createConcept(String bestMatch, String skosConceptURI) { Concept concept = new Concept(); concept.setUri(skosConceptURI); concept.setConceptId(stripConceptId(skosConceptURI)); concept.setBestMatch(bestMatch); concept.setDefinedBy(schemeUri); concept.setSchemeURI(this.schemeUri); concept.setType(""); String encodedURI = URLEncoder.encode(skosConceptURI); String encodedFormat = URLEncoder.encode("application/rdf+xml"); String url = conceptSkosMosURL + "uri=" + encodedURI + "&format=" + encodedFormat; // Utilize the XML directly instead of the SKOS API try { concept = SKOSUtils .createConceptUsingXMLFromURL(concept, url, "en", false); } catch (Exception ex) { logger.debug("Error occurred for creating concept " + skosConceptURI, ex); return null; } return concept; } public List<Concept> getConceptsByURIWithSparql(String uri) throws Exception { // deprecating this method...just return an empty list List<Concept> conceptList = new ArrayList<>(); return conceptList; } protected String getAgrovocTermCode(String rdf) throws Exception { String termcode = ""; try { Document doc = XMLUtils.parse(rdf); NodeList nodes = doc.getElementsByTagName("hasCodeAgrovoc"); if (nodes.item(0) != null) { Node node = nodes.item(0); termcode = node.getTextContent(); } } catch (SAXException | IOException | ParserConfigurationException e) { // e.printStackTrace(); throw e; } return termcode; } protected String getConceptURIFromRDF(String rdf) { String conceptUri = ""; try { Document doc = XMLUtils.parse(rdf); NodeList nodes = doc.getElementsByTagName("skos:Concept"); Node node = nodes.item(0); NamedNodeMap attrs = node.getAttributes(); Attr idAttr = (Attr) attrs.getNamedItem("rdf:about"); conceptUri = idAttr.getTextContent(); } catch (IOException | ParserConfigurationException | SAXException e) { e.printStackTrace(); System.err.println("rdf: " + rdf); } return conceptUri; } // When utilizing the getTermExpansion method, will get a list of URIs back // and not just one URI protected List<String> getConceptURIsListFromRDF(String rdf) { List<String> conceptUris = new ArrayList<>(); try { Document doc = XMLUtils.parse(rdf); NodeList nodes = doc.getElementsByTagName("skos:Concept"); int numberNodes = nodes.getLength(); int n; for (n = 0; n < numberNodes; n++) { Node node = nodes.item(n); NamedNodeMap attrs = node.getAttributes(); Attr idAttr = (Attr) attrs.getNamedItem("rdf:about"); String conceptUri = idAttr.getTextContent(); conceptUris.add(conceptUri); } } catch (IOException | ParserConfigurationException | SAXException e) { e.printStackTrace(); System.err.println("rdf: " + rdf); } return conceptUris; } protected String getDbpediaDescription(String uri) throws Exception { String descriptionSource = " (Source: DBpedia)"; String description = ""; String qs = "" + "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> \n" + "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> \n" + "PREFIX foaf: <http://xmlns.com/foaf/0.1/> \n" + "PREFIX dbpedia-owl: <http://dbpedia.org/ontology/>\n" + "SELECT DISTINCT ?description WHERE { \n" + "<" + uri + "> rdfs:comment ?description . \n" + "FILTER (LANG(?description)='en' ) \n" + "}"; // System.out.println(qs); List<HashMap> resultList = new ArrayList<>(); QueryExecution qexec = null; try { Query query = QueryFactory.create(qs); qexec = QueryExecutionFactory.sparqlService(this.dbpedia_endpoint, query); qexec.setTimeout(5000, TimeUnit.MILLISECONDS); resultList = new ArrayList<>(); ResultSet resultSet = qexec.execSelect(); int resultSetSize = 0; while (resultSet.hasNext()) { resultSetSize++; QuerySolution solution = resultSet.nextSolution(); Iterator varnames = solution.varNames(); HashMap<String, String> hm = new HashMap<>(); while (varnames.hasNext()) { String name = (String) varnames.next(); RDFNode rdfnode = solution.get(name); // logger.info("rdf node name, type: "+ name // +", "+getRDFNodeType(rdfnode)); if (rdfnode.isLiteral()) { Literal literal = rdfnode.asLiteral(); String nodeval = literal.getString(); hm.put(name, nodeval); } else if (rdfnode.isResource()) { Resource resource = rdfnode.asResource(); String nodeval = resource.toString(); hm.put(name, nodeval); } } resultList.add(hm); } description = ""; for (HashMap map : resultList) { if (map.containsKey("description")) { description = (String) map.get("description"); } } } catch (Exception ex) { throw ex; } // Adding source so it is clear that this description comes from DBPedia return description + descriptionSource; } /** * @param uri The URI */ protected String stripConceptId(String uri) { String conceptId = ""; int lastslash = uri.lastIndexOf('/'); conceptId = uri.substring(lastslash + 1, uri.length()); return conceptId; } /** * @param str The String */ protected String extractConceptId(String str) { try { return str.substring(1, str.length() - 1); } catch (Exception ex) { return ""; } } /** * The code here utilizes the SKOSMOS REST API for Agrovoc * This returns JSON LD so we would parse JSON instead of RDF * The code above can still be utilized if we need to employ the web services directly */ //Get search results for a particular term and language code private String getSKOSMosSearchResults(String term, String lang) { String urlEncodedTerm = URLEncoder.encode(term); //Utilize 'starts with' using the * operator at the end String searchUrlString = this.conceptsSkosMosSearch + "query=" + urlEncodedTerm + "*" + "&lang=" + lang; URL searchURL = null; try { searchURL = new URL(searchUrlString); } catch (Exception e) { logger.error("Exception occurred in instantiating URL for " + searchUrlString, e); // If the url is having trouble, just return null for the concept return null; } String results = null; try { StringWriter sw = new StringWriter(); BufferedReader in = new BufferedReader(new InputStreamReader( searchURL.openStream())); String inputLine; while ((inputLine = in.readLine()) != null) { sw.write(inputLine); } in.close(); results = sw.toString(); logger.debug(results); } catch (Exception ex) { logger.error("Error occurred in getting concept from the URL " + searchUrlString, ex); return null; } return results; } //JSON-LD array private List<String> getConceptURIsListFromSkosMosResult(String results) { List<String> conceptURIs = new ArrayList<>(); ObjectNode json = (ObjectNode) JacksonUtils.parseJson(results); //Format should be: { ..."results":["uri":uri...] if (json.has("results")) { ArrayNode jsonArray = (ArrayNode) json.get("results"); int numberResults = jsonArray.size(); int i; for(i = 0; i < numberResults; i++) { ObjectNode jsonObject = (ObjectNode) jsonArray.get(i); if(jsonObject.has("uri")) { conceptURIs.add(jsonObject.get("uri").asText()); } } } return conceptURIs; } }
31.673367
107
0.703871
cc399ae186de69bbe07075a4b1b2707a489bebc8
451
package com.spike.microservice.dubbo.business.demo; import org.springframework.context.support.ClassPathXmlApplicationContext; public class TestProvider { public static void main(String[] args) throws Exception { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext( new String[] { "dubbo-provider.xml", "spring-mysql.xml" }); // context.start(); System.in.read(); // 按任意键退出 context.close(); } }
28.1875
80
0.733925
b84302a0d83683ba5a7cb717c9600c4398cbac6b
5,538
package com.store.web.controller.system; import com.store.common.annotation.Log; import com.store.common.constant.UserConstants; import com.store.common.core.domain.StoreResult; import com.store.common.enums.BusinessType; import com.store.common.utils.SecurityUtils; import com.store.system.service.ISysUserService; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import com.store.common.constant.Constants; import com.store.common.core.domain.AjaxResult; import com.store.common.core.domain.entity.SysMenu; import com.store.common.core.domain.entity.SysUser; import com.store.common.core.domain.model.LoginBody; import com.store.common.core.domain.model.LoginUser; import com.store.common.utils.ServletUtils; import com.store.framework.web.service.SysLoginService; import com.store.framework.web.service.SysPermissionService; import com.store.framework.web.service.TokenService; import com.store.system.service.ISysMenuService; /** * 登录验证 * * @author store */ @RestController public class SysLoginController { @Autowired private SysLoginService loginService; @Autowired private ISysMenuService menuService; @Autowired private SysPermissionService permissionService; @Autowired private TokenService tokenService; @Autowired private ISysUserService userService; /** * 登录方法 * * @param loginBody 登录信息 * @return 结果 */ @PostMapping("/login") public AjaxResult login(@RequestBody LoginBody loginBody) { AjaxResult ajax = AjaxResult.success(); // 生成令牌 java.lang.String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(), loginBody.getUuid()); ajax.put(Constants.TOKEN, token); return ajax; } /** * web的登录 */ @Log(title = "") @PostMapping("/users/login") public StoreResult weblogin(@Validated @RequestBody SysUser user) { HashMap map = new HashMap(); // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName()))) { SysUser user1=userService.selectUserByUserName(user.getUserName()); if (!SecurityUtils.matchesPassword(user.getPassword(),user1.getPassword())) return StoreResult.error("用户'" + user.getUserName() + "'用户名或密码错误!"); map.put("user_id",user1.getUserId()); map.put("userName",user1.getUserName()); return StoreResult.success("用户'" + user.getUserName() + "'登陆成功!","user",map); } return StoreResult.error("用户'" + user.getUserName() + "'不存在"); } /** * 检查用户是否已经存在 */ @Log(title = "检查用户是否已经存在") @PostMapping("/users/findUserName") public StoreResult findUserName(@Validated @RequestBody SysUser user) { if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName()))) { return StoreResult.error("新增用户'" + user.getUserName() + "'已经存在,不能注册"); } return StoreResult.success("新增用户'" + user.getUserName() + "'不存在,可以注册"); } /** * 注册用户 */ @Log(title = "注册用户") @PostMapping("/users/register") public StoreResult register(@Validated @RequestBody SysUser user) { if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName()))) { return StoreResult.error("新增用户'" + user.getUserName() + "'已经存在,不能注册"); } user.setDeptId(Long.valueOf("108")); user.setPhonenumber("12345"); user.setEmail("qq@qq.com"); user.setSex("0"); user.setStatus("0"); user.setPostIds(new long[]{Long.valueOf("4")}); user.setRoleIds(new long[]{Long.valueOf("2")}); user.setNickName(user.getUserName()); user.setCreateBy("store用户"); user.setPassword(SecurityUtils.encryptPassword(user.getPassword())); return userService.insertUser(user) > 0 ? StoreResult.success() : StoreResult.error(); } /** * 获取用户信息 * * @return 用户信息 */ @GetMapping("getInfo") public AjaxResult getInfo() { LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest()); SysUser user = loginUser.getUser(); // 角色集合 Set<java.lang.String> roles = permissionService.getRolePermission(user); // 权限集合 Set<String> permissions = permissionService.getMenuPermission(user); AjaxResult ajax = AjaxResult.success(); ajax.put("user", user); ajax.put("roles", roles); ajax.put("permissions", permissions); return ajax; } /** * 获取路由信息 * * @return 路由信息 */ @GetMapping("getRouters") public AjaxResult getRouters() { LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest()); // 用户信息 SysUser user = loginUser.getUser(); List<SysMenu> menus = menuService.selectMenuTreeByUserId(user.getUserId()); return AjaxResult.success(menuService.buildMenus(menus)); } }
33.361446
122
0.673167
7122203580d9f2a3a8f01a021a06570cc66f885c
802
package io.github.jaychoufans.dao; import io.github.jaychoufans.model.Role; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import java.util.List; import java.util.Map; @Mapper public interface RoleMapper { int deleteByPrimaryKey(Integer roleId); int insertSelective(Role record); Role selectByPrimaryKey(Integer roleId); int updateByPrimaryKeySelective(Role record); int countByRoleName(@Param("roleName") String roleName, @Param("roleId") Integer roleId); void deleteRoleUserRsByUserId(Long userId); void deleteRoleUserRsByRoleId(Integer roleId); List<Role> selectRoleList(Map<String, Object> map); int getTotalRole(Map<String, Object> map); List<Role> findByUserId(Long userId); int insertRolePermissions(Map<String, Object> map); }
22.914286
90
0.790524
66f36d2d550c5df48c19fd09e8b98ccbc2bedf2a
778
package com.gluuten.model; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.hibernate.validator.constraints.Email; import org.hibernate.validator.constraints.NotEmpty; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import java.io.Serializable; /** * Created by yusufaslan on 1.06.2017. */ @Data @NoArgsConstructor @AllArgsConstructor public class SignUp implements Serializable { @NotEmpty @Size(min = 4,max = 15) private String firstName; @NotEmpty @Size(min = 4,max = 15) private String lastName; @NotEmpty @Email @Size(min = 4,max = 15) private String userName; @NotNull @Size(min = 5, max = 15) private String password; }
19.45
52
0.724936
f64bb83ea2cd2f9e61959483a9328c52035fbc73
5,702
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.asterix.metadata.declared; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import org.apache.asterix.common.cluster.IClusterStateManager; import org.apache.asterix.common.exceptions.CompilationException; import org.apache.asterix.common.exceptions.ErrorCode; import org.apache.asterix.common.functions.FunctionSignature; import org.apache.asterix.external.adapter.factory.GenericAdapterFactory; import org.apache.asterix.metadata.api.IDatasourceFunction; import org.apache.asterix.om.types.IAType; import org.apache.asterix.om.utils.RecordUtil; import org.apache.hyracks.algebricks.common.constraints.AlgebricksAbsolutePartitionConstraint; import org.apache.hyracks.algebricks.common.constraints.AlgebricksPartitionConstraint; import org.apache.hyracks.algebricks.common.exceptions.AlgebricksException; import org.apache.hyracks.algebricks.common.utils.Pair; import org.apache.hyracks.algebricks.core.algebra.base.LogicalVariable; import org.apache.hyracks.algebricks.core.algebra.expressions.IVariableTypeEnvironment; import org.apache.hyracks.algebricks.core.algebra.functions.FunctionIdentifier; import org.apache.hyracks.algebricks.core.algebra.metadata.IDataSource; import org.apache.hyracks.algebricks.core.algebra.metadata.IDataSourcePropertiesProvider; import org.apache.hyracks.algebricks.core.algebra.operators.logical.IOperatorSchema; import org.apache.hyracks.algebricks.core.algebra.properties.INodeDomain; import org.apache.hyracks.algebricks.core.algebra.properties.RandomPartitioningProperty; import org.apache.hyracks.algebricks.core.algebra.properties.StructuralPropertiesVector; import org.apache.hyracks.algebricks.core.jobgen.impl.JobGenContext; import org.apache.hyracks.api.dataflow.IOperatorDescriptor; import org.apache.hyracks.api.job.JobSpecification; import org.apache.hyracks.storage.am.common.api.ITupleFilterFactory; import org.apache.hyracks.storage.am.common.api.ITupleProjectorFactory; public abstract class FunctionDataSource extends DataSource { public FunctionDataSource(DataSourceId id, INodeDomain domain) throws AlgebricksException { super(id, RecordUtil.FULLY_OPEN_RECORD_TYPE, null, DataSource.Type.FUNCTION, domain); schemaTypes = new IAType[] { itemType }; } @Override public boolean isScanAccessPathALeaf() { return true; } @Override public IDataSourcePropertiesProvider getPropertiesProvider() { // Unordered Random partitioning on all nodes return scanVariables -> new StructuralPropertiesVector(new RandomPartitioningProperty(domain), Collections.emptyList()); } @Override public Pair<IOperatorDescriptor, AlgebricksPartitionConstraint> buildDatasourceScanRuntime( MetadataProvider metadataProvider, IDataSource<DataSourceId> dataSource, List<LogicalVariable> scanVariables, List<LogicalVariable> projectVariables, boolean projectPushed, List<LogicalVariable> minFilterVars, List<LogicalVariable> maxFilterVars, ITupleFilterFactory tupleFilterFactory, long outputLimit, IOperatorSchema opSchema, IVariableTypeEnvironment typeEnv, JobGenContext context, JobSpecification jobSpec, Object implConfig, ITupleProjectorFactory tupleProjectorFactory) throws AlgebricksException { if (tupleFilterFactory != null || outputLimit >= 0) { throw CompilationException.create(ErrorCode.COMPILATION_ILLEGAL_STATE, "tuple filter and limit are not supported by FunctionDataSource"); } GenericAdapterFactory adapterFactory = new GenericAdapterFactory(); adapterFactory.setOutputType(RecordUtil.FULLY_OPEN_RECORD_TYPE); IClusterStateManager csm = metadataProvider.getApplicationContext().getClusterStateManager(); FunctionDataSourceFactory factory = new FunctionDataSourceFactory(createFunction(metadataProvider, getLocations(csm))); adapterFactory.configure(factory); return metadataProvider.buildExternalDatasetDataScannerRuntime(jobSpec, itemType, adapterFactory); } protected abstract IDatasourceFunction createFunction(MetadataProvider metadataProvider, AlgebricksAbsolutePartitionConstraint locations); protected AlgebricksAbsolutePartitionConstraint getLocations(IClusterStateManager csm) { String[] allPartitions = csm.getClusterLocations().getLocations(); Set<String> ncs = new HashSet<>(Arrays.asList(allPartitions)); return new AlgebricksAbsolutePartitionConstraint(ncs.toArray(new String[ncs.size()])); } protected static DataSourceId createDataSourceId(FunctionIdentifier fid, String... parameters) { return new DataSourceId(FunctionSignature.getDataverseName(fid), fid.getName(), parameters); } }
53.28972
113
0.789723
f9c4cd511374ea4c6aee45bea40230da00168299
92
package net.ftlines.blog.cdidemo.service; public class GenerateSystemReportEvent { }
15.333333
42
0.771739
71d6d98a52bfd02c27bbc9767afcb01e39a20fe1
131
package com.breakersoft.plow.crond; public enum CrondTask { ORPHAN_PROC_CHECK, DOWN_NODE_CHECK, DEALLOC_PROC_CHECK }
14.555556
35
0.755725
f6d4f180df01fe82038f9f60b405e9d0b24317ef
1,241
// -------------------------------------------------------------------------------- // Copyright 2002-2021 Echo Three, 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 // // 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.echothree.model.control.selector.server.evaluator; public interface BaseSelectorEvaluatorDebugFlags { boolean BaseSelectorEvaluator = false; boolean BaseItemSelectorEvaluator = false; boolean BasePartySelectorEvaluator = false; boolean OfferItemSelectorEvaluator = false; boolean EmployeeSelectorEvaluator = false; boolean BaseContactMechanismSelectorEvaluator = false; boolean BasePostalAddressSelectorEvaluator = false; }
41.366667
83
0.663175
75c64175137a89ae06c04cffe19d48871cfd9749
8,875
/* * Copyright 2016 The Bazel Authors. All rights reserved. * * 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.google.idea.blaze.base.lang.buildfile.psi; import com.google.idea.blaze.base.lang.buildfile.language.BuildFileType; import com.google.idea.blaze.base.lang.buildfile.references.QuoteType; import com.google.idea.blaze.base.lang.buildfile.search.BlazePackage; import com.google.idea.blaze.base.model.primitives.Label; import com.google.idea.blaze.base.sync.workspace.WorkspaceHelper; import com.intellij.extapi.psi.PsiFileBase; import com.intellij.navigation.ItemPresentation; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.project.Project; import com.intellij.psi.FileViewProvider; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiNamedElement; import com.intellij.util.PathUtil; import com.intellij.util.Processor; import icons.BlazeIcons; import java.io.File; import javax.annotation.Nullable; import javax.swing.Icon; /** Build file PSI element */ public class BuildFile extends PsiFileBase implements BuildElement, DocStringOwner { /** The blaze file type */ public enum BlazeFileType { SkylarkExtension, BuildPackage, // "BUILD", "BUILD.bazel" Workspace, // the top-level WORKSPACE file } public static String getBuildFileString(Project project, String filePath) { Label label = WorkspaceHelper.getBuildLabel(project, new File(filePath)); if (label == null) { return "BUILD file: " + filePath; } String labelString = label.toString(); return labelString.replace(":__pkg__", "/" + PathUtil.getFileName(filePath)); } public BuildFile(FileViewProvider viewProvider) { super(viewProvider, BuildFileType.INSTANCE.getLanguage()); } @Override public FileType getFileType() { return BuildFileType.INSTANCE; } public BlazeFileType getBlazeFileType() { String fileName = getFileName(); if (fileName.startsWith("BUILD")) { return BlazeFileType.BuildPackage; } if (fileName.equals("WORKSPACE")) { return BlazeFileType.Workspace; } return BlazeFileType.SkylarkExtension; } @Nullable @Override public StringLiteral getDocString() { if (getBlazeFileType() != BlazeFileType.SkylarkExtension) { return null; } for (PsiElement cur = getFirstChild(); cur != null; cur = cur.getNextSibling()) { if (cur instanceof StringLiteral && ((StringLiteral) cur).getQuoteType() == QuoteType.TripleDouble) { return (StringLiteral) cur; } if (cur instanceof BuildElement) { return null; } } return null; } @Nullable @Override public BlazePackage getBlazePackage() { return BlazePackage.getContainingPackage(this); } public String getFileName() { return getViewProvider().getVirtualFile().getName(); } public String getFilePath() { return getOriginalFile().getViewProvider().getVirtualFile().getPath(); } public File getFile() { return new File(getFilePath()); } /** * The label of the containing blaze package (this is always the parent directory for BUILD files, * but may be a more distant ancestor for Skylark extensions) */ @Nullable public Label getPackageLabel() { BlazePackage parentPackage = getBlazePackage(); return parentPackage != null ? parentPackage.getPackageLabel() : null; } /** The path for this file, formatted as a BUILD label. */ @Nullable public Label getBuildLabel() { BlazePackage containingPackage = getBlazePackage(); return containingPackage != null ? containingPackage.getBuildLabelForChild(getFilePath()) : null; } /** Finds a top-level rule with a "name" keyword argument with the given value. */ @Nullable public FuncallExpression findRule(String name) { for (FuncallExpression expr : findChildrenByClass(FuncallExpression.class)) { String ruleName = expr.getNameArgumentValue(); if (name.equals(ruleName)) { return expr; } } return null; } @Nullable public FunctionStatement findDeclaredFunction(String name) { for (FunctionStatement fn : getFunctionDeclarations()) { if (name.equals(fn.getName())) { return fn; } } return null; } @Nullable public FunctionStatement findLoadedFunction(String name) { for (LoadStatement loadStatement : findChildrenByClass(LoadStatement.class)) { for (LoadedSymbol loadedSymbol : loadStatement.getImportedSymbolElements()) { if (name.equals(loadedSymbol.getSymbolString())) { PsiElement element = loadedSymbol.getLoadedElement(); return element instanceof FunctionStatement ? (FunctionStatement) element : null; } } } return null; } public BuildElement findSymbolInScope(String name) { BuildElement[] resultHolder = new BuildElement[1]; Processor<BuildElement> processor = buildElement -> { if (buildElement instanceof LoadedSymbol) { buildElement = BuildElement.asBuildElement(((LoadedSymbol) buildElement).getVisibleElement()); } if (buildElement instanceof PsiNamedElement && name.equals(buildElement.getName())) { resultHolder[0] = buildElement; return false; } return true; }; searchSymbolsInScope(processor, null); return resultHolder[0]; } /** * Iterates over all top-level assignment statements, function definitions and loaded symbols. * * @return false if searching was stopped (e.g. because the desired element was found). */ public boolean searchSymbolsInScope( Processor<BuildElement> processor, @Nullable PsiElement stopAtElement) { for (BuildElement child : findChildrenByClass(BuildElement.class)) { if (child == stopAtElement) { break; } if (child instanceof AssignmentStatement) { TargetExpression target = ((AssignmentStatement) child).getLeftHandSideExpression(); if (target != null && !processor.process(target)) { return false; } } else if (child instanceof FunctionStatement) { if (!processor.process(child)) { return false; } } } // search nested load statements last (breadth-first search) for (BuildElement child : findChildrenByClass(BuildElement.class)) { if (child == stopAtElement) { break; } if (child instanceof LoadStatement) { for (LoadedSymbol importedSymbol : ((LoadStatement) child).getImportedSymbolElements()) { if (!processor.process(importedSymbol)) { return false; } } } } return true; } /** Searches functions declared in this file, then loaded Skylark extensions, if relevant. */ @Nullable public FunctionStatement findFunctionInScope(String name) { FunctionStatement localFn = findDeclaredFunction(name); if (localFn != null) { return localFn; } return findLoadedFunction(name); } public FunctionStatement[] getFunctionDeclarations() { return findChildrenByClass(FunctionStatement.class); } @Override public Icon getIcon(int flags) { return BlazeIcons.BuildFile; } @Override public String getPresentableText() { return toString(); } @Override public ItemPresentation getPresentation() { final BuildFile element = this; return new ItemPresentation() { @Override public String getPresentableText() { return element.getName(); } @Override public String getLocationString() { String label = getBuildFileString(element.getProject(), element.getFilePath()); return String.format("(%s)", label); } @Override public Icon getIcon(boolean unused) { return element.getIcon(0); } }; } @Override public String toString() { return getBuildFileString(getProject(), getFilePath()); } @Nullable @Override public PsiElement getReferencedElement() { return null; } @Override public <P extends PsiElement> P[] childrenOfClass(Class<P> psiClass) { return findChildrenByClass(psiClass); } @Override public <P extends PsiElement> P firstChildOfClass(Class<P> psiClass) { return findChildByClass(psiClass); } }
30.709343
100
0.68969
cc600cc178afbb68ee16818f33f6f917e80efe0e
3,134
package org.broad.igv.feature.genome; import htsjdk.samtools.seekablestream.SeekableStream; import org.broad.igv.util.FileUtils; import org.broad.igv.util.LittleEndianInputStream; import org.broad.igv.util.stream.IGVSeekableStreamFactory; import java.io.IOException; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /** * Created by jrobinso on 6/13/17. */ public class TwoBitSequence implements Sequence { static int SIGNATURE_LE = 0x1a412743; static int SIGNATURE_BE = 0x4327411a; static int HEADER_BLOCK_SIZE = 12500; String path; public TwoBitSequence(String path) throws IOException { this.path = path; init(); } private void init() throws IOException { SeekableStream is = null; is = IGVSeekableStreamFactory.getInstance().getStreamFor(path); SeekableStream bis = IGVSeekableStreamFactory.getInstance().getBufferedStream(is, 1000); LittleEndianInputStream lis = new LittleEndianInputStream(bis); int signature = lis.readInt(); boolean littleEndian = SIGNATURE_LE == signature; // TODO -- handle big endian int version = lis.readInt(); // Should be zero int seqCount = lis.readInt(); int reserved = lis.readInt(); // Should be zero Map<String, Integer> offsets = new LinkedHashMap<>(); for (int i = 0; i < seqCount; i++) { byte nameSize = lis.readByte(); byte[] seqNameBytes = new byte[nameSize]; lis.readFully(seqNameBytes); String seqName = new String(seqNameBytes); int offset = lis.readInt(); offsets.put(seqName, offset); } for (Integer offset : offsets.values()) { bis.seek(offset); int dnaSize = lis.readInt(); int nBlockCount = lis.readInt(); int [] nBlockStarts = new int[nBlockCount]; for(int i=0; i<nBlockCount; i++) { nBlockStarts[i] = lis.readInt(); } int [] nBlockSizes = new int[nBlockCount]; for(int i=0; i<nBlockCount; i++) { nBlockSizes[i] = lis.readInt(); } int maskBlockCount = lis.readInt(); int [] maskBlockStarts = new int[maskBlockCount]; for(int i=0; i<maskBlockCount; i++) { maskBlockStarts[i] = lis.readInt(); } int [] maskBlockSizes = new int[maskBlockCount]; for(int i=0; i<maskBlockCount; i++) { maskBlockSizes[i] = lis.readInt(); } } } @Override public byte[] getSequence(String chr, int start, int end, boolean useCache) { return new byte[0]; } @Override public byte getBase(String chr, int position) { return 0; } @Override public List<String> getChromosomeNames() { return null; } @Override public int getChromosomeLength(String chrname) { return 0; } @Override public boolean isRemote() { return FileUtils.isRemote(path); } }
25.479675
96
0.596362
e918676e79485238e899e3daf44eb46d30a32138
1,031
package no.unit.nva.cristin.mapper; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.function.Executable; import java.util.concurrent.atomic.AtomicReference; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.StringContains.containsString; import static org.junit.jupiter.api.Assertions.assertThrows; public class AbstractPublicationInstanceBuilderImplTest { @Test public void publicationInstanceBuilderConstructorThrowsNullPointerExceptionIfParameterIsNull() { CristinObject cristinObjectThatIsNull = null; AtomicReference<PublicationInstanceBuilderImpl> publicationInstanceBuilder = null; Executable action = () -> publicationInstanceBuilder.set(new PublicationInstanceBuilderImpl(cristinObjectThatIsNull)); NullPointerException exception = assertThrows(NullPointerException.class, action); assertThat(exception.getMessage(),containsString(PublicationInstanceBuilderImpl.ERROR_CRISTIN_OBJECT_IS_NULL)); } }
42.958333
119
0.807953
39045f1ed57306e0eafa9348c6dbccad4fe2ac8c
3,015
/* * Copyright 2018 Nextworks s.r.l. * * 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 it.nextworks.nfvmano.timeo.sbdriver.sdn.provisioning; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; /** * Created by Francesca Moscatelli on 19/04/17. * * @author Nextworks S.r.l. (f.moscatelli AT nextworks.it) */ public class Connection { @JsonProperty("connectionId") @JsonInclude(JsonInclude.Include.NON_EMPTY) String connectionId; @JsonProperty("connectionStatus") String connectionStatus; @JsonProperty("tenantId") String tenantId; @JsonProperty("connectionSource") PathRequestSource source; @JsonProperty("connectionDestination") List<PathRequestDestination> destination; @JsonProperty("computedPath") ComputedPath computedPath; @JsonProperty("priority") int priority; @JsonCreator public Connection(@JsonProperty("connectionId") String connectionId, @JsonProperty("tenantId") String tenantId, @JsonProperty("conncetionSource") PathRequestSource source, @JsonProperty("connectionDestination") List<PathRequestDestination> destination, @JsonProperty("computedPath") ComputedPath computedPath) { this.connectionId = connectionId; this.connectionStatus = "CS_COMPUTED"; this.tenantId = tenantId; this.source = source; this.destination = destination; this.computedPath = computedPath; for (ComputedStep step : computedPath.getComputedStep()) { if (step.getOrder() == 0) { this.priority = step.getStepQueue(); } } } @JsonProperty("connectionId") public String getConnectionId() { return connectionId; } @JsonProperty("connectionStatus") public String getConnectionStatus() { return connectionStatus; } @JsonProperty("tenantId") public String getTenantId() { return tenantId; } @JsonProperty("connectionSource") public PathRequestSource getSource() { return source; } @JsonProperty("connectionDestination") public List<PathRequestDestination> getDestination() { return destination; } @JsonProperty("computedPath") public ComputedPath getComputedPath() { return computedPath; } }
29.558824
102
0.687894
47f380a94e6d8ec4b74beff8e19ffbdc2f367cb1
822
package academy.devdojo.maratonajava.javacore.Aintroductionclasses.test; import academy.devdojo.maratonajava.javacore.Aintroductionclasses.domain.Student; public class StudentTest02 { public static void main(String[] args) { Student student1 = new Student(); Student student2 = new Student(); student1.name = "Marry"; student1.age = 22; student1.gender = 'F'; student2.name = "Clarissa"; student2.age = 19; student2.gender = 'F'; System.out.println(student1.name); System.out.println(student1.age); System.out.println(student1.gender); System.out.println("-----------------"); System.out.println(student2.name); System.out.println(student2.age); System.out.println(student2.gender); } }
28.344828
81
0.63382
7aad1427a7a80a0dadb052f366f0023d85c995c5
3,550
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jclouds.blobstore.util; import static org.assertj.core.api.Fail.failBecauseExceptionWasNotThrown; import static org.jclouds.blobstore.util.BlobStoreUtils.getNameFor; import static org.jclouds.reflect.Reflection2.method; import static org.testng.Assert.assertEquals; import java.net.URI; import java.util.List; import org.jclouds.reflect.Invocation; import org.jclouds.rest.internal.GeneratedHttpRequest; import org.testng.annotations.Test; import com.google.common.base.Throwables; import com.google.common.collect.ImmutableList; import org.jclouds.ContextBuilder; import org.jclouds.blobstore.BlobStore; import org.jclouds.blobstore.BlobStoreContext; import org.jclouds.blobstore.domain.Blob; @Test(groups = "unit") public class BlobStoreUtilsTest { public void testGetKeyForAzureS3AndRackspace() { GeneratedHttpRequest request = requestForEndpointAndArgs( "https://jclouds.blob.core.windows.net/adriancole-blobstore0/five", ImmutableList.<Object> of("adriancole-blobstore0", "five")); assertEquals(getNameFor(request), "five"); } public void testGetKeyForAtmos() { GeneratedHttpRequest request = requestForEndpointAndArgs( "https://storage4.clouddrive.com/v1/MossoCloudFS_dc1f419c-5059-4c87-a389-3f2e33a77b22/adriancole-blobstore0/four", ImmutableList.<Object> of("adriancole-blobstore0/four")); assertEquals(getNameFor(request), "four"); } public void testReadOnlyBlobStore() { BlobStoreContext context = ContextBuilder.newBuilder("transient").build(BlobStoreContext.class); try { BlobStore rwBlobStore = context.getBlobStore(); BlobStore roBlobStore = ReadOnlyBlobStore.newReadOnlyBlobStore(rwBlobStore); String containerName = "name"; rwBlobStore.createContainerInLocation(null, containerName); Blob blob = rwBlobStore.blobBuilder("blob") .payload(new byte[0]) .build(); rwBlobStore.putBlob(containerName, blob); try { roBlobStore.putBlob(containerName, blob); failBecauseExceptionWasNotThrown(UnsupportedOperationException.class); } catch (UnsupportedOperationException uoe) { // expected } } finally { context.close(); } } GeneratedHttpRequest requestForEndpointAndArgs(String endpoint, List<Object> args) { try { Invocation invocation = Invocation.create(method(String.class, "toString"), args); return GeneratedHttpRequest.builder().method("POST").endpoint(URI.create(endpoint)).invocation(invocation) .build(); } catch (SecurityException e) { throw Throwables.propagate(e); } } }
40.340909
126
0.723662
f4554554c5f3edfdf23111a513278f456a89af4f
1,078
package de.hpi.bpt.chimera.parser.datamodel; import java.util.UUID; import org.apache.log4j.Logger; import org.json.JSONException; import org.json.JSONObject; import de.hpi.bpt.chimera.model.datamodel.DataAttribute; import de.hpi.bpt.chimera.parser.IllegalCaseModelException; import de.hpi.bpt.chimera.validation.NameValidation; public class DataAttributeParser { private static final Logger log = Logger.getLogger((DataAttributeParser.class).getName()); private DataAttributeParser() { } public static DataAttribute parseDataAttribute(JSONObject dataAttributeJson) { DataAttribute dataAttribute = new DataAttribute(); try { String name = dataAttributeJson.getString("name"); NameValidation.validateName(name); dataAttribute.setName(name); dataAttribute.setId(UUID.randomUUID().toString().replaceAll("-", "")); String type = dataAttributeJson.getString("datatype"); dataAttribute.setType(type); } catch (JSONException e) { log.error(e); throw new IllegalCaseModelException("Invalid DataAttribute"); } return dataAttribute; } }
27.641026
91
0.770872
c1f3a4ae1f83fa08ae995a538a7f152fd4b65c32
2,383
/* * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH under * one or more contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright ownership. * Licensed under the Zeebe Community License 1.1. You may not use this file * except in compliance with the Zeebe Community License 1.1. */ package io.zeebe.test.util.bpmn.random; import io.zeebe.test.util.bpmn.random.steps.AbstractExecutionStep; import io.zeebe.test.util.bpmn.random.steps.StepPublishMessage; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; /** * Segment of an execution path. This will not execute a process start to finish but only covers a * part of the process. * * <p>Execution path segments are mutable */ public final class ExecutionPathSegment { private final List<AbstractExecutionStep> steps = new ArrayList<>(); public void append(final AbstractExecutionStep executionStep) { steps.add(executionStep); } public void append(final ExecutionPathSegment pathToAdd) { steps.addAll(pathToAdd.getSteps()); } public void replace(final int index, final AbstractExecutionStep executionStep) { steps.subList(index, steps.size()).clear(); steps.add(executionStep); } public void insert(final int index, final StepPublishMessage stepPublishMessage) { steps.add(index, stepPublishMessage); } public List<AbstractExecutionStep> getSteps() { return Collections.unmodifiableList(steps); } public Map<String, Object> collectVariables() { final Map<String, Object> result = new HashMap<>(); steps.forEach(step -> result.putAll(step.getVariables())); return result; } @Override public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final ExecutionPathSegment that = (ExecutionPathSegment) o; return steps.equals(that.steps); } @Override public int hashCode() { return steps.hashCode(); } }
28.710843
98
0.736047
385795721b3a966d3852c7247f8df51891b5a4e7
353
package de.fhbielefeld.newsboard.model.module; import de.fhbielefeld.newsboard.model.Repository; /** * Data access interface for external modules. */ public interface ExternalModuleDao extends Repository { ExternalModule get(ModuleId reference); int update(ExternalModule externalModule); int create(ExternalModule externalModule); }
22.0625
55
0.784703
3e3a61a051195cad20d6aa95f4317b6511647677
199
package com.bjsxt.service; import com.bjsxt.domain.ForexAccount; import com.baomidou.mybatisplus.extension.service.IService; public interface ForexAccountService extends IService<ForexAccount>{ }
22.111111
68
0.839196
2232dbeb60ef70b1b4344c1d85a1aff87f875558
1,839
package com.wasu.demo9.shiro; import com.wasu.demo9.dao.UserMapper; import com.wasu.demo9.pojo.User; import org.apache.shiro.authc.*; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; import org.springframework.beans.factory.annotation.Autowired; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @ClassName:ShiroRealm * @Description: TODO * @Author: Syl * @Date: 2021/7/19 15:27 */ public class ShiroRealm extends AuthorizingRealm { private Logger logger = LoggerFactory.getLogger(getClass()); @Autowired private UserMapper userMapper; @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { return null; } /** * 登录认证 * @param authenticationToken * @return * @throws AuthenticationException */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { String userName = (String) authenticationToken.getPrincipal(); String password = new String((char[])authenticationToken.getCredentials()); logger.info("用户" + userName + "认证-----ShiroRealm.doGetAuthenticationInfo"); User user = userMapper.findByUserName(userName); if (user == null) { throw new UnknownAccountException("用户名或密码错误!"); } if (!password.equals(user.getPassword())) { throw new IncorrectCredentialsException("用户名或密码错误!"); } if (user.getStatus().equals("0")) { throw new LockedAccountException("账号已被锁定,请联系管理员!"); } SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, getName()); return info; } }
32.839286
130
0.704187
fe55eb950ec9d362f1ca1ef1d08d6908d5f927fd
2,759
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.isis.metamodel.facets.object.domainobject.auditing; import java.util.Optional; import org.apache.isis.applib.annotation.Auditing; import org.apache.isis.commons.internal.exceptions._Exceptions; import org.apache.isis.config.IsisConfiguration; import org.apache.isis.config.metamodel.facets.AuditObjectsConfiguration; import org.apache.isis.metamodel.facetapi.FacetHolder; import org.apache.isis.metamodel.facets.object.audit.AuditableFacet; import org.apache.isis.metamodel.facets.object.audit.AuditableFacetAbstract; import lombok.val; public class AuditableFacetForDomainObjectAnnotation extends AuditableFacetAbstract { public static AuditableFacet create( Optional<Auditing> auditingIfAny, IsisConfiguration configuration, FacetHolder holder) { val auditing = auditingIfAny.orElse(Auditing.AS_CONFIGURED); switch (auditing) { case NOT_SPECIFIED: case AS_CONFIGURED: val auditObjects = AuditObjectsConfiguration.from(configuration); switch (auditObjects) { case NONE: return null; default: return auditingIfAny.isPresent() ? new AuditableFacetForDomainObjectAnnotationAsConfigured(holder) : new AuditableFacetFromConfiguration(holder); } case DISABLED: // explicitly disable return new AuditableFacetForDomainObjectAnnotation(Enablement.DISABLED, holder); case ENABLED: return new AuditableFacetForDomainObjectAnnotation(Enablement.ENABLED, holder); default: throw _Exceptions.unmatchedCase(auditing); } } protected AuditableFacetForDomainObjectAnnotation( Enablement enablement, FacetHolder holder) { super(holder, enablement); } }
36.786667
92
0.699529
3e44c32b5a889dff5da7db8ef74d75e58d4990db
3,322
package de.skuld.web.model; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.v3.oas.annotations.media.Schema; import java.util.Objects; import org.springframework.validation.annotation.Validated; /** * MetaData */ @Validated @javax.annotation.Generated(value = "io.swagger.codegen.v3.generators.java.SpringCodegen", date = "2022-02-22T13:22:34.185Z[GMT]") public class MetaData { @JsonProperty("uuid") private String uuid = null; @JsonProperty("date") private String date = null; @JsonProperty("status") private StatusEnum status = null; public MetaData uuid(String uuid) { this.uuid = uuid; return this; } /** * Get uuid * * @return uuid **/ @Schema(description = "") public String getUuid() { return uuid; } public void setUuid(String uuid) { this.uuid = uuid; } public MetaData date(String date) { this.date = date; return this; } /** * Get date * * @return date **/ @Schema(description = "") public String getDate() { return date; } public void setDate(String date) { this.date = date; } public MetaData status(StatusEnum status) { this.status = status; return this; } /** * Get status * * @return status **/ @Schema(description = "") public StatusEnum getStatus() { return status; } public void setStatus(StatusEnum status) { this.status = status; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } MetaData metaData = (MetaData) o; return Objects.equals(this.uuid, metaData.uuid) && Objects.equals(this.date, metaData.date) && Objects.equals(this.status, metaData.status); } @Override public int hashCode() { return Objects.hash(uuid, date, status); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class MetaData {\n"); sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" status: ").append(toIndentedString(status)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces (except the first * line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } /** * Gets or Sets status */ public enum StatusEnum { CREATED("CREATED"), GENERATING("GENERATING"), GENERATED("GENERATED"), SORTING_ADDING("SORTING_ADDING"), FINISHED("FINISHED"); private String value; StatusEnum(String value) { this.value = value; } @JsonCreator public static StatusEnum fromValue(String text) { for (StatusEnum b : StatusEnum.values()) { if (String.valueOf(b.value).equals(text)) { return b; } } return null; } @Override @JsonValue public String toString() { return String.valueOf(value); } } }
20.133333
130
0.62342
fcc7934c9040ba469983f93a78f28796652a1b59
6,044
package com.jnape.palatable.lambda.functions.builtin.fn7; import com.jnape.palatable.lambda.functions.Fn1; import com.jnape.palatable.lambda.functions.Fn2; import com.jnape.palatable.lambda.functions.Fn3; import com.jnape.palatable.lambda.functions.Fn4; import com.jnape.palatable.lambda.functions.Fn5; import com.jnape.palatable.lambda.functions.Fn6; import com.jnape.palatable.lambda.functions.Fn7; import com.jnape.palatable.lambda.functor.Applicative; /** * Lift into and apply an {@link Fn6} to six {@link Applicative} values, returning the result inside the same * {@link Applicative} context. * * @param <A> the function's first argument type * @param <B> the function's second argument type * @param <C> the function's third argument type * @param <D> the function's fourth argument type * @param <E> the function's fifth argument type * @param <F> the function's sixth argument type * @param <G> the function's return type * @param <App> the applicative witness * @param <AppG> the inferred applicative return type * @see Applicative#zip(Applicative) */ public final class LiftA6<A, B, C, D, E, F, G, App extends Applicative<?, App>, AppG extends Applicative<G, App>> implements Fn7<Fn6<A, B, C, D, E, F, G>, Applicative<A, App>, Applicative<B, App>, Applicative<C, App>, Applicative<D, App>, Applicative<E, App>, Applicative<F, App>, AppG> { private static final LiftA6<?, ?, ?, ?, ?, ?, ?, ?, ?> INSTANCE = new LiftA6<>(); private LiftA6() { } @Override public AppG checkedApply(Fn6<A, B, C, D, E, F, G> fn, Applicative<A, App> appA, Applicative<B, App> appB, Applicative<C, App> appC, Applicative<D, App> appD, Applicative<E, App> appE, Applicative<F, App> appF) { return appA.<G>zip(appB.zip(appC.zip(appD.zip(appE.zip(appF.fmap( f -> e -> d -> c -> b -> a -> fn.apply(a, b, c, d, e, f))))))).coerce(); } @SuppressWarnings("unchecked") public static <A, B, C, D, E, F, G, App extends Applicative<?, App>, AppG extends Applicative<G, App>> LiftA6<A, B, C, D, E, F, G, App, AppG> liftA6() { return (LiftA6<A, B, C, D, E, F, G, App, AppG>) INSTANCE; } public static <A, B, C, D, E, F, G, App extends Applicative<?, App>, AppG extends Applicative<G, App>> Fn6<Applicative<A, App>, Applicative<B, App>, Applicative<C, App>, Applicative<D, App>, Applicative<E, App>, Applicative<F, App>, AppG> liftA6(Fn6<A, B, C, D, E, F, G> fn) { return LiftA6.<A, B, C, D, E, F, G, App, AppG>liftA6().apply(fn); } public static <A, B, C, D, E, F, G, App extends Applicative<?, App>, AppG extends Applicative<G, App>> Fn5<Applicative<B, App>, Applicative<C, App>, Applicative<D, App>, Applicative<E, App>, Applicative<F, App>, AppG> liftA6(Fn6<A, B, C, D, E, F, G> fn, Applicative<A, App> appA) { return LiftA6.<A, B, C, D, E, F, G, App, AppG>liftA6(fn).apply(appA); } public static <A, B, C, D, E, F, G, App extends Applicative<?, App>, AppG extends Applicative<G, App>> Fn4<Applicative<C, App>, Applicative<D, App>, Applicative<E, App>, Applicative<F, App>, AppG> liftA6(Fn6<A, B, C, D, E, F, G> fn, Applicative<A, App> appA, Applicative<B, App> appB) { return LiftA6.<A, B, C, D, E, F, G, App, AppG>liftA6(fn, appA).apply(appB); } public static <A, B, C, D, E, F, G, App extends Applicative<?, App>, AppG extends Applicative<G, App>> Fn3<Applicative<D, App>, Applicative<E, App>, Applicative<F, App>, AppG> liftA6(Fn6<A, B, C, D, E, F, G> fn, Applicative<A, App> appA, Applicative<B, App> appB, Applicative<C, App> appC) { return LiftA6.<A, B, C, D, E, F, G, App, AppG>liftA6(fn, appA, appB).apply(appC); } public static <A, B, C, D, E, F, G, App extends Applicative<?, App>, AppG extends Applicative<G, App>> Fn2<Applicative<E, App>, Applicative<F, App>, AppG> liftA6(Fn6<A, B, C, D, E, F, G> fn, Applicative<A, App> appA, Applicative<B, App> appB, Applicative<C, App> appC, Applicative<D, App> appD) { return LiftA6.<A, B, C, D, E, F, G, App, AppG>liftA6(fn, appA, appB, appC).apply(appD); } public static <A, B, C, D, E, F, G, App extends Applicative<?, App>, AppG extends Applicative<G, App>> Fn1<Applicative<F, App>, AppG> liftA6(Fn6<A, B, C, D, E, F, G> fn, Applicative<A, App> appA, Applicative<B, App> appB, Applicative<C, App> appC, Applicative<D, App> appD, Applicative<E, App> appE) { return LiftA6.<A, B, C, D, E, F, G, App, AppG>liftA6(fn, appA, appB, appC, appD).apply(appE); } public static <A, B, C, D, E, F, G, App extends Applicative<?, App>, AppG extends Applicative<G, App>> AppG liftA6(Fn6<A, B, C, D, E, F, G> fn, Applicative<A, App> appA, Applicative<B, App> appB, Applicative<C, App> appC, Applicative<D, App> appD, Applicative<E, App> appE, Applicative<F, App> appF) { return LiftA6.<A, B, C, D, E, F, G, App, AppG>liftA6(fn, appA, appB, appC, appD, appE).apply(appF); } }
51.220339
118
0.527134
346ca064c56071643b3ca4d295278305030feb25
4,347
package us.ihmc.pathPlanning.visibilityGraphs.dataStructure; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import us.ihmc.euclid.interfaces.EpsilonComparable; import us.ihmc.euclid.tuple2D.Point2D; import us.ihmc.euclid.tuple2D.interfaces.Point2DReadOnly; import us.ihmc.euclid.tuple3D.interfaces.Point3DReadOnly; /** * Visibility graph node data structure associated with a navigable region, * holding cost information, and connected graph edges */ public class VisibilityGraphNode implements EpsilonComparable<VisibilityGraphNode> { private static final double hashGridSize = 1e-3; private final VisibilityGraphNavigableRegion visibilityGraphNavigableRegion; private final ConnectionPoint3D pointInWorld; private final Point2D point2DInLocal; private boolean edgesHaveBeenDetermined = false; private double costFromStart = Double.NaN; private boolean hasBeenExpanded = false; private VisibilityGraphNode bestParentNode = null; private final int hashCode; private final HashSet<VisibilityGraphEdge> edges = new HashSet<>(); public VisibilityGraphNode(Point3DReadOnly pointInWorld, Point2DReadOnly pointInLocal, VisibilityGraphNavigableRegion visibilityGraphNavigableRegion) { this(pointInWorld, pointInLocal, visibilityGraphNavigableRegion, visibilityGraphNavigableRegion.getMapId()); } public VisibilityGraphNode(Point3DReadOnly pointInWorld, Point2DReadOnly pointInLocal, VisibilityGraphNavigableRegion visibilityGraphNavigableRegion, int mapId) { this.visibilityGraphNavigableRegion = visibilityGraphNavigableRegion; this.pointInWorld = new ConnectionPoint3D(pointInWorld, mapId); this.point2DInLocal = new Point2D(pointInLocal); hashCode = computeHashCode(this); } public int getRegionId() { return pointInWorld.getRegionId(); } public VisibilityGraphNavigableRegion getVisibilityGraphNavigableRegion() { return visibilityGraphNavigableRegion; } public ConnectionPoint3D getPointInWorld() { return pointInWorld; } public Point2DReadOnly getPoint2DInLocal() { return point2DInLocal; } public synchronized void addEdge(VisibilityGraphEdge edge) { if (edge != null) { edges.add(edge); } } public HashSet<VisibilityGraphEdge> getEdges() { return edges; } public double distanceXYSquared(VisibilityGraphNode target) { return pointInWorld.distanceXYSquared(target.pointInWorld); } public double getCostFromStart() { return costFromStart; } public void setCostFromStart(double costFromStart, VisibilityGraphNode bestParentNode) { this.costFromStart = costFromStart; this.bestParentNode = bestParentNode; } public VisibilityGraphNode getBestParentNode() { return bestParentNode; } public boolean getHasBeenExpanded() { return hasBeenExpanded; } public void setHasBeenExpanded(boolean hasBeenExpanded) { this.hasBeenExpanded = hasBeenExpanded; } public boolean getEdgesHaveBeenDetermined() { return edgesHaveBeenDetermined; } public void setEdgesHaveBeenDetermined(boolean edgesHaveBeenDetermined) { this.edgesHaveBeenDetermined = edgesHaveBeenDetermined; } @Override public int hashCode() { return hashCode; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; VisibilityGraphNode other = (VisibilityGraphNode) obj; return epsilonEquals(other, 1e-8); } @Override public boolean epsilonEquals(VisibilityGraphNode other, double epsilon) { return pointInWorld.epsilonEquals(other.pointInWorld, epsilon); } @Override public String toString() { return pointInWorld.toString(); } private static int computeHashCode(VisibilityGraphNode node) { final int prime = 31; int result = 1; result = prime * result + (int) Math.round(node.getPointInWorld().getX() / hashGridSize); result = prime * result + (int) Math.round(node.getPointInWorld().getY() / hashGridSize); return result; } }
26.506098
152
0.723257
1a5772de270b916aa17b58b23467e9f039672298
654
package com.binea.redis; /** * Created by binea * Date: 4/11/2017 * TIME: 7:15 PM */ //@Configuration public class RedisConfig { // @Bean // JedisConnectionFactory jedisConnectionFactory() { // return new JedisConnectionFactory(); // } // // @Bean // public RedisTemplate<String, User> redisTemplate(RedisConnectionFactory factory) { // RedisTemplate<String, User> template = new RedisTemplate<>(); // template.setConnectionFactory(factory); // template.setKeySerializer(new StringRedisSerializer()); // template.setValueSerializer(new RedisObjectSerializer()); // return template; // } }
27.25
88
0.668196
8d0cda65faf10d3697c4713318fa5a2c2187199a
4,474
package com.crazymoosen; import java.util.ArrayList; import java.util.List; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; import org.bukkit.plugin.java.JavaPlugin; import com.crazymoosen.listeners.ListenForWhenABlockBreaks; import com.crazymoosen.listeners.ListenForWhenMobsAreKilled; public class RunListeners extends JavaPlugin { private boolean enabled; @Override public void onEnable() { FileConfiguration config = getConfig(); config.options().copyDefaults(true); saveDefaultConfig(); try { enabled = ((Boolean)config.get("plugin-on")).booleanValue(); } catch(ClassCastException e) { return; } if(enabled) { getServer().getConsoleSender().sendMessage(ChatColor.GRAY + "[" + ChatColor.AQUA + "IncreasingItemDrops" + ChatColor.GRAY + "]" + ChatColor.GREEN + " Enabled"); getCommand("itemdrops").setExecutor(this); getServer().getPluginManager().registerEvents(new ListenForWhenABlockBreaks(), this); getServer().getPluginManager().registerEvents(new ListenForWhenMobsAreKilled(), this); new Config(this); } else { getServer().getConsoleSender().sendMessage(ChatColor.GRAY + "[" + ChatColor.AQUA + "IncreasingItemDrops" + ChatColor.GRAY + "]" + ChatColor.RED + " Disabled"); return; } int pluginId = 11298; @SuppressWarnings("unused") Metrics metric = new Metrics((JavaPlugin)this, pluginId); } public void printToConsole(String msg) { getServer().getConsoleSender().sendMessage(msg); } public static List<String> names = new ArrayList<String>(); List<String> arguments = new ArrayList<String>(); @Override public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args){ if (arguments.isEmpty()) { arguments.add("add"); arguments.add("remove"); } List<String> result = new ArrayList<String>(); if (args.length == 1) { for (String a : arguments) { if (a.toLowerCase().startsWith(args[0].toLowerCase())) result.add(a); } return result; } return null; } @Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if (!(sender instanceof Player)) {sender.sendMessage(ChatColor.RED + "(!) Only players may execute this command!"); return true;} Player p = (Player) sender; if (cmd.getName().equalsIgnoreCase("itemdrops")) { if (args.length > 0) { if (args[0].equalsIgnoreCase("add") || args[0].equalsIgnoreCase("remove")) { if (args[0].equalsIgnoreCase("add")) { try { if(names.contains(args[1].toString())) { p.sendMessage(ChatColor.RED + "(!) This player is already an Increasing Item Drops player!"); } else { if(Bukkit.getOnlinePlayers().contains(Bukkit.getPlayer(args[1].toString()))) { p.sendMessage(ChatColor.GREEN + "(!) This player is now an Increasing Item Drops player."); names.add(args[1].toString()); } else { p.sendMessage(ChatColor.RED + "(!)This player is not online."); return true; } } } catch (Exception e) { p.sendMessage(ChatColor.RED + "(!) Specify a player to add them to the list!"); } } else { try { if(names.contains(args[1].toString())) { p.sendMessage(ChatColor.GREEN + "(!) This player is now not an Increasing Item Drops player."); names.remove(args[1].toString()); } else { p.sendMessage(ChatColor.RED + "(!) You can't remove a player that is not an Increasing Item Drops player!"); } } catch (Exception e) { p.sendMessage(ChatColor.RED + "(!) Specify a player to add them to the list!"); } } } else { p.sendMessage("Give an argument of add or remove to add them from Increasing Item Drops or to remove them from Increasing Item Drops!"); } } else { p.sendMessage("Give an argument of add or remove to add them from Increasing Item Drops or to remove them from Increasing Item Drops!"); } } return true; } }
29.826667
164
0.628744
834c625c02ab5f386601b7013c9038a04d49a139
3,797
package com.example.alfasdk.Network; import android.content.Context; import android.content.Intent; import android.os.Handler; import android.os.HandlerThread; import android.os.Message; import android.util.Log; import androidx.localbroadcastmanager.content.LocalBroadcastManager; import com.example.alfasdk.BaseActivity; import com.example.alfasdk.Const.Constants; import java.io.BufferedWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.Calendar; import java.util.HashMap; import java.util.Map; public class MessageServerThread extends HandlerThread { private static MessageServerThread instance; private final Context context; public Handler mHandler; MessageSocket socket; String action = null; public MessageServerThread(Context context) { super("MessageServerThread", HandlerThread.MAX_PRIORITY); this.context = context; start(); } public static void kill() { if (instance != null) { instance.quit(); instance = null; } } public static MessageServerThread getInstance(Context context) { if (instance == null) { instance = new MessageServerThread(context); } return instance; } @Override protected void onLooperPrepared() { super.onLooperPrepared(); mHandler = new Handler(getLooper()) { @Override public void handleMessage(Message msg) { try { if (socket == null) { MessageSocket.context = context; socket = MessageSocket.getInstance(); Log.d("MessageSocket", "write connected"); } if (socket != null && socket.isConnected()) { Log.d("tesingbipl", "handleMessage: " + Calendar.getInstance().getTime()); writeToSocket(msg, socket); } } catch (Exception e) { e.printStackTrace(); if (e instanceof java.net.ConnectException) { broadcastResponse(BaseActivity.STATE_CONNECT_EXCEPTION, null); } else { broadcastResponse(null, null); } } } }; } public void write(Map<Integer, String> map) { try { if (mHandler == null) { // Log.d("testCrash", "handler is null"); onLooperPrepared(); } Message msg = mHandler.obtainMessage(); msg.obj = map; mHandler.sendMessage(msg); } catch (Exception e) { e.printStackTrace(); } } private void writeToSocket(Message msg, MessageSocket socket) throws IOException { HashMap<Integer, String> map = (HashMap<Integer, String>) msg.obj; PrintWriter mOut; mOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true); // Log.d("tesingbipl", "on success writeToSocket: " + Calendar.getInstance().getTime()); String final_str = map.get(2) + "<END>"; mOut.println(final_str); Log.i("printLogTime", "write to socket: " + msg); Log.d("MessageSocket", "write: " + final_str); action = map.get(1); } private void broadcastResponse(String msgType, String response) { Intent intent = new Intent(Constants.MSG_SERVER_BROADCAST); intent.putExtra("msgType", msgType); intent.putExtra("response", response); LocalBroadcastManager.getInstance(context).sendBroadcast(intent); } }
27.715328
100
0.585989
e62b873b5c36e122cae12d6bf7d9227e989281cb
5,268
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~ Copyright 2020 Adobe ~ ~ 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.adobe.dx.responsive.internal; import static org.junit.jupiter.api.Assertions.*; import com.adobe.dx.responsive.ResponsiveConfiguration; import com.adobe.dx.testing.AbstractTest; import java.util.Arrays; import java.util.Collection; import java.util.LinkedHashMap; import java.util.concurrent.Callable; import org.apache.commons.lang.StringUtils; import org.apache.sling.api.resource.Resource; import org.apache.sling.api.resource.ValueMap; import org.apache.sling.caconfig.ConfigurationBuilder; import org.apache.sling.testing.mock.caconfig.MockContextAwareConfig; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import io.wcm.testing.mock.aem.junit5.AemContext; public class ResponsivePropertiesTest extends AbstractTest { public final static String[] BREAKPOINTS = new String[] {"Mobile", "Tablet", "Desktop"}; ResponsiveConfiguration configuration; public static ResponsiveConfiguration initResponsiveConfiguration(AemContext context) { context.create().resource(CONTENT_ROOT, "sling:configRef", CONF_ROOT); MockContextAwareConfig.registerAnnotationClasses(context, ResponsiveConfiguration.class); MockContextAwareConfig.writeConfiguration(context, CONTENT_ROOT, ResponsiveConfiguration.class,"breakpoints", BREAKPOINTS); return context.resourceResolver() .getResource(CONTENT_ROOT) .adaptTo(ConfigurationBuilder.class) .as(ResponsiveConfiguration.class); } @BeforeEach void setup() { configuration = initResponsiveConfiguration(context); } LinkedHashMap<String,String> getProperty(final ResponsiveConfiguration rConfig, String key, Object...entries) { String path = "/content/" + StringUtils.join(Arrays.asList(entries), "/"); context.build().resource(path, entries).commit(); Resource resource = context.resourceResolver().getResource(path); ResponsiveProperties responsiveProperties = new ResponsiveProperties(rConfig, resource.getValueMap()); return (LinkedHashMap<String,String>)responsiveProperties.get(key); } void assertLinkedHashMapEqual(String message, LinkedHashMap<String,String> result, String... properties) { LinkedHashMap<String,String> expected = new LinkedHashMap<>(); for (int i = 0; i < properties.length; i += 2) { expected.put(properties[i], properties[i+1]); } assertEquals(expected, result, message); } @Test void get() { assertLinkedHashMapEqual("three widths are provided", getProperty(configuration, "width", "widthTablet", 34,"widthMobile", 12, "widthDesktop", 43), "mobile", "12", "tablet", "34", "desktop", "43"); assertLinkedHashMapEqual("no mobile", getProperty(configuration, "width", "widthTablet", 34, "widthDesktop", 43), "mobile", null, "tablet", "34", "desktop", "43"); assertLinkedHashMapEqual("only desktop", getProperty(configuration, "width", "widthDesktop", 43), "mobile", null, "tablet", null, "desktop", "43"); assertLinkedHashMapEqual("should work with boolean too...", getProperty(configuration, "inherit", "inheritMobile", true, "inheritDesktop", false), "mobile", "true", "tablet", null, "desktop", "false"); assertNull(getProperty(configuration, "height", "blah", 34,"foo", 12), "no value should be null"); assertNull(getProperty(configuration, "height", "blah", 34,"foo", 12,"heightDesktop", ""), "blank value should be null"); assertNull(new ResponsiveProperties(configuration, ValueMap.EMPTY).get(null)); } @Test void unsupported() { ResponsiveProperties props = new ResponsiveProperties(configuration, ValueMap.EMPTY); final Collection<Callable> unsupportedOperations = Arrays.asList( () -> {props.clear(); return 0;}, () -> {props.putAll(ValueMap.EMPTY); return 0;}, () -> props.put("foo", "bar"), () -> props.containsKey("foo"), () -> props.containsValue("bar"), () -> props.size(), () -> props.values(), () -> props.keySet(), () -> props.entrySet(), () -> props.isEmpty(), () -> props.remove("foo")); for (Callable callable : unsupportedOperations) { assertThrows(UnsupportedOperationException.class, () -> callable.call()); } } }
45.808696
131
0.655657
8e6ecdef9907819a295409c553bc678a48e1f683
1,768
package savedobject; import java.io.*; import lombok.Cleanup; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import lombok.ToString; import org.junit.Assert; import org.junit.Test; import me.noip.chankyin.mrmrg.utils.io.SavedObject; import me.noip.chankyin.mrmrg.utils.io.SavedObjectInputStream; import me.noip.chankyin.mrmrg.utils.io.SavedObjectOutputStream; import me.noip.chankyin.mrmrg.utils.io.SavedProperty; @EqualsAndHashCode @ToString public class TestObjectSave{ @SavedProperty(1) private String testObjectSave = "a"; @SavedObject(2) @NoArgsConstructor @EqualsAndHashCode(callSuper = true) @ToString(callSuper = true) public static class Foo extends TestObjectSave{ @SavedProperty(2) private String foo = "b"; private int i = 0xdeadbeef; } @SavedObject(3) @NoArgsConstructor @EqualsAndHashCode(callSuper = true) @ToString(callSuper = true) public static class Bar extends Foo{ @SavedProperty(value = 2, removed = 3) private String bar = "c"; @SavedProperty(3) private long i = 0xd3adc0debeeffaceL; } @Test public void testWrite() throws Exception{ testWrite0(new Bar()); } @Test public void testRead() throws Exception{ Bar bar = new Bar(); testWrite0(bar); Object object = testRead0(); Assert.assertEquals(bar, object); } public void testWrite0(Object object) throws Exception{ @Cleanup OutputStream os = new FileOutputStream(new File(".", "Bar.dat")); SavedObjectOutputStream soos = new SavedObjectOutputStream(os); soos.writeSavedObject(object); } public Object testRead0() throws Exception{ @Cleanup InputStream is = new FileInputStream(new File(".", "Bar.dat")); SavedObjectInputStream sois = new SavedObjectInputStream(is, true); return sois.readSavedObject(null); } }
26.38806
76
0.760181
5b08e4abab6592a092326c9655739c8114190c0c
966
/* * Copyright 2018 Bradley Steele * * 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 me.bradleysteele.commons.resource; /** * @author Bradley Steele * @version 1.0 */ public interface ResourceLoadResultHandler { /** * @param resource the resource that is loaded. */ void onComplete(Resource resource); /** * @param e exception thrown when attempting to load. */ default void onFailure(Exception e) {} }
28.411765
75
0.708075
f65f7d8b74c08d4bde289cd5fb3abffa9b58dbf3
1,521
package com.huiyu.blog.security; import com.huiyu.blog.model.User; import com.huiyu.blog.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; @Service public class MongoDBUserDetailsService implements UserDetailsService { @Autowired private UserService userService; @Override public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException { User user = userService.findUserByName(s); if (user == null) { throw new UsernameNotFoundException(s); } return new org.springframework.security.core.userdetails.User( user.getUsername(), user.getPassword(), true, true, true, true, testAuthority() ); } private List<GrantedAuthority> testAuthority() { List<GrantedAuthority> roles = new ArrayList<>(); roles.add(new GrantedAuthority() { @Override public String getAuthority() { return "test_role"; } }); return roles; } }
30.42
86
0.668639
790be64e8d0195c20fb1b36864557c243925bc45
4,220
package net.filebot.web; import static org.junit.Assert.*; import java.util.List; import java.util.Locale; import org.junit.Test; public class AnidbClientTest { static AnidbClient anidb = new AnidbClient("filebot", 6); /** * 74 episodes */ SearchResult monsterSearchResult = new SearchResult(1539, "Monster"); /** * 45 episodes */ SearchResult twelvekingdomsSearchResult = new SearchResult(26, "Juuni Kokuki"); /** * 38 episodes, lots of special characters */ SearchResult princessTutuSearchResult = new SearchResult(516, "Princess Tutu"); @Test public void getAnimeTitles() throws Exception { SearchResult[] animeTitles = anidb.getAnimeTitles(); assertTrue(animeTitles.length > 8000); } @Test public void search() throws Exception { List<SearchResult> results = anidb.search("one piece", Locale.ENGLISH); SearchResult result = results.get(0); assertEquals("One Piece", result.getName()); assertEquals(69, result.getId()); } @Test public void searchNoMatch() throws Exception { List<SearchResult> results = anidb.search("i will not find anything for this query string", Locale.ENGLISH); assertTrue(results.isEmpty()); } @Test public void searchTitleAlias() throws Exception { // Seikai no Senki (main title), Banner of the Stars (official English title) assertEquals("Seikai no Senki", anidb.search("banner of the stars", Locale.ENGLISH).get(0).getName()); assertEquals("Seikai no Senki", anidb.search("seikai no senki", Locale.ENGLISH).get(0).getName()); // no matching title assertEquals("Naruto", anidb.search("naruto", Locale.ENGLISH).get(0).getName()); } @Test public void getEpisodeListAll() throws Exception { List<Episode> list = anidb.getEpisodeList(monsterSearchResult, SortOrder.Airdate, Locale.ENGLISH); assertEquals(77, list.size()); Episode first = list.get(0); assertEquals("Monster", first.getSeriesName()); assertEquals("2004-04-07", first.getSeriesInfo().getStartDate().toString()); assertEquals("Herr Dr. Tenma", first.getTitle()); assertEquals("1", first.getEpisode().toString()); assertEquals("1", first.getAbsolute().toString()); assertEquals(null, first.getSeason()); assertEquals("2004-04-07", first.getAirdate().toString()); assertEquals("17843", first.getId().toString()); } @Test public void getEpisodeListAllShortLink() throws Exception { List<Episode> list = anidb.getEpisodeList(twelvekingdomsSearchResult, SortOrder.Airdate, Locale.ENGLISH); assertEquals(47, list.size()); Episode first = list.get(0); assertEquals("The Twelve Kingdoms", first.getSeriesName()); assertEquals("2002-04-09", first.getSeriesInfo().getStartDate().toString()); assertEquals("Shadow of the Moon, The Sea of Shadow - Chapter 1", first.getTitle()); assertEquals("1", first.getEpisode().toString()); assertEquals("1", first.getAbsolute().toString()); assertEquals(null, first.getSeason()); assertEquals("2002-04-09", first.getAirdate().toString()); } @Test public void getEpisodeListEncoding() throws Exception { assertEquals("Raven Princess - An der schönen blauen Donau", anidb.getEpisodeList(princessTutuSearchResult, SortOrder.Airdate, Locale.ENGLISH).get(6).getTitle()); } @Test public void getEpisodeListI18N() throws Exception { List<Episode> list = anidb.getEpisodeList(monsterSearchResult, SortOrder.Airdate, Locale.JAPANESE); Episode last = list.get(73); assertEquals("MONSTER", last.getSeriesName()); assertEquals("2004-04-07", last.getSeriesInfo().getStartDate().toString()); assertEquals("本当の怪物", last.getTitle()); assertEquals("74", last.getEpisode().toString()); assertEquals("74", last.getAbsolute().toString()); assertEquals(null, last.getSeason()); assertEquals("2005-09-28", last.getAirdate().toString()); } @Test public void getEpisodeListTrimRecap() throws Exception { assertEquals("Sea God of the East, Azure Sea of the West - Transition Chapter", anidb.getEpisodeList(twelvekingdomsSearchResult, SortOrder.Airdate, Locale.ENGLISH).get(44).getTitle()); } @Test public void getEpisodeListLink() throws Exception { assertEquals("http://anidb.net/a1539", anidb.getEpisodeListLink(monsterSearchResult).toURL().toString()); } }
33.492063
186
0.733412
0924fee36c2b3c9bb8a00ee2ef9e49b94f2a93ec
2,857
/* * Copyright 2011 Azwan Adli Abdullah * * 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.gh4a.fragment; import org.eclipse.egit.github.core.Repository; import org.eclipse.egit.github.core.client.PageIterator; import org.eclipse.egit.github.core.service.StarService; import android.os.Bundle; import android.support.v7.widget.RecyclerView; import com.gh4a.Gh4Application; import com.gh4a.R; import com.gh4a.activities.RepositoryActivity; import com.gh4a.adapter.RepositoryAdapter; import com.gh4a.adapter.RootAdapter; import java.util.HashMap; public class StarredRepositoryListFragment extends PagedDataBaseFragment<Repository> { public static StarredRepositoryListFragment newInstance(String login, String sortOrder, String sortDirection) { StarredRepositoryListFragment f = new StarredRepositoryListFragment(); Bundle args = new Bundle(); args.putString("user", login); args.putString("sort_order", sortOrder); args.putString("sort_direction", sortDirection); f.setArguments(args); return f; } private String mLogin; private String mSortOrder; private String mSortDirection; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mLogin = getArguments().getString("user"); mSortOrder = getArguments().getString("sort_order"); mSortDirection = getArguments().getString("sort_direction"); } @Override protected RootAdapter<Repository, ? extends RecyclerView.ViewHolder> onCreateAdapter() { return new RepositoryAdapter(getActivity()); } @Override protected int getEmptyTextResId() { return R.string.no_starred_repos_found; } @Override public void onItemClick(Repository repository) { startActivity(RepositoryActivity.makeIntent(getActivity(), repository)); } @Override protected PageIterator<Repository> onCreateIterator() { StarService starService = (StarService) Gh4Application.get().getService(Gh4Application.STAR_SERVICE); HashMap<String, String> filterData = new HashMap<>(); filterData.put("sort", mSortOrder); filterData.put("direction", mSortDirection); return starService.pageStarred(mLogin, filterData); } }
34.421687
92
0.724536
6c3f4dcd79f421a22f401e3960fe4f457930e6eb
28,982
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.keyboard_accessory.bar_component; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.instanceOf; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import static org.chromium.chrome.browser.keyboard_accessory.AccessoryAction.AUTOFILL_SUGGESTION; import static org.chromium.chrome.browser.keyboard_accessory.AccessoryAction.GENERATE_PASSWORD_AUTOMATIC; import static org.chromium.chrome.browser.keyboard_accessory.bar_component.KeyboardAccessoryProperties.BAR_ITEMS; import static org.chromium.chrome.browser.keyboard_accessory.bar_component.KeyboardAccessoryProperties.SHEET_TITLE; import static org.chromium.chrome.browser.keyboard_accessory.bar_component.KeyboardAccessoryProperties.SKIP_CLOSING_ANIMATION; import static org.chromium.chrome.browser.keyboard_accessory.bar_component.KeyboardAccessoryProperties.VISIBLE; import com.google.android.material.tabs.TabLayout; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.robolectric.annotation.Config; import org.chromium.base.metrics.RecordHistogram; import org.chromium.base.metrics.RecordHistogramJni; import org.chromium.base.metrics.test.ShadowRecordHistogram; import org.chromium.base.task.test.CustomShadowAsyncTask; import org.chromium.base.test.BaseRobolectricTestRunner; import org.chromium.base.test.util.JniMocker; import org.chromium.chrome.browser.flags.ChromeFeatureList; import org.chromium.chrome.browser.keyboard_accessory.AccessoryAction; import org.chromium.chrome.browser.keyboard_accessory.AccessoryBarContents; import org.chromium.chrome.browser.keyboard_accessory.ManualFillingMetricsRecorder; import org.chromium.chrome.browser.keyboard_accessory.bar_component.KeyboardAccessoryProperties.AutofillBarItem; import org.chromium.chrome.browser.keyboard_accessory.bar_component.KeyboardAccessoryProperties.BarItem; import org.chromium.chrome.browser.keyboard_accessory.data.KeyboardAccessoryData; import org.chromium.chrome.browser.keyboard_accessory.data.KeyboardAccessoryData.Action; import org.chromium.chrome.browser.keyboard_accessory.data.PropertyProvider; import org.chromium.chrome.browser.keyboard_accessory.tab_layout_component.KeyboardAccessoryTabLayoutCoordinator; import org.chromium.components.autofill.AutofillDelegate; import org.chromium.components.autofill.AutofillSuggestion; import org.chromium.components.autofill.PopupItemId; import org.chromium.components.feature_engagement.FeatureConstants; import org.chromium.ui.modelutil.ListObservable; import org.chromium.ui.modelutil.PropertyKey; import org.chromium.ui.modelutil.PropertyModel; import org.chromium.ui.modelutil.PropertyObservable.PropertyObserver; import org.chromium.ui.test.util.modelutil.FakeViewProvider; import java.util.HashMap; /** * Controller tests for the keyboard accessory component. */ @RunWith(BaseRobolectricTestRunner.class) @Config(manifest = Config.NONE, shadows = {CustomShadowAsyncTask.class, ShadowRecordHistogram.class}) public class KeyboardAccessoryControllerTest { @Rule public JniMocker mocker = new JniMocker(); @Mock private PropertyObserver<PropertyKey> mMockPropertyObserver; @Mock private ListObservable.ListObserver<Void> mMockActionListObserver; @Mock private KeyboardAccessoryCoordinator.VisibilityDelegate mMockVisibilityDelegate; @Mock private KeyboardAccessoryModernView mMockView; @Mock private KeyboardAccessoryTabLayoutCoordinator mMockTabLayout; @Mock private KeyboardAccessoryCoordinator.TabSwitchingDelegate mMockTabSwitchingDelegate; @Mock private AutofillDelegate mMockAutofillDelegate; @Mock private RecordHistogram.Natives mMockRecordHistogram; private final KeyboardAccessoryData.Tab mTestTab = new KeyboardAccessoryData.Tab("Passwords", null, null, 0, 0, null); private KeyboardAccessoryCoordinator mCoordinator; private PropertyModel mModel; private KeyboardAccessoryMediator mMediator; @Before public void setUp() { ShadowRecordHistogram.reset(); MockitoAnnotations.initMocks(this); setAutofillFeature(false); mocker.mock(RecordHistogramJni.TEST_HOOKS, mMockRecordHistogram); when(mMockView.getTabLayout()).thenReturn(mock(TabLayout.class)); when(mMockTabLayout.getTabSwitchingDelegate()).thenReturn(mMockTabSwitchingDelegate); mCoordinator = new KeyboardAccessoryCoordinator( mMockTabLayout, mMockVisibilityDelegate, new FakeViewProvider<>(mMockView)); mMediator = mCoordinator.getMediatorForTesting(); mModel = mMediator.getModelForTesting(); } private void setAutofillFeature(boolean enabled) { HashMap<String, Boolean> features = new HashMap<>(); features.put(ChromeFeatureList.AUTOFILL_KEYBOARD_ACCESSORY, enabled); ChromeFeatureList.setTestFeatures(features); } @Test public void testCreatesValidSubComponents() { assertThat(mCoordinator, is(notNullValue())); assertThat(mMediator, is(notNullValue())); assertThat(mModel, is(notNullValue())); } @Test public void testModelNotifiesVisibilityChangeOnShowAndHide() { mModel.addObserver(mMockPropertyObserver); // Setting the visibility on the model should make it propagate that it's visible. mModel.set(VISIBLE, true); verify(mMockPropertyObserver).onPropertyChanged(mModel, VISIBLE); assertThat(mModel.get(VISIBLE), is(true)); // Resetting the visibility on the model to should make it propagate that it's visible. mModel.set(VISIBLE, false); verify(mMockPropertyObserver, times(2)).onPropertyChanged(mModel, VISIBLE); assertThat(mModel.get(VISIBLE), is(false)); } @Test public void testModelNotifiesAboutActionsChangedByProvider() { // Set a default tab to prevent visibility changes to trigger now: setTabs(new KeyboardAccessoryData.Tab[] {mTestTab}); mModel.get(BAR_ITEMS).addObserver(mMockActionListObserver); PropertyProvider<Action[]> testProvider = new PropertyProvider<>(GENERATE_PASSWORD_AUTOMATIC); mCoordinator.registerActionProvider(testProvider); // If the coordinator receives an initial actions, the model should report an insertion. mCoordinator.show(); Action testAction = new Action(null, 0, null); testProvider.notifyObservers(new Action[] {testAction}); verify(mMockActionListObserver).onItemRangeInserted(mModel.get(BAR_ITEMS), 0, 1); assertThat(mModel.get(BAR_ITEMS).size(), is(1)); assertThat(mModel.get(BAR_ITEMS).get(0).getAction(), is(equalTo(testAction))); // If the coordinator receives a new set of actions, the model should report a change. testProvider.notifyObservers(new Action[] {testAction}); verify(mMockActionListObserver).onItemRangeChanged(mModel.get(BAR_ITEMS), 0, 1, null); assertThat(mModel.get(BAR_ITEMS).size(), is(1)); assertThat(mModel.get(BAR_ITEMS).get(0).getAction(), is(equalTo(testAction))); // If the coordinator receives an empty set of actions, the model should report a deletion. testProvider.notifyObservers(new Action[] {}); verify(mMockActionListObserver).onItemRangeRemoved(mModel.get(BAR_ITEMS), 0, 1); assertThat(mModel.get(BAR_ITEMS).size(), is(0)); // There should be no notification if no actions are reported repeatedly. testProvider.notifyObservers(new Action[] {}); verifyNoMoreInteractions(mMockActionListObserver); } @Test public void testModelNotifiesAboutActionsChangedByProviderForRedesign() { setAutofillFeature(true); // Set a default tab to prevent visibility changes to trigger now: setTabs(new KeyboardAccessoryData.Tab[] {mTestTab}); mModel.get(BAR_ITEMS).addObserver(mMockActionListObserver); PropertyProvider<Action[]> testProvider = new PropertyProvider<>(GENERATE_PASSWORD_AUTOMATIC); mCoordinator.registerActionProvider(testProvider); // If the coordinator receives an initial action, the model should report an insertion. mCoordinator.show(); Action testAction = new Action(null, 0, null); testProvider.notifyObservers(new Action[] {testAction}); verify(mMockActionListObserver).onItemRangeInserted(mModel.get(BAR_ITEMS), 0, 2); assertThat(mModel.get(BAR_ITEMS).size(), is(2)); // Plus tab switcher. assertThat(mModel.get(BAR_ITEMS).get(0).getAction(), is(equalTo(testAction))); // If the coordinator receives a new set of actions, the model should report a change. testProvider.notifyObservers(new Action[] {testAction}); verify(mMockActionListObserver).onItemRangeChanged(mModel.get(BAR_ITEMS), 0, 2, null); assertThat(mModel.get(BAR_ITEMS).size(), is(2)); // Plus tab switcher. assertThat(mModel.get(BAR_ITEMS).get(0).getAction(), is(equalTo(testAction))); // If the coordinator receives an empty set of actions, the model should report a deletion. testProvider.notifyObservers(new Action[] {}); // First call of onItemRangeChanged(mModel.get(BAR_ITEMS), 0, 1, null); verify(mMockActionListObserver).onItemRangeRemoved(mModel.get(BAR_ITEMS), 1, 1); assertThat(mModel.get(BAR_ITEMS).size(), is(1)); // Only the tab switcher. // There should be no notification if no actions are reported repeatedly. testProvider.notifyObservers(new Action[] {}); verify(mMockActionListObserver, times(2)) .onItemRangeChanged(mModel.get(BAR_ITEMS), 0, 1, null); verifyNoMoreInteractions(mMockActionListObserver); } @Test public void testModelDoesntNotifyUnchangedVisibility() { mModel.addObserver(mMockPropertyObserver); // Setting the visibility on the model should make it propagate that it's visible. mModel.set(VISIBLE, true); verify(mMockPropertyObserver).onPropertyChanged(mModel, VISIBLE); assertThat(mModel.get(VISIBLE), is(true)); // Marking it as visible again should not result in a notification. mModel.set(VISIBLE, true); verify(mMockPropertyObserver) // Unchanged number of invocations. .onPropertyChanged(mModel, VISIBLE); assertThat(mModel.get(VISIBLE), is(true)); } @Test public void testTogglesVisibility() { mCoordinator.show(); assertThat(mModel.get(VISIBLE), is(true)); mCoordinator.dismiss(); assertThat(mModel.get(VISIBLE), is(false)); } @Test public void testSortsActionsBasedOnType() { PropertyProvider<Action[]> generationProvider = new PropertyProvider<>(GENERATE_PASSWORD_AUTOMATIC); PropertyProvider<AutofillSuggestion[]> autofillSuggestionProvider = new PropertyProvider<>(AUTOFILL_SUGGESTION); mCoordinator.registerActionProvider(generationProvider); mCoordinator.registerAutofillProvider(autofillSuggestionProvider, mMockAutofillDelegate); AutofillSuggestion suggestion1 = new AutofillSuggestion( "FirstSuggestion", "", /* itemTag= */ "", 0, false, 0, false, false, false); AutofillSuggestion suggestion2 = new AutofillSuggestion( "SecondSuggestion", "", /* itemTag= */ "", 0, false, 0, false, false, false); Action generationAction = new Action("Generate", GENERATE_PASSWORD_AUTOMATIC, (a) -> {}); autofillSuggestionProvider.notifyObservers( new AutofillSuggestion[] {suggestion1, suggestion2}); generationProvider.notifyObservers(new Action[] {generationAction}); // Autofill suggestions should always come last before mandatory tab switcher. assertThat(mModel.get(BAR_ITEMS).size(), is(3)); assertThat(mModel.get(BAR_ITEMS).get(0).getAction(), is(generationAction)); assertThat(mModel.get(BAR_ITEMS).get(1), instanceOf(AutofillBarItem.class)); AutofillBarItem autofillBarItem1 = (AutofillBarItem) mModel.get(BAR_ITEMS).get(1); assertThat(autofillBarItem1.getSuggestion(), is(suggestion1)); assertThat(mModel.get(BAR_ITEMS).get(2), instanceOf(AutofillBarItem.class)); AutofillBarItem autofillBarItem2 = (AutofillBarItem) mModel.get(BAR_ITEMS).get(2); assertThat(autofillBarItem2.getSuggestion(), is(suggestion2)); } @Test public void testMovesTabSwitcherToEndForRedesign() { setAutofillFeature(true); PropertyProvider<Action[]> generationProvider = new PropertyProvider<>(GENERATE_PASSWORD_AUTOMATIC); PropertyProvider<Action[]> autofillSuggestionProvider = new PropertyProvider<>(AUTOFILL_SUGGESTION); mCoordinator.registerActionProvider(generationProvider); mCoordinator.registerActionProvider(autofillSuggestionProvider); Action suggestion1 = new Action("FirstSuggestion", AUTOFILL_SUGGESTION, (a) -> {}); Action suggestion2 = new Action("SecondSuggestion", AUTOFILL_SUGGESTION, (a) -> {}); Action generationAction = new Action("Generate", GENERATE_PASSWORD_AUTOMATIC, (a) -> {}); autofillSuggestionProvider.notifyObservers(new Action[] {suggestion1, suggestion2}); generationProvider.notifyObservers(new Action[] {generationAction}); // Autofill suggestions should always come last, independent of when they were added. assertThat(mModel.get(BAR_ITEMS).size(), is(4)); // Additional tab switcher assertThat(mModel.get(BAR_ITEMS).get(0).getAction(), is(generationAction)); assertThat(mModel.get(BAR_ITEMS).get(1).getAction(), is(suggestion1)); assertThat(mModel.get(BAR_ITEMS).get(2).getAction(), is(suggestion2)); assertThat(mModel.get(BAR_ITEMS).get(3).getViewType(), is(BarItem.Type.TAB_LAYOUT)); } @Test public void testDeletingActionsAffectsOnlyOneType() { PropertyProvider<Action[]> generationProvider = new PropertyProvider<>(GENERATE_PASSWORD_AUTOMATIC); PropertyProvider<AutofillSuggestion[]> autofillSuggestionProvider = new PropertyProvider<>(AUTOFILL_SUGGESTION); mCoordinator.registerActionProvider(generationProvider); mCoordinator.registerAutofillProvider(autofillSuggestionProvider, mMockAutofillDelegate); AutofillSuggestion suggestion = new AutofillSuggestion( "Suggestion", "", /* itemTag= */ "", 0, false, 0, false, false, false); Action generationAction = new Action("Generate", GENERATE_PASSWORD_AUTOMATIC, (a) -> {}); autofillSuggestionProvider.notifyObservers( new AutofillSuggestion[] {suggestion, suggestion}); generationProvider.notifyObservers(new Action[] {generationAction}); assertThat(mModel.get(BAR_ITEMS).size(), is(3)); // Drop all Autofill suggestions. Only the generation action should remain. autofillSuggestionProvider.notifyObservers(new AutofillSuggestion[0]); assertThat(mModel.get(BAR_ITEMS).size(), is(1)); assertThat(mModel.get(BAR_ITEMS).get(0).getAction(), is(generationAction)); // Readd an Autofill suggestion and drop the generation. Only the suggestion should remain. autofillSuggestionProvider.notifyObservers(new AutofillSuggestion[] {suggestion}); generationProvider.notifyObservers(new Action[0]); assertThat(mModel.get(BAR_ITEMS).size(), is(1)); assertThat(mModel.get(BAR_ITEMS).get(0), instanceOf(AutofillBarItem.class)); AutofillBarItem autofillBarItem = (AutofillBarItem) mModel.get(BAR_ITEMS).get(0); assertThat(autofillBarItem.getSuggestion(), is(suggestion)); } @Test public void testGenerationActionsRemovedWhenNotVisible() { // Make the accessory visible and add an action to it. mCoordinator.show(); mModel.get(BAR_ITEMS).add(new BarItem( BarItem.Type.ACTION_BUTTON, new Action(null, GENERATE_PASSWORD_AUTOMATIC, null))); // Hiding the accessory should also remove actions. mCoordinator.dismiss(); assertThat(mModel.get(BAR_ITEMS).size(), is(0)); } @Test public void testShowsTitleForActiveTabs() { // Add an inactive tab and ensure the sheet title isn't already set. mCoordinator.show(); setTabs(new KeyboardAccessoryData.Tab[] {mTestTab}); mModel.set(SHEET_TITLE, ""); assertThat(mCoordinator.hasActiveTab(), is(false)); // Changing the active tab should also change the title. setActiveTab(mTestTab); assertThat(mModel.get(SHEET_TITLE), equalTo("Passwords")); assertThat(mCoordinator.hasActiveTab(), is(true)); } @Test public void testCreatesAddressItemWithIPH() { PropertyProvider<AutofillSuggestion[]> autofillSuggestionProvider = new PropertyProvider<>(AUTOFILL_SUGGESTION); int suggestionId = 0x1; // The address ID is located in the least 16 bit. AutofillSuggestion addressSuggestion = new AutofillSuggestion( "John", "Main Str", /* itemTag= */ "", 0, false, suggestionId, false, false, false); mCoordinator.registerAutofillProvider(autofillSuggestionProvider, mMockAutofillDelegate); autofillSuggestionProvider.notifyObservers( new AutofillSuggestion[] {addressSuggestion, addressSuggestion, addressSuggestion}); assertThat(getAutofillItemAt(0).getFeatureForIPH(), is(nullValue())); mCoordinator.prepareUserEducation(); assertThat(getAutofillItemAt(0).getFeatureForIPH(), is(FeatureConstants.KEYBOARD_ACCESSORY_ADDRESS_FILL_FEATURE)); assertThat(getAutofillItemAt(1).getFeatureForIPH(), is(nullValue())); assertThat(getAutofillItemAt(2).getFeatureForIPH(), is(nullValue())); } @Test public void testCreatesPaymentItemWithIPH() { PropertyProvider<AutofillSuggestion[]> autofillSuggestionProvider = new PropertyProvider<>(AUTOFILL_SUGGESTION); int suggestionId = 0x10000; // The payment ID is located in the higher 16 bit. AutofillSuggestion paymentSuggestion = new AutofillSuggestion("John", "4828 ****", /* itemTag= */ "", 0, false, suggestionId, false, false, false); mCoordinator.registerAutofillProvider(autofillSuggestionProvider, mMockAutofillDelegate); autofillSuggestionProvider.notifyObservers( new AutofillSuggestion[] {paymentSuggestion, paymentSuggestion, paymentSuggestion}); assertThat(getAutofillItemAt(0).getFeatureForIPH(), is(nullValue())); mCoordinator.prepareUserEducation(); assertThat(getAutofillItemAt(0).getFeatureForIPH(), is(FeatureConstants.KEYBOARD_ACCESSORY_PAYMENT_FILLING_FEATURE)); assertThat(getAutofillItemAt(1).getFeatureForIPH(), is(nullValue())); assertThat(getAutofillItemAt(2).getFeatureForIPH(), is(nullValue())); } @Test public void testCreatesIPHForSecondPasswordItem() { PropertyProvider<AutofillSuggestion[]> autofillSuggestionProvider = new PropertyProvider<>(AUTOFILL_SUGGESTION); AutofillSuggestion passwordSuggestion1 = new AutofillSuggestion("John", "****", /* itemTg= */ "", 0, false, PopupItemId.ITEM_ID_USERNAME_ENTRY, false, false, false); AutofillSuggestion passwordSuggestion2 = new AutofillSuggestion("Eva", "*******", /* itemTag= */ "", 0, false, PopupItemId.ITEM_ID_PASSWORD_ENTRY, false, false, false); mCoordinator.registerAutofillProvider(autofillSuggestionProvider, mMockAutofillDelegate); autofillSuggestionProvider.notifyObservers(new AutofillSuggestion[] { passwordSuggestion1, passwordSuggestion2, passwordSuggestion2}); assertThat(getAutofillItemAt(0).getFeatureForIPH(), is(nullValue())); mCoordinator.prepareUserEducation(); assertThat(getAutofillItemAt(0).getFeatureForIPH(), is(nullValue())); assertThat(getAutofillItemAt(1).getFeatureForIPH(), is(FeatureConstants.KEYBOARD_ACCESSORY_PASSWORD_FILLING_FEATURE)); assertThat(getAutofillItemAt(2).getFeatureForIPH(), is(nullValue())); } @Test public void testSkipAnimationsOnlyUntilNextShow() { assertThat(mModel.get(SKIP_CLOSING_ANIMATION), is(false)); mCoordinator.skipClosingAnimationOnce(); assertThat(mModel.get(SKIP_CLOSING_ANIMATION), is(true)); mCoordinator.show(); assertThat(mModel.get(SKIP_CLOSING_ANIMATION), is(false)); } @Test public void testRecordsOneImpressionForEveryInitialContentOnVisibilityChange() { assertThat(RecordHistogram.getHistogramTotalCountForTesting( KeyboardAccessoryMetricsRecorder.UMA_KEYBOARD_ACCESSORY_BAR_SHOWN), is(0)); // Adding a tab contributes to the tabs and the total bucket. setTabs(new KeyboardAccessoryData.Tab[] {mTestTab}); mCoordinator.show(); assertThat(getShownMetricsCount(AccessoryBarContents.WITH_TABS), is(1)); assertThat(getShownMetricsCount(AccessoryBarContents.ANY_CONTENTS), is(1)); // Adding an action contributes to the actions bucket. Tabs and total are logged again. mCoordinator.dismiss(); // Hide, so it's brought up again. mModel.get(BAR_ITEMS).add(new BarItem( BarItem.Type.ACTION_BUTTON, new Action(null, GENERATE_PASSWORD_AUTOMATIC, null))); mCoordinator.show(); assertThat(getShownMetricsCount(AccessoryBarContents.WITH_ACTIONS), is(1)); assertThat(getShownMetricsCount(AccessoryBarContents.WITH_TABS), is(2)); assertThat(getShownMetricsCount(AccessoryBarContents.ANY_CONTENTS), is(2)); // Adding suggestions adds to the suggestions bucket - and again to tabs and total. mCoordinator.dismiss(); // Hide, so it's brought up again. PropertyProvider<AutofillSuggestion[]> autofillSuggestionProvider = new PropertyProvider<>(AUTOFILL_SUGGESTION); AutofillSuggestion suggestion = new AutofillSuggestion( "Label", "sublabel", /* itemTag= */ "", 0, false, 0, false, false, false); mCoordinator.registerAutofillProvider(autofillSuggestionProvider, mMockAutofillDelegate); autofillSuggestionProvider.notifyObservers(new AutofillSuggestion[] {suggestion}); mCoordinator.show(); // Hiding the keyboard clears actions, so don't log more actions from here on out. assertThat(getShownMetricsCount(AccessoryBarContents.WITH_AUTOFILL_SUGGESTIONS), is(1)); assertThat(getShownMetricsCount(AccessoryBarContents.WITH_ACTIONS), is(1)); assertThat(getShownMetricsCount(AccessoryBarContents.WITH_TABS), is(3)); assertThat(getShownMetricsCount(AccessoryBarContents.ANY_CONTENTS), is(3)); // Removing suggestions adds to everything but the suggestions bucket. The value remains. mCoordinator.dismiss(); // Hide, so it's brought up again. autofillSuggestionProvider.notifyObservers(new AutofillSuggestion[0]); mCoordinator.show(); assertThat(getShownMetricsCount(AccessoryBarContents.WITH_AUTOFILL_SUGGESTIONS), is(1)); assertThat(getShownMetricsCount(AccessoryBarContents.WITH_ACTIONS), is(1)); assertThat(getShownMetricsCount(AccessoryBarContents.WITH_TABS), is(4)); assertThat(getShownMetricsCount(AccessoryBarContents.ANY_CONTENTS), is(4)); } @Test public void testRecordsContentBarImpressionOnceAndContentsUpToOnce() { assertThat(RecordHistogram.getHistogramTotalCountForTesting( KeyboardAccessoryMetricsRecorder.UMA_KEYBOARD_ACCESSORY_BAR_SHOWN), is(0)); // First showing contains tabs only. setTabs(new KeyboardAccessoryData.Tab[] {mTestTab}); mCoordinator.show(); assertThat(getShownMetricsCount(AccessoryBarContents.WITH_TABS), is(1)); assertThat(getShownMetricsCount(AccessoryBarContents.ANY_CONTENTS), is(1)); // New actions are recorded in specific buckets but don't affect the general ANY_CONTENTS. mModel.get(BAR_ITEMS).add(new BarItem( BarItem.Type.ACTION_BUTTON, new Action(null, GENERATE_PASSWORD_AUTOMATIC, null))); assertThat(getShownMetricsCount(AccessoryBarContents.WITH_ACTIONS), is(1)); assertThat(getShownMetricsCount(AccessoryBarContents.ANY_CONTENTS), is(1)); PropertyProvider<AutofillSuggestion[]> autofillSuggestionProvider = new PropertyProvider<>(AUTOFILL_SUGGESTION); AutofillSuggestion suggestion = new AutofillSuggestion( "Label", "sublabel", /* itemTag= */ "", 0, false, 0, false, false, false); mCoordinator.registerAutofillProvider(autofillSuggestionProvider, mMockAutofillDelegate); autofillSuggestionProvider.notifyObservers(new AutofillSuggestion[] {suggestion}); assertThat(getShownMetricsCount(AccessoryBarContents.WITH_AUTOFILL_SUGGESTIONS), is(1)); // The other changes were not recorded again - just the changes. assertThat(getShownMetricsCount(AccessoryBarContents.WITH_ACTIONS), is(1)); assertThat(getShownMetricsCount(AccessoryBarContents.WITH_TABS), is(1)); assertThat(getShownMetricsCount(AccessoryBarContents.NO_CONTENTS), is(0)); } @Test public void testRecordsAgainIfExistingItemsChange() { assertThat(RecordHistogram.getHistogramTotalCountForTesting( KeyboardAccessoryMetricsRecorder.UMA_KEYBOARD_ACCESSORY_BAR_SHOWN), is(0)); // Add a tab and show, so the accessory is permanently visible. setTabs(new KeyboardAccessoryData.Tab[] {mTestTab}); mCoordinator.show(); // Adding an action fills the bar impression bucket and the actions set once. mModel.get(BAR_ITEMS).set( new BarItem[] {new BarItem(BarItem.Type.ACTION_BUTTON, new Action("One", GENERATE_PASSWORD_AUTOMATIC, null)), new BarItem(BarItem.Type.ACTION_BUTTON, new Action("Two", GENERATE_PASSWORD_AUTOMATIC, null))}); assertThat(getGenerationImpressionCount(), is(1)); assertThat(getShownMetricsCount(AccessoryBarContents.WITH_ACTIONS), is(1)); // Adding another action leaves bar impressions unchanged but affects the actions bucket. mModel.get(BAR_ITEMS).set( new BarItem[] {new BarItem(BarItem.Type.ACTION_BUTTON, new Action("Uno", GENERATE_PASSWORD_AUTOMATIC, null)), new BarItem(BarItem.Type.ACTION_BUTTON, new Action("Dos", GENERATE_PASSWORD_AUTOMATIC, null))}); assertThat(getShownMetricsCount(AccessoryBarContents.WITH_ACTIONS), is(1)); assertThat(getGenerationImpressionCount(), is(2)); } private int getGenerationImpressionCount() { return RecordHistogram.getHistogramValueCountForTesting( ManualFillingMetricsRecorder.UMA_KEYBOARD_ACCESSORY_ACTION_IMPRESSION, AccessoryAction.GENERATE_PASSWORD_AUTOMATIC); } private int getShownMetricsCount(@AccessoryBarContents int bucket) { return RecordHistogram.getHistogramValueCountForTesting( KeyboardAccessoryMetricsRecorder.UMA_KEYBOARD_ACCESSORY_BAR_SHOWN, bucket); } private void setTabs(KeyboardAccessoryData.Tab[] tabs) { mCoordinator.setTabs(tabs); when(mMockTabSwitchingDelegate.hasTabs()).thenReturn(true); } private void setActiveTab(KeyboardAccessoryData.Tab tab) { when(mMockTabSwitchingDelegate.getActiveTab()).thenReturn(tab); when(mMockTabSwitchingDelegate.hasTabs()).thenReturn(true); mCoordinator.getMediatorForTesting().onActiveTabChanged(0); } private AutofillBarItem getAutofillItemAt(int position) { return (AutofillBarItem) mModel.get(BAR_ITEMS).get(position); } }
51.846154
126
0.721034
002a71a455c88266dca20e22e592488718059fe7
396
package com.sliit.af.model.repository; import java.util.List; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.stereotype.Repository; import com.sliit.af.model.CourseMaterial; @Repository public interface CourseMaterialRepository extends MongoRepository<CourseMaterial, String> { public List<CourseMaterial> findByCourseNo(String courseNo); }
24.75
91
0.838384
8477b55196e75f0d9b574435008294113e699366
2,444
/* * Copyright (C) 2011 Eiichiro Uchiumi. All Rights Reserved. * * 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.eiichiro.acidhouse; import org.eiichiro.acidhouse.metamodel.Property; /** * {@code Filter} qualifies the entities to which a {@code Command} is applied. * You can get {@code Filter} instances from metamodel property and can pass to * {@code GetList}, {@code GetScalar}, {@code Update} and {@code Delete}'s * {@code filter(Filter...)} method. * As an example in App Engine: * <pre> * import org.eiichiro.acidhouse.Session; * import org.eiichiro.acidhouse.appengine.AppEngineDatastoreSession; * ... * * // Creating 'Session' instance. * Session session = new AppEngineDatastoreSession(); * // Getting metamodel instance of 'Entity3' class. * Entity3_ entity3_ = Metamodels.metamodel(Entity3.class); * // Qualifying entities which their 'entity1.i' proerty is greater than or * // equal to 13, and 15 or 16. * List&lt;Entity3&gt; entity3s = session * .get(entity3_) * .filter(entity3_.entity1.i.greaterThanOrEqualTo(13), * entity3_.entity1.i.in(15, 16)) * .execute(); * </pre> * * @see ComparableProperty * @see Metamodel * @see GetList * @see GetScalar * @see Update * @see Delete * @author <a href="mailto:mail@eiichiro.org">Eiichiro Uchiumi</a> */ public interface Filter<T> { /** * Returns the metamodel {@code Property} this {@code Filter} is applied to. * * @return The metamodel {@code Property} this {@code Filter} is applied to. */ public Property<?, T> property(); /** * Indicates whether the specified entity matches to this {@code Filter} or * not. This method is invoked by {@code Command} implementation for * in-memory filtering. * * @param entity The entity to be filtered. * @return Whether the specified entity matches to this {@code Filter} or * not. */ public boolean matches(Object entity); }
33.479452
80
0.699673
7f91cdd455b06acef5664063c96214ae895f3019
548
package work.koreyoshi.base.exception; /** * @author zhoujx */ public class FileException extends BaseCustomException{ public FileException(String message, int code){ this.message = message; this.code = code; } public static FileException notExists(){ return new FileException("文件不存在", 20030); } public static FileException readError(){ return new FileException("文件读失败", 20010); } public static FileException writeError(){ return new FileException("文件写失败", 20020); } }
21.92
55
0.662409
8cb27168e407fd51a3fa5acd792908f590651ad3
521
import static junit.framework.TestCase.assertEquals; import static org.junit.Assert.assertNotEquals; import org.junit.Test; public class ComparadorTest { @Test public void numeros_iguales() { ComparadorDeValores valorEsperado = new ComparadorDeValores(5); assertEquals(valorEsperado, new ComparadorDeValores(5)); } @Test public void numeros_diferentes() { ComparadorDeValores valorEsperado = new ComparadorDeValores(5); assertNotEquals(valorEsperado, new ComparadorDeValores(10)); } }
22.652174
65
0.769674