conflict_resolution
stringlengths
27
16k
<<<<<<< ======= import io.micrometer.core.instrument.Counter; >>>>>>> import io.micrometer.core.instrument.Counter; <<<<<<< import org.junit.jupiter.api.extension.ExtendWith; import ru.lanwen.wiremock.ext.WiremockResolver; ======= import reactor.ipc.netty.NettyContext; import reactor.ipc.netty.http.server.HttpServer; >>>>>>> import org.junit.jupiter.api.extension.ExtendWith; import ru.lanwen.wiremock.ext.WiremockResolver; import java.util.concurrent.TimeUnit; <<<<<<< @ExtendWith(WiremockResolver.class) ======= import static org.assertj.core.api.Assertions.assertThat; >>>>>>> @ExtendWith(WiremockResolver.class) <<<<<<< void encodeMetricName(@WiremockResolver.Wiremock WireMockServer server) { ======= void encodeMetricName() throws InterruptedException { CountDownLatch metadataRequests = new CountDownLatch(1); AtomicReference<String> metadataMetricName = new AtomicReference<>(); AtomicReference<String> requestBody = new AtomicReference<>(); Pattern p = Pattern.compile("/api/v1/metrics/([^?]+)\\?.*"); NettyContext server = HttpServer.create(0) .newHandler((req, resp) -> { Matcher matcher = p.matcher(req.uri()); if (matcher.matches()) { metadataMetricName.set(matcher.group(1)); metadataRequests.countDown(); } requestBody.set(req.receive().asString().blockFirst()); return req.receive().then(resp.status(200).send()); }).block(); >>>>>>> void encodeMetricName(@WiremockResolver.Wiremock WireMockServer server) { <<<<<<< return server.baseUrl(); ======= return "http://localhost:" + server.address().getPort(); >>>>>>> return server.baseUrl(); <<<<<<< server.stubFor(any(anyUrl())); registry.counter("my.counter#abc").increment(); registry.publish(); server.verify(putRequestedFor(urlMatching("/api/v1/metrics/my.counter%23abc?.+"))); ======= try { Counter.builder("my.counter#abc") .baseUnit(TimeUnit.MICROSECONDS.toString().toLowerCase()) .register(registry) .increment(Math.PI); registry.publish(); metadataRequests.await(10, TimeUnit.SECONDS); assertThat(metadataMetricName.get()).isEqualTo("my.counter%23abc"); assertThat(requestBody.get()).isEqualTo("{\"type\":\"count\",\"unit\":\"microsecond\"}"); } finally { server.dispose(); registry.close(); } >>>>>>> server.stubFor(any(anyUrl())); Counter.builder("my.counter#abc") .baseUnit(TimeUnit.MICROSECONDS.toString().toLowerCase()) .register(registry) .increment(Math.PI); registry.publish(); server.verify(putRequestedFor( urlMatching("/api/v1/metrics/my.counter%23abc?.+")) .withRequestBody(equalToJson("{\"type\":\"count\",\"unit\":\"microsecond\"}") )); registry.close();
<<<<<<< import static io.micrometer.core.instrument.util.StringEscapeUtils.escapeJson; import static java.util.Objects.requireNonNull; ======= import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toList; >>>>>>> import static io.micrometer.core.instrument.util.StringEscapeUtils.escapeJson; <<<<<<< this.config = config; this.httpClient = httpClient; ======= >>>>>>>
<<<<<<< import java.util.function.Function; ======= import okhttp3.Cache; >>>>>>> import java.util.function.Function; import okhttp3.Cache; <<<<<<< @Test void requestTagsWithClass(@WiremockResolver.Wiremock WireMockServer server) throws IOException { Request request = new Request.Builder() .url(server.baseUrl() + "/helloworld.txt") .tag(Tags.class, Tags.of("requestTag1", "tagValue1")) .build(); testRequestTags(server, request); } @Test void requestTagsWithoutClass(@WiremockResolver.Wiremock WireMockServer server) throws IOException { Request request = new Request.Builder() .url(server.baseUrl() + "/helloworld.txt") .tag(Tags.of("requestTag1", "tagValue1")) .build(); testRequestTags(server, request); } private void testRequestTags(@WiremockResolver.Wiremock WireMockServer server, Request request) throws IOException { server.stubFor(any(anyUrl())); OkHttpClient client = new OkHttpClient.Builder() .eventListener(OkHttpMetricsEventListener.builder(registry, "okhttp.requests") .uriMapper(req -> req.url().encodedPath()) .tags(Tags.of("foo", "bar")) .build()) .build(); client.newCall(request).execute().close(); assertThat(registry.get("okhttp.requests") .tags("foo", "bar", "uri", "/helloworld.txt", "status", "200", "requestTag1", "tagValue1") .timer().count()).isEqualTo(1L); } ======= @Test void cachedResponsesDoNotLeakMemory(@WiremockResolver.Wiremock WireMockServer server, @TempDir Path tempDir) throws IOException { OkHttpMetricsEventListener okHttpMetricsEventListener = OkHttpMetricsEventListener.builder(registry, "okhttp.requests").build(); OkHttpClient clientWithCache = new OkHttpClient.Builder() .eventListener(okHttpMetricsEventListener) .cache(new Cache(tempDir.toFile(), 55555)) .build(); server.stubFor(any(anyUrl()).willReturn(aResponse().withHeader("Cache-Control", "max-age=9600"))); Request request = new Request.Builder() .url(server.baseUrl()) .build(); clientWithCache.newCall(request).execute().close(); assertThat(okHttpMetricsEventListener.callState).isEmpty(); try (Response response = clientWithCache.newCall(request).execute()) { assertThat(response.cacheResponse()).isNotNull(); } assertThat(okHttpMetricsEventListener.callState).isEmpty(); } >>>>>>> @Test void cachedResponsesDoNotLeakMemory(@WiremockResolver.Wiremock WireMockServer server, @TempDir Path tempDir) throws IOException { OkHttpMetricsEventListener okHttpMetricsEventListener = OkHttpMetricsEventListener.builder(registry, "okhttp.requests").build(); OkHttpClient clientWithCache = new OkHttpClient.Builder() .eventListener(okHttpMetricsEventListener) .cache(new Cache(tempDir.toFile(), 55555)) .build(); server.stubFor(any(anyUrl()).willReturn(aResponse().withHeader("Cache-Control", "max-age=9600"))); Request request = new Request.Builder() .url(server.baseUrl()) .build(); clientWithCache.newCall(request).execute().close(); assertThat(okHttpMetricsEventListener.callState).isEmpty(); try (Response response = clientWithCache.newCall(request).execute()) { assertThat(response.cacheResponse()).isNotNull(); } assertThat(okHttpMetricsEventListener.callState).isEmpty(); } @Test void requestTagsWithClass(@WiremockResolver.Wiremock WireMockServer server) throws IOException { Request request = new Request.Builder() .url(server.baseUrl() + "/helloworld.txt") .tag(Tags.class, Tags.of("requestTag1", "tagValue1")) .build(); testRequestTags(server, request); } @Test void requestTagsWithoutClass(@WiremockResolver.Wiremock WireMockServer server) throws IOException { Request request = new Request.Builder() .url(server.baseUrl() + "/helloworld.txt") .tag(Tags.of("requestTag1", "tagValue1")) .build(); testRequestTags(server, request); } private void testRequestTags(@WiremockResolver.Wiremock WireMockServer server, Request request) throws IOException { server.stubFor(any(anyUrl())); OkHttpClient client = new OkHttpClient.Builder() .eventListener(OkHttpMetricsEventListener.builder(registry, "okhttp.requests") .uriMapper(req -> req.url().encodedPath()) .tags(Tags.of("foo", "bar")) .build()) .build(); client.newCall(request).execute().close(); assertThat(registry.get("okhttp.requests") .tags("foo", "bar", "uri", "/helloworld.txt", "status", "200", "requestTag1", "tagValue1") .timer().count()).isEqualTo(1L); }
<<<<<<< // fetch metrics registry.get("kafka.consumer.records.lag.max").tags(tags).gauge(); // consumer coordinator metrics registry.get("kafka.consumer.assigned.partitions").tags(tags).gauge(); ======= // consumer group metrics registry.get("kafka.consumer.assigned.partitions").tag("client.id", "consumer-1").gauge(); >>>>>>> // consumer coordinator metrics registry.get("kafka.consumer.assigned.partitions").tags(tags).gauge();
<<<<<<< private Stream<String> writeFunctionCounter(FunctionCounter counter) { return Stream.of(event(counter.getId(), new Attribute("throughput", counter.count()))); ======= // VisibleForTesting Stream<String> writeCounter(FunctionCounter counter) { double count = counter.count(); if (Double.isFinite(count)) { return Stream.of(event(counter.getId(), new Attribute("throughput", count))); } return Stream.empty(); >>>>>>> // VisibleForTesting Stream<String> writeFunctionCounter(FunctionCounter counter) { double count = counter.count(); if (Double.isFinite(count)) { return Stream.of(event(counter.getId(), new Attribute("throughput", count))); } return Stream.empty(); <<<<<<< private Stream<String> writeTimeGauge(TimeGauge gauge) { ======= // VisibleForTesting Stream<String> writeGauge(TimeGauge gauge) { >>>>>>> // VisibleForTesting Stream<String> writeTimeGauge(TimeGauge gauge) {
<<<<<<< * Copyright 2019 Pivotal Software, Inc. ======= * Copyright 2018 VMware, Inc. >>>>>>> * Copyright 2019 VMware, Inc.
<<<<<<< private final Iterable<BiFunction<Request, Response, Tag>> contextSpecificTags; private final boolean includeHostTag; ======= private final Iterable<Tag> unknownRequestTags; >>>>>>> private final Iterable<BiFunction<Request, Response, Tag>> contextSpecificTags; private final Iterable<Tag> unknownRequestTags; private final boolean includeHostTag; <<<<<<< protected OkHttpMetricsEventListener(MeterRegistry registry, String requestsMetricName, Function<Request, String> urlMapper, Iterable<Tag> extraTags, Iterable<BiFunction<Request, Response, Tag>> contextSpecificTags) { this(registry, requestsMetricName, urlMapper, extraTags, contextSpecificTags, true); } OkHttpMetricsEventListener(MeterRegistry registry, String requestsMetricName, Function<Request, String> urlMapper, Iterable<Tag> extraTags, Iterable<BiFunction<Request, Response, Tag>> contextSpecificTags, boolean includeHostTag) { ======= OkHttpMetricsEventListener(MeterRegistry registry, String requestsMetricName, Function<Request, String> urlMapper, Iterable<Tag> extraTags, Iterable<String> requestTagKeys) { >>>>>>> protected OkHttpMetricsEventListener(MeterRegistry registry, String requestsMetricName, Function<Request, String> urlMapper, Iterable<Tag> extraTags, Iterable<BiFunction<Request, Response, Tag>> contextSpecificTags) { this(registry, requestsMetricName, urlMapper, extraTags, contextSpecificTags, emptyList(), true); } OkHttpMetricsEventListener(MeterRegistry registry, String requestsMetricName, Function<Request, String> urlMapper, Iterable<Tag> extraTags, Iterable<BiFunction<Request, Response, Tag>> contextSpecificTags, Iterable<String> requestTagKeys, boolean includeHostTag) { <<<<<<< this.contextSpecificTags = contextSpecificTags; this.includeHostTag = includeHostTag; ======= List<Tag> unknownRequestTags = new ArrayList<>(); for (String requestTagKey : requestTagKeys) { unknownRequestTags.add(Tag.of(requestTagKey, "UNKNOWN")); } this.unknownRequestTags = unknownRequestTags; >>>>>>> this.contextSpecificTags = contextSpecificTags; this.includeHostTag = includeHostTag; List<Tag> unknownRequestTags = new ArrayList<>(); for (String requestTagKey : requestTagKeys) { unknownRequestTags.add(Tag.of(requestTagKey, "UNKNOWN")); } this.unknownRequestTags = unknownRequestTags; <<<<<<< // NOTE: This feature won't work with Prometheus meter registry due to tag mismatch. Tags requestTags = requestAvailable ? getRequestTags(request) : Tags.empty(); Iterable<Tag> tags = Tags.of( "method", requestAvailable ? request.method() : TAG_VALUE_UNKNOWN, "uri", getUriTag(state, request), "status", getStatusMessage(state.response, state.exception) ) .and(extraTags) .and(stream(contextSpecificTags.spliterator(), false) .map(contextTag -> contextTag.apply(request, state.response)) .collect(toList())) .and(requestTags) .and(generateTagsForRoute(request)); if (includeHostTag) { tags = Tags.of(tags).and("host", requestAvailable ? request.url().host() : TAG_VALUE_UNKNOWN); } ======= Iterable<Tag> tags = Tags.concat(extraTags, Tags.of( "method", requestAvailable ? request.method() : "UNKNOWN", "uri", getUriTag(state, request), "status", getStatusMessage(state.response, state.exception), "host", requestAvailable ? request.url().host() : "UNKNOWN" )).and(getRequestTags(request)); >>>>>>> Iterable<Tag> tags = Tags.of( "method", requestAvailable ? request.method() : TAG_VALUE_UNKNOWN, "uri", getUriTag(state, request), "status", getStatusMessage(state.response, state.exception) ) .and(extraTags) .and(stream(contextSpecificTags.spliterator(), false) .map(contextTag -> contextTag.apply(request, state.response)) .collect(toList())) .and(getRequestTags(request)) .and(generateTagsForRoute(request)); if (includeHostTag) { tags = Tags.of(tags).and("host", requestAvailable ? request.url().host() : TAG_VALUE_UNKNOWN); } <<<<<<< private Tags tags = Tags.empty(); private Collection<BiFunction<Request, Response, Tag>> contextSpecificTags = new ArrayList<>(); private boolean includeHostTag = true; ======= private Iterable<Tag> tags = Collections.emptyList(); private Iterable<String> requestTagKeys = Collections.emptyList(); >>>>>>> private Tags tags = Tags.empty(); private Collection<BiFunction<Request, Response, Tag>> contextSpecificTags = new ArrayList<>(); private boolean includeHostTag = true; private Iterable<String> requestTagKeys = Collections.emptyList(); <<<<<<< /** * Historically, OkHttp Metrics provided by {@link OkHttpMetricsEventListener} included a * {@code host} tag for the target host being called. To align with other HTTP client metrics, * this was changed to {@code target.host}, but to maintain backwards compatibility the {@code host} * tag can also be included. By default, {@code includeHostTag} is {@literal true} so both tags are included. * * @param includeHostTag whether to include the {@code host} tag * @return this builder * @since 1.5.0 */ public Builder includeHostTag(boolean includeHostTag) { this.includeHostTag = includeHostTag; return this; } ======= /** * Tag keys for {@link Request#tag()} or {@link Request#tag(Class)}. * * These keys will be added with {@literal UNKNOWN} values when {@link Request} is {@literal null}. * Note that this is required only for Prometheus as it requires tag match for the same metric. * * @param requestTagKeys request tag keys * @return this builder * @since 1.3.9 */ public Builder requestTagKeys(String... requestTagKeys) { return requestTagKeys(Arrays.asList(requestTagKeys)); } /** * Tag keys for {@link Request#tag()} or {@link Request#tag(Class)}. * * These keys will be added with {@literal UNKNOWN} values when {@link Request} is {@literal null}. * Note that this is required only for Prometheus as it requires tag match for the same metric. * * @param requestTagKeys request tag keys * @return this builder * @since 1.3.9 */ public Builder requestTagKeys(Iterable<String> requestTagKeys) { this.requestTagKeys = requestTagKeys; return this; } >>>>>>> /** * Historically, OkHttp Metrics provided by {@link OkHttpMetricsEventListener} included a * {@code host} tag for the target host being called. To align with other HTTP client metrics, * this was changed to {@code target.host}, but to maintain backwards compatibility the {@code host} * tag can also be included. By default, {@code includeHostTag} is {@literal true} so both tags are included. * * @param includeHostTag whether to include the {@code host} tag * @return this builder * @since 1.5.0 */ public Builder includeHostTag(boolean includeHostTag) { this.includeHostTag = includeHostTag; return this; } /** * Tag keys for {@link Request#tag()} or {@link Request#tag(Class)}. * * These keys will be added with {@literal UNKNOWN} values when {@link Request} is {@literal null}. * Note that this is required only for Prometheus as it requires tag match for the same metric. * * @param requestTagKeys request tag keys * @return this builder * @since 1.3.9 */ public Builder requestTagKeys(String... requestTagKeys) { return requestTagKeys(Arrays.asList(requestTagKeys)); } /** * Tag keys for {@link Request#tag()} or {@link Request#tag(Class)}. * * These keys will be added with {@literal UNKNOWN} values when {@link Request} is {@literal null}. * Note that this is required only for Prometheus as it requires tag match for the same metric. * * @param requestTagKeys request tag keys * @return this builder * @since 1.3.9 */ public Builder requestTagKeys(Iterable<String> requestTagKeys) { this.requestTagKeys = requestTagKeys; return this; } <<<<<<< return new OkHttpMetricsEventListener(registry, name, uriMapper, tags, contextSpecificTags, includeHostTag); ======= return new OkHttpMetricsEventListener(registry, name, uriMapper, tags, requestTagKeys); >>>>>>> return new OkHttpMetricsEventListener(registry, name, uriMapper, tags, contextSpecificTags, requestTagKeys, includeHostTag);
<<<<<<< import java.util.Map; import java.util.concurrent.ConcurrentHashMap; ======= import java.util.Arrays; import java.util.Collection; import java.util.concurrent.CopyOnWriteArrayList; >>>>>>> import java.util.Arrays; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; <<<<<<< Timer timer = new StatsdTimer(id, lineBuilder(id), processor, clock, distributionStatisticConfig, pauseDetector, getBaseTimeUnit(), ======= // Adds an infinity bucket for SLA violation calculation if (distributionStatisticConfig.getSlaBoundaries() != null) { distributionStatisticConfig = addInfBucket(distributionStatisticConfig); } Timer timer = new StatsdTimer(id, lineBuilder(id), publisher, clock, distributionStatisticConfig, pauseDetector, getBaseTimeUnit(), >>>>>>> // Adds an infinity bucket for SLA violation calculation if (distributionStatisticConfig.getSlaBoundaries() != null) { distributionStatisticConfig = addInfBucket(distributionStatisticConfig); } Timer timer = new StatsdTimer(id, lineBuilder(id), processor, clock, distributionStatisticConfig, pauseDetector, getBaseTimeUnit(), <<<<<<< DistributionSummary summary = new StatsdDistributionSummary(id, lineBuilder(id), processor, clock, distributionStatisticConfig, scale); ======= // Adds an infinity bucket for SLA violation calculation if (distributionStatisticConfig.getSlaBoundaries() != null) { distributionStatisticConfig = addInfBucket(distributionStatisticConfig); } DistributionSummary summary = new StatsdDistributionSummary(id, lineBuilder(id), publisher, clock, distributionStatisticConfig, scale); >>>>>>> // Adds an infinity bucket for SLA violation calculation if (distributionStatisticConfig.getSlaBoundaries() != null) { distributionStatisticConfig = addInfBucket(distributionStatisticConfig); } DistributionSummary summary = new StatsdDistributionSummary(id, lineBuilder(id), processor, clock, distributionStatisticConfig, scale);
<<<<<<< * Copyright 2019 Pivotal Software, Inc. ======= * Copyright 2017 VMware, Inc. >>>>>>> * Copyright 2019 VMware, Inc.
<<<<<<< this.tags = HashTreePMap.empty(); this.conventionTags = id.getTagsAsIterable().iterator().hasNext() ? id.getConventionTags(this.namingConvention).stream() .map(t -> sanitize(t.getKey()) + ":" + sanitize(t.getValue())) .collect(Collectors.joining(",")) : null; ======= synchronized (tagsLock) { this.tags = HashTreePMap.empty(); this.conventionTags = id.getTags().iterator().hasNext() ? id.getConventionTags(this.namingConvention).stream() .map(t -> sanitize(t.getKey()) + ":" + sanitize(t.getValue())) .collect(Collectors.joining(",")) : null; } >>>>>>> synchronized (tagsLock) { this.tags = HashTreePMap.empty(); this.conventionTags = id.getTagsAsIterable().iterator().hasNext() ? id.getConventionTags(this.namingConvention).stream() .map(t -> sanitize(t.getKey()) + ":" + sanitize(t.getValue())) .collect(Collectors.joining(",")) : null; }
<<<<<<< private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(); @Nullable ======= private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(new DaemonThreadFactory()); >>>>>>> private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(new DaemonThreadFactory()); @Nullable
<<<<<<< return majorVersion == null || majorVersion < 7 ? TEMPLATE_BODY_BEFORE_VERSION_7 : TEMPLATE_BODY_AFTER_VERSION_7; ======= return majorVersion < 7 ? TEMPLATE_BODY_BEFORE_VERSION_7.apply(config.index()) : TEMPLATE_BODY_AFTER_VERSION_7.apply(config.index()); >>>>>>> return majorVersion == null || majorVersion < 7 ? TEMPLATE_BODY_BEFORE_VERSION_7.apply(config.index()) : TEMPLATE_BODY_AFTER_VERSION_7.apply(config.index());
<<<<<<< import io.micrometer.core.lang.Nullable; ======= import io.micrometer.core.util.internal.logging.InternalLogger; import io.micrometer.core.util.internal.logging.InternalLoggerFactory; >>>>>>> import io.micrometer.core.lang.Nullable; import io.micrometer.core.util.internal.logging.InternalLogger; import io.micrometer.core.util.internal.logging.InternalLoggerFactory; <<<<<<< this(config, clock, new NamedThreadFactory("logging-metrics-publisher"), defaultLoggingSink(), null); ======= this(config, clock, new NamedThreadFactory("logging-metrics-publisher"), log::info); >>>>>>> this(config, clock, new NamedThreadFactory("logging-metrics-publisher"), log::info, null); <<<<<<< private static Consumer<String> defaultLoggingSink() { try { Class<?> slf4jLogger = Class.forName("org.slf4j.LoggerFactory"); Object logger = slf4jLogger.getMethod("getLogger", Class.class).invoke(null, LoggingMeterRegistry.class); final Method loggerInfo = logger.getClass().getMethod("info", String.class); return stmt -> { try { loggerInfo.invoke(logger, stmt); } catch (IllegalAccessException | InvocationTargetException e) { throw new RuntimeException(e); // should never happen } }; } catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { return System.out::println; } } private Function<Meter, String> defaultMeterIdPrinter() { return (meter) -> getConventionName(meter.getId()) + getConventionTags(meter.getId()).stream() .map(t -> t.getKey() + "=" + t.getValue()) .collect(joining(",", "{", "}")); } ======= >>>>>>> private Function<Meter, String> defaultMeterIdPrinter() { return (meter) -> getConventionName(meter.getId()) + getConventionTags(meter.getId()).stream() .map(t -> t.getKey() + "=" + t.getValue()) .collect(joining(",", "{", "}")); } <<<<<<< private Consumer<String> loggingSink = defaultLoggingSink(); @Nullable private Function<Meter, String> meterIdPrinter; ======= private Consumer<String> loggingSink = log::info; >>>>>>> private Consumer<String> loggingSink = log::info; @Nullable private Function<Meter, String> meterIdPrinter;
<<<<<<< @Issue("#987") @Test void indexNameSupportsIndexNameWithoutDateSuffix() { ElasticMeterRegistry registry = new ElasticMeterRegistry(new ElasticConfig() { @Override public String get(String key) { return null; } @Override public String index() { return "my-metrics"; } @Override public String indexDateFormat() { return ""; } @Override public String indexDateSeparator() { return ""; } }, clock); assertThat(registry.indexName()).isEqualTo("my-metrics"); } ======= @Issue("#1505") @Test void getVersionWhenVersionIs5AndNotPrettyPrinted() { String responseBody = "{\"status\":200,\"name\":\"Sematext-Logsene\",\"cluster_name\":\"elasticsearch\",\"cluster_uuid\":\"anything\",\"version\":{\"number\":\"5.3.0\",\"build_hash\":\"3adb13b\",\"build_date\":\"2017-03-23T03:31:50.652Z\",\"build_snapshot\":false,\"lucene_version\":\"6.4.1\"},\"tagline\":\"You Know, for Search\"}"; assertThat(ElasticMeterRegistry.getMajorVersion(responseBody)).isEqualTo(5); } >>>>>>> @Issue("#987") @Test void indexNameSupportsIndexNameWithoutDateSuffix() { ElasticMeterRegistry registry = new ElasticMeterRegistry(new ElasticConfig() { @Override public String get(String key) { return null; } @Override public String index() { return "my-metrics"; } @Override public String indexDateFormat() { return ""; } @Override public String indexDateSeparator() { return ""; } }, clock); assertThat(registry.indexName()).isEqualTo("my-metrics"); } @Issue("#1505") @Test void getVersionWhenVersionIs5AndNotPrettyPrinted() { String responseBody = "{\"status\":200,\"name\":\"Sematext-Logsene\",\"cluster_name\":\"elasticsearch\",\"cluster_uuid\":\"anything\",\"version\":{\"number\":\"5.3.0\",\"build_hash\":\"3adb13b\",\"build_date\":\"2017-03-23T03:31:50.652Z\",\"build_snapshot\":false,\"lucene_version\":\"6.4.1\"},\"tagline\":\"You Know, for Search\"}"; assertThat(ElasticMeterRegistry.getMajorVersion(responseBody)).isEqualTo(5); }
<<<<<<< bucket -> Tags.concat(id.getTagsAsIterable(), "le", DoubleFormat.decimalOrWhole(bucket.bucket(timer.baseTimeUnit())))); ======= // We look for Long.MAX_VALUE to ensure a sensible tag on our +Inf bucket bucket -> Tags.concat(id.getTags(), "le", bucket.bucket() != Long.MAX_VALUE ? DoubleFormat.decimalOrWhole(bucket.bucket(timer.baseTimeUnit())) : "+Inf")); >>>>>>> // We look for Long.MAX_VALUE to ensure a sensible tag on our +Inf bucket bucket -> Tags.concat(id.getTagsAsIterable(), "le", bucket.bucket() != Long.MAX_VALUE ? DoubleFormat.decimalOrWhole(bucket.bucket(timer.baseTimeUnit())) : "+Inf")); <<<<<<< bucket -> Tags.concat(id.getTagsAsIterable(), "le", DoubleFormat.decimalOrWhole(bucket.bucket()))); ======= // We look for Long.MAX_VALUE to ensure a sensible tag on our +Inf bucket bucket -> Tags.concat(id.getTags(), "le", bucket.bucket() != Long.MAX_VALUE ? DoubleFormat.decimalOrWhole(bucket.bucket()) : "+Inf")); >>>>>>> // We look for Long.MAX_VALUE to ensure a sensible tag on our +Inf bucket bucket -> Tags.concat(id.getTagsAsIterable(), "le", bucket.bucket() != Long.MAX_VALUE ? DoubleFormat.decimalOrWhole(bucket.bucket()) : "+Inf"));
<<<<<<< * Copyright 2019 Pivotal Software, Inc. ======= * Copyright 2017 VMware, Inc. >>>>>>> * Copyright 2019 VMware, Inc.
<<<<<<< import java.net.MalformedURLException; import java.net.URLEncoder; ======= import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.*; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Base64; >>>>>>> import java.util.ArrayList; import java.net.MalformedURLException; import java.net.URLEncoder; <<<<<<< return Stream.of(influxLineProtocol(m.getId(), "unknown", fields.build())); ======= if (fields.isEmpty()) { return Stream.empty(); } return Stream.of(influxLineProtocol(m.getId(), "unknown", fields.stream(), clock.wallTime())); >>>>>>> if (fields.isEmpty()) { return Stream.empty(); } return Stream.of(influxLineProtocol(m.getId(), "unknown", fields.stream()));
<<<<<<< @Test void clear() { registry.counter("my.counter"); registry.counter("my.counter2"); assertThat(registry.find("my.counter").counter()).isNotNull(); assertThat(registry.find("my.counter2").counter()).isNotNull(); registry.clear(); assertThat(registry.find("my.counter").counter()).isNull(); assertThat(registry.find("my.counter2").counter()).isNull(); } ======= @Test void gaugeRegistersGaugeOnceAndSubsequentGaugeCallsWillNotRegister() { registry.gauge("my.gauge", 1d); registry.gauge("my.gauge", 2d); assertThat(registry.get("my.gauge").gauge().value()).isEqualTo(1d); } >>>>>>> @Test void clear() { registry.counter("my.counter"); registry.counter("my.counter2"); assertThat(registry.find("my.counter").counter()).isNotNull(); assertThat(registry.find("my.counter2").counter()).isNotNull(); registry.clear(); assertThat(registry.find("my.counter").counter()).isNull(); assertThat(registry.find("my.counter2").counter()).isNull(); } @Test void gaugeRegistersGaugeOnceAndSubsequentGaugeCallsWillNotRegister() { registry.gauge("my.gauge", 1d); registry.gauge("my.gauge", 2d); assertThat(registry.get("my.gauge").gauge().value()).isEqualTo(1d); }
<<<<<<< import io.micrometer.core.instrument.util.Assert; import io.micrometer.core.lang.Nullable; ======= import io.micrometer.core.annotation.Timed; >>>>>>> import io.micrometer.core.annotation.Timed; import io.micrometer.core.lang.Nullable; <<<<<<< Assert.notNull(f, "callable"); long id = start(); ======= Sample sample = start(); >>>>>>> Sample sample = start(); <<<<<<< Assert.notNull(f, "supplier"); long id = start(); ======= Sample sample = start(); >>>>>>> Sample sample = start(); <<<<<<< default void record(Consumer<Long> f) { Assert.notNull(f, "consumer"); long id = start(); ======= default void record(Consumer<Sample> f) { Sample sample = start(); >>>>>>> default void record(Consumer<Sample> f) { Sample sample = start(); <<<<<<< Assert.notNull(f, "runnable"); long id = start(); ======= Sample sample = start(); >>>>>>> Sample sample = start();
<<<<<<< * Copyright 2019 Pivotal Software, Inc. ======= * Copyright 2017 VMware, Inc. >>>>>>> * Copyright 2019 VMware, Inc.
<<<<<<< MeterRegistry registry = new StatsdMeterRegistry(config, clock); DistributionSummary summary = DistributionSummary.builder("my.summary").serviceLevelObjectives(1.0, 2).register(registry); ======= registry = new StatsdMeterRegistry(config, clock); DistributionSummary summary = DistributionSummary.builder("my.summary").sla(1, 2).register(registry); >>>>>>> registry = new StatsdMeterRegistry(config, clock); DistributionSummary summary = DistributionSummary.builder("my.summary").serviceLevelObjectives(1.0, 2).register(registry); <<<<<<< void timersWithServiceLevelObjectivesHaveInfBucket() { StatsdMeterRegistry registry = new StatsdMeterRegistry(configWithFlavor(StatsdFlavor.ETSY), clock); Timer.builder("my.timer").serviceLevelObjectives(Duration.ofMillis(1)).register(registry); ======= void timersWithSlasHaveInfBucket() { registry = new StatsdMeterRegistry(configWithFlavor(StatsdFlavor.ETSY), clock); Timer timer = Timer.builder("my.timer").sla(Duration.ofMillis(1)).register(registry); >>>>>>> void timersWithServiceLevelObjectivesHaveInfBucket() { registry = new StatsdMeterRegistry(configWithFlavor(StatsdFlavor.ETSY), clock); Timer.builder("my.timer").serviceLevelObjectives(Duration.ofMillis(1)).register(registry); <<<<<<< void distributionSummariesWithServiceLevelObjectivesHaveInfBucket() { StatsdMeterRegistry registry = new StatsdMeterRegistry(configWithFlavor(StatsdFlavor.ETSY), clock); DistributionSummary summary = DistributionSummary.builder("my.distribution").serviceLevelObjectives(1.0).register(registry); ======= void distributionSummariesWithSlasHaveInfBucket() { registry = new StatsdMeterRegistry(configWithFlavor(StatsdFlavor.ETSY), clock); DistributionSummary summary = DistributionSummary.builder("my.distribution").sla(1).register(registry); >>>>>>> void distributionSummariesWithServiceLevelObjectivesHaveInfBucket() { registry = new StatsdMeterRegistry(configWithFlavor(StatsdFlavor.ETSY), clock); DistributionSummary summary = DistributionSummary.builder("my.distribution").serviceLevelObjectives(1.0).register(registry); <<<<<<< StatsdMeterRegistry registry = new StatsdMeterRegistry(configWithFlavor(StatsdFlavor.ETSY), clock); Timer timer = Timer.builder("my.timer").serviceLevelObjectives(Duration.ofMillis(1)).register(registry); ======= registry = new StatsdMeterRegistry(configWithFlavor(StatsdFlavor.ETSY), clock); Timer timer = Timer.builder("my.timer").sla(Duration.ofMillis(1)).register(registry); >>>>>>> registry = new StatsdMeterRegistry(configWithFlavor(StatsdFlavor.ETSY), clock); Timer timer = Timer.builder("my.timer").serviceLevelObjectives(Duration.ofMillis(1)).register(registry);
<<<<<<< private final Sinks.Many<String> sink; private volatile boolean shutdown; ======= private final FluxSink<String> sink; private volatile boolean shutdown = false; >>>>>>> private final FluxSink<String> sink; private volatile boolean shutdown;
<<<<<<< private Stream<WavefrontMetricLineData> writeMeter(Meter meter) { ======= // VisibleForTesting Stream<String> writeMeter(Meter meter) { >>>>>>> // VisibleForTesting Stream<WavefrontMetricLineData> writeMeter(Meter meter) {
<<<<<<< import java.util.concurrent.CountDownLatch; ======= import java.util.HashSet; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; >>>>>>> import java.util.HashSet; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future;
<<<<<<< import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; ======= import org.pcollections.HashTreePMap; import org.pcollections.PMap; >>>>>>> import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; <<<<<<< private static final AtomicReferenceFieldUpdater<TelegrafStatsdLineBuilder, NamingConvention> namingConventionUpdater = AtomicReferenceFieldUpdater.newUpdater(TelegrafStatsdLineBuilder.class, NamingConvention.class, "namingConvention"); private final Object conventionTagsLock = new Object(); ======= private final Object tagsLock = new Object(); >>>>>>> private final Object conventionTagsLock = new Object(); <<<<<<< for (; ; ) { if (namingConventionUpdater.compareAndSet(this, this.namingConvention, next)) break; } this.name = telegrafEscape(next.name(id.getName(), id.getType(), id.getBaseUnit())); synchronized (conventionTagsLock) { this.tags.clear(); ======= synchronized (tagsLock) { if (this.namingConvention == next) { return; } this.tags = HashTreePMap.empty(); >>>>>>> synchronized (conventionTagsLock) { if (this.namingConvention == next) { return; } this.tags.clear();
<<<<<<< MeterRegistryConfigurer(ObjectProvider<List<MeterRegistryCustomizer<?>>> customizers, ObjectProvider<List<MeterFilter>> filters, ObjectProvider<List<MeterBinder>> binders, boolean addToGlobalRegistry) { this.customizers = customizers; this.filters = filters; this.binders = binders; ======= private final boolean hasCompositeMeterRegistry; MeterRegistryConfigurer(Collection<MeterBinder> binders, Collection<MeterFilter> filters, Collection<MeterRegistryCustomizer<?>> customizers, boolean addToGlobalRegistry, boolean hasCompositeMeterRegistry) { this.binders = (binders != null ? binders : Collections.emptyList()); this.filters = (filters != null ? filters : Collections.emptyList()); this.customizers = (customizers != null ? customizers : Collections.emptyList()); >>>>>>> private final boolean hasCompositeMeterRegistry; MeterRegistryConfigurer(ObjectProvider<List<MeterRegistryCustomizer<?>>> customizers, ObjectProvider<List<MeterFilter>> filters, ObjectProvider<List<MeterBinder>> binders, boolean addToGlobalRegistry, boolean hasCompositeMeterRegistry) { this.customizers = customizers; this.filters = filters; this.binders = binders;
<<<<<<< import com.amcolabs.quizapp.serverutils.ServerCalls; import com.squareup.picasso.Callback; ======= >>>>>>> import com.amcolabs.quizapp.serverutils.ServerCalls; import com.squareup.picasso.Callback; <<<<<<< LOST_QUIZ_MESAGE("You Lost"), GLOBAL_RANKINGS("Global Rankings"), LOCAL_RANKINGS("Local Rankings"); ======= LOST_QUIZ_MESAGE("You Lost :("), TIE_QUIZ_MESAGE("Its A TIE!"), PROFILE_WON_STATS_TEXT("Won"), PROFILE_LOST_STATS_TEXT("Lost"), PROFILE_TIE_STATS_TEXT("Tie"); >>>>>>> LOST_QUIZ_MESAGE("You Lost"), GLOBAL_RANKINGS("Global Rankings"), LOCAL_RANKINGS("Local Rankings"), TIE_QUIZ_MESAGE("Its A TIE!"), PROFILE_WON_STATS_TEXT("Won"), PROFILE_LOST_STATS_TEXT("Lost"), PROFILE_TIE_STATS_TEXT("Tie");
<<<<<<< for(Crate crate : cc.getCrates()) { if(crate.getCrateType() != CrateType.MENU) { if(e.getView().getTitle().equals(crate.getPreviewName()) || e.getView().getTitle().equals(crate.getCrateInventoryName())) { e.setCancelled(true); ItemStack item = e.getCurrentItem(); if(item != null) { if(e.getRawSlot() == 49) {// Clicked the menu button. if(playerInMenu(player)) { GUIMenu.openGUI(player); } }else if(e.getRawSlot() == 50) {// Clicked the next button. if(getPage(player) < crate.getMaxPage()) { nextPage(player); openPreview(player, crate); } }else if(e.getRawSlot() == 48) {// Clicked the back button. if(getPage(player) > 1 && getPage(player) <= crate.getMaxPage()) { backPage(player); openPreview(player, crate); } ======= if(playerCrate.get(player.getUniqueId()) != null) { Crate crate = playerCrate.get(player.getUniqueId()); if(inventory.getName().equals(crate.getPreviewName()) || inventory.getName().equals(crate.getCrateInventoryName())) { e.setCancelled(true); ItemStack item = e.getCurrentItem(); if(item != null) { if(e.getRawSlot() == 49) {// Clicked the menu button. if(playerInMenu(player)) { GUIMenu.openGUI(player); } }else if(e.getRawSlot() == 50) {// Clicked the next button. if(getPage(player) < crate.getMaxPage()) { nextPage(player); openPreview(player, crate); } }else if(e.getRawSlot() == 48) {// Clicked the back button. if(getPage(player) > 1 && getPage(player) <= crate.getMaxPage()) { backPage(player); openPreview(player, crate); >>>>>>> if(playerCrate.get(player.getUniqueId()) != null) { Crate crate = playerCrate.get(player.getUniqueId()); if(e.getView().getTitle().equals(crate.getPreviewName()) || e.getView().getTitle().equals(crate.getCrateInventoryName())) { e.setCancelled(true); ItemStack item = e.getCurrentItem(); if(item != null) { if(e.getRawSlot() == 49) {// Clicked the menu button. if(playerInMenu(player)) { GUIMenu.openGUI(player); } }else if(e.getRawSlot() == 50) {// Clicked the next button. if(getPage(player) < crate.getMaxPage()) { nextPage(player); openPreview(player, crate); } }else if(e.getRawSlot() == 48) {// Clicked the back button. if(getPage(player) > 1 && getPage(player) <= crate.getMaxPage()) { backPage(player); openPreview(player, crate);
<<<<<<< HashMap<String,ItemDataBean> dataMap = iddao.findAllActiveMap(sb.getId(), ecb.getId()); ======= >>>>>>> <<<<<<< ======= HashMap<String,ItemDataBean> dataMap = (HashMap<String, ItemDataBean>) getAllActive(data); >>>>>>> HashMap<String,ItemDataBean> dataMap = (HashMap<String, ItemDataBean>) getAllActive(data); <<<<<<< protected DisplayItemWithGroupBean buildMatrixForRepeatingGroups(DisplayItemWithGroupBean diwgb, DisplayItemGroupBean itemGroup, EventCRFBean ecb, SectionBean sb,List<ItemBean>itBeans, HashMap<String,ItemDataBean> dataMap) { ======= private Map getAllActive(List<ItemDataBean>al){ Map returnMap = new HashMap<String,ItemDataBean>(); for(ItemDataBean itBean:al){ if(itBean!=null) returnMap.put(new String(itBean.getItemId()+","+itBean.getOrdinal()), itBean); } return returnMap; } protected DisplayItemWithGroupBean buildMatrixForRepeatingGroups(DisplayItemWithGroupBean diwgb, DisplayItemGroupBean itemGroup, EventCRFBean ecb, SectionBean sb,List<ItemBean>itBeans, Map<String,ItemDataBean> dataMap) { >>>>>>> private Map getAllActive(List<ItemDataBean>al){ Map returnMap = new HashMap<String,ItemDataBean>(); for(ItemDataBean itBean:al){ if(itBean!=null) returnMap.put(new String(itBean.getItemId()+","+itBean.getOrdinal()), itBean); } return returnMap; } protected DisplayItemWithGroupBean buildMatrixForRepeatingGroups(DisplayItemWithGroupBean diwgb, DisplayItemGroupBean itemGroup, EventCRFBean ecb, SectionBean sb,List<ItemBean>itBeans, Map<String,ItemDataBean> dataMap) { <<<<<<< LOGGER.debug("itemData::"+itemData); ======= groupHasData = true;//to indicate any item in the group has data; logger.debug("itemData::"+itemData); >>>>>>> groupHasData = true;//to indicate any item in the group has data; <<<<<<< private HashMap reshuffleErrorGroupNames(HashMap errors, List<DisplayItemWithGroupBean> allItems) { for (int i = 0; i < allItems.size(); i++) { DisplayItemWithGroupBean diwb = allItems.get(i); if (diwb.isInGroup()) { List<DisplayItemGroupBean> dgbs = diwb.getItemGroups(); int manualRows = getManualRows(dgbs); int totalRows = dgbs.size(); LOGGER.debug("found manual rows " + manualRows + " and total rows " + totalRows + " from ordinal " + diwb.getOrdinal()); for (DisplayItemGroupBean digb : dgbs) { ItemGroupBean igb = digb.getItemGroupBean(); List<DisplayItemBean> dibs = digb.getItems(); int placeHolder = 1; while (totalRows - manualRows > 2) { for (DisplayItemBean dib : dibs) { // needs to be 2, 3, 4 ... in the place of 4, 3, 2... String intendedKey = getGroupItemInputName(digb, placeHolder, dib); String replacementKey = getGroupItemManualInputName(digb, manualRows + 1, dib); if (errors.containsKey(intendedKey)) { // String errorMessage = (String)errors.get(intendedKey); errors.put(replacementKey, errors.get(intendedKey)); errors.remove(intendedKey); LOGGER.debug("removing: " + intendedKey + " and replacing it with " + replacementKey); } } placeHolder++; manualRows++; } // but what about the last row? use the placeholder for (DisplayItemBean dib : dibs) { String lastIntendedKey = getGroupItemInputName(digb, placeHolder, dib); String lastReplacementKey = getGroupItemInputName(digb, 1, dib); if (!lastIntendedKey.equals(lastReplacementKey) && errors.containsKey(lastIntendedKey)) { // String errorMessage = (String)errors.get(intendedKey); errors.put(lastReplacementKey, errors.get(lastIntendedKey)); errors.remove(lastIntendedKey); LOGGER.debug("removing: " + lastIntendedKey + " and replacing it with " + lastReplacementKey); } } } } } return errors; } ======= >>>>>>>
<<<<<<< public ArrayList<RuleSetBean> findAllByStudyEventDefWhereItemIsNull(StudyEventDefinitionBean sed){ String query = "from " + getDomainClassName() + " ruleSet where ruleSet.studyEventDefinitionId = :studyEventDefId and ruleSet.itemId is null"; org.hibernate.Query q = getCurrentSession().createQuery(query); q.setInteger("studyEventDefId", sed.getId()); return (ArrayList<RuleSetBean>) q.list(); } public ArrayList<RuleSetBean> findAllByStudyEventDefIdWhereItemIsNull(Integer studyEventDefId){ String query = "from " + getDomainClassName() + " ruleSet where ruleSet.studyEventDefinitionId = :studyEventDefId and ruleSet.itemId is null"; org.hibernate.Query q = getCurrentSession().createQuery(query); q.setInteger("studyEventDefId", studyEventDefId); return (ArrayList<RuleSetBean>) q.list(); } ======= >>>>>>> public ArrayList<RuleSetBean> findAllByStudyEventDefIdWhereItemIsNull(Integer studyEventDefId){ String query = "from " + getDomainClassName() + " ruleSet where ruleSet.studyEventDefinitionId = :studyEventDefId and ruleSet.itemId is null"; org.hibernate.Query q = getCurrentSession().createQuery(query); q.setInteger("studyEventDefId", studyEventDefId); return (ArrayList<RuleSetBean>) q.list(); }
<<<<<<< sqlParameters.add(new SqlParameter(responseLabel)); sqlParameters.add(new SqlParameter(resOptions.replaceAll("\\\\,", "\\,"))); sqlParameters.add(new SqlParameter(resValues.replace("\\\\", "\\"))); sqlParameters.add(new SqlParameter(responseType.toLowerCase())); //in versionIdString there is one parameter:crfId ======= sqlParameters.add(new SqlParameter(responseLabel)); sqlParameters.add(new SqlParameter(resOptions.replaceAll("\\\\,", "\\,"))); sqlParameters.add(new SqlParameter(resValues.replace("\\\\", "\\"))); sqlParameters.add(new SqlParameter(responseType.toLowerCase())); //in versionIdString there one parameter:crfId >>>>>>> sqlParameters.add(new SqlParameter(responseLabel)); sqlParameters.add(new SqlParameter(resOptions.replaceAll("\\\\,", "\\,"))); sqlParameters.add(new SqlParameter(resValues.replace("\\\\", "\\"))); sqlParameters.add(new SqlParameter(responseType.toLowerCase())); //in versionIdString there is one parameter:crfId <<<<<<< sqlParameters.add(new SqlParameter(responseLabel)); sqlParameters.add(new SqlParameter(updatedResOptions)); sqlParameters.add(new SqlParameter(updatedResValues)); sqlParameters.add(new SqlParameter(responseType.toLowerCase())); //in versionIdString there is one parameter:crfId sqlParameters.add(new SqlParameter(crfId+"",JDBCType.INTEGER)); ======= sqlParameters.add(new SqlParameter(responseLabel)); sqlParameters.add(new SqlParameter(updatedResOptions)); sqlParameters.add(new SqlParameter(updatedResValues)); sqlParameters.add(new SqlParameter(responseType.toLowerCase())); //in versionIdString there one parameter:crfId sqlParameters.add(new SqlParameter(crfId+"",JDBCType.INTEGER)); >>>>>>> sqlParameters.add(new SqlParameter(responseLabel)); sqlParameters.add(new SqlParameter(updatedResOptions)); sqlParameters.add(new SqlParameter(updatedResValues)); sqlParameters.add(new SqlParameter(responseType.toLowerCase())); //in versionIdString there is one parameter:crfId sqlParameters.add(new SqlParameter(crfId+"",JDBCType.INTEGER)); <<<<<<< + ",'" + page + "','" + questionNum + "','" + regexp1 + "','" + regexpError + "', " + (isRequired ? 1 : 0) + ")"; ======= + ",?,?,?,?, " //page, questionNum, regexp1, regexpError + (isRequired ? 1 : 0) + ")"; >>>>>>> + ",?,?,?,?, " //page, questionNum, regexp1, regexpError + (isRequired ? 1 : 0) + ")"; <<<<<<< + ",'" + page + "','" + questionNum + "','" + regexp1 + "','" + regexpError + "', " + isRequired + ")"; ======= + ",?,?,?,?, " //page, questionNum, regexp1, regexpError + isRequired + ")"; >>>>>>> + ",?,?,?,?, " //page, questionNum, regexp1, regexpError + isRequired + ")"; <<<<<<< sqlParameters.add(new SqlParameter(subHeader)); sqlParameters.add(new SqlParameter(header)); sqlParameters.add(new SqlParameter(leftItemText)); sqlParameters.add(new SqlParameter(rightItemText)); ======= sqlParameters.add(new SqlParameter(subHeader)); sqlParameters.add(new SqlParameter(header)); sqlParameters.add(new SqlParameter(leftItemText)); sqlParameters.add(new SqlParameter(rightItemText)); //in versionIdString there one parameter:crfId >>>>>>> sqlParameters.add(new SqlParameter(subHeader)); sqlParameters.add(new SqlParameter(header)); sqlParameters.add(new SqlParameter(leftItemText)); sqlParameters.add(new SqlParameter(rightItemText)); //in versionIdString there one parameter:crfId <<<<<<< ======= /** * stripQuotes, utility function meant to replace single quotes in strings * with double quotes for SQL compatability. Don't -> Don''t, for example. * * @param subj * the subject line * @return A string with all the quotes escaped. */ public String stripQuotes(String subj) { if (subj == null) { return null; } String returnme = ""; String[] subjarray = subj.split("'"); if (subjarray.length == 1) { returnme = subjarray[0]; } else { for (int i = 0; i < subjarray.length - 1; i++) { returnme += subjarray[i]; returnme += "''"; } returnme += subjarray[subjarray.length - 1]; } return returnme; } >>>>>>> /** * stripQuotes, utility function meant to replace single quotes in strings * with double quotes for SQL compatability. Don't -> Don''t, for example. * * @param subj * the subject line * @return A string with all the quotes escaped. */ public String stripQuotes(String subj) { if (subj == null) { return null; } String returnme = ""; String[] subjarray = subj.split("'"); if (subjarray.length == 1) { returnme = subjarray[0]; } else { for (int i = 0; i < subjarray.length - 1; i++) { returnme += subjarray[i]; returnme += "''"; } returnme += subjarray[subjarray.length - 1]; } return returnme; }
<<<<<<< import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.core.io.support.ResourcePatternResolver; ======= >>>>>>> import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.core.io.support.ResourcePatternResolver; <<<<<<< // tbh change to print out properties ======= >>>>>>> <<<<<<< ======= >>>>>>> <<<<<<< ======= >>>>>>> <<<<<<< /* * OutputStream outputStream = new FileOutputStream(f); byte buf[] = * new byte[1024]; int len; try { while ((len = * inputStream.read(buf)) > 0) outputStream.write(buf, 0, len); } * finally { outputStream.close(); inputStream.close(); } */ ======= /* * OutputStream outputStream = new FileOutputStream(f); byte buf[] = * new byte[1024]; int len; try { while ((len = * inputStream.read(buf)) > 0) outputStream.write(buf, 0, len); } * finally { outputStream.close(); inputStream.close(); } */ >>>>>>> /* * OutputStream outputStream = new FileOutputStream(f); byte buf[] = * new byte[1024]; int len; try { while ((len = * inputStream.read(buf)) > 0) outputStream.write(buf, 0, len); } * finally { outputStream.close(); inputStream.close(); } */ <<<<<<< // // TODO comment out system out after dev // private static void logMe(String message) { // System.out.println(message); // logger.info(message); // } ======= >>>>>>> // // TODO comment out system out after dev // private static void logMe(String message) { // System.out.println(message); // logger.info(message); // }
<<<<<<< SecurityManager sm = (SecurityManager) SpringServletAccess.getApplicationContext(context).getBean("securityManager"); String password = sm.genPassword(); String passwordHash = sm.encrytPassword(password, getUserDetails()); ======= SecurityManager sm = ((SecurityManager) SpringServletAccess.getApplicationContext(context).getBean("securityManager")); >>>>>>> SecurityManager sm = (SecurityManager) SpringServletAccess.getApplicationContext(context).getBean("securityManager");
<<<<<<< @JsonProperty public Value targetValue; // Denotation (e.g., answer) @JsonProperty public int NBestInd = -1; // Position on the NBEST list @JsonProperty public String timeStamp; @JsonProperty public String definition; ======= public List<Formula> alternativeFormulas; // Alternative logical form (less canonical) @JsonProperty public Value targetValue; // Denotation (e.g., answer) >>>>>>> @JsonProperty public Value targetValue; // Denotation (e.g., answer) @JsonProperty public int NBestInd = -1; // Position on the NBEST list @JsonProperty public String timeStamp; @JsonProperty public String definition; public List<Formula> alternativeFormulas; // Alternative logical form (less canonical) <<<<<<< } else if (!Sets.newHashSet("id", "utterance", "targetFormula", "targetValue", "targetValues", "context", "original", "timeStamp", "NBestInd", "definition").contains(label)) { ======= } else if ("rawDerivations".equals(label) || "derivations".equals(label)) { // Unfeaturized ex.predDerivations = new ArrayList<>(); for (int j = 1; j < arg.children.size(); j++) ex.predDerivations.add(rawDerivationFromLispTree(arg.child(j))); } else if (!Sets.newHashSet("id", "utterance", "targetFormula", "targetValue", "targetValues", "context", "original").contains(label)) { >>>>>>> } else if ("rawDerivations".equals(label) || "derivations".equals(label)) { // Unfeaturized ex.predDerivations = new ArrayList<>(); for (int j = 1; j < arg.children.size(); j++) ex.predDerivations.add(rawDerivationFromLispTree(arg.child(j))); } else if (!Sets.newHashSet("id", "utterance", "targetFormula", "targetValue", "targetValues", "context", "original", "timeStamp", "NBestInd", "definition").contains(label)) {
<<<<<<< String propValue = (String) pros.get(propName); ======= String propValue = (String)pros.get(propName); >>>>>>> String propValue = (String) pros.get(propName); <<<<<<< // replacePaths(vals); vals = replaceWebapp(vals); ======= >>>>>>> // replacePaths(vals); vals = replaceWebapp(vals); <<<<<<< catalina = System.getProperty("CATALINA_HOME"); } ======= catalina = System.getProperty("CATALINA_HOME"); } >>>>>>> catalina = System.getProperty("CATALINA_HOME"); } <<<<<<< } // logMe("catalina home - " + value); // logMe("CATALINA_HOME system variable is " + System.getProperty("CATALINA_HOME")); // logMe("CATALINA_HOME system env variable is " + System.getenv("CATALINA_HOME")); // logMe(" -Dcatalina.home system property variable is"+System.getProperty(" -Dcatalina.home")); // logMe("CATALINA.HOME system env variable is"+System.getenv("catalina.home")); // logMe("CATALINA_BASE system env variable is"+System.getenv("CATALINA_BASE")); // Map<String, String> env = System.getenv(); // for (String envName : env.keySet()) { // logMe("%s=%s%n"+ envName+ env.get(envName)); // } ======= } >>>>>>> } <<<<<<< ======= >>>>>>> <<<<<<< private void copyBaseToDest(ResourceLoader resourceLoader) { ======= private void copyBaseToDest(ResourceLoader resourceLoader) { >>>>>>> private void copyBaseToDest(ResourceLoader resourceLoader) { <<<<<<< ======= >>>>>>> <<<<<<< ======= >>>>>>> <<<<<<< // String tmp1 = placeholder_file_path.substring(6); // String tmp2 = tmp1.substring(0, tmp1.indexOf("WEB-INF") - 1); ======= >>>>>>> // String tmp1 = placeholder_file_path.substring(6); // String tmp2 = tmp1.substring(0, tmp1.indexOf("WEB-INF") - 1); <<<<<<< ======= >>>>>>> <<<<<<< /* * OutputStream outputStream = new FileOutputStream(f); byte buf[] = * new byte[1024]; int len; try { while ((len = * inputStream.read(buf)) > 0) outputStream.write(buf, 0, len); } * finally { outputStream.close(); inputStream.close(); } */ ======= >>>>>>> /* * OutputStream outputStream = new FileOutputStream(f); byte buf[] = * new byte[1024]; int len; try { while ((len = * inputStream.read(buf)) > 0) outputStream.write(buf, 0, len); } * finally { outputStream.close(); inputStream.close(); } */ <<<<<<< /* // TODO comment out system out after dev private static void logMe(String message) { // System.out.println(message); //logger.info(message); } */ ======= >>>>>>>
<<<<<<< private Filter<ReceiptRow> mFilter; private TripRow(File directory, String price, Date startDate, Date endDate, WBCurrency currency, float miles, SourceEnum source) { ======= private TripRow(File directory, Date startDate, Date endDate, WBCurrency currency, float miles, SourceEnum source) { >>>>>>> private Filter<ReceiptRow> mFilter; private TripRow(File directory, Date startDate, Date endDate, WBCurrency currency, float miles, SourceEnum source) { <<<<<<< public Filter<ReceiptRow> getFilter() { return mFilter; } public boolean hasFilter() { return mFilter != null; } public void setFilter(Filter<ReceiptRow> filter) { mFilter = filter; } ======= >>>>>>> public Filter<ReceiptRow> getFilter() { return mFilter; } public boolean hasFilter() { return mFilter != null; } public void setFilter(Filter<ReceiptRow> filter) { mFilter = filter; } <<<<<<< public Builder setFilter(Filter<ReceiptRow> filter) { _filter = filter; return this; } public Builder setFilter(JSONObject json) { if (json != null) { try { _filter = FilterFactory.getReceiptFilter(json); } catch (JSONException e) { } } return this; } public Builder setFilter(String json) { if (!TextUtils.isEmpty(json)) { try { _filter = FilterFactory.getReceiptFilter(new JSONObject(json)); } catch (JSONException e) { } } return this; } ======= >>>>>>> public Builder setFilter(Filter<ReceiptRow> filter) { _filter = filter; return this; } public Builder setFilter(JSONObject json) { if (json != null) { try { _filter = FilterFactory.getReceiptFilter(json); } catch (JSONException e) { } } return this; } public Builder setFilter(String json) { if (!TextUtils.isEmpty(json)) { try { _filter = FilterFactory.getReceiptFilter(new JSONObject(json)); } catch (JSONException e) { } } return this; } <<<<<<< tripRow.setDailySubTotal(_dailySubTotal); tripRow.setFilter(_filter); ======= >>>>>>> tripRow.setFilter(_filter);
<<<<<<< } /** * 不压缩图片 * to change sd card pc to bmp type * @param pictureurl * @return * @throws IOException */ public static Bitmap GetLocalOrNetBitmapNoZip(String url) throws IOException { String sdcard=Environment.getExternalStorageDirectory().getPath(); BitmapFactory.Options options=new BitmapFactory.Options(); options.inTempStorage=new byte[5*1024]; Bitmap bitmap=BitmapFactory.decodeFile(sdcard+url,options); return bitmap; } ======= } /** * 得到Sqlite商品图片url */ public ArrayList<HashMap<String, Object>> GetPicArrayList(Cursor c) throws IOException{ findpiclist.clear(); HashMap<String, Object> map = new HashMap<String, Object>(); c.moveToFirst(); String rowpicturl =subStringPictureurl(c.getString(c.getColumnIndex("pictureurl"))); map.put("pictureurl", GetLocalOrNetBitmapWithoutScale(rowpicturl)); findpiclist.add(map); return findpiclist; } /** * 得到商品图片不进行缩放 * @param url * @return * @throws IOException */ public static Bitmap GetLocalOrNetBitmapWithoutScale(String url) throws IOException { String sdcard=Environment.getExternalStorageDirectory().getPath(); Bitmap bitmap=BitmapFactory.decodeFile(sdcard+url); return bitmap; } >>>>>>> } /** * 不压缩图片 * to change sd card pc to bmp type * @param pictureurl * @return * @throws IOException */ public static Bitmap GetLocalOrNetBitmapNoZip(String url) throws IOException { String sdcard=Environment.getExternalStorageDirectory().getPath(); BitmapFactory.Options options=new BitmapFactory.Options(); options.inTempStorage=new byte[5*1024]; Bitmap bitmap=BitmapFactory.decodeFile(sdcard+url,options); return bitmap; } /** * 得到Sqlite商品图片url */ public ArrayList<HashMap<String, Object>> GetPicArrayList(Cursor c) throws IOException{ findpiclist.clear(); HashMap<String, Object> map = new HashMap<String, Object>(); c.moveToFirst(); String rowpicturl =subStringPictureurl(c.getString(c.getColumnIndex("pictureurl"))); map.put("pictureurl", GetLocalOrNetBitmapWithoutScale(rowpicturl)); findpiclist.add(map); return findpiclist; } /** * 得到商品图片不进行缩放 * @param url * @return * @throws IOException */ public static Bitmap GetLocalOrNetBitmapWithoutScale(String url) throws IOException { String sdcard=Environment.getExternalStorageDirectory().getPath(); Bitmap bitmap=BitmapFactory.decodeFile(sdcard+url); return bitmap; }
<<<<<<< ======= import com.thin.downloadmanager.DefaultRetryPolicy; >>>>>>> import com.thin.downloadmanager.DefaultRetryPolicy;
<<<<<<< ======= import javax.servlet.http.Part; >>>>>>> import javax.servlet.http.Part; <<<<<<< import org.slf4j.Logger; import org.slf4j.LoggerFactory; ======= import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; >>>>>>> import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; <<<<<<< missingParameters.add(value.getMissingParameter()); ======= violationMessages.add(String.format( "Missing mandatory parameter: %s", value.getMissingParameter())); >>>>>>> missingParameters.add(value.getMissingParameter());
<<<<<<< when(Factory.getConnection(API_KEY, false)).thenReturn(mockConnection); when(Factory.getChannelManager(mockConnection, mockPusherOptions)).thenReturn(mockChannelManager); ======= when(Factory.getConnection(API_KEY)).thenReturn(mockConnection); when(Factory.getChannelManager(mockConnection)).thenReturn(mockChannelManager); >>>>>>> when(Factory.getConnection(API_KEY, false)).thenReturn(mockConnection); when(Factory.getChannelManager(mockConnection)).thenReturn(mockChannelManager);
<<<<<<< import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; ======= import org.springframework.security.core.context.SecurityContextHolder; >>>>>>> import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; <<<<<<< * * By default it used Apache Rest Client for communicating with the OAuth2 * Server. ======= * * By default it used Apache Rest Client for communicating with the OAuth2 Server.<br> * * Spring Security framework initializes the {@link org.springframework.security.core.context.SecurityContext} * with the {@code OAuth2Authentication} which is provided as part of {@link #loadAuthentication} method. <br> * This gives you the following options: * <li> * <ul>All Spring security features are supported that uses * {@link org.springframework.security.core.context.SecurityContext#getAuthentication()}</ul> * <ul>You can access the {@code Authentication} via {@link SecurityContextHolder#getContext()} * also within asynchronous threads.</ul> * <ul>You can access the {@code Token} via {@link SpringSecurityContext#getToken()} * also within asynchronous threads.</ul> * </li> * >>>>>>> * * By default it used Apache Rest Client for communicating with the OAuth2 Server.<br> * * Spring Security framework initializes the {@link org.springframework.security.core.context.SecurityContext} * with the {@code OAuth2Authentication} which is provided as part of {@link #loadAuthentication} method. <br> * This gives you the following options: * <li> * <ul>All Spring security features are supported that uses * {@link org.springframework.security.core.context.SecurityContext#getAuthentication()}</ul> * <ul>You can access the {@code Authentication} via {@link SecurityContextHolder#getContext()} * also within asynchronous threads.</ul> * <ul>You can access the {@code Token} via {@link SpringSecurityContext#getToken()} * also within asynchronous threads.</ul> * </li> * <<<<<<< // TODO IAS support AccessToken token = checkAndCreateToken(accessToken); Set<String> scopes = token.getScopes(); ======= Token token = checkAndCreateToken(accessToken); ValidationResult validationResult = tokenValidator.validate(token); if (validationResult.isErroneous()) { throw new InvalidTokenException(validationResult.getErrorDescription()); } return getOAuth2Authentication(token, serviceConfiguration.getClientId(), getScopes(token)); } static OAuth2Authentication getOAuth2Authentication(Token token, String clientId, Set<String> scopes) { AuthorizationRequest authorizationRequest = new AuthorizationRequest(new HashMap<>(), null, clientId, scopes.stream().collect(Collectors.toSet()), new HashSet<>(), null, true, "", "", null); SecurityContext.setToken(token); return new OAuth2Authentication(authorizationRequest.createOAuth2Request(), null); } private Set<String> getScopes(Token token) { Set<String> scopes = token instanceof AccessToken ? ((AccessToken) token).getScopes() : Collections.emptySet(); >>>>>>> Token token = checkAndCreateToken(accessToken); ValidationResult validationResult = tokenValidator.validate(token); if (validationResult.isErroneous()) { throw new InvalidTokenException(validationResult.getErrorDescription()); } SecurityContext.setToken(token); return getOAuth2Authentication(token, serviceConfiguration.getClientId(), getScopes(token)); } static OAuth2Authentication getOAuth2Authentication(Token token, String clientId, Set<String> scopes) { Authentication userAuthentication = null; // TODO no SAPUserDetails support. Using spring alternative? final AuthorizationRequest authorizationRequest = new AuthorizationRequest(clientId, scopes); authorizationRequest.setAuthorities(getAuthorities(scopes)); authorizationRequest.setApproved(true); return new OAuth2Authentication(authorizationRequest.createOAuth2Request(), userAuthentication); } private Set<String> getScopes(Token token) { Set<String> scopes = token instanceof AccessToken ? ((AccessToken) token).getScopes() : Collections.emptySet(); <<<<<<< ValidationResult validationResult = tokenValidator.validate(token); if (validationResult.isValid()) { SecurityContext.setToken(token); final AuthorizationRequest clientAuthentication = createAuthorizationRequest(token, scopes); Authentication userAuthentication = null; // TODO no SAPUserDetails support. Using spring // alternative? return new OAuth2Authentication(clientAuthentication.createOAuth2Request(), userAuthentication); } else { throw new InvalidTokenException(validationResult.getErrorDescription()); } ======= return scopes; >>>>>>> return scopes;
<<<<<<< private boolean[] anchoredTokens; // Tokens which anchored rules are defined on public boolean allAnchored = true; ======= private int[] numAnchors; // Number of times each token was anchored >>>>>>> private boolean[] anchoredTokens; // Tokens which anchored rules are defined on public boolean allAnchored = true; private int[] numAnchors; // Number of times each token was anchored <<<<<<< // Probability (normalized exp of score). public double prob = Double.NaN; //Probability (normalized exp of score). public double pragmatic_prob = Double.NaN; ======= >>>>>>> // Probability (normalized exp of score). public double prob = Double.NaN; // Probability after pragmatics public double pragmatic_prob = Double.NaN; <<<<<<< // Compute anchoredTokens and return the result // anchoredTokens[>= anchoredTokens.length] are False by default public boolean[] getAnchoredTokens() { if (anchoredTokens == null) { ======= /** * Return an int array numAnchors where numAnchors[i] is * the number of times we anchored on token i. * * numAnchors[>= numAnchors.length] are 0 by default. */ public int[] getNumAnchors() { if (numAnchors == null) { >>>>>>> /** * Return an int array numAnchors where numAnchors[i] is * the number of times we anchored on token i. * * numAnchors[>= numAnchors.length] are 0 by default. */ public int[] getNumAnchors() { if (numAnchors == null) {
<<<<<<< static final String MASTER_CLIENT_ID = "master_client_id"; static final String CLONE_CERTIFICATE = "clone_certificate"; ======= public static final String ASSERTION = "assertion"; >>>>>>> public static final String ASSERTION = "assertion"; static final String MASTER_CLIENT_ID = "master_client_id"; static final String CLONE_CERTIFICATE = "clone_certificate";
<<<<<<< allUploadersInitalized &= initializeMongoUploader(preferences); ======= initializeMongoUploader(context, preferences); >>>>>>> allUploadersInitalized &= initializeMongoUploader(context, preferences); <<<<<<< allUploadersInitalized &= initializeRestUploaders(preferences); ======= initializeRestUploaders(context, preferences); >>>>>>> allUploadersInitalized &= initializeRestUploaders(context, preferences); <<<<<<< private boolean initializeMongoUploader(NightscoutPreferences preferences) { ======= private void initializeMongoUploader(Context context, NightscoutPreferences preferences) { >>>>>>> private boolean initializeMongoUploader(Context context,NightscoutPreferences preferences) { <<<<<<< return false; ======= context.sendBroadcast(ToastReceiver.createIntent(context, R.string.unknown_mongo_host)); return; >>>>>>> context.sendBroadcast(ToastReceiver.createIntent(context, R.string.unknown_mongo_host)); return false; <<<<<<< return false; ======= context.sendBroadcast(ToastReceiver.createIntent(context, R.string.unknown_mongo_host)); return; >>>>>>> context.sendBroadcast(ToastReceiver.createIntent(context, R.string.unknown_mongo_host)); return false; <<<<<<< private boolean initializeRestUploaders(NightscoutPreferences preferences) { ======= private void initializeRestUploaders(Context context, NightscoutPreferences preferences) { >>>>>>> private boolean initializeRestUploaders(Context context ,NightscoutPreferences preferences) { <<<<<<< allInitialized &= false; ======= context.sendBroadcast( ToastReceiver.createIntent(context, R.string.illegal_rest_url)); >>>>>>> allInitialized &= false; context.sendBroadcast( ToastReceiver.createIntent(context, R.string.illegal_rest_url));
<<<<<<< import android.preference.*; ======= import android.preference.Preference; import android.preference.PreferenceFragment; import android.preference.PreferenceManager; import android.support.v4.app.FragmentActivity; >>>>>>> import android.preference.Preference; import android.preference.PreferenceFragment; import android.preference.PreferenceManager; import android.support.v4.app.FragmentActivity; import android.preference.*; <<<<<<< ======= import android.view.View; import android.view.ViewGroup; import com.google.common.base.Optional; >>>>>>> import android.view.View; import android.view.ViewGroup; import com.google.common.base.Optional; <<<<<<< @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); setupSimplePreferencesScreen(); } /** * Shows the simplified settings UI if the device configuration if the * device configuration dictates that a simplified, single-pane UI should be * shown. */ private void setupSimplePreferencesScreen() { if (!isSimplePreferences(this)) { return; } // In the simplified UI, fragments are not used at all and we instead // use the older PreferenceActivity APIs. // Add 'general' preferences. addPreferencesFromResource(R.xml.pref_general); // Add 'cloud storage' preferences, and a corresponding header. PreferenceCategory fakeHeader = new PreferenceCategory(this); fakeHeader.setTitle(R.string.pref_header_cloud_storage); getPreferenceScreen().addPreference(fakeHeader); addPreferencesFromResource(R.xml.pref_cloud_storage); // Add 'display' preferences, and a corresponding header. fakeHeader = new PreferenceCategory(this); fakeHeader.setTitle(R.string.pref_header_display_options); getPreferenceScreen().addPreference(fakeHeader); addPreferencesFromResource(R.xml.pref_display); // Add 'about' preferences, and a corresponding header. fakeHeader = new PreferenceCategory(this); fakeHeader.setTitle(R.string.pref_header_about); getPreferenceScreen().addPreference(fakeHeader); addPreferencesFromResource(R.xml.pref_about); // Add 'privacy' preferences, and a corresponding header. fakeHeader = new PreferenceCategory(this); fakeHeader.setTitle(R.string.pref_header_privacy); getPreferenceScreen().addPreference(fakeHeader); addPreferencesFromResource(R.xml.pref_privacy); // Add 'labs' preferences, and a corresponding header. fakeHeader = new PreferenceCategory(this); fakeHeader.setTitle(R.string.pref_header_labs); getPreferenceScreen().addPreference(fakeHeader); addPreferencesFromResource(R.xml.pref_labs); // Bind the summaries of EditText/List/Dialog/Ringtone preferences to // their values. When their values change, their summaries are updated // to reflect the new value, per the Android Design guidelines. bindPreferenceSummaryToValue(findPreference("cloud_storage_mongodb_uri")); bindPreferenceSummaryToValue(findPreference("cloud_storage_mongodb_device_status_collection")); bindPreferenceSummaryToValue(findPreference("cloud_storage_mongodb_collection")); bindPreferenceSummaryToValue(findPreference("cloud_storage_api_base")); bindPreferenceSummaryToValue(findPreference("acra.user.email")); bindPreferenceSummaryToValue(findPreference("display_options_units")); Preference autoConfigure = findPreference("auto_configure"); final Activity activity = this; autoConfigure.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { new AndroidBarcode(activity).scan(); return true; } }); try { PackageInfo pInfo = null; pInfo = getPackageManager().getPackageInfo(getPackageName(), 0); findPreference("about_version_number").setSummary(pInfo.versionName); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } } /** {@inheritDoc} */ @Override public boolean onIsMultiPane() { return isXLargeTablet(this) && !isSimplePreferences(this); } /** * Helper method to determine if the device has an extra-large screen. For * example, 10" tablets are extra-large. */ private static boolean isXLargeTablet(Context context) { return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_XLARGE; } /** * Determines whether the simplified settings UI should be shown. This is * true if this is forced via {@link #ALWAYS_SIMPLE_PREFS}, or the device * doesn't have newer APIs like {@link PreferenceFragment}, or the device * doesn't have an extra-large screen. In these cases, a single-pane * "simplified" settings UI should be shown. */ private static boolean isSimplePreferences(Context context) { return ALWAYS_SIMPLE_PREFS || Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB || !isXLargeTablet(context); } /** {@inheritDoc} */ @Override @TargetApi(Build.VERSION_CODES.HONEYCOMB) public void onBuildHeaders(List<Header> target) { if (!isSimplePreferences(this)) { loadHeadersFromResource(R.xml.pref_headers, target); } ======= protected static void showValidationError(final Context context, final String message) { final AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle(R.string.invalid_input_title); builder.setMessage(message); builder.setPositiveButton(R.string.ok, null); builder.show(); >>>>>>> protected static void showValidationError(final Context context, final String message) { final AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle(R.string.invalid_input_title); builder.setMessage(message); builder.setPositiveButton(R.string.ok, null); builder.show(); <<<<<<< public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.pref_privacy); // Bind the summaries of EditText/List/Dialog/Ringtone preferences // to their values. When their values change, their summaries are // updated to reflect the new value, per the Android Design // guidelines. } } // Specific to the barcode scanner public void onActivityResult(int requestCode, int resultCode, Intent intent) { IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent); NightscoutPreferences prefs = new AndroidPreferences(getApplicationContext()); if (scanResult != null && scanResult.getContents() != null) { NSBarcodeConfig barcode=new NSBarcodeConfig(scanResult.getContents(), prefs); if (barcode.hasMongoConfig()) { prefs.setMongoUploadEnabled(true); prefs.setMongoClientUri(barcode.getMongoUri().get()); prefs.setMongoCollection(barcode.getMongoCollection().get()); prefs.setMongoDeviceStatusCollection(barcode.getMongoDeviceStatusCollection().get()); } else { prefs.setMongoUploadEnabled(false); } if (barcode.hasApiConfig()) { prefs.setRestApiEnabled(true); prefs.setRestApiBaseUris(barcode.getApiUris()); } else { prefs.setRestApiEnabled(false); ======= public void onActivityResult(int requestCode, int resultCode, Intent data) { IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data); NightscoutPreferences prefs = new AndroidPreferences(PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext())); if (scanResult != null && scanResult.getContents() != null) { NSBarcodeConfig barcode=new NSBarcodeConfig(scanResult.getContents(),prefs); if (barcode.hasMongoConfig()) { prefs.setMongoUploadEnabled(true); if (barcode.getMongoUri().isPresent()) { prefs.setMongoClientUri(barcode.getMongoUri().get()); if (barcode.getMongoCollection().isPresent()) { prefs.setMongoCollection(barcode.getMongoCollection().get()); } if (barcode.getMongoDeviceStatusCollection().isPresent()) { prefs.setMongoDeviceStatusCollection(barcode.getMongoDeviceStatusCollection().get()); } } } else { prefs.setMongoUploadEnabled(false); } if (barcode.hasApiConfig()) { prefs.setRestApiEnabled(true); prefs.setRestApiBaseUris(barcode.getApiUris()); } else { prefs.setRestApiEnabled(false); } >>>>>>> public void onActivityResult(int requestCode, int resultCode, Intent data) { IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data); NightscoutPreferences prefs = new AndroidPreferences(PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext())); if (scanResult != null && scanResult.getContents() != null) { NSBarcodeConfig barcode=new NSBarcodeConfig(scanResult.getContents(),prefs); if (barcode.hasMongoConfig()) { prefs.setMongoUploadEnabled(true); if (barcode.getMongoUri().isPresent()) { prefs.setMongoClientUri(barcode.getMongoUri().get()); if (barcode.getMongoCollection().isPresent()) { prefs.setMongoCollection(barcode.getMongoCollection().get()); } if (barcode.getMongoDeviceStatusCollection().isPresent()) { prefs.setMongoDeviceStatusCollection(barcode.getMongoDeviceStatusCollection().get()); } } } else { prefs.setMongoUploadEnabled(false); } if (barcode.hasApiConfig()) { prefs.setRestApiEnabled(true); prefs.setRestApiBaseUris(barcode.getApiUris()); } else { prefs.setRestApiEnabled(false); }
<<<<<<< import com.microsoft.reef.client.*; ======= import com.microsoft.reef.client.CompletedJob; import com.microsoft.reef.client.FailedJob; import com.microsoft.reef.client.JobMessage; import com.microsoft.reef.client.RunningJob; import com.microsoft.reef.client.parameters.JobCompletedHandler; import com.microsoft.reef.client.parameters.JobFailedHandler; import com.microsoft.reef.client.parameters.JobMessageHandler; import com.microsoft.reef.client.parameters.JobRunningHandler; import com.microsoft.reef.driver.parameters.DriverIdentifier; import com.microsoft.reef.exception.JobException; >>>>>>> import com.microsoft.reef.client.CompletedJob; import com.microsoft.reef.client.FailedJob; import com.microsoft.reef.client.JobMessage; import com.microsoft.reef.client.RunningJob; import com.microsoft.reef.client.parameters.JobCompletedHandler; import com.microsoft.reef.client.parameters.JobFailedHandler; import com.microsoft.reef.client.parameters.JobMessageHandler; import com.microsoft.reef.client.parameters.JobRunningHandler; import com.microsoft.reef.driver.parameters.DriverIdentifier;
<<<<<<< String strDate = new Date().toString(); System.out.println("java side date " + strDate); long handle0 = NativeInterop.CallClrSystemOnStartHandler(new Date().toString()); ======= InteropReturnInfo interopReturnInfo = new InteropReturnInfo (); InteropLogger interopLogger = new InteropLogger(); System.out.println("before NativeInterop.createHandler1"); long handle = NativeInterop.createHandler1 (interopReturnInfo, interopLogger, "hello world"); >>>>>>> String strDate = new Date().toString(); System.out.println("java side date " + strDate); long handle0 = NativeInterop.CallClrSystemOnStartHandler(new Date().toString()); InteropReturnInfo interopReturnInfo = new InteropReturnInfo (); InteropLogger interopLogger = new InteropLogger(); System.out.println("before NativeInterop.createHandler1"); long handle = NativeInterop.createHandler1 (interopReturnInfo, interopLogger, "hello world"); <<<<<<< EManager eManager = new EManager(); InteropLogger interopLogger = new InteropLogger(); NativeInterop.CallClrSystemAllocatedEvaluatorHandlerOnNext(handle0, eManager, interopLogger, value); ======= NativeInterop.clrHandlerOnNext(handle, value); System.out.println("before Exception"); value[0] = (byte)0x1; value[1] = (byte)0x2; value[2] = (byte)0x3; NativeInterop.clrHandlerOnNext2(interopReturnInfo, interopLogger, handle, value); System.out.println("after Exception"); System.out.println("error code " + interopReturnInfo.getReturnCode()); String ex = interopReturnInfo.getExceptionList().get(0); System.out.println("exception str " + ex); value[0] = (byte)0x4; value[1] = (byte)0x5; value[2] = (byte)0x6; NativeInterop.clrHandlerOnNext2(interopReturnInfo, interopLogger, handle, value); System.out.println("after Exception"); System.out.println("error code " + interopReturnInfo.getReturnCode()); ex = interopReturnInfo.getExceptionList().get(0); System.out.println("exception str " + ex); ex = interopReturnInfo.getExceptionList().get(1); System.out.println("exception str " + ex); >>>>>>> EManager eManager = new EManager(); NativeInterop.CallClrSystemAllocatedEvaluatorHandlerOnNext(handle0, eManager, interopLogger, value);
<<<<<<< ======= import android.support.v4.app.FragmentActivity; >>>>>>> import android.support.v4.app.FragmentActivity; <<<<<<< String jsonConfig = null; NightscoutPreferences prefs; ======= private SettingsActivity.MainPreferenceFragment mainPreferenceFragment; >>>>>>> String jsonConfig = null; NightscoutPreferences prefs; private SettingsActivity.MainPreferenceFragment mainPreferenceFragment;
<<<<<<< import com.microsoft.reef.driver.task.TaskConfigurationOptions; ======= import com.microsoft.reef.driver.activity.ActivityConfiguration; import com.microsoft.reef.driver.activity.ActivityConfigurationOptions; >>>>>>> <<<<<<< .bindNamedParameter(TaskConfigurationOptions.Identifier.class, SELF) ======= >>>>>>>
<<<<<<< import java.io.IOException; import java.util.*; ======= import java.util.List; >>>>>>> import java.io.IOException; import java.util.List; <<<<<<< * Handle a context status update * * @param contextStatusProto indicating the current status of the context */ private synchronized void onContextStatusMessage( final ReefServiceProtos.ContextStatusProto contextStatusProto, final boolean notifyClientOnNewActiveContext) { final String contextID = contextStatusProto.getContextId(); final Optional<String> parentID = contextStatusProto.hasParentId() ? Optional.of(contextStatusProto.getParentId()) : Optional.<String>empty(); if (ReefServiceProtos.ContextStatusProto.State.READY == contextStatusProto.getContextState()) { if (!this.activeContextIds.contains(contextID)) { final EvaluatorContext context = new EvaluatorContext(contextID, this.evaluatorId, this.evaluatorDescriptor, parentID, this.configurationSerializer, this.contextControlHandler, this, this.messageDispatcher, this.exceptionCodec); addEvaluatorContext(context); if(contextStatusProto.getRecovery()){ // when we get a recovered active context, always notify application this.messageDispatcher.OnDriverRestartContextActive(context); } else{ if (notifyClientOnNewActiveContext) { this.messageDispatcher.onContextActive(context); } } } for (final ReefServiceProtos.ContextStatusProto.ContextMessageProto contextMessageProto : contextStatusProto.getContextMessageList()) { final byte[] theMessage = contextMessageProto.getMessage().toByteArray(); final String sourceID = contextMessageProto.getSourceId(); this.messageDispatcher.onContextMessage(new ContextMessageImpl(theMessage, contextID, sourceID)); } } else { if (!this.activeContextIds.contains(contextID)) { if (ReefServiceProtos.ContextStatusProto.State.FAIL == contextStatusProto.getContextState()) { // It failed right away addEvaluatorContext(new EvaluatorContext(contextID, this.evaluatorId, this.evaluatorDescriptor, parentID, this.configurationSerializer, this.contextControlHandler, this, this.messageDispatcher, this.exceptionCodec)); } else { throw new RuntimeException("unknown context signaling state " + contextStatusProto.getContextState()); } } final EvaluatorContext context = getEvaluatorContext(contextID); final EvaluatorContext parentContext = context.getParentId().isPresent() ? getEvaluatorContext(context.getParentId().get()) : null; removeEvaluatorContext(context); if (ReefServiceProtos.ContextStatusProto.State.FAIL == contextStatusProto.getContextState()) { context.onContextFailure(contextStatusProto); } else if (ReefServiceProtos.ContextStatusProto.State.DONE == contextStatusProto.getContextState()) { if (null != parentContext) { this.messageDispatcher.onContextClose(context.getClosedContext(parentContext)); } else { LOG.info("Root context closed. Evaluator closed will trigger final shutdown."); } } else { throw new RuntimeException("Unknown context state " + contextStatusProto.getContextState() + " for context " + contextID); } } } /** ======= >>>>>>>
<<<<<<< import com.microsoft.reef.javabridge.*; import com.microsoft.reef.util.logging.CLRBufferedLogHandler; ======= import com.microsoft.reef.webserver.AvroHttpRequest; import com.microsoft.reef.webserver.AvroHttpSerializer; >>>>>>> import com.microsoft.reef.javabridge.*; import com.microsoft.reef.util.logging.CLRBufferedLogHandler; import com.microsoft.reef.webserver.AvroHttpRequest; import com.microsoft.reef.webserver.AvroHttpSerializer;
<<<<<<< import net.minecraft.util.math.Vec3d; import net.minecraft.util.math.Vec3i; import net.minecraft.util.registry.Registry; ======= >>>>>>> import net.minecraft.util.math.Vec3d; import net.minecraft.util.math.Vec3i; import net.minecraft.util.registry.Registry; <<<<<<< public static void registerCarpetBehaviours() { DispenserBlock.registerBehavior(Items.GLASS_BOTTLE, new WaterBottleDispenserBehaviour()); DispenserBlock.registerBehavior(Items.CHEST, new MinecartDispenserBehaviour(AbstractMinecartEntity.Type.CHEST)); DispenserBlock.registerBehavior(Items.HOPPER, new MinecartDispenserBehaviour(AbstractMinecartEntity.Type.HOPPER)); DispenserBlock.registerBehavior(Items.FURNACE, new MinecartDispenserBehaviour(AbstractMinecartEntity.Type.FURNACE)); DispenserBlock.registerBehavior(Items.TNT, new MinecartDispenserBehaviour(AbstractMinecartEntity.Type.TNT)); DispenserBlock.registerBehavior(Items.STICK, new TogglingDispenserBehaviour()); Registry.ITEM.forEach(record -> { if (record instanceof MusicDiscItem) { DispenserBlock.registerBehavior(record, new DispenserRecords()); } }); } ======= >>>>>>> <<<<<<< public static class TogglingDispenserBehaviour extends ItemDispenserBehavior { private FakePlayerEntity player; private static Set<Block> toggleable = Sets.newHashSet( Blocks.STONE_BUTTON, Blocks.ACACIA_BUTTON, Blocks.BIRCH_BUTTON, Blocks.DARK_OAK_BUTTON, Blocks.JUNGLE_BUTTON, Blocks.OAK_BUTTON, Blocks.SPRUCE_BUTTON, Blocks.ACACIA_DOOR, Blocks.BIRCH_DOOR, Blocks.DARK_OAK_DOOR, Blocks.JUNGLE_DOOR, Blocks.OAK_DOOR, Blocks.SPRUCE_DOOR, Blocks.ACACIA_TRAPDOOR, Blocks.BIRCH_TRAPDOOR, Blocks.DARK_OAK_TRAPDOOR, Blocks.JUNGLE_TRAPDOOR, Blocks.OAK_TRAPDOOR, Blocks.SPRUCE_TRAPDOOR, Blocks.ACACIA_FENCE_GATE, Blocks.BIRCH_FENCE_GATE, Blocks.DARK_OAK_FENCE_GATE, Blocks.JUNGLE_FENCE_GATE, Blocks.OAK_FENCE_GATE, Blocks.SPRUCE_FENCE_GATE, Blocks.REPEATER, Blocks.COMPARATOR, Blocks.LEVER, Blocks.DAYLIGHT_DETECTOR, Blocks.NOTE_BLOCK, Blocks.REDSTONE_ORE, Blocks.BELL ); @Override protected ItemStack dispenseSilently(BlockPointer source, ItemStack stack) { if(!CarpetExtraSettings.dispensersToggleThings) { return super.dispenseSilently(source, stack); } World world = source.getWorld(); if(player == null) player = new FakePlayerEntity(world, "toggling"); Direction direction = (Direction) source.getBlockState().get(DispenserBlock.FACING); BlockPos pos = source.getBlockPos().offset(direction); BlockState state = world.getBlockState(pos); if(toggleable.contains(state.getBlock())) { boolean bool = state.activate( world, player, Hand.MAIN_HAND, new BlockHitResult( new Vec3d(new Vec3i(pos.getX(), pos.getY(), pos.getZ())), direction, pos, false ) ); if(bool) return stack; } return super.dispenseSilently(source, stack); } } ======= public static class TillSoilDispenserBehaviour extends ItemDispenserBehavior { @Override protected ItemStack dispenseSilently(BlockPointer blockPointer_1, ItemStack itemStack_1) { if (!CarpetExtraSettings.dispensersTillSoil) return super.dispenseSilently(blockPointer_1, itemStack_1); World world = blockPointer_1.getWorld(); Direction direction = blockPointer_1.getBlockState().get(DispenserBlock.FACING); BlockPos front = blockPointer_1.getBlockPos().offset(direction); BlockPos down = blockPointer_1.getBlockPos().down().offset(direction); BlockState frontState = world.getBlockState(front); BlockState downState = world.getBlockState(down); if (isFarmland(frontState) || isFarmland(downState)) return itemStack_1; if (canDirectlyTurnToFarmland(frontState)) world.setBlockState(front, Blocks.FARMLAND.getDefaultState()); else if (canDirectlyTurnToFarmland(downState)) world.setBlockState(down, Blocks.FARMLAND.getDefaultState()); else if (frontState.getBlock() == Blocks.COARSE_DIRT) world.setBlockState(front, Blocks.DIRT.getDefaultState()); else if (downState.getBlock() == Blocks.COARSE_DIRT) world.setBlockState(down, Blocks.DIRT.getDefaultState()); if (itemStack_1.damage(1, world.random, null)) itemStack_1.setCount(0); return itemStack_1; } private boolean canDirectlyTurnToFarmland(BlockState state) { return state.getBlock() == Blocks.DIRT || state.getBlock() == Blocks.GRASS_BLOCK || state.getBlock() == Blocks.GRASS_PATH; } private boolean isFarmland(BlockState state) { return state.getBlock() == Blocks.FARMLAND; } } >>>>>>> public static class TogglingDispenserBehaviour extends ItemDispenserBehavior { private FakePlayerEntity player; private static Set<Block> toggleable = Sets.newHashSet( Blocks.STONE_BUTTON, Blocks.ACACIA_BUTTON, Blocks.BIRCH_BUTTON, Blocks.DARK_OAK_BUTTON, Blocks.JUNGLE_BUTTON, Blocks.OAK_BUTTON, Blocks.SPRUCE_BUTTON, Blocks.ACACIA_DOOR, Blocks.BIRCH_DOOR, Blocks.DARK_OAK_DOOR, Blocks.JUNGLE_DOOR, Blocks.OAK_DOOR, Blocks.SPRUCE_DOOR, Blocks.ACACIA_TRAPDOOR, Blocks.BIRCH_TRAPDOOR, Blocks.DARK_OAK_TRAPDOOR, Blocks.JUNGLE_TRAPDOOR, Blocks.OAK_TRAPDOOR, Blocks.SPRUCE_TRAPDOOR, Blocks.ACACIA_FENCE_GATE, Blocks.BIRCH_FENCE_GATE, Blocks.DARK_OAK_FENCE_GATE, Blocks.JUNGLE_FENCE_GATE, Blocks.OAK_FENCE_GATE, Blocks.SPRUCE_FENCE_GATE, Blocks.REPEATER, Blocks.COMPARATOR, Blocks.LEVER, Blocks.DAYLIGHT_DETECTOR, Blocks.NOTE_BLOCK, Blocks.REDSTONE_ORE, Blocks.BELL ); @Override protected ItemStack dispenseSilently(BlockPointer source, ItemStack stack) { if(!CarpetExtraSettings.dispensersToggleThings) { return super.dispenseSilently(source, stack); } World world = source.getWorld(); if(player == null) player = new FakePlayerEntity(world, "toggling"); Direction direction = (Direction) source.getBlockState().get(DispenserBlock.FACING); BlockPos pos = source.getBlockPos().offset(direction); BlockState state = world.getBlockState(pos); if(toggleable.contains(state.getBlock())) { boolean bool = state.activate( world, player, Hand.MAIN_HAND, new BlockHitResult( new Vec3d(new Vec3i(pos.getX(), pos.getY(), pos.getZ())), direction, pos, false ) ); if(bool) return stack; } return super.dispenseSilently(source, stack); } } public static class TillSoilDispenserBehaviour extends ItemDispenserBehavior { @Override protected ItemStack dispenseSilently(BlockPointer blockPointer_1, ItemStack itemStack_1) { if (!CarpetExtraSettings.dispensersTillSoil) return super.dispenseSilently(blockPointer_1, itemStack_1); World world = blockPointer_1.getWorld(); Direction direction = blockPointer_1.getBlockState().get(DispenserBlock.FACING); BlockPos front = blockPointer_1.getBlockPos().offset(direction); BlockPos down = blockPointer_1.getBlockPos().down().offset(direction); BlockState frontState = world.getBlockState(front); BlockState downState = world.getBlockState(down); if (isFarmland(frontState) || isFarmland(downState)) return itemStack_1; if (canDirectlyTurnToFarmland(frontState)) world.setBlockState(front, Blocks.FARMLAND.getDefaultState()); else if (canDirectlyTurnToFarmland(downState)) world.setBlockState(down, Blocks.FARMLAND.getDefaultState()); else if (frontState.getBlock() == Blocks.COARSE_DIRT) world.setBlockState(front, Blocks.DIRT.getDefaultState()); else if (downState.getBlock() == Blocks.COARSE_DIRT) world.setBlockState(down, Blocks.DIRT.getDefaultState()); if (itemStack_1.damage(1, world.random, null)) itemStack_1.setCount(0); return itemStack_1; } private boolean canDirectlyTurnToFarmland(BlockState state) { return state.getBlock() == Blocks.DIRT || state.getBlock() == Blocks.GRASS_BLOCK || state.getBlock() == Blocks.GRASS_PATH; } private boolean isFarmland(BlockState state) { return state.getBlock() == Blocks.FARMLAND; } }
<<<<<<< private GlucoseUnits units; private String pwdName; ======= public static final String DEFAULT_MONGO_COLLECTION = "entries"; public static final String DEFAULT_MONGO_DEVICE_STATUS_COLLECTION = "devicestatus"; private boolean understand; >>>>>>> private GlucoseUnits units; private String pwdName; public static final String DEFAULT_MONGO_COLLECTION = "entries"; public static final String DEFAULT_MONGO_DEVICE_STATUS_COLLECTION = "devicestatus"; private boolean understand; <<<<<<< @Override public GlucoseUnits getPreferredUnits() { return units; } @Override public void setPreferredUnits(GlucoseUnits units) { this.units = units; } ======= @Override >>>>>>> @Override public GlucoseUnits getPreferredUnits() { return units; } @Override public void setPreferredUnits(GlucoseUnits units) { this.units = units; } @Override
<<<<<<< private final Set<TestDescriptor> children = new LinkedHashSet<>(); ======= private TestSource source; private final Set<AbstractTestDescriptor> children = new LinkedHashSet<>(); >>>>>>> private TestSource source; private final Set<TestDescriptor> children = new LinkedHashSet<>();
<<<<<<< @Classes({ SucceedingTestCase.class }) @UniqueIds({ "junit5:com.example.SampleTestCase#assertAllTest()", "junit5:com.example.SampleTestCase#assertAllFailingTest()", "junit5:com.example.SampleTestCase@AnInnerTestContext" }) ======= @Classes({ SampleTestCase.class, SucceedingTestCase.class, JUnit4TestCase.class }) @UniqueIds({ "junit5:com.example.SampleTestCase#assertAllTest()", "junit5:com.example.SampleTestCase#assertAllFailingTest()" }) >>>>>>> @Classes({ SampleTestCase.class, SucceedingTestCase.class, JUnit4TestCase.class }) @UniqueIds({ "junit5:com.example.SampleTestCase#assertAllTest()", "junit5:com.example.SampleTestCase#assertAllFailingTest()", "junit5:com.example.SampleTestCase@AnInnerTestContext" })
<<<<<<< ======= import lombok.Data; import lombok.EqualsAndHashCode; import org.junit.gen5.api.Name; import org.junit.gen5.api.Test; import org.junit.gen5.commons.util.AnnotationUtils; >>>>>>> import org.junit.gen5.api.Name; import org.junit.gen5.api.Test; import org.junit.gen5.commons.util.AnnotationUtils; <<<<<<< import org.junit.gen5.engine.AbstractTestDescriptor; ======= import org.junit.gen5.commons.util.StringUtils; >>>>>>> import org.junit.gen5.commons.util.StringUtils; import org.junit.gen5.engine.AbstractTestDescriptor; <<<<<<< ======= private final String displayName; private final TestDescriptor parent; >>>>>>> private final String displayName; <<<<<<< ======= this.parent = parent; this.displayName = determineDisplayName(); >>>>>>> this.displayName = determineDisplayName();
<<<<<<< import static org.junit.gen5.commons.util.ReflectionUtils.loadClass; ======= import java.lang.reflect.AnnotatedElement; >>>>>>> import static org.junit.gen5.commons.util.ReflectionUtils.loadClass; <<<<<<< private String createParameterIdPart(Method testMethod) { String parameterString = Arrays.stream(testMethod.getParameterTypes()).map(Class::getName).collect( Collectors.joining(",")); return "(" + parameterString + ")"; } private JUnit5Testable createTestable(String uniqueId, String engineId, List<String> parts, JUnit5Testable last) { if (parts.isEmpty()) return last; JUnit5Testable next = null; ======= private JUnit5Testable createElement(String uniqueId, List<String> parts) { AnnotatedElement currentJavaElement = null; Class<?> currentJavaContainer = null; >>>>>>> private JUnit5Testable createTestable(String uniqueId, String engineId, List<String> parts, JUnit5Testable last) { if (parts.isEmpty()) return last; JUnit5Testable next = null; <<<<<<< private Class<?> classByName(String className) { return loadClass(className).orElseThrow( () -> new IllegalArgumentException(String.format("Cannot resolve class name '%s'", className))); } private void throwCannotResolveClassException(Class<?> clazz) { throw new IllegalArgumentException( String.format("Cannot resolve class name '%s' because it's not a test container", clazz.getName())); ======= private static Class<?> loadClassByName(String className) { return ReflectionUtils.loadClass(className).orElse(null); >>>>>>> private Class<?> classByName(String className) { return loadClass(className).orElseThrow( () -> new IllegalArgumentException(String.format("Cannot resolve class name '%s'", className))); } private Class<?> loadClassByName(String className) { return ReflectionUtils.loadClass(className).orElse(null);
<<<<<<< import static com.salesmanager.core.business.constants.Constants.DEFAULT_STORE; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; ======= >>>>>>> import static com.salesmanager.core.business.constants.Constants.DEFAULT_STORE; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; <<<<<<< import org.springframework.web.bind.annotation.RestController; import springfox.documentation.annotations.ApiIgnore; ======= >>>>>>>
<<<<<<< import android.content.Context; ======= >>>>>>> import android.content.Context; <<<<<<< import com.google.common.collect.Lists; import com.nightscout.android.R; ======= >>>>>>> import com.google.common.collect.Lists; import com.nightscout.android.R; <<<<<<< /** * Enable mongo upload in shared preferences * * @param mongoUploadEnabled whether or not to upload directly to mongo */ ======= >>>>>>> /** * Enable mongo upload in shared preferences * * @param mongoUploadEnabled whether or not to upload directly to mongo */ <<<<<<< preferences.edit().putBoolean(PreferenceKeys.MONGO_UPLOADER_ENABLED, mongoUploadEnabled).apply(); ======= preferences.edit().putBoolean(PreferenceKeys.MONGO_UPLOADER_ENABLED,mongoUploadEnabled).apply(); >>>>>>> preferences.edit().putBoolean(PreferenceKeys.MONGO_UPLOADER_ENABLED, mongoUploadEnabled).apply(); <<<<<<< preferences.edit().putBoolean(PreferenceKeys.API_UPLOADER_ENABLED, restApiEnabled).apply(); ======= preferences.edit().putBoolean(PreferenceKeys.API_UPLOADER_ENABLED,restApiEnabled).apply(); >>>>>>> preferences.edit().putBoolean(PreferenceKeys.API_UPLOADER_ENABLED, restApiEnabled).apply();
<<<<<<< import org.json.JSONException; import org.json.JSONObject; ======= >>>>>>> import org.json.JSONException; import org.json.JSONObject; <<<<<<< ======= @Test public void isSpecialValue() throws Exception { byte[] record = new byte[]{ (byte) 0xC4, (byte) 0x88, (byte) 0x1A, (byte) 0x0B, (byte) 0x61, (byte) 0x34, (byte) 0x1A, (byte) 0x0B, (byte) 0x05, (byte) 0x00, (byte) 0x58, (byte) 0x3E }; EGVRecord egvRecord=new EGVRecord(record); assertThat(egvRecord.isSpecialValue(), is(true)); } >>>>>>> @Test public void isSpecialValue() throws Exception { byte[] record = new byte[]{ (byte) 0xC4, (byte) 0x88, (byte) 0x1A, (byte) 0x0B, (byte) 0x61, (byte) 0x34, (byte) 0x1A, (byte) 0x0B, (byte) 0x05, (byte) 0x00, (byte) 0x58, (byte) 0x3E }; EGVRecord egvRecord=new EGVRecord(record); assertThat(egvRecord.isSpecialValue(), is(true)); } <<<<<<< assertThat(egvRecord.getNoiseMode(), is(NoiseMode.None)); ======= assertThat(egvRecord.getNoiseMode(), is(NoiseMode.NOT_COMPUTED)); >>>>>>> assertThat(egvRecord.getNoiseMode(), is(NoiseMode.NOT_COMPUTED)); <<<<<<< @Test public void shouldConvertToJSONString() throws Exception { byte[] record = new byte[]{ (byte) 0xC4, (byte) 0x88, (byte) 0x1A, (byte) 0x0B, (byte) 0x61, (byte) 0x34, (byte) 0x1A, (byte) 0x0B, (byte) 0x05, (byte) 0x00, (byte) 0x58, (byte) 0x3E }; JSONObject obj = new JSONObject(); try { obj.put("sgv", 5); obj.put("date", Utils.receiverTimeToDate(186266721)); } catch (JSONException e) { e.printStackTrace(); } EGVRecord egvRecord = new EGVRecord(record); assertThat(egvRecord.toJSON().toString(), is(obj.toString())); } @Test public void isSpecialValue() throws Exception { byte specialValue = 0x00; byte[] record = new byte[]{ (byte) 0xC4, (byte) 0x88, (byte) 0x1A, (byte) 0x0B, (byte) 0x61, (byte) 0x34, (byte) 0x1A, (byte) 0x0B, specialValue, (byte) 0x00, (byte) 0x58, (byte) 0x3E }; EGVRecord egvRecord = new EGVRecord(record); assertThat(egvRecord.isSpecialValue(), is(true)); } @Test public void isNotSpecialValue() throws Exception { byte sgValue = 0x64; byte[] record = new byte[]{ (byte) 0xC4, (byte) 0x88, (byte) 0x1A, (byte) 0x0B, (byte) 0x61, (byte) 0x34, (byte) 0x1A, (byte) 0x0B, sgValue, (byte) 0x00, (byte) 0x58, (byte) 0x3E }; EGVRecord egvRecord = new EGVRecord(record); assertThat(egvRecord.isSpecialValue(), is(false)); } ======= //TODO (klee) Add tests for different trend arrows and noise modes >>>>>>> @Test public void shouldConvertToJSONString() throws Exception { byte[] record = new byte[]{ (byte) 0xC4, (byte) 0x88, (byte) 0x1A, (byte) 0x0B, (byte) 0x61, (byte) 0x34, (byte) 0x1A, (byte) 0x0B, (byte) 0x05, (byte) 0x00, (byte) 0x58, (byte) 0x3E }; JSONObject obj = new JSONObject(); try { obj.put("sgv", 5); obj.put("date", Utils.receiverTimeToDate(186266721)); } catch (JSONException e) { e.printStackTrace(); } EGVRecord egvRecord = new EGVRecord(record); assertThat(egvRecord.toJSON().toString(), is(obj.toString())); } @Test public void isSpecialValue() throws Exception { byte specialValue = 0x00; byte[] record = new byte[]{ (byte) 0xC4, (byte) 0x88, (byte) 0x1A, (byte) 0x0B, (byte) 0x61, (byte) 0x34, (byte) 0x1A, (byte) 0x0B, specialValue, (byte) 0x00, (byte) 0x58, (byte) 0x3E }; EGVRecord egvRecord = new EGVRecord(record); assertThat(egvRecord.isSpecialValue(), is(true)); } @Test public void isNotSpecialValue() throws Exception { byte sgValue = 0x64; byte[] record = new byte[]{ (byte) 0xC4, (byte) 0x88, (byte) 0x1A, (byte) 0x0B, (byte) 0x61, (byte) 0x34, (byte) 0x1A, (byte) 0x0B, sgValue, (byte) 0x00, (byte) 0x58, (byte) 0x3E }; EGVRecord egvRecord = new EGVRecord(record); assertThat(egvRecord.isSpecialValue(), is(false)); } //TODO (klee) Add tests for different trend arrows and noise modes
<<<<<<< import javax.validation.constraints.Email; import javax.validation.constraints.NotEmpty; ======= import org.hibernate.validator.constraints.Email; import org.hibernate.validator.constraints.NotEmpty; import com.fasterxml.jackson.annotation.JsonIgnore; >>>>>>> import javax.validation.constraints.Email; import javax.validation.constraints.NotEmpty; import com.fasterxml.jackson.annotation.JsonIgnore;
<<<<<<< import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; ======= import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; >>>>>>> import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; <<<<<<< ======= @GetMapping(value = {"/merchant/{store}/stores"}, produces = MediaType.APPLICATION_JSON_VALUE) @ApiOperation(httpMethod = "GET", value = "Get stores attached to merchant", notes = "Merchant (retailer) can have multiple stores", response = ReadableMerchantStore.class) @ApiImplicitParams({ @ApiImplicitParam(name = "lang", dataType = "String", defaultValue = "en")}) public List<ReadableMerchantStore> stores(@PathVariable String merchant, @ApiIgnore Language language) { return storeFacade.getChildStores(language, merchant); } >>>>>>> <<<<<<< /** * List child stores * @param code * @param request * @return */ @ResponseStatus(HttpStatus.OK) @GetMapping(value = {"/private/merchant/{code}/children"}, produces = MediaType.APPLICATION_JSON_VALUE) @ApiOperation(httpMethod = "GET", value = "Get child stores", notes = "", response = List.class) @ApiImplicitParams({ @ApiImplicitParam(name = "lang", dataType = "String", defaultValue = "en")}) public ReadableMerchantStoreList children( @PathVariable String code, @ApiIgnore Language language, @RequestParam(value = "page", required = false, defaultValue="0") Integer page, @RequestParam(value = "count", required = false, defaultValue="10") Integer count, HttpServletRequest request) { String userName = getUserFromRequest(request); validateUserPermission(userName, code); return storeFacade.getChildStores(language, code, page, count); } ======= /** * List child stores * @param code * @param request * @return */ @ResponseStatus(HttpStatus.OK) @GetMapping(value = {"/private/merchant/{merchant}/children"}, produces = MediaType.APPLICATION_JSON_VALUE) @ApiOperation(httpMethod = "GET", value = "Get child stores", notes = "", response = List.class) @ApiImplicitParams({ @ApiImplicitParam(name = "lang", dataType = "String", defaultValue = "en")}) public List<ReadableMerchantStore> children( @PathVariable String merchant, @ApiIgnore Language language, HttpServletRequest request) { String userName = getUserFromRequest(request); validateUserPermission(userName, merchant); return storeFacade.getChildStores(language, merchant); } >>>>>>> /** * List child stores * @param code * @param request * @return */ @ResponseStatus(HttpStatus.OK) @GetMapping(value = {"/private/merchant/{code}/children"}, produces = MediaType.APPLICATION_JSON_VALUE) @ApiOperation(httpMethod = "GET", value = "Get child stores", notes = "", response = List.class) @ApiImplicitParams({ @ApiImplicitParam(name = "lang", dataType = "String", defaultValue = "en")}) public ReadableMerchantStoreList children( @PathVariable String code, @ApiIgnore Language language, @RequestParam(value = "page", required = false, defaultValue="0") Integer page, @RequestParam(value = "count", required = false, defaultValue="10") Integer count, HttpServletRequest request) { String userName = getUserFromRequest(request); validateUserPermission(userName, code); return storeFacade.getChildStores(language, code, page, count); }
<<<<<<< private final UserService userService; ======= private static final Logger LOGGER = LoggerFactory.getLogger(GratificationService.class); @Autowired private UserService userService; >>>>>>> private static final Logger LOGGER = LoggerFactory.getLogger(GratificationService.class); private final UserService userService; <<<<<<< private final StandardTaskRepository taskRepo; private static final Logger LOGGER = LoggerFactory.getLogger(GratificationService.class); public GratificationService(UserService userService, LevelService levelService, StandardTaskRepository taskRepo) { this.userService = userService; this.levelService = levelService; this.taskRepo = taskRepo; } ======= >>>>>>> public GratificationService(UserService userService, LevelService levelService) { this.userService = userService; this.levelService = levelService; }
<<<<<<< ======= @Autowired private WorldRepository worldRepository; >>>>>>> @Autowired private WorldRepository worldRepository; <<<<<<< public void updateStandardTask(StandardTask externalStandardTask) { StandardTask foundInternalStandardTask = standardTaskRepository.findByKey(externalStandardTask.getKey()); //task not new if (foundInternalStandardTask != null) { String newStatus = externalStandardTask.getStatus(); String oldStatus = foundInternalStandardTask.getStatus(); if(!Objects.equals(TaskStates.CREATED, oldStatus)){ foundInternalStandardTask.setStatus(newStatus); standardTaskRepository.save(foundInternalStandardTask); ======= public void updateStandardTask(StandardTask currentState) { StandardTask lastState = standardTaskRepository.findByKey(currentState.getKey()); if (lastState != null) { SonarQuestStatus newStatus = SonarQuestStatus.fromStatusText(currentState.getStatus()); SonarQuestStatus oldStatus = SonarQuestStatus.fromStatusText(lastState.getStatus()); if (oldStatus != SonarQuestStatus.CREATED) { lastState.setStatus(newStatus.getText()); standardTaskRepository.save(lastState); >>>>>>> public void updateStandardTask(StandardTask currentState) { StandardTask lastState = standardTaskRepository.findByKey(currentState.getKey()); if (lastState != null) { SonarQuestStatus newStatus = SonarQuestStatus.fromStatusText(currentState.getStatus()); SonarQuestStatus oldStatus = SonarQuestStatus.fromStatusText(lastState.getStatus()); if (oldStatus != SonarQuestStatus.CREATED) { lastState.setStatus(newStatus.getText()); <<<<<<< } //new task else { externalStandardTask.setStatus(TaskStates.CREATED); standardTaskRepository.save(externalStandardTask); ======= } else { currentState.setStatus(SonarQuestStatus.CREATED.getText()); standardTaskRepository.save(currentState); >>>>>>> } else { currentState.setStatus(SonarQuestStatus.CREATED.getText()); standardTaskRepository.save(currentState);
<<<<<<< eventService.createEventForCreateQuest(questDto); ======= questDto.setCreatorName(user.getUsername()); >>>>>>> eventService.createEventForCreateQuest(questDto); questDto.setCreatorName(user.getUsername());
<<<<<<< topIcons = new TopIcons(); ======= mImageViewUSB = (ImageView) findViewById(R.id.imageViewUSB); mImageViewUpload = (ImageView) findViewById(R.id.imageViewUploadStatus); mImageViewUpload.setImageResource(R.drawable.ic_upload_fail); mImageViewUpload.setTag(R.drawable.ic_upload_fail); mWebView = (WebView)findViewById(R.id.webView); WebSettings webSettings = mWebView.getSettings(); webSettings.setJavaScriptEnabled(true); webSettings.setDatabaseEnabled(true); webSettings.setDomStorageEnabled(true); webSettings.setAppCacheEnabled(true); webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE); mWebView.setBackgroundColor(0); mWebView.loadUrl("file:///android_asset/index.html"); >>>>>>> mImageViewUSB = (ImageView) findViewById(R.id.imageViewUSB); mImageViewUpload = (ImageView) findViewById(R.id.imageViewUploadStatus); mImageViewUpload.setImageResource(R.drawable.ic_upload_fail); mImageViewUpload.setTag(R.drawable.ic_upload_fail); mWebView = (WebView)findViewById(R.id.webView); WebSettings webSettings = mWebView.getSettings(); webSettings.setJavaScriptEnabled(true); webSettings.setDatabaseEnabled(true); webSettings.setDomStorageEnabled(true); webSettings.setAppCacheEnabled(true); webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE); mWebView.setBackgroundColor(0); mWebView.loadUrl("file:///android_asset/index.html"); topIcons = new TopIcons();
<<<<<<< public static final String DEFAULT_MONGO_COLLECTION = "entries"; public static final String DEFAULT_MONGO_DEVICE_STATUS_COLLECTION = "devicestatus"; ======= private boolean understand; >>>>>>> public static final String DEFAULT_MONGO_COLLECTION = "entries"; public static final String DEFAULT_MONGO_DEVICE_STATUS_COLLECTION = "devicestatus"; private boolean understand;
<<<<<<< /* * Copyright 2012 Adam Murdoch * * 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.rubygrapefruit.platform; import net.rubygrapefruit.platform.internal.NativeLibraryLoader; import net.rubygrapefruit.platform.internal.NativeLibraryLocator; import net.rubygrapefruit.platform.internal.Platform; import net.rubygrapefruit.platform.internal.jni.NativeLibraryFunctions; import net.rubygrapefruit.platform.internal.jni.NativeLogger; import net.rubygrapefruit.platform.internal.jni.NativeVersion; import java.io.File; import java.util.HashMap; import java.util.Map; /** * Provides access to the native integrations. Use {@link #get(Class)} to load a particular integration. */ @ThreadSafe public class Native { private static NativeLibraryLoader loader; private static final Map<Class<?>, Object> integrations = new HashMap<Class<?>, Object>(); private Native() { } /** * Initialises the native integration, if not already initialized. * * @param extractDir The directory to extract native resources into. May be null, in which case a default is * selected. * * @throws NativeIntegrationUnavailableException When native integration is not available on the current machine. * @throws NativeException On failure to load the native integration. */ @ThreadSafe static public void init(File extractDir) throws NativeIntegrationUnavailableException, NativeException { synchronized (Native.class) { if (loader == null) { Platform platform = Platform.current(); try { loader = new NativeLibraryLoader(platform, new NativeLibraryLocator(extractDir)); loader.load(platform.getLibraryName(), platform.getLibraryVariants()); long nativeVersion = NativeLibraryFunctions.getVersion(); if (nativeVersion != NativeVersion.VERSION) { throw new NativeException(String.format("Unexpected native library version loaded. Expected %s, was %s.", NativeVersion.VERSION, nativeVersion)); } NativeLogger.initLogging(Native.class); } catch (NativeException e) { throw e; } catch (Throwable t) { throw new NativeException("Failed to initialise native integration.", t); } } } } /** * Locates a native integration of the given type. * * @return The native integration. Never returns null. * @throws NativeIntegrationUnavailableException When the given native integration is not available on the current * machine. * @throws NativeException On failure to load the native integration. */ @ThreadSafe public static <T extends NativeIntegration> T get(Class<T> type) throws NativeIntegrationUnavailableException, NativeException { init(null); synchronized (Native.class) { Platform platform = Platform.current(); Class<? extends T> canonicalType = platform.canonicalise(type); Object instance = integrations.get(canonicalType); if (instance == null) { try { instance = platform.get(canonicalType, loader); } catch (NativeException e) { throw e; } catch (Throwable t) { throw new NativeException(String.format("Failed to load native integration %s.", type.getSimpleName()), t); } integrations.put(canonicalType, instance); } return type.cast(instance); } } } ======= /* * Copyright 2012 Adam Murdoch * * 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.rubygrapefruit.platform; import net.rubygrapefruit.platform.internal.NativeLibraryLoader; import net.rubygrapefruit.platform.internal.NativeLibraryLocator; import net.rubygrapefruit.platform.internal.Platform; import net.rubygrapefruit.platform.internal.jni.NativeLibraryFunctions; import net.rubygrapefruit.platform.internal.jni.NativeVersion; import java.io.File; import java.util.HashMap; import java.util.Map; /** * Provides access to the native integrations. Use {@link #get(Class)} to load a particular integration. */ @ThreadSafe public class Native { private static NativeLibraryLoader loader; private static final Map<Class<?>, Object> integrations = new HashMap<Class<?>, Object>(); private Native() { } /** * Initialises the native integration, if not already initialized. * * @param extractDir The directory to extract native resources into. May be null, in which case a default is * selected. * * @throws NativeIntegrationUnavailableException When native integration is not available on the current machine. * @throws NativeException On failure to load the native integration. */ @ThreadSafe static public void init(File extractDir) throws NativeIntegrationUnavailableException, NativeException { synchronized (Native.class) { if (loader == null) { Platform platform = Platform.current(); try { loader = new NativeLibraryLoader(platform, new NativeLibraryLocator(extractDir)); loader.load(platform.getLibraryName(), platform.getLibraryVariants()); String nativeVersion = NativeLibraryFunctions.getVersion(); if (!nativeVersion.equals(NativeVersion.VERSION)) { throw new NativeException(String.format("Unexpected native library version loaded. Expected %s, was %s.", NativeVersion.VERSION, nativeVersion)); } } catch (NativeException e) { throw e; } catch (Throwable t) { throw new NativeException("Failed to initialise native integration.", t); } } } } /** * Locates a native integration of the given type. * * @return The native integration. Never returns null. * @throws NativeIntegrationUnavailableException When the given native integration is not available on the current * machine. * @throws NativeException On failure to load the native integration. */ @ThreadSafe public static <T extends NativeIntegration> T get(Class<T> type) throws NativeIntegrationUnavailableException, NativeException { init(null); synchronized (Native.class) { Platform platform = Platform.current(); Class<? extends T> canonicalType = platform.canonicalise(type); Object instance = integrations.get(canonicalType); if (instance == null) { try { instance = platform.get(canonicalType, loader); } catch (NativeException e) { throw e; } catch (Throwable t) { throw new NativeException(String.format("Failed to load native integration %s.", type.getSimpleName()), t); } integrations.put(canonicalType, instance); } return type.cast(instance); } } } >>>>>>> /* * Copyright 2012 Adam Murdoch * * 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.rubygrapefruit.platform; import net.rubygrapefruit.platform.internal.NativeLibraryLoader; import net.rubygrapefruit.platform.internal.NativeLibraryLocator; import net.rubygrapefruit.platform.internal.Platform; import net.rubygrapefruit.platform.internal.jni.NativeLibraryFunctions; import net.rubygrapefruit.platform.internal.jni.NativeLogger; import net.rubygrapefruit.platform.internal.jni.NativeVersion; import java.io.File; import java.util.HashMap; import java.util.Map; /** * Provides access to the native integrations. Use {@link #get(Class)} to load a particular integration. */ @ThreadSafe public class Native { private static NativeLibraryLoader loader; private static final Map<Class<?>, Object> integrations = new HashMap<Class<?>, Object>(); private Native() { } /** * Initialises the native integration, if not already initialized. * * @param extractDir The directory to extract native resources into. May be null, in which case a default is * selected. * * @throws NativeIntegrationUnavailableException When native integration is not available on the current machine. * @throws NativeException On failure to load the native integration. */ @ThreadSafe static public void init(File extractDir) throws NativeIntegrationUnavailableException, NativeException { synchronized (Native.class) { if (loader == null) { Platform platform = Platform.current(); try { loader = new NativeLibraryLoader(platform, new NativeLibraryLocator(extractDir)); loader.load(platform.getLibraryName(), platform.getLibraryVariants()); String nativeVersion = NativeLibraryFunctions.getVersion(); if (!nativeVersion.equals(NativeVersion.VERSION)) { throw new NativeException(String.format("Unexpected native library version loaded. Expected %s, was %s.", NativeVersion.VERSION, nativeVersion)); } NativeLogger.initLogging(Native.class); } catch (NativeException e) { throw e; } catch (Throwable t) { throw new NativeException("Failed to initialise native integration.", t); } } } } /** * Locates a native integration of the given type. * * @return The native integration. Never returns null. * @throws NativeIntegrationUnavailableException When the given native integration is not available on the current * machine. * @throws NativeException On failure to load the native integration. */ @ThreadSafe public static <T extends NativeIntegration> T get(Class<T> type) throws NativeIntegrationUnavailableException, NativeException { init(null); synchronized (Native.class) { Platform platform = Platform.current(); Class<? extends T> canonicalType = platform.canonicalise(type); Object instance = integrations.get(canonicalType); if (instance == null) { try { instance = platform.get(canonicalType, loader); } catch (NativeException e) { throw e; } catch (Throwable t) { throw new NativeException(String.format("Failed to load native integration %s.", type.getSimpleName()), t); } integrations.put(canonicalType, instance); } return type.cast(instance); } } }
<<<<<<< import java.util.UUID; ======= import java.util.Date; >>>>>>> import java.util.Date; import java.util.UUID; <<<<<<< assertTrue(index.supports(of(UUID.class), Cmp.EQUAL)); assertTrue(index.supports(of(UUID.class), Cmp.NOT_EQUAL)); ======= assertTrue(index.supports(of(Date.class), Cmp.EQUAL)); assertTrue(index.supports(of(Date.class), Cmp.LESS_THAN_EQUAL)); assertTrue(index.supports(of(Date.class), Cmp.LESS_THAN)); assertTrue(index.supports(of(Date.class), Cmp.GREATER_THAN)); assertTrue(index.supports(of(Date.class), Cmp.GREATER_THAN_EQUAL)); assertTrue(index.supports(of(Date.class), Cmp.NOT_EQUAL)); assertTrue(index.supports(of(Boolean.class), Cmp.EQUAL)); assertTrue(index.supports(of(Boolean.class), Cmp.NOT_EQUAL)); >>>>>>> assertTrue(index.supports(of(Date.class), Cmp.EQUAL)); assertTrue(index.supports(of(Date.class), Cmp.LESS_THAN_EQUAL)); assertTrue(index.supports(of(Date.class), Cmp.LESS_THAN)); assertTrue(index.supports(of(Date.class), Cmp.GREATER_THAN)); assertTrue(index.supports(of(Date.class), Cmp.GREATER_THAN_EQUAL)); assertTrue(index.supports(of(Date.class), Cmp.NOT_EQUAL)); assertTrue(index.supports(of(Boolean.class), Cmp.EQUAL)); assertTrue(index.supports(of(Boolean.class), Cmp.NOT_EQUAL)); assertTrue(index.supports(of(UUID.class), Cmp.EQUAL)); assertTrue(index.supports(of(UUID.class), Cmp.NOT_EQUAL));
<<<<<<< StandardScannerExecutor executor = new StandardScannerExecutor(job, kcvs, storeTx, manager.getFeatures(), numProcessingThreads, jobConfiguration); ======= StandardScannerExecutor executor = new StandardScannerExecutor(job, finishJob, kcvs, storeTx, manager.getFeatures(), numProcessingThreads, configuration); addJob(jobId,executor); >>>>>>> StandardScannerExecutor executor = new StandardScannerExecutor(job, finishJob, kcvs, storeTx, manager.getFeatures(), numProcessingThreads, jobConfiguration); addJob(jobId,executor);
<<<<<<< import com.thinkaurelius.titan.diskstorage.keycolumnvalue.*; ======= import com.google.common.collect.ImmutableList; >>>>>>> import com.thinkaurelius.titan.diskstorage.keycolumnvalue.*; import com.google.common.collect.ImmutableList;
<<<<<<< import com.thinkaurelius.titan.graphdb.database.cache.SchemaCache; ======= import com.thinkaurelius.titan.graphdb.database.cache.TypeCache; >>>>>>> import com.thinkaurelius.titan.graphdb.database.cache.SchemaCache; <<<<<<< private boolean isOpen; private AtomicLong txCounter; private Set<StandardTitanTx> openTransactions; ======= private volatile boolean isOpen = true; >>>>>>> private volatile boolean isOpen = true; private AtomicLong txCounter; private Set<StandardTitanTx> openTransactions; <<<<<<< this.schemaCache = configuration.getTypeCache(typeCacheRetrieval); isOpen = true; txCounter = new AtomicLong(0); openTransactions = Collections.newSetFromMap(new ConcurrentHashMap<StandardTitanTx, Boolean>(100,0.75f,1)); //Register instance and ensure uniqueness String uniqueInstanceId = configuration.getUniqueGraphId(); ModifiableConfiguration globalConfig = GraphDatabaseConfiguration.getGlobalSystemConfig(backend); if (globalConfig.has(REGISTRATION_TIME,uniqueInstanceId)) { throw new TitanException(String.format("A Titan graph with the same instance id [%s] is already open. Might required forced shutdown.",uniqueInstanceId)); } globalConfig.set(REGISTRATION_TIME, Timestamps.MILLI.getTime(), uniqueInstanceId); Log mgmtLog = backend.getSystemMgmtLog(); mgmtLogger = new ManagementLogger(this,mgmtLog,schemaCache); mgmtLog.registerReader(mgmtLogger); ======= this.typeCache = configuration.getTypeCache(typeCacheRetrieval); Runtime.getRuntime().addShutdownHook(new ShutdownThread(this)); >>>>>>> this.schemaCache = configuration.getTypeCache(typeCacheRetrieval); isOpen = true; txCounter = new AtomicLong(0); openTransactions = Collections.newSetFromMap(new ConcurrentHashMap<StandardTitanTx, Boolean>(100,0.75f,1)); //Register instance and ensure uniqueness String uniqueInstanceId = configuration.getUniqueGraphId(); ModifiableConfiguration globalConfig = GraphDatabaseConfiguration.getGlobalSystemConfig(backend); if (globalConfig.has(REGISTRATION_TIME,uniqueInstanceId)) { throw new TitanException(String.format("A Titan graph with the same instance id [%s] is already open. Might required forced shutdown.",uniqueInstanceId)); } globalConfig.set(REGISTRATION_TIME, Timestamps.MILLI.getTime(), uniqueInstanceId); Log mgmtLog = backend.getSystemMgmtLog(); mgmtLogger = new ManagementLogger(this,mgmtLog,schemaCache); mgmtLog.registerReader(mgmtLogger); Runtime.getRuntime().addShutdownHook(new ShutdownThread(this));
<<<<<<< new VertexToFaunusBinary().writeVertex(vertex, out); } public static void write(final Vertex vertex, final DataOutput out, final ElementIdHandler elementIdHandler) throws IOException { new VertexToFaunusBinary(elementIdHandler).writeVertex(vertex, out); } public void writeVertex(final Vertex vertex, final DataOutput out) throws IOException { out.writeLong(elementIdHandler.convertIdentifier(vertex.getId())); out.writeInt(0); ======= writeId(vertex.getId(), out); //out.writeInt(0); out.writeBoolean(false); out.writeLong(0); writeProperties(vertex, out); >>>>>>> new VertexToFaunusBinary().writeVertex(vertex, out); } public static void write(final Vertex vertex, final DataOutput out, final ElementIdHandler elementIdHandler) throws IOException { new VertexToFaunusBinary(elementIdHandler).writeVertex(vertex, out); } public void writeVertex(final Vertex vertex, final DataOutput out) throws IOException { out.writeLong(elementIdHandler.convertIdentifier(vertex.getId())); out.writeBoolean(false); out.writeLong(0); writeProperties(vertex, out); <<<<<<< out.writeLong(elementIdHandler.convertIdentifier(edge.getId())); out.writeInt(0); out.writeLong(elementIdHandler.convertIdentifier(edge.getVertex(direction.opposite()).getId())); ======= writeId(edge.getId(), out); out.writeBoolean(false); out.writeLong(0); >>>>>>> out.writeLong(elementIdHandler.convertIdentifier(edge.getId())); out.writeBoolean(false); out.writeLong(0);
<<<<<<< private List<KeySlice> getKeySlice(Cassandra.Client client, ByteBuffer startKey, ByteBuffer endKey, SliceQuery columnSlice, int count) throws StorageException { return getRangeSlices(client, new org.apache.cassandra.thrift.KeyRange().setStart_key(startKey).setEnd_key(endKey).setCount(count), columnSlice); ======= private List<KeySlice> getKeySlice(ByteBuffer startKey, ByteBuffer endKey, SliceQuery columnSlice, int count) throws StorageException { return getRangeSlices(new KeyRange().setStart_key(startKey).setEnd_key(endKey).setCount(count), columnSlice); >>>>>>> private List<KeySlice> getKeySlice(ByteBuffer startKey, ByteBuffer endKey, SliceQuery columnSlice, int count) throws StorageException { return getRangeSlices(new org.apache.cassandra.thrift.KeyRange().setStart_key(startKey).setEnd_key(endKey).setCount(count), columnSlice); <<<<<<< private List<KeySlice> getRangeSlices(Cassandra.Client client, org.apache.cassandra.thrift.KeyRange keyRange, @Nullable SliceQuery sliceQuery) throws StorageException { ======= private List<KeySlice> getRangeSlices(KeyRange keyRange, @Nullable SliceQuery sliceQuery) throws StorageException { >>>>>>> private List<KeySlice> getRangeSlices(org.apache.cassandra.thrift.KeyRange keyRange, @Nullable SliceQuery sliceQuery) throws StorageException {
<<<<<<< void setMongoUploadEnabled(boolean mongoUploadEnabled); void setRestApiEnabled(boolean restApiEnabled); ======= boolean getIUnderstand(); void setIUnderstand(boolean bool); // Unable to load values from res files for Robolectric tests public static final String DEFAULT_MONGO_COLLECTION = "cgm_data"; public static final String DEFAULT_MONGO_DEVICE_STATUS_COLLECTION = "devicestatus"; >>>>>>> void setMongoUploadEnabled(boolean mongoUploadEnabled); void setRestApiEnabled(boolean restApiEnabled); boolean getIUnderstand(); void setIUnderstand(boolean bool);
<<<<<<< /* ================================================================================== HELPER METHODS ==================================================================================*/ private void initialize(String store) throws BackendException { ======= protected void initialize(String store) throws StorageException { >>>>>>> /* ================================================================================== HELPER METHODS ==================================================================================*/ protected void initialize(String store) throws BackendException { <<<<<<< private void add(String store, String docid, Map<String, Object> doc, boolean isNew) { add(store, docid, doc, isNew, 0); } private void add(String store, String docid, Map<String, Object> doc, boolean isNew, int ttlInSeconds) { ======= protected void add(String store, String docid, Map<String, Object> doc, boolean isNew) { >>>>>>> protected void add(String store, String docid, Map<String, Object> doc, boolean isNew) { add(store, docid, doc, isNew, 0); } private void add(String store, String docid, Map<String, Object> doc, boolean isNew, int ttlInSeconds) {
<<<<<<< CompositeIndexType cIndex = (CompositeIndexType)index; IndexRecords updateRecords = indexMatches(vertex,cIndex,updateType==IndexUpdate.Type.DELETE,p.getPropertyKey(),new RecordEntry(p.getLongId(),p.getValue())); ======= CompositeIndexType iIndex = (CompositeIndexType)index; if (iIndex.getStatus()== SchemaStatus.DISABLED) continue; IndexRecords updateRecords = indexMatches(vertex,iIndex,updateType==IndexUpdate.Type.DELETE,p.getPropertyKey(),new RecordEntry(p)); >>>>>>> CompositeIndexType cIndex = (CompositeIndexType)index; IndexRecords updateRecords = indexMatches(vertex,cIndex,updateType==IndexUpdate.Type.DELETE,p.getPropertyKey(),new RecordEntry(p)); <<<<<<< updates.add(new IndexUpdate<StaticBuffer,Entry>(cIndex,updateType,getIndexKey(cIndex,record),getIndexEntry(cIndex,record,vertex), vertex)); ======= IndexUpdate update = new IndexUpdate<StaticBuffer,Entry>(iIndex,updateType,getIndexKey(iIndex,record),getIndexEntry(iIndex,record,vertex), vertex); int ttl = getIndexTTL(vertex,getKeysOfRecords(record)); if (ttl>0 && updateType== IndexUpdate.Type.ADD) update.setTTL(ttl); updates.add(update); >>>>>>> IndexUpdate update = new IndexUpdate<StaticBuffer,Entry>(cIndex,updateType,getIndexKey(cIndex,record),getIndexEntry(cIndex,record,vertex), vertex); int ttl = getIndexTTL(vertex,getKeysOfRecords(record)); if (ttl>0 && updateType== IndexUpdate.Type.ADD) update.setTTL(ttl); updates.add(update); <<<<<<< match[i] = new RecordEntry(relation.getLongId(),value); ======= match[i] = new RecordEntry(element.getID(),value,f.getFieldKey()); >>>>>>> match[i] = new RecordEntry(relation.getLongId(),value,f.getFieldKey()); <<<<<<< indexMatches(vertex,new RecordEntry[fields.length],matches,fields,0,false, replaceKey,new RecordEntry(0,replaceValue)); ======= indexMatches((InternalVertex)vertex,new RecordEntry[fields.length],matches,fields,0,false, replaceKey,new RecordEntry(0,replaceValue,replaceKey)); >>>>>>> indexMatches(vertex,new RecordEntry[fields.length],matches,fields,0,false, replaceKey,new RecordEntry(0,replaceValue,replaceKey)); <<<<<<< assert key.getDataType().equals(p.getValue().getClass()) : key + " -> " + p; values.add(new RecordEntry(p.getLongId(),p.getValue())); ======= values.add(new RecordEntry(p)); >>>>>>> assert key.getDataType().equals(p.getValue().getClass()) : key + " -> " + p; values.add(new RecordEntry(p));
<<<<<<< long relationIdDiff, vertexIdDiff = 0; if (titanType.isUnique(dir)) { assert data.getValuePosition() == in.getPosition(); if (rtype == RelationType.EDGE) ======= long relationIdDiff; Object other; int startKeyPos = in.getPosition(); int endKeyPos = 0; if (titanType.isEdgeLabel()) { long vertexIdDiff; if (multiplicity.isConstrained()) { >>>>>>> long relationIdDiff; Object other; int startKeyPos = in.getPosition(); int endKeyPos = 0; if (titanType.isEdgeLabel()) { long vertexIdDiff; if (multiplicity.isConstrained()) { <<<<<<< if (!excludeProperties && keysig.length > 0) { //Read sort key which only exists if type is not unique in this direction int keyLength = in.getPosition() + 1 - startKeyPos; //after reading the ids, we are on the last byte of the key in.movePositionTo(startKeyPos); ReadBuffer inkey = in; if (def.getSortOrder() == Order.DESC) inkey = in.subrange(keyLength, true); readInlineTypes(keysig, properties, inkey, tx); ======= endKeyPos = in.getPosition(); in.movePositionTo(data.getValuePosition()); >>>>>>> endKeyPos = in.getPosition(); in.movePositionTo(data.getValuePosition()); <<<<<<< long vertexIdDiff = 0; Integer ttl = null; long relationIdDiff = relation.getID() - relation.getVertex(position).getID(); if (relation.isEdge()) { vertexIdDiff = relation.getVertex((position + 1) % 2).getID() - relation.getVertex(position).getID(); ttl = relation.getProperty(Titan.TTL); if (null == ttl) { ttl = definition.getTtl(); } } ======= >>>>>>> Integer ttl = null; <<<<<<< sliceStart = IDHandler.getEdgeType(type.getID(), getDirID(Direction.OUT, rt)); sliceEnd = IDHandler.getEdgeType(type.getID(), getDirID(Direction.IN, rt)); assert sliceStart.compareTo(sliceEnd) < 0; ======= assert type.isEdgeLabel(); sliceStart = IDHandler.getEdgeType(type.getID(), getDirID(Direction.OUT, rt),type.isHiddenType()); sliceEnd = IDHandler.getEdgeType(type.getID(), getDirID(Direction.IN, rt),type.isHiddenType()); assert sliceStart.compareTo(sliceEnd)<0; >>>>>>> assert type.isEdgeLabel(); sliceStart = IDHandler.getEdgeType(type.getID(), getDirID(Direction.OUT, rt),type.isHiddenType()); sliceEnd = IDHandler.getEdgeType(type.getID(), getDirID(Direction.IN, rt),type.isHiddenType()); assert sliceStart.compareTo(sliceEnd)<0;
<<<<<<< /** * Retrieves the time-to-live for the given {@link TitanSchemaType}. * If none has been explicitly defined, 0 (unlimited TTL) is returned. * * @param type * @return */ public int getTTL(TitanSchemaType type); /** * Sets the time-to-live for the given {@link TitanSchemaType} * @param type the affected type * @param ttl time-to-live, in seconds */ public void setTTL(TitanSchemaType type, int ttl); ======= /* ##################### SCHEMA UPDATE ########################## */ /** * Changes the name of a {@link TitanSchemaElement} to the provided new name. * The new name must be valid and not already in use, otherwise an {@link IllegalArgumentException} is thrown. * * @param element * @param newName */ public void changeName(TitanSchemaElement element, String newName); /** * Updates the provided index according to the given {@link SchemaAction} * * @param index * @param updateAction */ public void updateIndex(TitanIndex index, SchemaAction updateAction); >>>>>>> /** * Retrieves the time-to-live for the given {@link TitanSchemaType}. * If none has been explicitly defined, 0 (unlimited TTL) is returned. * * @param type * @return */ public int getTTL(TitanSchemaType type); /** * Sets the time-to-live for the given {@link TitanSchemaType} * @param type the affected type * @param ttl time-to-live, in seconds */ public void setTTL(TitanSchemaType type, int ttl); /* ##################### SCHEMA UPDATE ########################## */ /** * Changes the name of a {@link TitanSchemaElement} to the provided new name. * The new name must be valid and not already in use, otherwise an {@link IllegalArgumentException} is thrown. * * @param element * @param newName */ public void changeName(TitanSchemaElement element, String newName); /** * Updates the provided index according to the given {@link SchemaAction} * * @param index * @param updateAction */ public void updateIndex(TitanIndex index, SchemaAction updateAction);
<<<<<<< import java.util.Collections; ======= import java.util.List; >>>>>>> import java.util.Collections; import java.util.List;
<<<<<<< import krasa.grepconsole.model.Operation; ======= import krasa.grepconsole.model.Operation; import org.jetbrains.annotations.NotNull; >>>>>>> import krasa.grepconsole.model.Operation; import org.jetbrains.annotations.NotNull; import krasa.grepconsole.model.Operation; <<<<<<< ======= import com.intellij.openapi.util.text.StringUtil; >>>>>>> import com.intellij.openapi.util.text.StringUtil;
<<<<<<< ======= public interface SystemType extends InternalType { >>>>>>> public interface SystemType extends InternalType {
<<<<<<< ======= import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.deser.std.StdDeserializer; import com.fasterxml.jackson.databind.jsontype.TypeSerializer; import com.fasterxml.jackson.databind.ser.std.StdSerializer; >>>>>>> <<<<<<< import org.apache.tinkerpop.shaded.jackson.core.JsonGenerator; import org.apache.tinkerpop.shaded.jackson.core.JsonProcessingException; import org.apache.tinkerpop.shaded.jackson.databind.SerializerProvider; import org.apache.tinkerpop.shaded.jackson.databind.ser.std.StdSerializer; ======= import org.apache.tinkerpop.gremlin.structure.Property; import org.apache.tinkerpop.gremlin.structure.io.graphson.GraphSONTokens; import org.apache.tinkerpop.gremlin.structure.io.graphson.GraphSONUtil; import org.apache.tinkerpop.shaded.kryo.Kryo; import org.apache.tinkerpop.shaded.kryo.Serializer; import org.apache.tinkerpop.shaded.kryo.io.Input; import org.apache.tinkerpop.shaded.kryo.io.Output; >>>>>>> import org.apache.tinkerpop.gremlin.structure.io.graphson.GraphSONTokens; import org.apache.tinkerpop.gremlin.structure.io.graphson.GraphSONUtil; import org.apache.tinkerpop.shaded.jackson.core.JsonGenerator; import org.apache.tinkerpop.shaded.jackson.core.JsonParser; import org.apache.tinkerpop.shaded.jackson.core.JsonProcessingException; import org.apache.tinkerpop.shaded.jackson.databind.DeserializationContext; import org.apache.tinkerpop.shaded.jackson.databind.SerializerProvider; import org.apache.tinkerpop.shaded.jackson.databind.deser.std.StdDeserializer; import org.apache.tinkerpop.shaded.jackson.databind.jsontype.TypeSerializer; import org.apache.tinkerpop.shaded.jackson.databind.ser.std.StdSerializer; import org.apache.tinkerpop.shaded.kryo.Kryo; import org.apache.tinkerpop.shaded.kryo.Serializer; import org.apache.tinkerpop.shaded.kryo.io.Input; import org.apache.tinkerpop.shaded.kryo.io.Output;
<<<<<<< private boolean enableAnsiColoring; private boolean hideAnsiCommands; ======= >>>>>>> <<<<<<< private boolean synchronous; ======= private String maxProcessingTime = MAX_PROCESSING_TIME_DEFAULT; @Transient private transient Integer maxProcessingTimeAsInt; >>>>>>> private String maxProcessingTime = MAX_PROCESSING_TIME_DEFAULT; @Transient private transient Integer maxProcessingTimeAsInt; private boolean synchronous; <<<<<<< public boolean isEnableAnsiColoring() { return enableAnsiColoring; } public void setEnableAnsiColoring(final boolean enableAnsiColoring) { this.enableAnsiColoring = enableAnsiColoring; } public boolean isHideAnsiCommands() { return hideAnsiCommands; } public void setHideAnsiCommands(final boolean hideAnsiCommands) { this.hideAnsiCommands = hideAnsiCommands; } ======= >>>>>>> <<<<<<< public boolean isSynchronous() { return synchronous; } public void setSynchronous(final boolean synchronous) { this.synchronous = synchronous; } ======= public String getMaxProcessingTime() { return maxProcessingTime; } public void setMaxProcessingTime(String maxProcessingTime) { if (maxProcessingTime == null || maxProcessingTime.length() == 0) { maxProcessingTime = MAX_PROCESSING_TIME_DEFAULT; } maxProcessingTime = normalize(maxProcessingTime); if (maxProcessingTime.length() == 0 || !NumberUtils.isNumber(maxProcessingTime)) { maxProcessingTime = MAX_PROCESSING_TIME_DEFAULT; } this.maxProcessingTime = maxProcessingTime; maxProcessingTimeAsInt = Integer.valueOf(maxProcessingTime); } protected String normalize(String s) { return s.trim().replaceAll("[\u00A0 ,.]", ""); } >>>>>>> public String getMaxProcessingTime() { return maxProcessingTime; } public void setMaxProcessingTime(String maxProcessingTime) { if (maxProcessingTime == null || maxProcessingTime.length() == 0) { maxProcessingTime = MAX_PROCESSING_TIME_DEFAULT; } maxProcessingTime = normalize(maxProcessingTime); if (maxProcessingTime.length() == 0 || !NumberUtils.isNumber(maxProcessingTime)) { maxProcessingTime = MAX_PROCESSING_TIME_DEFAULT; } this.maxProcessingTime = maxProcessingTime; maxProcessingTimeAsInt = Integer.valueOf(maxProcessingTime); } protected String normalize(String s) { return s.trim().replaceAll("[\u00A0 ,.]", ""); } public boolean isSynchronous() { return synchronous; } public void setSynchronous(final boolean synchronous) { this.synchronous = synchronous; }
<<<<<<< import com.thinkaurelius.titan.graphdb.relations.factory.RelationLoader; import com.thinkaurelius.titan.graphdb.transaction.InternalTitanTransaction; import com.thinkaurelius.titan.graphdb.transaction.StandardPersistTitanTx; import com.thinkaurelius.titan.graphdb.transaction.TransactionConfig; ======= >>>>>>> import com.thinkaurelius.titan.graphdb.transaction.InternalTitanTransaction; import com.thinkaurelius.titan.graphdb.transaction.StandardPersistTitanTx; import com.thinkaurelius.titan.graphdb.transaction.TransactionConfig; <<<<<<< List<Entry> entries = queryForEntries(query,getStoreTransaction(tx)); RelationLoader factory = tx.getRelationFactory(); VertexRelationLoader loader = new StandardVertexRelationLoader(query.getNode(),factory); ======= List<Entry> entries = queryForEntries(query,tx.getTxHandle()); VertexRelationLoader loader = new StandardVertexRelationLoader(query.getNode()); >>>>>>> List<Entry> entries = queryForEntries(query,getStoreTransaction(tx)); VertexRelationLoader loader = new StandardVertexRelationLoader(query.getNode());
<<<<<<< private JCheckBox ansi; private JCheckBox hideAnsiCharacters; ======= >>>>>>> <<<<<<< private JCheckBox synchronous; ======= private JFormattedTextField maxProcessingTime; >>>>>>> private JFormattedTextField maxProcessingTime; private JCheckBox synchronous; <<<<<<< public void setData(Profile data) { enableMaxLength.setSelected(data.isEnableMaxLengthLimit()); ansi.setSelected(data.isEnableAnsiColoring()); enableHighlightingCheckBox.setSelected(data.isEnabledHighlighting()); hideAnsiCharacters.setSelected(data.isHideAnsiCommands()); enableFiltering.setSelected(data.isEnabledInputFiltering()); showStatsInStatusBar.setSelected(data.isShowStatsInStatusBarByDefault()); showStatsInConsole.setSelected(data.isShowStatsInConsoleByDefault()); enableFoldings.setSelected(data.isEnableFoldings()); multilineOutput.setSelected(data.isMultiLineOutput()); maxLengthToMatch.setText(data.getMaxLengthToMatch()); synchronous.setSelected(data.isSynchronous()); } public void getData(Profile data) { data.setEnableMaxLengthLimit(enableMaxLength.isSelected()); data.setEnableAnsiColoring(ansi.isSelected()); data.setEnabledHighlighting(enableHighlightingCheckBox.isSelected()); data.setHideAnsiCommands(hideAnsiCharacters.isSelected()); data.setEnabledInputFiltering(enableFiltering.isSelected()); data.setShowStatsInStatusBarByDefault(showStatsInStatusBar.isSelected()); data.setShowStatsInConsoleByDefault(showStatsInConsole.isSelected()); data.setEnableFoldings(enableFoldings.isSelected()); data.setMultiLineOutput(multilineOutput.isSelected()); data.setMaxLengthToMatch(maxLengthToMatch.getText()); data.setSynchronous(synchronous.isSelected()); } public boolean isModified(Profile data) { if (enableMaxLength.isSelected() != data.isEnableMaxLengthLimit()) return true; if (ansi.isSelected() != data.isEnableAnsiColoring()) return true; if (enableHighlightingCheckBox.isSelected() != data.isEnabledHighlighting()) return true; if (hideAnsiCharacters.isSelected() != data.isHideAnsiCommands()) return true; if (enableFiltering.isSelected() != data.isEnabledInputFiltering()) return true; if (showStatsInStatusBar.isSelected() != data.isShowStatsInStatusBarByDefault()) return true; if (showStatsInConsole.isSelected() != data.isShowStatsInConsoleByDefault()) return true; if (enableFoldings.isSelected() != data.isEnableFoldings()) return true; if (multilineOutput.isSelected() != data.isMultiLineOutput()) return true; if (maxLengthToMatch.getText() != null ? !maxLengthToMatch.getText().equals(data.getMaxLengthToMatch()) : data.getMaxLengthToMatch() != null) return true; if (synchronous.isSelected() != data.isSynchronous()) return true; return false; } ======= >>>>>>>
<<<<<<< import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.components.ApplicationComponent; import com.intellij.openapi.components.PersistentStateComponent; import com.intellij.openapi.components.State; import com.intellij.openapi.components.Storage; import com.intellij.openapi.options.Configurable; import com.intellij.openapi.options.ConfigurationException; import com.intellij.openapi.project.Project; ======= import java.io.File; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.swing.*; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.components.ExportableApplicationComponent; import krasa.grepconsole.Cache; import krasa.grepconsole.Mode; >>>>>>> import java.io.File; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.swing.*; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.components.ExportableApplicationComponent; import krasa.grepconsole.Cache; import krasa.grepconsole.Mode; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.components.ApplicationComponent; import com.intellij.openapi.components.PersistentStateComponent; import com.intellij.openapi.components.State; import com.intellij.openapi.components.Storage; import com.intellij.openapi.options.Configurable; import com.intellij.openapi.options.ConfigurationException; import com.intellij.openapi.project.Project;
<<<<<<< import java.util.UUID; ======= import java.util.Date; >>>>>>> import java.util.Date; import java.util.UUID; <<<<<<< assertTrue(index.supports(of(UUID.class), Cmp.EQUAL)); assertTrue(index.supports(of(UUID.class), Cmp.NOT_EQUAL)); ======= assertTrue(index.supports(of(Date.class), Cmp.EQUAL)); assertTrue(index.supports(of(Date.class), Cmp.LESS_THAN_EQUAL)); assertTrue(index.supports(of(Date.class), Cmp.LESS_THAN)); assertTrue(index.supports(of(Date.class), Cmp.GREATER_THAN)); assertTrue(index.supports(of(Date.class), Cmp.GREATER_THAN_EQUAL)); assertTrue(index.supports(of(Date.class), Cmp.NOT_EQUAL)); assertTrue(index.supports(of(Boolean.class), Cmp.EQUAL)); assertTrue(index.supports(of(Boolean.class), Cmp.NOT_EQUAL)); >>>>>>> assertTrue(index.supports(of(Date.class), Cmp.EQUAL)); assertTrue(index.supports(of(Date.class), Cmp.LESS_THAN_EQUAL)); assertTrue(index.supports(of(Date.class), Cmp.LESS_THAN)); assertTrue(index.supports(of(Date.class), Cmp.GREATER_THAN)); assertTrue(index.supports(of(Date.class), Cmp.GREATER_THAN_EQUAL)); assertTrue(index.supports(of(Date.class), Cmp.NOT_EQUAL)); assertTrue(index.supports(of(Boolean.class), Cmp.EQUAL)); assertTrue(index.supports(of(Boolean.class), Cmp.NOT_EQUAL)); assertTrue(index.supports(of(UUID.class), Cmp.EQUAL)); assertTrue(index.supports(of(UUID.class), Cmp.NOT_EQUAL));
<<<<<<< @Override public Integer getTtl() { return null; } ======= @Override public Cardinality getCardinality() { return cardinality; } @Override public Iterable<IndexType> getKeyIndexes() { if (index==Index.NONE) return Collections.EMPTY_LIST; return ImmutableList.of((IndexType)indexDef); } private final InternalIndexType indexDef = new InternalIndexType() { private final IndexField[] fields = {IndexField.of(SystemKey.this)}; // private final Set<TitanKey> fieldSet = ImmutableSet.of((TitanKey)SystemKey.this); @Override public long getID() { return SystemKey.this.getID(); } @Override public IndexField[] getFieldKeys() { return fields; } @Override public IndexField getField(TitanKey key) { if (key.equals(SystemKey.this)) return fields[0]; else return null; } @Override public boolean indexesKey(TitanKey key) { return getField(key)!=null; } @Override public Cardinality getCardinality() { switch(index) { case UNIQUE: return Cardinality.SINGLE; case STANDARD: return Cardinality.SET; default: throw new AssertionError(); } } @Override public ConsistencyModifier getConsistencyModifier() { return ConsistencyModifier.LOCK; } @Override public ElementCategory getElement() { return ElementCategory.VERTEX; } @Override public boolean isInternalIndex() { return true; } @Override public boolean isExternalIndex() { return false; } @Override public String getBackingIndexName() { return Token.INTERNAL_INDEX_NAME; } @Override public String getName() { return "SystemIndex#"+getID(); } @Override public SchemaStatus getStatus() { return SchemaStatus.ENABLED; } @Override public void resetCache() {} //Use default hashcode and equals }; >>>>>>> @Override public Integer getTtl() { return null; } public Cardinality getCardinality() { return cardinality; } @Override public Iterable<IndexType> getKeyIndexes() { if (index==Index.NONE) return Collections.EMPTY_LIST; return ImmutableList.of((IndexType)indexDef); } private final InternalIndexType indexDef = new InternalIndexType() { private final IndexField[] fields = {IndexField.of(SystemKey.this)}; // private final Set<TitanKey> fieldSet = ImmutableSet.of((TitanKey)SystemKey.this); @Override public long getID() { return SystemKey.this.getID(); } @Override public IndexField[] getFieldKeys() { return fields; } @Override public IndexField getField(TitanKey key) { if (key.equals(SystemKey.this)) return fields[0]; else return null; } @Override public boolean indexesKey(TitanKey key) { return getField(key)!=null; } @Override public Cardinality getCardinality() { switch(index) { case UNIQUE: return Cardinality.SINGLE; case STANDARD: return Cardinality.SET; default: throw new AssertionError(); } } @Override public ConsistencyModifier getConsistencyModifier() { return ConsistencyModifier.LOCK; } @Override public ElementCategory getElement() { return ElementCategory.VERTEX; } @Override public boolean isInternalIndex() { return true; } @Override public boolean isExternalIndex() { return false; } @Override public String getBackingIndexName() { return Token.INTERNAL_INDEX_NAME; } @Override public String getName() { return "SystemIndex#"+getID(); } @Override public SchemaStatus getStatus() { return SchemaStatus.ENABLED; } @Override public void resetCache() {} //Use default hashcode and equals };
<<<<<<< import com.thinkaurelius.titan.diskstorage.util.StaticArrayEntry; ======= import com.thinkaurelius.titan.diskstorage.log.Message; import com.thinkaurelius.titan.diskstorage.log.ReadMarker; import com.thinkaurelius.titan.diskstorage.log.kcvs.KCVSLog; >>>>>>> import com.thinkaurelius.titan.diskstorage.util.StaticArrayEntry; import com.thinkaurelius.titan.diskstorage.log.Message; import com.thinkaurelius.titan.diskstorage.log.ReadMarker; import com.thinkaurelius.titan.diskstorage.log.kcvs.KCVSLog; <<<<<<< /** * The TTL of a relation (edge or property) is the minimum of: * 1) The TTL configured of the relation type (if exists) * 2) The TTL configured for the label any of the relation end point vertices (if exists) * * @param rel relation to determine the TTL for * @return */ public static int getTTL(InternalRelation rel) { InternalRelationType baseType = (InternalRelationType) rel.getType(); assert baseType.getBaseType()==null; int ttl = 0; Integer ettl = baseType.getTTL(); if (ettl>0) ttl = ettl; for (int i=0;i<rel.getArity();i++) { InternalVertex v = rel.getVertex(i); Integer vttl = ((InternalVertexLabel)v.getVertexLabel()).getTTL(); if (vttl>0 && (vttl<ttl || ttl<=0)) ttl = vttl; } return ttl; } public boolean prepareCommit(final Collection<InternalRelation> addedRelations, ======= private static class ModificationSummary { final boolean hasModifications; final boolean has2iModifications; private ModificationSummary(boolean hasModifications, boolean has2iModifications) { this.hasModifications = hasModifications; this.has2iModifications = has2iModifications; } } public ModificationSummary prepareCommit(final Collection<InternalRelation> addedRelations, >>>>>>> /** * The TTL of a relation (edge or property) is the minimum of: * 1) The TTL configured of the relation type (if exists) * 2) The TTL configured for the label any of the relation end point vertices (if exists) * * @param rel relation to determine the TTL for * @return */ public static int getTTL(InternalRelation rel) { InternalRelationType baseType = (InternalRelationType) rel.getType(); assert baseType.getBaseType()==null; int ttl = 0; Integer ettl = baseType.getTTL(); if (ettl>0) ttl = ettl; for (int i=0;i<rel.getArity();i++) { InternalVertex v = rel.getVertex(i); Integer vttl = ((InternalVertexLabel)v.getVertexLabel()).getTTL(); if (vttl>0 && (vttl<ttl || ttl<=0)) ttl = vttl; } return ttl; } private static class ModificationSummary { final boolean hasModifications; final boolean has2iModifications; private ModificationSummary(boolean hasModifications, boolean has2iModifications) { this.hasModifications = hasModifications; this.has2iModifications = has2iModifications; } } public ModificationSummary prepareCommit(final Collection<InternalRelation> addedRelations,
<<<<<<< import java.util.*; ======= import java.util.ArrayList; import java.util.List; import java.util.Map; >>>>>>> import java.util.*; import java.util.ArrayList; import java.util.List; import java.util.Map; <<<<<<< public XContentBuilder getContent(final List<IndexEntry> additions) throws StorageException { ======= public XContentBuilder getContent(List<IndexEntry> additions) throws BackendException { >>>>>>> public XContentBuilder getContent(final List<IndexEntry> additions) throws BackendException {
<<<<<<< import com.thinkaurelius.titan.diskstorage.configuration.ModifiableConfiguration; import com.thinkaurelius.titan.diskstorage.inmemory.InMemoryStorageAdapter; ======= >>>>>>> import com.thinkaurelius.titan.diskstorage.configuration.ModifiableConfiguration; import com.thinkaurelius.titan.diskstorage.inmemory.InMemoryStorageAdapter; <<<<<<< ModifiableConfiguration config = GraphDatabaseConfiguration.buildConfiguration(); config.set(GraphDatabaseConfiguration.STORAGE_BACKEND, InMemoryStorageAdapter.class.getCanonicalName()); config.set(GraphDatabaseConfiguration.IDS_FLUSH, false); ======= BaseConfiguration config = new BaseConfiguration(); config.subset(GraphDatabaseConfiguration.STORAGE_NAMESPACE).addProperty(GraphDatabaseConfiguration.STORAGE_BACKEND_KEY, InMemoryStoreManager.class.getCanonicalName()); config.subset(GraphDatabaseConfiguration.IDS_NAMESPACE).addProperty(GraphDatabaseConfiguration.IDS_FLUSH_KEY, false); config.subset(GraphDatabaseConfiguration.STORAGE_NAMESPACE).addProperty(GraphDatabaseConfiguration.IDAUTHORITY_WAIT_MS_KEY, 1); >>>>>>> ModifiableConfiguration config = GraphDatabaseConfiguration.buildConfiguration(); config.set(GraphDatabaseConfiguration.STORAGE_BACKEND, InMemoryStoreManager.class.getCanonicalName()); config.set(GraphDatabaseConfiguration.IDS_FLUSH, false); config.set(GraphDatabaseConfiguration.IDAUTHORITY_WAIT_MS,1);
<<<<<<< // KeyColumnValueStoreManager storeManager=null; final KeyColumnValueStoreManager storeManager = Backend.getStorageManager(localBasicConfiguration); ======= final KeyColumnValueStoreManager storeManager = Backend.getStorageManager(localbc); >>>>>>> final KeyColumnValueStoreManager storeManager = Backend.getStorageManager(localBasicConfiguration);
<<<<<<< * Set the image source from a bitmap, resource, asset, file or other URI, starting with a given orientation * setting, scale and center. This is the best method to use when you want scale and center to be restored * after screen orientation change; it avoids any redundant loading of tiles in the wrong orientation. * @param imageSource Image source. ======= * Display an image from a file in internal or external storage, starting with a given orientation setting, scale * and center. This is the best method to use when you want scale and center to be restored after screen orientation * change; it avoids any redundant loading of tiles in the wrong orientation. * @param fileUri URI of the file to display e.g. '/sdcard/DCIM1000.PNG' or 'file:///scard/DCIM1000.PNG' (these are equivalent). * @param state State to be restored. Nullable. * @param displayRegion Set the region to display instead of the whole image. Nullable. * @deprecated Method name is outdated, other URIs are now accepted so use {@link #setImageUri(android.net.Uri, ImageViewState)} or {@link #setImageUri(String, ImageViewState)}. */ @Deprecated public final void setImageFile(String fileUri, ImageViewState state, Rect displayRegion) { setImageUri(fileUri, state, displayRegion); } /** * Display an image from resources. * @param resId Resource ID. */ public final void setImageResource(int resId) { setImageResource(resId, null); } /** * Display an image from resources, starting with a given orientation setting, scale and center. * This is the best method to use when you want scale and center to be restored after screen orientation * change; it avoids any redundant loading of tiles in the wrong orientation. * @param resId Resource ID. >>>>>>> * Set the image source from a bitmap, resource, asset, file or other URI, starting with a given orientation * setting, scale and center. This is the best method to use when you want scale and center to be restored * after screen orientation change; it avoids any redundant loading of tiles in the wrong orientation. * @param imageSource Image source. <<<<<<< * Set the image source from a bitmap, resource, asset, file or other URI, providing a preview image to be * displayed until the full size image is loaded. * * You must declare the dimensions of the full size image by calling {@link ImageSource#withDimensions(int, int)} * on the imageSource object. The preview source will be ignored if you don't provide dimensions, * and if you provide a bitmap for the full size image. * @param imageSource Image source. Dimensions must be declared. * @param previewSource Optional source for a preview image to be displayed and allow interaction while the full size image loads. ======= * Display an image from resources, starting with a given orientation setting, scale and center. * This is the best method to use when you want scale and center to be restored after screen orientation * change; it avoids any redundant loading of tiles in the wrong orientation. * @param resId Resource ID. * @param state State to be restored. Nullable. * @param displayRegion Set the region to display instead of the whole image. Nullable. */ public final void setImageResource(int resId, ImageViewState state, Rect displayRegion) { setImageUri(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getContext().getPackageName() + "/" + resId, state, displayRegion); } /** * Display an image from a file in assets. * @param assetName asset name. >>>>>>> * Set the image source from a bitmap, resource, asset, file or other URI, providing a preview image to be * displayed until the full size image is loaded. * * You must declare the dimensions of the full size image by calling {@link ImageSource#withDimensions(int, int)} * on the imageSource object. The preview source will be ignored if you don't provide dimensions, * and if you provide a bitmap for the full size image. * @param imageSource Image source. Dimensions must be declared. * @param previewSource Optional source for a preview image to be displayed and allow interaction while the full size image loads. <<<<<<< readySent = false; imageLoadedSent = false; bitmap = null; preview = false; ======= displayRegion = null; dimensionsReadySent = false; baseLayerReadySent = false; >>>>>>> sRegion = null; pRegion = null; readySent = false; imageLoadedSent = false; bitmap = null; preview = false; <<<<<<< ======= * Called by worker task when decoder is ready and image size and EXIF orientation is known. */ private void onImageInited(ImageRegionDecoder decoder, int sWidth, int sHeight, int sOrientation) { this.decoder = decoder; if (displayRegion == null) { this.sWidth = sWidth; this.sHeight = sHeight; } else { this.sWidth = displayRegion.width(); this.sHeight = displayRegion.height(); } this.sOrientation = sOrientation; requestLayout(); invalidate(); // Inform subclasses that image dimensions are known and the scale and translate are set. if (!dimensionsReadySent) { preDraw(); dimensionsReadySent = true; onImageReady(); if (onImageEventListener != null) { onImageEventListener.onImageReady(); } } } /** * Called by worker task when a tile has loaded. Redraws the view. */ private synchronized void onTileLoaded() { invalidate(); // If all base layer tiles are ready, inform subclasses the image is ready to display on next draw. if (!baseLayerReadySent) { boolean baseLayerReady = true; for (Map.Entry<Integer, List<Tile>> tileMapEntry : tileMap.entrySet()) { if (tileMapEntry.getKey() == fullImageSampleSize) { for (Tile tile : tileMapEntry.getValue()) { if (tile.loading || tile.bitmap == null) { baseLayerReady = false; } } } } if (baseLayerReady) { baseLayerReadySent = true; onBaseLayerReady(); if (onImageEventListener != null) { onImageEventListener.onBaseLayerReady(); } } } } /** >>>>>>>
<<<<<<< newMapping.setEntity(new StringEntity(objectMapper.writeValueAsString(readMapping("/strict_mapping.json")), Charset.forName("UTF-8"))); ======= newMapping.setEntity(new StringEntity(objectMapper.writeValueAsString(readMapping(version, "/strict_mapping.json")), StandardCharsets.UTF_8)); >>>>>>> newMapping.setEntity(new StringEntity(objectMapper.writeValueAsString(readMapping("/strict_mapping.json")), StandardCharsets.UTF_8)); <<<<<<< final Map<String, Object> content = ImmutableMap.of("template", "janusgraph_test_mapping*", "mappings", readMapping("/strict_mapping.json").getMappings()); newTemplate.setEntity(new StringEntity(objectMapper.writeValueAsString(content), Charset.forName("UTF-8"))); ======= final Map<String, Object> content = ImmutableMap.of("template", "janusgraph_test_mapping*", "mappings", readMapping(version, "/strict_mapping.json").getMappings()); newTemplate.setEntity(new StringEntity(objectMapper.writeValueAsString(content), StandardCharsets.UTF_8)); >>>>>>> final Map<String, Object> content = ImmutableMap.of("template", "janusgraph_test_mapping*", "mappings", readMapping("/strict_mapping.json").getMappings()); newTemplate.setEntity(new StringEntity(objectMapper.writeValueAsString(content), StandardCharsets.UTF_8)); <<<<<<< newMapping.setEntity(new StringEntity(objectMapper.writeValueAsString(readMapping("/dynamic_mapping.json")), Charset.forName("UTF-8"))); ======= newMapping.setEntity(new StringEntity(objectMapper.writeValueAsString(readMapping(version, "/dynamic_mapping.json")), StandardCharsets.UTF_8)); >>>>>>> newMapping.setEntity(new StringEntity(objectMapper.writeValueAsString(readMapping("/dynamic_mapping.json")), StandardCharsets.UTF_8));
<<<<<<< import org.archicontribs.modelrepository.grafico.IGraficoConstants; import org.archicontribs.modelrepository.grafico.IRepositoryListener; import org.archicontribs.modelrepository.grafico.RepositoryListenerManager; ======= >>>>>>> import org.archicontribs.modelrepository.grafico.IRepositoryListener; import org.archicontribs.modelrepository.grafico.RepositoryListenerManager; <<<<<<< import org.eclipse.jgit.transport.FetchResult; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; ======= >>>>>>> import org.eclipse.jgit.transport.FetchResult; <<<<<<< // Update ProxyAuthenticator ProxyAuthenticator.update(repo.getOnlineRepositoryURL()); // Fetch FetchResult fetchResult = repo.fetchFromRemote(npw, null, false); // We got here, so the tree can be refreshed later ======= // Update Proxy ProxyAuthenticator.update(); repo.fetchFromRemote(npw, null, false); >>>>>>> // Update ProxyAuthenticator ProxyAuthenticator.update(); // Fetch FetchResult fetchResult = repo.fetchFromRemote(npw, null, false); // We got here, so the tree can be refreshed later
<<<<<<< ======= import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Shader; >>>>>>> import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Shader; <<<<<<< } /* private void getGPSLocation() { Location location = null; LocationManager mlocManager = (LocationManager) mContext.getSystemService( Context.LOCATION_SERVICE ); LocationListener mlocListener = new CityCardLocationListener(); Location loc = mlocManager.getLastKnownLocation( LocationManager.NETWORK_PROVIDER ); Log.v( TAG, "#printGPSCoordinates lat: " + loc.getLatitude() + " lang: " + loc.getLongitude() ); if ( mlocManager.isProviderEnabled( LocationManager.GPS_PROVIDER) ) { mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener); } else Log.w( TAG, "GPS is TURNED OFF " ); }*/ ======= } /** * Checks if the service with the given name is currently running on the device. * **/ public boolean isServiceRunning(String serviceName) { ActivityManager manager = (ActivityManager) mContext.getSystemService(mContext.ACTIVITY_SERVICE); for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { if (service.service.getClassName().equals(serviceName)) { // Log.i(TAG, "#isServiceAlreadyRunning " + serviceName + " is already running."); return true; } } return false; } /*** * Get the device unique id called IMEI. * Sometimes, this returns 00000000000000000 for the rooted devices. * ***/ public String getDeviceImei() { TelephonyManager tm = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE); return tm.getDeviceId(); } /*** * Share an application over the social network like Facebook, Twitter etc. * @param sharingMsg Message to be pre-populated when the 3rd party app dialog opens up. * @param emailSubject Message that shows up as a subject while sharing through email. * @param title Title of the sharing options prompt. For e.g. "Share via" or "Share using" * ***/ public void share(String sharingMsg, String emailSubject, String title) { Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND); sharingIntent.setType("text/plain"); sharingIntent.putExtra(Intent.EXTRA_TEXT, sharingMsg); sharingIntent.putExtra(Intent.EXTRA_SUBJECT, emailSubject); mContext.startActivity( Intent.createChooser( sharingIntent, title ) ); } /*** * Check the type of data connection that is currently available on * the device. * @return <code>ConnectivityManager.TYPE_*</code> as a type of * internet connection on the device. Returns -1 in case of error or none of * <code>ConnectivityManager.TYPE_*</code> is found. * ***/ public int getDataConnectionType() { ConnectivityManager connMgr = (ConnectivityManager) mContext.getSystemService( Context.CONNECTIVITY_SERVICE ); if( connMgr != null && connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) != null ) { if ( connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnected() ) return ConnectivityManager.TYPE_MOBILE; if ( connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected() ) return ConnectivityManager.TYPE_WIFI; else return -1; }else return -1; } /*** * Checks if the input parameter is a valid email. * ***/ public boolean isValidEmail(String email) { final String emailPattern = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; Matcher matcher; Pattern pattern = Pattern.compile(emailPattern); matcher = pattern.matcher(email); if( matcher != null ) return matcher.matches(); else return false; } /*** * Capitalize a each word in the string. * ***/ public static String capitalizeString(String string) { char[] chars = string.toLowerCase().toCharArray(); boolean found = false; for (int i = 0; i < chars.length; i++) { if (!found && Character.isLetter(chars[i])) { chars[i] = Character.toUpperCase(chars[i]); found = true; } else if (Character.isWhitespace(chars[i]) || chars[i]=='.' || chars[i]=='\'') { // You can add other chars here found = false; } } return String.valueOf(chars); } /*** * * ***/ public void tileBackground(int layoutIdOfRootView, int resIdOfTile) { try { //Tiling the background. Bitmap bmp = BitmapFactory.decodeResource(mContext.getResources(), resIdOfTile); // deprecated constructor call // BitmapDrawable bitmapDrawable = new BitmapDrawable(bmp); BitmapDrawable bitmapDrawable = new BitmapDrawable( mContext.getResources(), bmp); bitmapDrawable.setTileModeXY(Shader.TileMode.REPEAT, Shader.TileMode.REPEAT); View view = ((Activity) mContext).findViewById( layoutIdOfRootView ); if( view != null ) setBackground( view, bitmapDrawable); } catch (Exception e) { Log.e(TAG, "#tileBackground Exception while tiling the background of the view"); } } /*** * Sets the passed-in drawable parameter as a background to the * passed in target parameter in an SDK independent way. This * is the recommended way of setting background rather * than using native background setters provided by {@link View} * class * * @param target View to set background to. * @param drawable background image * ***/ @SuppressLint("NewApi") public void setBackground(View target, Drawable drawable) { if( Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { target.setBackgroundDrawable(drawable); } else { target.setBackground(drawable); } } public void tileBackground(int layoutId, View viewToTileBg, int resIdOfTile) { try { //Tiling the background. Bitmap bmp = BitmapFactory.decodeResource(mContext.getResources(), resIdOfTile); // deprecated constructor // BitmapDrawable bitmapDrawable = new BitmapDrawable(bmp); BitmapDrawable bitmapDrawable = new BitmapDrawable( mContext.getResources(), bmp); bitmapDrawable.setTileModeXY(Shader.TileMode.REPEAT, Shader.TileMode.REPEAT); View view = viewToTileBg.findViewById(layoutId); if( view != null ) setBackground(view, bitmapDrawable); } catch (Exception e) { Log.e(TAG, "#tileBackground Exception while tiling the background of the view"); } } public boolean isDatabasePresent(String packageName, String dbName) { SQLiteDatabase checkDB = null; try { checkDB = SQLiteDatabase.openDatabase( "/data/data/" + packageName + "/databases/" + dbName, null, SQLiteDatabase.OPEN_READONLY ); checkDB.close(); } catch (SQLiteException e) { // database doesn't exist yet. e.printStackTrace(); Log.e(TAG, "The database does not exist."); } catch ( Exception e) { e.printStackTrace(); Log.e(TAG, "Exception "); } boolean isDbPresent = checkDB != null ? true : false; /* if(isDbPresent) Log.i(TAG, dbName + " database exists"); else Log.i(TAG, "Database DOES NOT exists");*/ return isDbPresent; } >>>>>>> } /** * Checks if the service with the given name is currently running on the device. * **/ public boolean isServiceRunning(String serviceName) { ActivityManager manager = (ActivityManager) mContext.getSystemService(mContext.ACTIVITY_SERVICE); for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { if (service.service.getClassName().equals(serviceName)) { // Log.i(TAG, "#isServiceAlreadyRunning " + serviceName + " is already running."); return true; } } return false; } /*** * Get the device unique id called IMEI. * Sometimes, this returns 00000000000000000 for the rooted devices. * ***/ public String getDeviceImei() { TelephonyManager tm = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE); return tm.getDeviceId(); } /*** * Share an application over the social network like Facebook, Twitter etc. * @param sharingMsg Message to be pre-populated when the 3rd party app dialog opens up. * @param emailSubject Message that shows up as a subject while sharing through email. * @param title Title of the sharing options prompt. For e.g. "Share via" or "Share using" * ***/ public void share(String sharingMsg, String emailSubject, String title) { Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND); sharingIntent.setType("text/plain"); sharingIntent.putExtra(Intent.EXTRA_TEXT, sharingMsg); sharingIntent.putExtra(Intent.EXTRA_SUBJECT, emailSubject); mContext.startActivity( Intent.createChooser( sharingIntent, title ) ); } /*** * Check the type of data connection that is currently available on * the device. * @return <code>ConnectivityManager.TYPE_*</code> as a type of * internet connection on the device. Returns -1 in case of error or none of * <code>ConnectivityManager.TYPE_*</code> is found. * ***/ public int getDataConnectionType() { ConnectivityManager connMgr = (ConnectivityManager) mContext.getSystemService( Context.CONNECTIVITY_SERVICE ); if( connMgr != null && connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) != null ) { if ( connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnected() ) return ConnectivityManager.TYPE_MOBILE; if ( connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected() ) return ConnectivityManager.TYPE_WIFI; else return -1; }else return -1; } /*** * Checks if the input parameter is a valid email. * ***/ public boolean isValidEmail(String email) { final String emailPattern = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; Matcher matcher; Pattern pattern = Pattern.compile(emailPattern); matcher = pattern.matcher(email); if( matcher != null ) return matcher.matches(); else return false; } /*** * Capitalize a each word in the string. * ***/ public static String capitalizeString(String string) { char[] chars = string.toLowerCase().toCharArray(); boolean found = false; for (int i = 0; i < chars.length; i++) { if (!found && Character.isLetter(chars[i])) { chars[i] = Character.toUpperCase(chars[i]); found = true; } else if (Character.isWhitespace(chars[i]) || chars[i]=='.' || chars[i]=='\'') { // You can add other chars here found = false; } } return String.valueOf(chars); } /*** * * ***/ public void tileBackground(int layoutIdOfRootView, int resIdOfTile) { try { //Tiling the background. Bitmap bmp = BitmapFactory.decodeResource(mContext.getResources(), resIdOfTile); // deprecated constructor call // BitmapDrawable bitmapDrawable = new BitmapDrawable(bmp); BitmapDrawable bitmapDrawable = new BitmapDrawable( mContext.getResources(), bmp); bitmapDrawable.setTileModeXY(Shader.TileMode.REPEAT, Shader.TileMode.REPEAT); View view = ((Activity) mContext).findViewById( layoutIdOfRootView ); if( view != null ) setBackground( view, bitmapDrawable); } catch (Exception e) { Log.e(TAG, "#tileBackground Exception while tiling the background of the view"); } } /*** * Sets the passed-in drawable parameter as a background to the * passed in target parameter in an SDK independent way. This * is the recommended way of setting background rather * than using native background setters provided by {@link View} * class * * @param target View to set background to. * @param drawable background image * ***/ @SuppressLint("NewApi") public void setBackground(View target, Drawable drawable) { if( Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { target.setBackgroundDrawable(drawable); } else { target.setBackground(drawable); } } public void tileBackground(int layoutId, View viewToTileBg, int resIdOfTile) { try { //Tiling the background. Bitmap bmp = BitmapFactory.decodeResource(mContext.getResources(), resIdOfTile); // deprecated constructor // BitmapDrawable bitmapDrawable = new BitmapDrawable(bmp); BitmapDrawable bitmapDrawable = new BitmapDrawable( mContext.getResources(), bmp); bitmapDrawable.setTileModeXY(Shader.TileMode.REPEAT, Shader.TileMode.REPEAT); View view = viewToTileBg.findViewById(layoutId); if( view != null ) setBackground(view, bitmapDrawable); } catch (Exception e) { Log.e(TAG, "#tileBackground Exception while tiling the background of the view"); } } public boolean isDatabasePresent(String packageName, String dbName) { SQLiteDatabase checkDB = null; try { checkDB = SQLiteDatabase.openDatabase( "/data/data/" + packageName + "/databases/" + dbName, null, SQLiteDatabase.OPEN_READONLY ); checkDB.close(); } catch (SQLiteException e) { // database doesn't exist yet. e.printStackTrace(); Log.e(TAG, "The database does not exist."); } catch ( Exception e) { e.printStackTrace(); Log.e(TAG, "Exception "); } boolean isDbPresent = checkDB != null ? true : false; return isDbPresent; }
<<<<<<< TABLE_COLUMN_HIGHTLIGHTING = true; ======= QUOTING_ENFORCED = false; >>>>>>> QUOTING_ENFORCED = false; TABLE_COLUMN_HIGHTLIGHTING = true; <<<<<<< public boolean isTableColumnHighlightingEnabled() { return getState().TABLE_COLUMN_HIGHTLIGHTING; } public void setTableColumnHighlightingEnabled(boolean columnHighlightingEnabled) { getState().TABLE_COLUMN_HIGHTLIGHTING = columnHighlightingEnabled; } ======= public boolean isQuotingEnforced() { return getState().QUOTING_ENFORCED; } public void setQuotingEnforced(boolean quotingEnforced) { getState().QUOTING_ENFORCED = quotingEnforced; } >>>>>>> public boolean isQuotingEnforced() { return getState().QUOTING_ENFORCED; } public void setQuotingEnforced(boolean quotingEnforced) { getState().QUOTING_ENFORCED = quotingEnforced; } public boolean isTableColumnHighlightingEnabled() { return getState().TABLE_COLUMN_HIGHTLIGHTING; } public void setTableColumnHighlightingEnabled(boolean columnHighlightingEnabled) { getState().TABLE_COLUMN_HIGHTLIGHTING = columnHighlightingEnabled; }
<<<<<<< private JCheckBox cbTableColumnHighlighting; ======= private JCheckBox cbQuotingEnforced; >>>>>>> private JCheckBox cbQuotingEnforced; private JCheckBox cbTableColumnHighlighting; <<<<<<< !Objects.equals(cbEditorUsage.getSelectedIndex(), csvEditorSettingsExternalizable.getEditorPrio().ordinal()) || isModified(cbTableColumnHighlighting, csvEditorSettingsExternalizable.isTableColumnHighlightingEnabled()); ======= !Objects.equals(cbEditorUsage.getSelectedIndex(), csvEditorSettingsExternalizable.getEditorPrio().ordinal()) || isModified(cbQuotingEnforced, csvEditorSettingsExternalizable.isQuotingEnforced()); >>>>>>> !Objects.equals(cbEditorUsage.getSelectedIndex(), csvEditorSettingsExternalizable.getEditorPrio().ordinal()) || isModified(cbQuotingEnforced, csvEditorSettingsExternalizable.isQuotingEnforced()) || !Objects.equals(cbEditorUsage.getSelectedIndex(), csvEditorSettingsExternalizable.getEditorPrio().ordinal()) || isModified(cbTableColumnHighlighting, csvEditorSettingsExternalizable.isTableColumnHighlightingEnabled()); <<<<<<< cbTableColumnHighlighting.setSelected(csvEditorSettingsExternalizable.isTableColumnHighlightingEnabled()); ======= cbQuotingEnforced.setSelected(csvEditorSettingsExternalizable.isQuotingEnforced()); >>>>>>> cbQuotingEnforced.setSelected(csvEditorSettingsExternalizable.isQuotingEnforced()); cbTableColumnHighlighting.setSelected(csvEditorSettingsExternalizable.isTableColumnHighlightingEnabled()); <<<<<<< csvEditorSettingsExternalizable.setTableColumnHighlightingEnabled(cbTableColumnHighlighting.isSelected()); ======= csvEditorSettingsExternalizable.setQuotingEnforced(cbQuotingEnforced.isSelected()); >>>>>>> csvEditorSettingsExternalizable.setQuotingEnforced(cbQuotingEnforced.isSelected()); csvEditorSettingsExternalizable.setTableColumnHighlightingEnabled(cbTableColumnHighlighting.isSelected());
<<<<<<< csvEditorSettingsExternalizable.setTableColumnHighlightingEnabled(false); ======= csvEditorSettingsExternalizable.setQuotingEnforced(true); >>>>>>> csvEditorSettingsExternalizable.setQuotingEnforced(true); csvEditorSettingsExternalizable.setTableColumnHighlightingEnabled(false); <<<<<<< assertEquals(false, csvEditorSettingsExternalizable.isTableColumnHighlightingEnabled()); ======= assertEquals(true, csvEditorSettingsExternalizable.isQuotingEnforced()); >>>>>>> assertEquals(true, csvEditorSettingsExternalizable.isQuotingEnforced()); assertEquals(false, csvEditorSettingsExternalizable.isTableColumnHighlightingEnabled()); <<<<<<< csvEditorSettingsExternalizable.setTableColumnHighlightingEnabled(false); ======= csvEditorSettingsExternalizable.setQuotingEnforced(true); >>>>>>> csvEditorSettingsExternalizable.setQuotingEnforced(true); csvEditorSettingsExternalizable.setTableColumnHighlightingEnabled(false); <<<<<<< assertEquals(freshOptionSet.TABLE_COLUMN_HIGHTLIGHTING, csvEditorSettingsExternalizable.isTableColumnHighlightingEnabled()); ======= assertEquals(freshOptionSet.QUOTING_ENFORCED, csvEditorSettingsExternalizable.isQuotingEnforced()); >>>>>>> assertEquals(freshOptionSet.QUOTING_ENFORCED, csvEditorSettingsExternalizable.isQuotingEnforced()); assertEquals(freshOptionSet.TABLE_COLUMN_HIGHTLIGHTING, csvEditorSettingsExternalizable.isTableColumnHighlightingEnabled());