text:
// ******* Flyout MANAGER ******** //
$axure.internal(function($ax) {
    var _flyoutManager = $ax.flyoutManager = {};

    var getFlyoutLabel = function(panelId) {
        return panelId + '_flyout';
    };

    var _unregisterPanel = function(panelId, keepShown) {
        $ax.geometry.unregister(getFlyoutLabel(panelId));
        if(panelToSrc[panelId]) {
            $ax.style.RemoveRolloverOverride(panelToSrc[panelId]);
            delete panelToSrc[panelId];
        }
        if(!keepShown) {
            $ax.action.addAnimation(panelId, $ax.action.queueTypes.fade, function() {
                $ax('#' + panelId).hide();
            });
        }
    };
    _flyoutManager.unregisterPanel = _unregisterPanel;

    var genPoint = $ax.geometry.genPoint;

    var _updateFlyout = function(panelId) {
        var label = getFlyoutLabel(panelId);
        if(!$ax.geometry.polygonRegistered(label)) return;
        var info = $ax.geometry.getPolygonInfo(label);
        var rects = info && info.rects;

        var targetWidget = $ax.getWidgetInfo(panelId);
        rects.target = $ax.geometry.genRect(targetWidget);

        // Src will stay the same, just updating
        $ax.flyoutManager.registerFlyout(rects, panelId, panelToSrc[panelId]);

        if(!$ax.geometry.checkInsideRegion(label)) _unregisterPanel(panelId);
    };
    _flyoutManager.updateFlyout = _updateFlyout;

    var panelToSrc = {};
    var _registerFlyout = function(rects, panelId, srcId) {
        var label = _getFlyoutLabel(panelId);
        var callback = function(info) {
            // If leaving object or already outside it, then unregister, otherwise just return
            if(!info.exiting && !info.outside) return;
            _unregisterPanel(panelId);
        };
        var points = [];

        var lastSrcId = panelToSrc[panelId];
        if(lastSrcId != srcId) {
            if(lastSrcId) $ax.style.RemoveRolloverOverride(lastSrcId);
            if(srcId) {
                $ax.style.AddRolloverOverride(srcId);
                panelToSrc[panelId] = srcId;
            } else delete panelToSrc[panelId];
        }

        // rects should be one or two rectangles
        if(!rects.src) {
            var rect = rects.target;
            points.push(genPoint(rect.Left(), rect.Top()));
            points.push(genPoint(rect.Right(), rect.Top()));
            points.push(genPoint(rect.Right(), rect.Bottom()));
            points.push(genPoint(rect.Left(), rect.Bottom()));
        } else {
            var r0 = rects.src;
            var r1 = rects.target;

            // Right left of right, left right of left, top below top, bottom above bottom
            var rlr = r0.Right() <= r1.Right();
            var lrl = r0.Left() >= r1.Left();
            var tbt = r0.Top() >= r1.Top();
            var bab = r0.Bottom() <= r1.Bottom();

            var info = { rlr: rlr, lrl: lrl, tbt: tbt, bab: bab };

            if((rlr && lrl) || (tbt && bab)) {
                points = getSmallPolygon(r0, r1, info);
            } else {
                points = getLargePolygon(r0, r1, info);
            }
        }

        $ax.geometry.registerPolygon(label, points, callback, { rects: rects });
    };
    _flyoutManager.registerFlyout = _registerFlyout;

    var _getFlyoutLabel = function(panelId) {
        return panelId + '_flyout';
    };

    var _reregisterAllFlyouts = function() {
        for(var panelId in panelToSrc) _reregisterFlyout(panelId);
    };
    _flyoutManager.reregisterAllFlyouts = _reregisterAllFlyouts;

    var _reregisterFlyout = function(panelId) {
        var rects = $ax.geometry.getPolygonInfo(getFlyoutLabel(panelId)).rects;
        _registerFlyout(rects, panelId, panelToSrc[panelId]);
    };

    // This is the reduced size polygon connecting r0 to r1 by means of horizontal or vertical lines.
    var getSmallPolygon = function(r0, r1, info) {
        var points = [];

        // NOTE: currently I make the assumption that if horizontal/vertical connecting lines from the src hit the target
        //        Meaning if horizontal, rlr and lrl are true, and if vertical, tbt and bab are true.

        var r0Left = r0.Left();
        var r0Right = r0.Right();
        var r0Top = r0.Top();
        var r0Bottom = r0.Bottom();
        var r1Left = r1.Left();
        var r1Right = r1.Right();
        var r1Top = r1.Top();
        var r1Bottom = r1.Bottom();

        points.push(genPoint(r1Left, r1Top));

        if(!info.tbt) {
            points.push(genPoint(r0Left, r1Top));
            points.push(genPoint(r0Left, r0Top));
            points.push(genPoint(r0Right, r0Top));
            points.push(genPoint(r0Right, r1Top));
        }

        points.push(genPoint(r1Right, r1Top));

        if(!info.rlr) {
            points.push(genPoint(r1Right, r0Top));
            points.push(genPoint(r0Right, r0Top));
            points.push(genPoint(r0Right, r0Bottom));
            points.push(genPoint(r1Right, r0Bottom));
        }

        points.push(genPoint(r1Right, r1Bottom));

        if(!info.bab) {
            points.push(genPoint(r0Right, r1Bottom));
            points.push(genPoint(r0Right, r0Bottom));
            points.push(genPoint(r0Left, r0Bottom));
            points.push(genPoint(r0Left, r1Bottom));
        }

        points.push(genPoint(r1Left, r1Bottom));

        if(!info.lrl) {
            points.push(genPoint(r1Left, r0Bottom));
            points.push(genPoint(r0Left, r0Bottom));
            points.push(genPoint(r0Left, r0Top));
            points.push(genPoint(r1Left, r0Top));
        }

        return points;
    };

    // This is the original algorithm that connects the most extream corners to make polygon
    var getLargePolygon = function(r0, r1, info) {
        var points = [];

        var r0Left = r0.Left();
        var r0Right = r0.Right();
        var r0Top = r0.Top();
        var r0Bottom = r0.Bottom();
        var r1Left = r1.Left();
        var r1Right = r1.Right();
        var r1Top = r1.Top();
        var r1Bottom = r1.Bottom();

        // Top lefts
        if(info.tbt) {
            if(!info.lrl) points.push(genPoint(r0Left, r0Top));
            points.push(genPoint(r1Left, r1Top));
        } else {
            if(info.lrl) points.push(genPoint(r1Left, r1Top));
            points.push(genPoint(r0Left, r0Top));
        }

        // Top rights
        if(info.tbt) {
            points.push(genPoint(r1Right, r1Top));
            if(!info.rlr) points.push(genPoint(r0Right, r0Top));
        } else {
            points.push(genPoint(r0Right, r0Top));
            if(info.rlr) points.push(genPoint(r1Right, r1Top));
        }

        // Bottom rights
        if(info.bab) {
            if(!info.rlr) points.push(genPoint(r0Right, r0Bottom));
            points.push(genPoint(r1Right, r1Bottom));
        } else {
            if(info.rlr) points.push(genPoint(r1Right, r1Bottom));
            points.push(genPoint(r0Right, r0Bottom));
        }

        // Bottom Lefts
        if(info.bab) {
            points.push(genPoint(r1Left, r1Bottom));
            if(!info.lrl) points.push(genPoint(r0Left, r0Bottom));
        } else {
            points.push(genPoint(r0Left, r0Bottom));
            if(info.lrl) points.push(genPoint(r1Left, r1Bottom));
        }
        return points;
    };
});

// ******* Placeholder Manager ********* //

$axure.internal(function($ax) {
    var _placeholderManager = $ax.placeholderManager = {};
    var idToPlaceholderInfo = {};

    var _registerPlaceholder = function(elementId, text, password) {
        idToPlaceholderInfo[elementId] = { text: text, password: password, active: false };
    };
    _placeholderManager.registerPlaceholder = _registerPlaceholder;

    _placeholderManager.refreshPlaceholder = function (elementId) {
        var info = idToPlaceholderInfo[elementId];
        if (!info || !info.active) return;
        $ax.style.SetWidgetPlaceholder(elementId, true, info.text, info.password);
    }

    var _updatePlaceholder = function(elementId, active, clearText) {
        var inputId = $ax.repeater.applySuffixToElementId(elementId, '_input');

        var info = idToPlaceholderInfo[elementId];
        if(!info || info.active == active) return;
        info.active = active;

        if(active) var value = info.text;
        else if(!ANDROID) value = clearText ? '' : document.getElementById(inputId).value;
        else {
            var currentText = document.getElementById(inputId).value;
            if(!clearText) value = currentText;
            else if(currentText == info.text) value = "";
            else {
                var lastIndex = currentText.lastIndexOf(info.text);
                //here i am assuming the text is always inserted in front
                value = currentText.substring(0, lastIndex);
            }
        }

        $ax.style.SetWidgetPlaceholder(elementId, active, value, info.password);
    };
    _placeholderManager.updatePlaceholder = _updatePlaceholder;

    var _isActive = function(elementId) {
        var info = idToPlaceholderInfo[elementId];
        return Boolean(info && info.active);
    };
    _placeholderManager.isActive = _isActive;

    var _selectRange = function(elementId, start, end) {
        $jobj(elementId).each(function() {
            if(this.setSelectionRange) {
                var validTypes = ["text", "search", "url", "tel", "password"];
                if(this.tagName.toLowerCase() != "input" || validTypes.indexOf(this.type) > -1) {
                    this.focus();
                    this.setSelectionRange(start, end);
                }
            } else if(this.createTextRange) {
                var range = this.createTextRange();
                range.collapse(true);
                range.moveEnd('character', end);
                range.moveStart('character', start);
                range.select();
            }
        });
    };
    _placeholderManager.selectRange = _selectRange;

    var _moveCaret = function(id, index) {
        var inputIndex = id.indexOf('_input');
        if(inputIndex == -1) return;
        var inputId = id.substring(0, inputIndex);

        if(!_isActive(inputId)) return;
        _selectRange(id, index, index);
    };
    _placeholderManager.moveCaret = _moveCaret;
});


text:
package org.apache.kafka.streams.kstream.internals;

import org.apache.kafka.common.MetricName;
import org.apache.kafka.common.header.internals.RecordHeaders;
import org.apache.kafka.common.metrics.Metrics;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.common.utils.LogContext;
import org.apache.kafka.common.utils.MockTime;
import org.apache.kafka.streams.KeyValue;
import org.apache.kafka.streams.KeyValueTimestamp;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.kstream.Aggregator;
import org.apache.kafka.streams.kstream.EmitStrategy;
import org.apache.kafka.streams.kstream.Initializer;
import org.apache.kafka.streams.kstream.Merger;
import org.apache.kafka.streams.kstream.SessionWindows;
import org.apache.kafka.streams.kstream.Windowed;
import org.apache.kafka.streams.processor.StateStoreContext;
import org.apache.kafka.streams.processor.api.Processor;
import org.apache.kafka.streams.processor.api.Record;
import org.apache.kafka.streams.processor.internals.metrics.TaskMetrics;
import org.apache.kafka.streams.processor.internals.ProcessorRecordContext;
import org.apache.kafka.streams.processor.internals.metrics.StreamsMetricsImpl;
import org.apache.kafka.common.utils.LogCaptureAppender;
import org.apache.kafka.common.utils.LogCaptureAppender.Event;
import org.apache.kafka.streams.state.KeyValueIterator;
import org.apache.kafka.streams.state.SessionBytesStoreSupplier;
import org.apache.kafka.streams.state.SessionStore;
import org.apache.kafka.streams.state.StoreBuilder;
import org.apache.kafka.streams.state.Stores;
import org.apache.kafka.streams.state.internals.RocksDbTimeOrderedSessionBytesStoreSupplier;
import org.apache.kafka.streams.state.internals.ThreadCache;
import org.apache.kafka.test.InternalMockProcessorContext;
import org.apache.kafka.test.MockRecordCollector;
import org.apache.kafka.test.StreamsTestUtils;
import org.apache.kafka.test.TestUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Properties;
import java.util.stream.Collectors;

import static java.time.Duration.ofMillis;
import static java.util.Arrays.asList;
import static org.apache.kafka.common.utils.Utils.mkEntry;
import static org.apache.kafka.common.utils.Utils.mkMap;
import static org.apache.kafka.test.StreamsTestUtils.getMetricByName;
import static org.hamcrest.CoreMatchers.hasItem;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.greaterThan;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

@RunWith(Parameterized.class)
public class KStreamSessionWindowAggregateProcessorTest {

    private static final long GAP_MS = 5 * 60 * 1000L;
    private static final String STORE_NAME = "session-store";

    private final MockTime time = new MockTime();
    private final Metrics metrics = new Metrics();
    private final StreamsMetricsImpl streamsMetrics = new StreamsMetricsImpl(metrics, "test", StreamsConfig.METRICS_LATEST, time);
    private final String threadId = Thread.currentThread().getName();
    private final Initializer<Long> initializer = () -> 0L;
    private final Aggregator<String, String, Long> aggregator = (aggKey, value, aggregate) -> aggregate + 1;
    private final Merger<String, Long> sessionMerger = (aggKey, aggOne, aggTwo) -> aggOne + aggTwo;
    private final List<KeyValueTimestamp<Windowed<String>, Change<Long>>> results = new ArrayList<>();

    private InternalMockProcessorContext<Windowed<String>, Change<Long>> context;
    private KStreamSessionWindowAggregate<String, String, Long> sessionAggregator;
    private Processor<String, String, Windowed<String>, Change<Long>> processor;
    private SessionStore<String, Long> sessionStore;

    @Parameterized.Parameter
    public EmitStrategy.StrategyType type;

    @Parameterized.Parameters(name = "{0}")
    public static Collection<Object[]> data() {
        return asList(new Object[][] {
            {EmitStrategy.StrategyType.ON_WINDOW_UPDATE},
            {EmitStrategy.StrategyType.ON_WINDOW_CLOSE}
        });
    }

    private EmitStrategy emitStrategy;
    private boolean emitFinal;

    @Before
    public void setup() {
        setup(true);
    }

    private void setup(final boolean enableCache) {
        // Always process
        final Properties prop = StreamsTestUtils.getStreamsConfig();
        prop.put(StreamsConfig.InternalConfig.EMIT_INTERVAL_MS_KSTREAMS_WINDOWED_AGGREGATION, 0);
        final StreamsConfig config = new StreamsConfig(prop);

        context = new InternalMockProcessorContext<Windowed<String>, Change<Long>>(
            TestUtils.tempDirectory(),
            Serdes.String(),
            Serdes.String(),
            streamsMetrics,
            config,
            MockRecordCollector::new,
            new ThreadCache(new LogContext("testCache "), 100000, streamsMetrics),
            time
        ) {
            @Override
            public <K extends Windowed<String>, V extends Change<Long>> void forward(final Record<K, V> record) {
                results.add(new KeyValueTimestamp<>(record.key(), record.value(), record.timestamp()));
            }
        };

        emitFinal = type.equals(EmitStrategy.StrategyType.ON_WINDOW_CLOSE);
        emitStrategy = EmitStrategy.StrategyType.forType(type);

        sessionAggregator = new KStreamSessionWindowAggregate<>(
            SessionWindows.ofInactivityGapWithNoGrace(ofMillis(GAP_MS)),
            STORE_NAME,
            emitStrategy,
            initializer,
            aggregator,
            sessionMerger);

        if (processor != null) {
            processor.close();
        }
        processor = sessionAggregator.get();

        // Set initial timestamp for CachingSessionStore to prepare entry from as default
        // InternalMockProcessorContext#timestamp returns -1.
        context.setTime(0L);
        TaskMetrics.droppedRecordsSensor(threadId, context.taskId().toString(), streamsMetrics);

        initStore(enableCache);
        processor.init(context);
    }

    private void initStore(final boolean enableCaching) {
        final SessionBytesStoreSupplier supplier = emitStrategy.type() == EmitStrategy.StrategyType.ON_WINDOW_CLOSE ?
            new RocksDbTimeOrderedSessionBytesStoreSupplier(STORE_NAME, GAP_MS * 3, true) :
            Stores.persistentSessionStore(STORE_NAME, ofMillis(GAP_MS * 3));

        final StoreBuilder<SessionStore<String, Long>> storeBuilder = Stores.sessionStoreBuilder(supplier, Serdes.String(), Serdes.Long())
            .withLoggingDisabled();

        if (enableCaching && emitStrategy.type() != EmitStrategy.StrategyType.ON_WINDOW_CLOSE) {
            storeBuilder.withCachingEnabled();
        }

        if (sessionStore != null) {
            sessionStore.close();
        }
        sessionStore = storeBuilder.build();
        sessionStore.init((StateStoreContext) context, sessionStore);
    }

    @After
    public void closeStore() {
        sessionStore.close();
        processor.close();
    }

    @Test
    public void shouldCreateSingleSessionWhenWithinGap() {
        processor.process(new Record<>("john", "first", 0L));
        processor.process(new Record<>("john", "second", 500L));

        try (final KeyValueIterator<Windowed<String>, Long> values =
                 sessionStore.findSessions("john", 0, 2000)) {
            assertTrue(values.hasNext());
            assertEquals(Long.valueOf(2), values.next().value);
        }
    }

    @Test
    public void shouldMergeSessions() {
        final String sessionId = "mel";
        processor.process(new Record<>(sessionId, "first", 0L));
        assertTrue(sessionStore.findSessions(sessionId, 0, 0).hasNext());

        // move time beyond gap
        processor.process(new Record<>(sessionId, "second", GAP_MS + 1));
        assertTrue(sessionStore.findSessions(sessionId, GAP_MS + 1, GAP_MS + 1).hasNext());
        // should still exist as not within gap
        assertTrue(sessionStore.findSessions(sessionId, 0, 0).hasNext());
        // move time back
        processor.process(new Record<>(sessionId, "third", GAP_MS / 2));

        try (final KeyValueIterator<Windowed<String>, Long> iterator =
                 sessionStore.findSessions(sessionId, 0, GAP_MS + 1)) {
            final KeyValue<Windowed<String>, Long> kv = iterator.next();

            assertEquals(Long.valueOf(3), kv.value);
            assertFalse(iterator.hasNext());
        }
    }

    @Test
    public void shouldUpdateSessionIfTheSameTime() {
        processor.process(new Record<>("mel", "first", 0L));
        processor.process(new Record<>("mel", "second", 0L));
        try (final KeyValueIterator<Windowed<String>, Long> iterator =
                 sessionStore.findSessions("mel", 0, 0)) {
            assertEquals(Long.valueOf(2L), iterator.next().value);
            assertFalse(iterator.hasNext());
        }
    }

    @Test
    public void shouldHaveMultipleSessionsForSameIdWhenTimestampApartBySessionGap() {
        final String sessionId = "mel";
        long now = 0;
        processor.process(new Record<>(sessionId, "first", now));
        now += GAP_MS + 1;
        processor.process(new Record<>(sessionId, "second", now));
        processor.process(new Record<>(sessionId, "second", now));
        now += GAP_MS + 1;
        processor.process(new Record<>(sessionId, "third", now));
        processor.process(new Record<>(sessionId, "third", now));
        processor.process(new Record<>(sessionId, "third", now));

        sessionStore.flush();

        if (emitFinal) {
            assertEquals(
                Arrays.asList(
                    new KeyValueTimestamp<>(
                        new Windowed<>(sessionId, new SessionWindow(0, 0)),
                        new Change<>(1L, null),
                        0L),
                    new KeyValueTimestamp<>(
                        new Windowed<>(sessionId, new SessionWindow(GAP_MS + 1, GAP_MS + 1)),
                        new Change<>(2L, null),
                        GAP_MS + 1)
                ),
                results
            );
        } else {
            assertEquals(
                Arrays.asList(
                    new KeyValueTimestamp<>(
                        new Windowed<>(sessionId, new SessionWindow(0, 0)),
                        new Change<>(1L, null),
                        0L),
                    new KeyValueTimestamp<>(
                        new Windowed<>(sessionId, new SessionWindow(GAP_MS + 1, GAP_MS + 1)),
                        new Change<>(2L, null),
                        GAP_MS + 1),
                    new KeyValueTimestamp<>(
                        new Windowed<>(sessionId, new SessionWindow(now, now)),
                        new Change<>(3L, null),
                        now)
                ),
                results
            );
        }
    }

    @Test
    public void shouldRemoveMergedSessionsFromStateStore() {
        processor.process(new Record<>("a", "1", 0L));

        // first ensure it is in the store
        try (final KeyValueIterator<Windowed<String>, Long> a1 =
                 sessionStore.findSessions("a", 0, 0)) {
            assertEquals(KeyValue.pair(new Windowed<>("a", new SessionWindow(0, 0)), 1L), a1.next());
        }

        processor.process(new Record<>("a", "2", 100L));
        // a1 from above should have been removed
        // should have merged session in store
        try (final KeyValueIterator<Windowed<String>, Long> a2 =
                 sessionStore.findSessions("a", 0, 100)) {
            assertEquals(KeyValue.pair(new Windowed<>("a", new SessionWindow(0, 100)), 2L), a2.next());
            assertFalse(a2.hasNext());
        }
    }

    @Test
    public void shouldHandleMultipleSessionsAndMerging() {
        processor.process(new Record<>("a", "1", 0L));
        processor.process(new Record<>("b", "1", 0L));
        processor.process(new Record<>("c", "1", 0L));
        processor.process(new Record<>("d", "1", 0L));
        processor.process(new Record<>("d", "2", GAP_MS / 2));
        processor.process(new Record<>("a", "2", GAP_MS + 1));
        processor.process(new Record<>("b", "2", GAP_MS + 1));
        processor.process(new Record<>("a", "3", GAP_MS + 1 + GAP_MS / 2));
        processor.process(new Record<>("c", "3", GAP_MS + 1 + GAP_MS / 2));

        sessionStore.flush();

        if (emitFinal) {
            assertEquals(Arrays.asList(
                new KeyValueTimestamp<>(
                    new Windowed<>("a", new SessionWindow(0, 0)),
                    new Change<>(1L, null),
                    0L),
                new KeyValueTimestamp<>(
                    new Windowed<>("b", new SessionWindow(0, 0)),
                    new Change<>(1L, null),
                    0L),
                new KeyValueTimestamp<>(
                    new Windowed<>("c", new SessionWindow(0, 0)),
                    new Change<>(1L, null),
                    0L),
                new KeyValueTimestamp<>(
                    new Windowed<>("d", new SessionWindow(0, GAP_MS / 2)),
                    new Change<>(2L, null),
                    GAP_MS / 2)
                ),
                results);
        } else {
            assertEquals(
                Arrays.asList(
                    new KeyValueTimestamp<>(
                        new Windowed<>("a", new SessionWindow(0, 0)),
                        new Change<>(1L, null),
                        0L),
                    new KeyValueTimestamp<>(
                        new Windowed<>("b", new SessionWindow(0, 0)),
                        new Change<>(1L, null),
                        0L),
                    new KeyValueTimestamp<>(
                        new Windowed<>("c", new SessionWindow(0, 0)),
                        new Change<>(1L, null),
                       0L),
                    new KeyValueTimestamp<>(
                        new Windowed<>("d", new SessionWindow(0, GAP_MS / 2)),
                        new Change<>(2L, null),
                        GAP_MS / 2),
                    new KeyValueTimestamp<>(
                        new Windowed<>("b", new SessionWindow(GAP_MS + 1, GAP_MS + 1)),
                        new Change<>(1L, null),
                        GAP_MS + 1),
                    new KeyValueTimestamp<>(
                        new Windowed<>("a", new SessionWindow(GAP_MS + 1, GAP_MS + 1 + GAP_MS / 2)),
                        new Change<>(2L, null),
                        GAP_MS + 1 + GAP_MS / 2),
                    new KeyValueTimestamp<>(new Windowed<>(
                        "c",
                        new SessionWindow(GAP_MS + 1 + GAP_MS / 2, GAP_MS + 1 + GAP_MS / 2)), new Change<>(1L, null),
                        GAP_MS + 1 + GAP_MS / 2)
                    ),
                    results
            );
        }
    }

    @Test
    public void shouldGetAggregatedValuesFromValueGetter() {
        final KTableValueGetter<Windowed<String>, Long> getter = sessionAggregator.view().get();
        getter.init(context);
        processor.process(new Record<>("a", "1", 0L));
        processor.process(new Record<>("a", "1", GAP_MS + 1));
        processor.process(new Record<>("a", "2", GAP_MS + 1));
        final long t0 = getter.get(new Windowed<>("a", new SessionWindow(0, 0))).value();
        final long t1 = getter.get(new Windowed<>("a", new SessionWindow(GAP_MS + 1, GAP_MS + 1))).value();
        assertEquals(1L, t0);
        assertEquals(2L, t1);
    }

    @Test
    public void shouldImmediatelyForwardNewSessionWhenNonCachedStore() {
        if (emitFinal)
            return;

        initStore(false);
        processor.init(context);

        processor.process(new Record<>("a", "1", 0L));
        processor.process(new Record<>("b", "1", 0L));
        processor.process(new Record<>("c", "1", 0L));

        assertEquals(
            Arrays.asList(
                new KeyValueTimestamp<>(
                    new Windowed<>("a", new SessionWindow(0, 0)),
                    new Change<>(1L, null),
                    0L),
                new KeyValueTimestamp<>(
                    new Windowed<>("b", new SessionWindow(0, 0)),
                    new Change<>(1L, null),
                    0L),
                new KeyValueTimestamp<>(
                    new Windowed<>("c", new SessionWindow(0, 0)),
                    new Change<>(1L, null),
                    0L)
            ),
            results
        );
    }

    @Test
    public void shouldImmediatelyForwardRemovedSessionsWhenMerging() {
        if (emitFinal)
            return;

        initStore(false);
        processor.init(context);

        processor.process(new Record<>("a", "1", 0L));
        processor.process(new Record<>("a", "1", 5L));
        assertEquals(
            Arrays.asList(
                new KeyValueTimestamp<>(
                    new Windowed<>("a", new SessionWindow(0, 0)),
                    new Change<>(1L, null),
                    0L),
                new KeyValueTimestamp<>(
                    new Windowed<>("a", new SessionWindow(0, 0)),
                    new Change<>(null, null),
                    0L),
                new KeyValueTimestamp<>(
                    new Windowed<>("a", new SessionWindow(0, 5)),
                    new Change<>(2L, null),
                    5L)
            ),
            results
        );
    }

    @Test
    public void shouldLogAndMeterWhenSkippingNullKeyWithBuiltInMetrics() {
        setup(false);
        context.setRecordContext(
            new ProcessorRecordContext(-1, -2, -3, "topic", new RecordHeaders())
        );

        try (final LogCaptureAppender appender =
                 LogCaptureAppender.createAndRegister(KStreamSessionWindowAggregate.class)) {

            processor.process(new Record<>(null, "1", 0L));

            assertThat(
                appender.getEvents().stream()
                    .filter(e -> e.getLevel().equals("WARN"))
                    .map(Event::getMessage)
                    .collect(Collectors.toList()),
                hasItem("Skipping record due to null key. topic=[topic] partition=[-3] offset=[-2]")
            );
        }

        assertEquals(
            1.0,
            getMetricByName(context.metrics().metrics(), "dropped-records-total", "stream-task-metrics").metricValue()
        );
    }

    @Test
    public void shouldLogAndMeterWhenSkippingLateRecordWithZeroGrace() {
        setup(false);
        final Processor<String, String, Windowed<String>, Change<Long>> processor = new KStreamSessionWindowAggregate<>(
            SessionWindows.ofInactivityGapAndGrace(ofMillis(10L), ofMillis(0L)),
            STORE_NAME,
            EmitStrategy.onWindowUpdate(),
            initializer,
            aggregator,
            sessionMerger
        ).get();
        processor.init(context);

        // dummy record to establish stream time = 0
        context.setRecordContext(new ProcessorRecordContext(0, -2, -3, "topic", new RecordHeaders()));
        processor.process(new Record<>("dummy", "dummy", 0L));

        // record arrives on time, should not be skipped
        context.setRecordContext(new ProcessorRecordContext(0, -2, -3, "topic", new RecordHeaders()));
        processor.process(new Record<>("OnTime1", "1", 0L));

        // dummy record to advance stream time = 11, 10 for gap time plus 1 to place outside window
        context.setRecordContext(new ProcessorRecordContext(11, -2, -3, "topic", new RecordHeaders()));
        processor.process(new Record<>("dummy", "dummy", 11L));

        try (final LogCaptureAppender appender =
                 LogCaptureAppender.createAndRegister(KStreamSessionWindowAggregate.class)) {

            // record is late
            context.setRecordContext(new ProcessorRecordContext(0, -2, -3, "topic", new RecordHeaders()));
            processor.process(new Record<>("Late1", "1", 0L));

            assertThat(
                appender.getMessages(),
                hasItem("Skipping record for expired window." +
                    " topic=[topic] partition=[-3] offset=[-2] timestamp=[0] window=[0,0] expiration=[1] streamTime=[11]")
            );
        }

        final MetricName dropTotal;
        final MetricName dropRate;
        dropTotal = new MetricName(
            "dropped-records-total",
            "stream-task-metrics",
            "The total number of dropped records",
            mkMap(
                mkEntry("thread-id", threadId),
                mkEntry("task-id", "0_0")
            )
        );
        dropRate = new MetricName(
            "dropped-records-rate",
            "stream-task-metrics",
            "The average number of dropped records per second",
            mkMap(
                mkEntry("thread-id", threadId),
                mkEntry("task-id", "0_0")
            )
        );
        assertThat(metrics.metrics().get(dropTotal).metricValue(), is(1.0));
        assertThat(
            (Double) metrics.metrics().get(dropRate).metricValue(),
            greaterThan(0.0)
        );
    }

    @Test
    public void shouldLogAndMeterWhenSkippingLateRecordWithNonzeroGrace() {
        setup(false);
        final Processor<String, String, Windowed<String>, Change<Long>> processor = new KStreamSessionWindowAggregate<>(
            SessionWindows.ofInactivityGapAndGrace(ofMillis(10L), ofMillis(1L)),
            STORE_NAME,
            EmitStrategy.onWindowUpdate(),
            initializer,
            aggregator,
            sessionMerger
        ).get();
        processor.init(context);

        try (final LogCaptureAppender appender =
                 LogCaptureAppender.createAndRegister(KStreamSessionWindowAggregate.class)) {

            // dummy record to establish stream time = 0
            context.setRecordContext(new ProcessorRecordContext(0, -2, -3, "topic", new RecordHeaders()));
            processor.process(new Record<>("dummy", "dummy", 0L));

            // record arrives on time, should not be skipped
            context.setRecordContext(new ProcessorRecordContext(0, -2, -3, "topic", new RecordHeaders()));
            processor.process(new Record<>("OnTime1", "1", 0L));

            // dummy record to advance stream time = 11, 10 for gap time plus 1 to place at edge of window
            context.setRecordContext(new ProcessorRecordContext(11, -2, -3, "topic", new RecordHeaders()));
            processor.process(new Record<>("dummy", "dummy", 11L));

            // delayed record arrives on time, should not be skipped
            context.setRecordContext(new ProcessorRecordContext(0, -2, -3, "topic", new RecordHeaders()));
            processor.process(new Record<>("OnTime2", "1", 0L));

            // dummy record to advance stream time = 12, 10 for gap time plus 2 to place outside window
            context.setRecordContext(new ProcessorRecordContext(12, -2, -3, "topic", new RecordHeaders()));
            processor.process(new Record<>("dummy", "dummy", 12L));

            // delayed record arrives late
            context.setRecordContext(new ProcessorRecordContext(0, -2, -3, "topic", new RecordHeaders()));
            processor.process(new Record<>("Late1", "1", 0L));

            assertThat(
                appender.getMessages(),
                hasItem("Skipping record for expired window." +
                    " topic=[topic] partition=[-3] offset=[-2] timestamp=[0] window=[0,0] expiration=[1] streamTime=[12]")
            );
        }

        final MetricName dropTotal;
        final MetricName dropRate;
        dropTotal = new MetricName(
            "dropped-records-total",
            "stream-task-metrics",
            "The total number of dropped records",
            mkMap(
                mkEntry("thread-id", threadId),
                mkEntry("task-id", "0_0")
            )
        );
        dropRate = new MetricName(
            "dropped-records-rate",
            "stream-task-metrics",
            "The average number of dropped records per second",
            mkMap(
                mkEntry("thread-id", threadId),
                mkEntry("task-id", "0_0")
            )
        );

        assertThat(metrics.metrics().get(dropTotal).metricValue(), is(1.0));
        assertThat(
            (Double) metrics.metrics().get(dropRate).metricValue(),
            greaterThan(0.0));
    }
}

redpajama_set_name: RedPajamaGithub


text:
'use strict';

var JSHint = require( 'jshint' ).JSHINT;
var tokenizeMarkdown = require( 'tokenize-markdown' );
var contribJSHint = require( './lib/jshint' );
var grunt = require( 'grunt' );

/**
 * Use Grunt to load a file from the file system
 *
 * @param  {String} fileName The file name to load
 * @return {Object}          An object representing the file and its contents
 */
function readfile( fileName ) {
  // Read the file and return an object with the file's name & contents
  return {
    name: fileName,
    contents: grunt.file.read( fileName )
  };
}

/**
 * Take in an object with a file's name & contents, and return an object
 * containing the tokenized and filtered markdown tokens
 *
 * (options object is specified first because it will be bound as the first
 * argument within the .map() function chain in the task definition)
 *
 * @param {Object} options             An options object for filtering tokens
 * @param {String|RegExp} options.lang RegEx or String specifying language(s)
 *                                     that should be included in results
 * @param {Object} fileObj             An object describing a file
 * @param {String} fileObj.name        The path (filename) of the file
 * @param {String} fileObj.contents    The contents of the file, as a string
 * @return {Object} An object { file: 'fileName', tokens: tokenObjectArray }
 */
function tokenizeFile( options, fileObj ) {
  // Convert to tokens using the specified language filter parameters
  var tokens = tokenizeMarkdown.fromString( fileObj.contents, {
    type: 'code',
    lang: options.lang
  });

  // Map results into an object defining the tokens for this file
  return {
    file: fileObj.name,
    tokens: tokens
  };
}

/**
 * Reducer function to run JSHint against each file's tokens and aggregate any errors
 *
 * @param  {Object} options An object specifying the JSHint options to use
 * @param  {Array}  errors  Reducer memo array, collecting any JSHint errors
 * @param  {Object} item    The item defining the tokens for a given file
 * @return {Array} An array of aggregated JSHint errors
 */
function reduceToJSHintErrors( options, errors, file ) {

  // For each code file, run JSHint and see if it fails.
  file.tokens.forEach(function evaluateToken( snippet ) {
    var didFail = ! JSHint.jshint( snippet.text, options );

    if ( didFail && JSHint.errors.length ) {
      // Add each identified error to the output
      JSHint.errors.forEach(function recordError( error ) {
        errors.push({
          // File path
          file: file.name,
          // JSHint error object
          error: error
        });
      });
    }
  });

  return errors;
}

// Export the task definition
module.exports = function( grunt ) {
  var desc = 'Run JSHint against code snippets within Markdown slides.';

  grunt.registerMultiTask( 'codeblock-jshint', desc, function codeBlockJSHintTask() {
    var done = this.async();

    // Get any configured options, defaulting the search paths to any markdown
    // files below the working directory other than those in node_modules
    var options = this.options({
      lang: /(js|javascript)/,
      force: false
    });

    // If force is true, report JSHint errors but dont fail the task
    var force = options.force;
    delete options.force;

    // Use logic borrowed from grunt-contrib-jshint to select the reporter to use
    var reporter = contribJSHint.init( grunt ).selectReporter( options );

    // Expand the fileSrc glob to a file names list
    var results = grunt.file.expand( this.filesSrc )
      // Load each file into memory
      .map( readfile )
      // Convert each file to Markdown tokens
      .map( tokenizeFile.bind( null, options ) )
      // Process each files' tokens with JSHint and return a unified error list
      // (use .bind to pass the reducer method any provided JSHint options)
      .reduce( reduceToJSHintErrors.bind( null, options.jshintOptions ), [] );

    // Log results
    reporter( results );

    // If no errors occurred, we're green
    var noErrors = ! results.length;

    var eventType;

    if ( noErrors ) {
      eventType = 'success';
    } else {
      eventType = force ? 'forced' : 'error';
    }

    // Emit an event (used exclusively for testing)
    grunt.event.emit( 'codeblock-jshint', eventType, results );

    // End the task: Fail if errors were logged, unless force was set
    done( noErrors || force );
  });
};


text:
<?php

/**
 * @file
 * Contains \Drupal\Console\Generator\EntityGenerator.
 */

namespace Drupal\Console\Generator;

class EntityConfigGenerator extends Generator
{
    /**
     * Generator Entity.
     *
     * @param string $module       Module name
     * @param string $entity_name  Entity machine name
     * @param string $entity_class Entity class name
     * @param string $label        Entity label
     * @param string $bundle_of    Entity machine name of the content entity this config entity acts as a bundle for.
     */
    public function generate($module, $entity_name, $entity_class, $label, $bundle_of = null)
    {
        $parameters = [
          'module' => $module,
          'entity_name' => $entity_name,
          'entity_class' => $entity_class,
          'label' => $label,
          'bundle_of' => $bundle_of,
        ];

        $this->renderFile(
            'module/config/schema/entity.schema.yml.twig',
            $this->getSite()->getModulePath($module).'/config/schema/'.$entity_name.'.schema.yml',
            $parameters
        );

        $this->renderFile(
            'module/routing-entity.yml.twig',
            $this->getSite()->getModulePath($module).'/'.$module.'.routing.yml',
            $parameters,
            FILE_APPEND
        );

        $this->renderFile(
            'module/links.menu-entity-config.yml.twig',
            $this->getSite()->getModulePath($module).'/'.$module.'.links.menu.yml',
            $parameters,
            FILE_APPEND
        );

        $this->renderFile(
            'module/links.action-entity.yml.twig',
            $this->getSite()->getModulePath($module).'/'.$module.'.links.action.yml',
            $parameters,
            FILE_APPEND
        );

        $this->renderFile(
            'module/src/interface-entity.php.twig',
            $this->getSite()->getSourcePath($module).'/'.$entity_class.'Interface.php',
            $parameters
        );

        $this->renderFile(
            'module/src/Entity/entity.php.twig',
            $this->getSite()->getEntityPath($module).'/'.$entity_class.'.php',
            $parameters
        );

        $this->renderFile(
            'module/src/Form/entity.php.twig',
            $this->getSite()->getFormPath($module).'/'.$entity_class.'Form.php',
            $parameters
        );

        $this->renderFile(
            'module/src/Form/entity-delete.php.twig',
            $this->getSite()->getFormPath($module).'/'.$entity_class.'DeleteForm.php',
            $parameters
        );

        $this->renderFile(
            'module/src/entity-listbuilder.php.twig',
            $this->getSite()->getSourcePath($module).'/'.$entity_class.'ListBuilder.php',
            $parameters
        );
    }
}


text:
def html_tag(*names)
  names.each do | name |
    name = name.to_s
    eval %(
    def #{name}(*attr, &block)
      raise "Expected hash or nothing" if attr.length > 1
      attributes = (attr[0] || {}).map { | k, v | %s(\#{k}="\#{v}") }.join(" ")
      if block_given?
	puts "<#{name} \#{attributes}>"
	yield
	puts "</#{name}>"
      else
	puts "<#{name} \#{attributes}/>"
      end
    end)
  end
end
html_tag :html, :head, :title, :body, :h1, :h2, :h3, :p

html do
  head do
    title do
      puts "Whiteout test case"
    end
  end
  body do
    [["It's a ruby quiz!",
    "Nice idea, James!",
    "Keep on the good work!"],

    ["And some lorem ipsum dolor...",
    "Oh, and remember, I need a lot more lines of ruby code to show that zlib compression really has an advantage.",
    "But creating lots and lots of text is no problem."]].each do | paragraph |
      h1 do puts paragraph[0] end
      p do ||
	puts paragraph[1..-1]
      end
    end
  end
end


text:
namespace Mastermind {
    using Gadgeteer;
    using GTM = Gadgeteer.Modules;

    public partial class Program : Gadgeteer.Program {

        /// The Button module using socket 11 of the mainboard.
        private Gadgeteer.Modules.GHIElectronics.Button button;

        /// The LED Strip module using socket 8 of the mainboard.
        private Gadgeteer.Modules.GHIElectronics.LEDStrip ledStrip;

        /// The Joystick module using socket 9 of the mainboard.
        private Gadgeteer.Modules.GHIElectronics.Joystick joystick;

        /// The Display TE35 module using sockets 14, 13, 12 and 10 of the mainboard.
        private Gadgeteer.Modules.GHIElectronics.DisplayTE35 displayTE35;

        /// This property provides access to the Mainboard API. This is normally not necessary for an end user program.
        protected new static GHIElectronics.Gadgeteer.FEZSpider Mainboard {
            get {
                return ((GHIElectronics.Gadgeteer.FEZSpider)(Gadgeteer.Program.Mainboard));
            }
            set {
                Gadgeteer.Program.Mainboard = value;
            }
        }

        /// This method runs automatically when the device is powered, and calls ProgramStarted.
        public static void Main() {
            // Important to initialize the Mainboard first
            Program.Mainboard = new GHIElectronics.Gadgeteer.FEZSpider();
            Program p = new Program();
            p.InitializeModules();
            p.ProgramStarted();
            // Starts Dispatcher
            p.Run();
        }

        private void InitializeModules() {
            this.button = new GTM.GHIElectronics.Button(11);
            this.ledStrip = new GTM.GHIElectronics.LEDStrip(8);
            this.joystick = new GTM.GHIElectronics.Joystick(9);
            this.displayTE35 = new GTM.GHIElectronics.DisplayTE35(14, 13, 12, 10);
        }
    }
}


text:
package org.sagebionetworks.bridge.config;

import java.net.URI;
import java.net.URISyntaxException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import org.sagebionetworks.bridge.BridgeUtils;
import org.sagebionetworks.bridge.redis.JedisOps;

/**
 * Production-only Spring config. This includes things that we don't want in our unit tests for
 * reliability/repeatability concerns, most notably Redis
 */
@Configuration
public class BridgeProductionSpringConfig {

    @Autowired
    BridgeConfig bridgeConfig;

    @Bean(name = "jedisOps")
    public JedisOps jedisOps() throws Exception {
        return new JedisOps(jedisPool());
    }

    @Bean
    public JedisPool jedisPool() throws Exception {
        return createJedisPool("elasticache.url");
    }

    private JedisPool createJedisPool(String redisServerProperty) throws Exception {
        final JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxTotal(bridgeConfig.getPropertyAsInt("redis.max.total"));
        poolConfig.setMinIdle(bridgeConfig.getPropertyAsInt("redis.min.idle"));
        poolConfig.setMaxIdle(bridgeConfig.getPropertyAsInt("redis.max.idle"));
        poolConfig.setTestOnCreate(true);
        poolConfig.setTestOnBorrow(true);
        poolConfig.setTestOnReturn(true);
        poolConfig.setTestWhileIdle(true);

        final String url = bridgeConfig.get(redisServerProperty);
        final JedisPool jedisPool = constructJedisPool(url, poolConfig);

        // Shutdown hook
        Runtime.getRuntime().addShutdownHook(new Thread(jedisPool::destroy));

        return jedisPool;
    }

    private JedisPool constructJedisPool(final String url, final JedisPoolConfig poolConfig)
            throws URISyntaxException {

        URI redisURI = new URI(url);
        String password = BridgeUtils.extractPasswordFromURI(redisURI);

        if (password != null) {
            return new JedisPool(poolConfig, redisURI.getHost(), redisURI.getPort(),
                    bridgeConfig.getPropertyAsInt("redis.timeout"), password);
        }
        return new JedisPool(poolConfig, redisURI.getHost(), redisURI.getPort(),
                bridgeConfig.getPropertyAsInt("redis.timeout"));
    }
}


text:
package namecom

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/url"
)

var _ = bytes.MinRead

// ListDomains returns all domains in the account. It omits some information that can be retrieved from GetDomain.
func (n *NameCom) ListDomains(request *ListDomainsRequest) (*ListDomainsResponse, error) {
	endpoint := fmt.Sprintf("/v4/domains")

	values := url.Values{}
	if request.PerPage != 0 {
		values.Set("perPage", fmt.Sprintf("%d", request.PerPage))
	}
	if request.Page != 0 {
		values.Set("page", fmt.Sprintf("%d", request.Page))
	}

	body, err := n.get(endpoint, values)
	if err != nil {
		return nil, err
	}

	resp := &ListDomainsResponse{}

	err = json.NewDecoder(body).Decode(resp)
	if err != nil {
		return nil, err
	}

	return resp, nil
}

// GetDomain returns details about a specific domain
func (n *NameCom) GetDomain(request *GetDomainRequest) (*Domain, error) {
	endpoint := fmt.Sprintf("/v4/domains/%s", request.DomainName)

	values := url.Values{}

	body, err := n.get(endpoint, values)
	if err != nil {
		return nil, err
	}

	resp := &Domain{}

	err = json.NewDecoder(body).Decode(resp)
	if err != nil {
		return nil, err
	}

	return resp, nil
}

// CreateDomain purchases a new domain. Domains that are not regularly priced require the purchase_price field to be specified.
func (n *NameCom) CreateDomain(request *CreateDomainRequest) (*CreateDomainResponse, error) {
	endpoint := fmt.Sprintf("/v4/domains")

	post := &bytes.Buffer{}
	err := json.NewEncoder(post).Encode(request)
	if err != nil {
		return nil, err
	}

	body, err := n.post(endpoint, post)
	if err != nil {
		return nil, err
	}

	resp := &CreateDomainResponse{}

	err = json.NewDecoder(body).Decode(resp)
	if err != nil {
		return nil, err
	}

	return resp, nil
}

// EnableAutorenew enables the domain to be automatically renewed when it gets close to expiring.
func (n *NameCom) EnableAutorenew(request *EnableAutorenewForDomainRequest) (*Domain, error) {
	endpoint := fmt.Sprintf("/v4/domains")

	post := &bytes.Buffer{}
	err := json.NewEncoder(post).Encode(request)
	if err != nil {
		return nil, err
	}

	body, err := n.post(endpoint, post)
	if err != nil {
		return nil, err
	}

	resp := &Domain{}

	err = json.NewDecoder(body).Decode(resp)
	if err != nil {
		return nil, err
	}

	return resp, nil
}

// DisableAutorenew disables automatic renewals, thus requiring the domain to be renewed manually.
func (n *NameCom) DisableAutorenew(request *DisableAutorenewForDomainRequest) (*Domain, error) {
	endpoint := fmt.Sprintf("/v4/domains")

	post := &bytes.Buffer{}
	err := json.NewEncoder(post).Encode(request)
	if err != nil {
		return nil, err
	}

	body, err := n.post(endpoint, post)
	if err != nil {
		return nil, err
	}

	resp := &Domain{}

	err = json.NewDecoder(body).Decode(resp)
	if err != nil {
		return nil, err
	}

	return resp, nil
}

// RenewDomain will renew a domain. Purchase_price is required if the renewal is not regularly priced.
func (n *NameCom) RenewDomain(request *RenewDomainRequest) (*RenewDomainResponse, error) {
	endpoint := fmt.Sprintf("/v4/domains")

	post := &bytes.Buffer{}
	err := json.NewEncoder(post).Encode(request)
	if err != nil {
		return nil, err
	}

	body, err := n.post(endpoint, post)
	if err != nil {
		return nil, err
	}

	resp := &RenewDomainResponse{}

	err = json.NewDecoder(body).Decode(resp)
	if err != nil {
		return nil, err
	}

	return resp, nil
}

// GetAuthCodeForDomain returns the Transfer Authorization Code for the domain.
func (n *NameCom) GetAuthCodeForDomain(request *AuthCodeRequest) (*AuthCodeResponse, error) {
	endpoint := fmt.Sprintf("/v4/domains")

	values := url.Values{}
	if request.DomainName != "" {
		values.Set("domainName", request.DomainName)
	}

	body, err := n.get(endpoint, values)
	if err != nil {
		return nil, err
	}

	resp := &AuthCodeResponse{}

	err = json.NewDecoder(body).Decode(resp)
	if err != nil {
		return nil, err
	}

	return resp, nil
}

// PurchasePrivacy will add Whois Privacy protection to a domain or will an renew existing subscription.
func (n *NameCom) PurchasePrivacy(request *PrivacyRequest) (*PrivacyResponse, error) {
	endpoint := fmt.Sprintf("/v4/domains")

	post := &bytes.Buffer{}
	err := json.NewEncoder(post).Encode(request)
	if err != nil {
		return nil, err
	}

	body, err := n.post(endpoint, post)
	if err != nil {
		return nil, err
	}

	resp := &PrivacyResponse{}

	err = json.NewDecoder(body).Decode(resp)
	if err != nil {
		return nil, err
	}

	return resp, nil
}

// SetNameservers will set the nameservers for the Domain.
func (n *NameCom) SetNameservers(request *SetNameserversRequest) (*Domain, error) {
	endpoint := fmt.Sprintf("/v4/domains/%s:setNameservers", request.DomainName)

	post := &bytes.Buffer{}
	err := json.NewEncoder(post).Encode(request)
	if err != nil {
		return nil, err
	}

	body, err := n.post(endpoint, post)
	if err != nil {
		return nil, err
	}

	resp := &Domain{}

	err = json.NewDecoder(body).Decode(resp)
	if err != nil {
		return nil, err
	}

	return resp, nil
}

// SetContacts will set the contacts for the Domain.
func (n *NameCom) SetContacts(request *SetContactsRequest) (*Domain, error) {
	endpoint := fmt.Sprintf("/v4/domains")

	post := &bytes.Buffer{}
	err := json.NewEncoder(post).Encode(request)
	if err != nil {
		return nil, err
	}

	body, err := n.post(endpoint, post)
	if err != nil {
		return nil, err
	}

	resp := &Domain{}

	err = json.NewDecoder(body).Decode(resp)
	if err != nil {
		return nil, err
	}

	return resp, nil
}

// LockDomain will lock a domain so that it cannot be transfered to another registrar.
func (n *NameCom) LockDomain(request *LockDomainRequest) (*Domain, error) {
	endpoint := fmt.Sprintf("/v4/domains")

	post := &bytes.Buffer{}
	err := json.NewEncoder(post).Encode(request)
	if err != nil {
		return nil, err
	}

	body, err := n.post(endpoint, post)
	if err != nil {
		return nil, err
	}

	resp := &Domain{}

	err = json.NewDecoder(body).Decode(resp)
	if err != nil {
		return nil, err
	}

	return resp, nil
}

// UnlockDomain will unlock a domain so that it can be transfered to another registrar.
func (n *NameCom) UnlockDomain(request *UnlockDomainRequest) (*Domain, error) {
	endpoint := fmt.Sprintf("/v4/domains")

	post := &bytes.Buffer{}
	err := json.NewEncoder(post).Encode(request)
	if err != nil {
		return nil, err
	}

	body, err := n.post(endpoint, post)
	if err != nil {
		return nil, err
	}

	resp := &Domain{}

	err = json.NewDecoder(body).Decode(resp)
	if err != nil {
		return nil, err
	}

	return resp, nil
}

// CheckAvailability will check a list of domains to see if they are purchaseable. A Maximum of 50 domains can be specified.
func (n *NameCom) CheckAvailability(request *AvailabilityRequest) (*SearchResponse, error) {
	endpoint := fmt.Sprintf("/v4/domains:checkAvailability")

	post := &bytes.Buffer{}
	err := json.NewEncoder(post).Encode(request)
	if err != nil {
		return nil, err
	}

	body, err := n.post(endpoint, post)
	if err != nil {
		return nil, err
	}

	resp := &SearchResponse{}

	err = json.NewDecoder(body).Decode(resp)
	if err != nil {
		return nil, err
	}

	return resp, nil
}

// Search will perform a search for specified keywords.
func (n *NameCom) Search(request *SearchRequest) (*SearchResponse, error) {
	endpoint := fmt.Sprintf("/v4/domains:search")

	post := &bytes.Buffer{}
	err := json.NewEncoder(post).Encode(request)
	if err != nil {
		return nil, err
	}

	body, err := n.post(endpoint, post)
	if err != nil {
		return nil, err
	}

	resp := &SearchResponse{}

	err = json.NewDecoder(body).Decode(resp)
	if err != nil {
		return nil, err
	}

	return resp, nil
}

// SearchStream will return JSON encoded SearchResults as they are recieved from the registry. The SearchResults are separated by newlines. This can allow clients to react to results before the search is fully completed.
func (n *NameCom) SearchStream(request *SearchRequest) (*SearchResult, error) {
	endpoint := fmt.Sprintf("/v4/domains:searchStream")

	post := &bytes.Buffer{}
	err := json.NewEncoder(post).Encode(request)
	if err != nil {
		return nil, err
	}

	body, err := n.post(endpoint, post)
	if err != nil {
		return nil, err
	}

	resp := &SearchResult{}

	err = json.NewDecoder(body).Decode(resp)
	if err != nil {
		return nil, err
	}

	return resp, nil
}


text:
dev_build_version=$(shell git describe --tags --always --dirty)

# TODO: run golint and errcheck, but only to catch *new* violations and
# decide whether to change code or not (e.g. we need to be able to whitelist
# violations already in the code). They can be useful to catch errors, but
# they are just too noisy to be a requirement for a CI -- we don't even *want*
# to fix some of the things they consider to be violations.
.PHONY: ci
ci: deps checkgofmt vet staticcheck ineffassign predeclared test

.PHONY: deps
deps:
	go get -d -v -t ./...

.PHONY: updatedeps
updatedeps:
	go get -d -v -t -u -f ./...

.PHONY: install
install:
	go install -ldflags '-X "main.version=dev build $(dev_build_version)"' ./...

.PHONY: release
release:
	@GO111MODULE=on go install github.com/goreleaser/goreleaser
	goreleaser --rm-dist

.PHONY: docker
docker:
	@echo $(dev_build_version) > VERSION
	docker build -t fullstorydev/grpcurl:$(dev_build_version) .
	@rm VERSION

.PHONY: checkgofmt
checkgofmt:
	gofmt -s -l .
	@if [ -n "$$(gofmt -s -l .)" ]; then \
		exit 1; \
	fi

.PHONY: vet
vet:
	go vet ./...

# This all works fine with Go modules, but without modules,
# CI is just getting latest master for dependencies like grpc.
.PHONY: staticcheck
staticcheck:
	@GO111MODULE=on go install honnef.co/go/tools/cmd/staticcheck
	staticcheck ./...

.PHONY: ineffassign
ineffassign:
	@GO111MODULE=on go install github.com/gordonklaus/ineffassign
	ineffassign .

.PHONY: predeclared
predeclared:
	@GO111MODULE=on go install github.com/nishanths/predeclared
	predeclared .

# Intentionally omitted from CI, but target here for ad-hoc reports.
.PHONY: golint
golint:
	@GO111MODULE=on go install golang.org/x/lint/golint
	golint -min_confidence 0.9 -set_exit_status ./...

# Intentionally omitted from CI, but target here for ad-hoc reports.
.PHONY: errcheck
errcheck:
	@GO111MODULE=on go install github.com/kisielk/errcheck
	errcheck ./...

.PHONY: test
test:
	go test -race ./...


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mycotaxon 9(1): 94 (1979)

#### Original name
Russula viridofusca Grund

### Remarks
null


text:
<?php

/**
 * Singleton Class
 *
 */
class AVH_EC_Singleton
{

	/**
	 *
	 * @param $class
	 * @param $arg1
	 */
	function &getInstance ($class, $arg1 = null)
	{
		static $instances = array(); // array of instance names
		if (array_key_exists($class, $instances)) {
			$instance = & $instances[$class];
		} else {
			if (! class_exists($class)) {
				switch ($class) {
					case 'AVH_EC_Core':
						require_once (AVHEC_ABSOLUTE_WORKING_DIR . '/class/avh-ec.core.php');
						break;
					case 'AVH_EC_Category_Group':
						require_once (AVHEC_ABSOLUTE_WORKING_DIR . '/class/avh-ec.category-group.php');
						break;
					case 'AVH_EC_Widget_Helper_Class':
						require_once (AVHEC_ABSOLUTE_WORKING_DIR . '/class/avh-ec.widget-helper.php');
						break;
				}
			}
			$instances[$class] = new $class($arg1);
			$instance = & $instances[$class];
		}
		return $instance;
	} // getInstance
} // singleton

/**
 * Include the necessary files
 *
 */
require_once (AVHEC_ABSOLUTE_WORKING_DIR . '/helpers/avh-forms.php');
require_once (AVHEC_ABSOLUTE_WORKING_DIR . '/class/avh-ec.widgets.php');

/**
 * Initialize the plugin
 *
 */
function avhextendedcategories_init ()
{
	// Admin
	if (is_admin()) {
		require_once (AVHEC_ABSOLUTE_WORKING_DIR . '/class/avh-ec.admin.php');
		$avhec_admin = new AVH_EC_Admin();
	}
	AVH_EC_Singleton::getInstance('AVH_EC_Core');

	add_action('widgets_init', 'avhextendedcategories_widgets_init');

} // End avhamazon_init()

/**
 * Register the widget
 *
 * @WordPress Action widgets_init
 * @since 3.0
 *
 */
function avhextendedcategories_widgets_init ()
{
	register_widget('WP_Widget_AVH_ExtendedCategories_Normal');
	register_widget('WP_Widget_AVH_ExtendedCategories_Top');
	register_widget('WP_Widget_AVH_ExtendedCategories_Category_Group');
}

add_action('plugins_loaded', 'avhextendedcategories_init');
?>


text:
package de.regis24.hackathlon.bam.agent;

import org.springframework.batch.core.BatchStatus;
import org.springframework.batch.core.ExitStatus;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobInstance;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.JobParametersInvalidException;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.core.explore.JobExplorer;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.launch.NoSuchJobException;
import org.springframework.batch.core.repository.JobExecutionAlreadyRunningException;
import org.springframework.batch.core.repository.JobInstanceAlreadyCompleteException;
import org.springframework.batch.core.repository.JobRestartException;
import org.springframework.batch.item.ExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;

import javax.batch.operations.JobOperator;

import lombok.Builder;
import lombok.Getter;

@RestController
@RequestMapping("/bam")
public class BamEndpoint {

  @Autowired(required = false)
  private List<Job> jobs = new ArrayList<>();
  @Autowired
  private BamJdbcDao bamJdbcDao;
  @Autowired
  private JobExplorer jobExplorer;
  @Autowired
  private JobLauncher jobLauncher;
  @Autowired
  private ApplicationContext ctx;

  @RequestMapping("stats")
  public Stats stats() {
    return Stats.builder()
        .numberOfExecutions(bamJdbcDao.getNumberOfExecutions())
        .numberOfProcessedItems(bamJdbcDao.getNumberOfItemsImported())
        .totalExecutedTime(bamJdbcDao.getTotalExecutionTime())
        .build();
  }

  @RequestMapping("jobs")
  public List<JobStats> jobStats() {
    return jobs.stream()
        .map(this::lastJobExecution)
        .filter(jobExecution -> jobExecution != null)
        .map(this::toJobStats)
        .collect(Collectors.toList());
  }

  @RequestMapping("job/{jobName}")
  public List<BamJobExecution> singleJob(@PathVariable("jobName") String jobName)
      throws NoSuchJobException {
    List<JobInstance> jobInstances = jobExplorer.getJobInstances(jobName, 0, 1);
    if (!CollectionUtils.isEmpty(jobInstances)) {
      List<JobExecution> executions = jobExplorer.getJobExecutions(jobInstances.get(0));
      return executions.stream().map(BamJobExecution::fromJobExecution)
          .collect(Collectors.toList());
    }
    return new ArrayList<>();
  }

  @RequestMapping("job/{jobName}/run")
  public void runJob(@PathVariable("jobName") String jobName){
	  Job job = (Job) ctx.getBean(jobName);
	  try {
		jobLauncher.run(job, new JobParametersBuilder().toJobParameters());
	} catch (Exception e) {
	}
  }

  private JobStats toJobStats(JobExecution jobExecution) {
    int skippedItems = 0;
    int writtenItems = 0;
    for (StepExecution stepExecution : jobExecution.getStepExecutions()) {
      skippedItems += stepExecution.getReadSkipCount()
                      + stepExecution.getProcessSkipCount()
                      + stepExecution.getWriteSkipCount();
      writtenItems += stepExecution.getWriteCount();
    }

    return JobStats.builder()
        .jobName(jobExecution.getJobInstance().getJobName())
        .numberOfSkippedItems(skippedItems)
        .numberOfWrittenItems(writtenItems)
        .resultOfLastExecution(jobExecution.getExitStatus().getExitCode())
        .build();
  }

  private JobExecution lastJobExecution(Job job) {
    List<JobInstance> jobInstances = jobExplorer.getJobInstances(job.getName(), 0, 1);
    if (!CollectionUtils.isEmpty(jobInstances)) {
      List<JobExecution> jobExecutions = jobExplorer.getJobExecutions(jobInstances.get(0));
      if (!CollectionUtils.isEmpty(jobExecutions)) {
        return jobExecutions.get(0);
      }
    }
    return null;
  }

  @Getter
  @Builder
  public static class Stats {

    private int numberOfExecutions;
    private int numberOfProcessedItems;
    private long totalExecutedTime;
  }

  @Getter
  @Builder
  public static class JobStats {

    String jobName;
    int numberOfWrittenItems;
    int numberOfSkippedItems;
    String resultOfLastExecution;
  }

  @Getter
  public static class BamJobExecution {

    public static final BamJobExecution fromJobExecution(JobExecution jobExecution) {
      BamJobExecution execution = new BamJobExecution();
      execution.jobParameters = jobExecution.getJobParameters();
      execution.jobInstance = jobExecution.getJobInstance();
      execution.status = jobExecution.getStatus();
      execution.startTime = jobExecution.getStartTime();
      execution.endTime = jobExecution.getEndTime();
      execution.lastUpdated = jobExecution.getLastUpdated();
      execution.exitStatus = jobExecution.getExitStatus();
      execution.executionContext = jobExecution.getExecutionContext();
      execution.failureExceptions = jobExecution.getFailureExceptions();
      execution.jobConfigurationName = jobExecution.getJobConfigurationName();
      execution.stepExecutions = jobExecution.getStepExecutions().stream()
          .map(BamStepExecution::fromStepExecution)
          .collect(Collectors.toSet());
      return execution;
    }

    private JobParameters jobParameters;
    private JobInstance jobInstance;
    private Collection<BamStepExecution> stepExecutions = new HashSet<>();
    private BatchStatus status = BatchStatus.STARTING;
    private Date startTime = null;
    private Date createTime = new Date(System.currentTimeMillis());
    private Date endTime = null;
    private Date lastUpdated = null;
    private ExitStatus exitStatus = ExitStatus.UNKNOWN;
    private ExecutionContext executionContext = new ExecutionContext();
    private List<Throwable> failureExceptions = new ArrayList<>();
    private String jobConfigurationName;
  }

  @Getter
  public static class BamStepExecution {

    public static final BamStepExecution fromStepExecution(StepExecution stepExecution) {
      BamStepExecution execution = new BamStepExecution();
      execution.stepName = stepExecution.getStepName();
      execution.status = stepExecution.getStatus();
      execution.readCount = stepExecution.getReadCount();
      execution.writeCount = stepExecution.getWriteCount();
      execution.commitCount = stepExecution.getCommitCount();
      execution.readSkipCount = stepExecution.getReadSkipCount();
      execution.rollbackCount = stepExecution.getRollbackCount();
      execution.processSkipCount = stepExecution.getProcessSkipCount();
      execution.writeSkipCount = stepExecution.getWriteSkipCount();
      execution.startTime = stepExecution.getStartTime();
      execution.endTime = stepExecution.getEndTime();
      execution.lastUpdated = stepExecution.getLastUpdated();
      execution.executionContext = stepExecution.getExecutionContext();
      execution.exitStatus = stepExecution.getExitStatus();
      execution.terminateOnly = stepExecution.isTerminateOnly();
      execution.filterCount = stepExecution.getFilterCount();
      execution.failureExceptions = stepExecution.getFailureExceptions();
      return execution;
    }

    private String stepName;

    private BatchStatus status = BatchStatus.STARTING;

    private int readCount = 0;

    private int writeCount = 0;

    private int commitCount = 0;

    private int rollbackCount = 0;

    private int readSkipCount = 0;

    private int processSkipCount = 0;

    private int writeSkipCount = 0;

    private Date startTime = new Date(System.currentTimeMillis());

    private Date endTime = null;

    private Date lastUpdated = null;

    private ExecutionContext executionContext = new ExecutionContext();

    private ExitStatus exitStatus = ExitStatus.EXECUTING;

    private boolean terminateOnly;

    private int filterCount;

    private List<Throwable> failureExceptions = new CopyOnWriteArrayList<Throwable>();
  }
}


text:
#ifndef _DATA_H_
#define _DATA_H_

#include <xcb/xcb.h>
#include <xcb/damage.h>

#define XTOQ_DAMAGE 0
#define XTOQ_EXPOSE 1
#define XTOQ_CREATE 2
#define XTOQ_DESTROY 3

typedef struct xtoq_context_t {
    xcb_connection_t *conn;
    xcb_drawable_t window;
    xcb_window_t parent;
    xcb_damage_damage_t damage;
    int x;
    int y;
    int width;
    int height;
    int damaged_x;
    int damaged_y;
    int damaged_width;
    int damaged_height;
	char *name;					/* The name of the window */
	int wm_delete_set;			/* Flag for WM_DELETE_WINDOW, 1 if set */
    void *local_data;   // Area for data client cares about
} xtoq_context_t;

typedef struct xtoq_event_t {
    xtoq_context_t *context;
    int event_type;
} xtoq_event_t;

typedef struct image_data_t {
    uint8_t *data;
    int length;
}  image_data_t;

typedef struct xtoq_image_t {
    xcb_image_t *image;
    int x;
    int y;
    int width;
    int height;
} xtoq_image_t;

typedef void (*xtoq_event_cb_t) (xtoq_event_t const *event);

extern int _damage_event;

#endif


text:
<?xml version="1.0" encoding="UTF-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout="@layout/preference_item_vertical">
    <PreferenceCategory
        android:layout="@layout/preference_category_widget"
        android:title="编辑信息">
        <Preference
            android:icon="@mipmap/ic_launcher"
            android:key="@string/preference_user_avatar"
            android:layout="@layout/preference_item_horizontal_icon"
            android:title="头像" />
        <EditTextPreference
            android:defaultValue=""
            android:key="@string/preference_screen_name"
            android:layout="@layout/preference_item_horizontal"
            android:title="用户名" />
        <org.sunger.net.ui.widget.RadioGroupPreference
            android:key="@string/preference_user_gender"
            android:layout="@layout/preference_item_horizontal"
            android:title="性别" />
        <EditTextPreference
            android:defaultValue=""
            android:key="@string/preference_user_description"
            android:layout="@layout/preference_item_vertical"
            android:title="个性签名" />
    </PreferenceCategory>
</PreferenceScreen>


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Composition;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Remote;
using Microsoft.CodeAnalysis.Text;

namespace Microsoft.CodeAnalysis.FindSymbols
{
    public static partial class SymbolFinder
    {
        [ExportRemoteServiceCallbackDispatcher(typeof(IRemoteSymbolFinderService)), Shared]
        internal sealed class CallbackDispatcher : RemoteServiceCallbackDispatcher, IRemoteSymbolFinderService.ICallback
        {
            [ImportingConstructor]
            [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
            public CallbackDispatcher()
            {
            }

            private FindLiteralsServerCallback GetFindLiteralsCallback(RemoteServiceCallbackId callbackId)
                => (FindLiteralsServerCallback)GetCallback(callbackId);

            private FindReferencesServerCallback GetFindReferencesCallback(RemoteServiceCallbackId callbackId)
                => (FindReferencesServerCallback)GetCallback(callbackId);

            // references

            public ValueTask AddReferenceItemsAsync(RemoteServiceCallbackId callbackId, int count, CancellationToken cancellationToken)
                => GetFindReferencesCallback(callbackId).AddItemsAsync(count, cancellationToken);

            public ValueTask ReferenceItemCompletedAsync(RemoteServiceCallbackId callbackId, CancellationToken cancellationToken)
                => GetFindReferencesCallback(callbackId).ItemCompletedAsync(cancellationToken);

            public ValueTask OnCompletedAsync(RemoteServiceCallbackId callbackId, CancellationToken cancellationToken)
                => GetFindReferencesCallback(callbackId).OnCompletedAsync(cancellationToken);

            public ValueTask OnDefinitionFoundAsync(RemoteServiceCallbackId callbackId, SerializableSymbolGroup symbolGroup, CancellationToken cancellationToken)
                => GetFindReferencesCallback(callbackId).OnDefinitionFoundAsync(symbolGroup, cancellationToken);

            public ValueTask OnFindInDocumentCompletedAsync(RemoteServiceCallbackId callbackId, DocumentId documentId, CancellationToken cancellationToken)
                => GetFindReferencesCallback(callbackId).OnFindInDocumentCompletedAsync(documentId, cancellationToken);

            public ValueTask OnFindInDocumentStartedAsync(RemoteServiceCallbackId callbackId, DocumentId documentId, CancellationToken cancellationToken)
                => GetFindReferencesCallback(callbackId).OnFindInDocumentStartedAsync(documentId, cancellationToken);

            public ValueTask OnReferenceFoundAsync(RemoteServiceCallbackId callbackId, SerializableSymbolGroup symbolGroup, SerializableSymbolAndProjectId definition, SerializableReferenceLocation reference, CancellationToken cancellationToken)
                => GetFindReferencesCallback(callbackId).OnReferenceFoundAsync(symbolGroup, definition, reference, cancellationToken);

            public ValueTask OnStartedAsync(RemoteServiceCallbackId callbackId, CancellationToken cancellationToken)
                => GetFindReferencesCallback(callbackId).OnStartedAsync(cancellationToken);

            // literals

            public ValueTask AddLiteralItemsAsync(RemoteServiceCallbackId callbackId, int count, CancellationToken cancellationToken)
                => GetFindLiteralsCallback(callbackId).AddItemsAsync(count, cancellationToken);

            public ValueTask LiteralItemCompletedAsync(RemoteServiceCallbackId callbackId, CancellationToken cancellationToken)
                => GetFindLiteralsCallback(callbackId).ItemCompletedAsync(cancellationToken);

            public ValueTask OnLiteralReferenceFoundAsync(RemoteServiceCallbackId callbackId, DocumentId documentId, TextSpan span, CancellationToken cancellationToken)
                => GetFindLiteralsCallback(callbackId).OnLiteralReferenceFoundAsync(documentId, span, cancellationToken);
        }
    }
}


text:
package org.locationtech.geomesa.plugin.ui

import com.typesafe.scalalogging.slf4j.Logging
import org.apache.wicket.ajax.AjaxRequestTarget
import org.apache.wicket.ajax.markup.html.AjaxLink
import org.apache.wicket.ajax.markup.html.form.AjaxSubmitLink
import org.apache.wicket.behavior.AttributeAppender
import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow
import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow.WindowClosedCallback
import org.apache.wicket.markup.html.basic.Label
import org.apache.wicket.markup.html.form.{CheckBox, Form}
import org.apache.wicket.markup.html.image.Image
import org.apache.wicket.markup.html.link.BookmarkablePageLink
import org.apache.wicket.markup.html.list.{ListItem, ListView}
import org.apache.wicket.markup.html.panel.Fragment
import org.apache.wicket.model.{Model, PropertyModel}
import org.apache.wicket.{AttributeModifier, PageParameters, ResourceReference}
import org.geoserver.web.GeoServerBasePage
import org.geotools.feature.simple.SimpleFeatureTypeBuilder
import org.locationtech.geomesa.core.data.AccumuloDataStore
import org.locationtech.geomesa.jobs.index.AttributeIndexJob
import org.locationtech.geomesa.utils.geotools.SimpleFeatureTypes
import org.locationtech.geomesa.utils.stats.IndexCoverage

import scala.collection.JavaConversions._
import scala.collection.JavaConverters._
import scala.util.{Failure, Success, Try}

class GeoMesaFeaturePage(parameters: PageParameters) extends GeoMesaBasePage with Logging {

  import org.locationtech.geomesa.plugin.ui.GeoMesaFeaturePage._

  val featureName = parameters.getString(FEATURE_NAME_PARAM)
  val workspaceName = parameters.getString(WORKSPACE_PARAM)
  val dataStoreName = parameters.getString(DATASTORE_PARAM)

  // check that link parameters give us a valid datastore/feature
  def loadStore() =
    for {
      dataStoreInfo <- Try(getCatalog.getDataStoreByName(workspaceName, dataStoreName))
      dataStore <- Try(dataStoreInfo.getDataStore(null).asInstanceOf[AccumuloDataStore])
      sft = dataStore.getSchema(featureName)
      if (sft != null)
    } yield {
      (dataStore, sft)
    }

  loadStore() match {
    case Success((dataStore, sft)) => initUi(dataStore, SimpleFeatureTypes.encodeType(sft))
    case Failure(e) =>
      error(s"Error: could not find feature '$featureName' in data store " +
            s"'$dataStoreName' in workspace '$workspaceName'.")
      setResponsePage(classOf[GeoMesaDataStoresPage])
  }

  def initUi(dataStore: AccumuloDataStore, spec: String) = {
    import org.locationtech.geomesa.utils.geotools.SimpleFeatureTypes._
    val FeatureSpec(attributes, _) = SimpleFeatureTypes.parse(spec)

    // create a copy of the original attributes since the original gets modified by wicket
    val copy = attributes.map { a => a.copy() }

    // modal form for uploading an xml config
    val modalWindow = new ModalWindow("modalConfirm")
    // modal loading dialog
    val modalWaiting = new ModalWindow("modalWaiting")

    val form = new Form("form") {
      // each row in the form is an attribute with a checkbox indicating if it is indexed
      val listView = new ListView[AttributeSpec]("attributes", attributes.toList.asJava) {
        override def populateItem(item: ListItem[AttributeSpec]) = {
          val attribute = item.getModel.getObject
          item.add(new Label("name", attribute.name))
          item.add(new Label("type", attribute.clazz.getSimpleName))
          val checkbox = new CheckBox("indexed")
          attribute match {
            case a: GeomAttributeSpec =>
              // geometry attributes can't be indexed except the default one
              checkbox.setModel(Model.of(a.default))
              checkbox.setEnabled(false)
              val title = "Geometry properties can not indexed on demand"
              checkbox.add(new AttributeModifier("title", true, Model.of(title)))
            case a: NonGeomAttributeSpec =>
              checkbox.setModel(new PropertyModel(attribute, "index"))
          }
          item.add(checkbox)
          // add css to stripe the rows
          val css = if (item.getIndex % 2 == 0) "even" else "odd"
          item.add(new AttributeAppender("class", new Model(css), " "))
        }
      }

      add(listView)

      // cancel form button
      /*_*/add(new BookmarkablePageLink("cancel", classOf[GeoMesaDataStoresPage]))/*_*/

      // link to open the confirmation dialog
      add(new AjaxLink("save") {
        override def onClick(target: AjaxRequestTarget) = {
          modalWindow.show(target)
        }
      })
    }

    add(form)

    val loadingContainer = new Fragment(modalWaiting.getContentId, "waitingFragment", this)
    loadingContainer
      .add(new Image("loading", new ResourceReference(classOf[GeoServerBasePage], "img/ajax-loader.gif")))

    modalWaiting.setContent(loadingContainer)
    modalWaiting.setResizable(false)
    // have to specify explicit heights - these were calculated from the css
    modalWaiting.setInitialWidth(200)
    modalWaiting.setInitialHeight(85)
    modalWaiting.setTitle("Please Wait...")

    add(modalWaiting)

    val confirmContainer = new Fragment(modalWindow.getContentId, "confirmFragment", this)
    confirmContainer.add(new Label("confirmLabel", "Indexing attributes may take a while. Continue?"))

    // submit link
    confirmContainer.add(new AjaxSubmitLink("confirm", form) {
      // need to trigger the close of the window with js, otherwise it won't close until request returns
      add(new AttributeModifier("onclick", true, Model.of("Wicket.Window.get().close();")) {
        override def newValue(currentValue: String, newValue: String): String = newValue + currentValue
      })
      protected def onSubmit(target: AjaxRequestTarget, form: Form[_]) {
        // pull out any changes
        val changed = attributes.zip(copy)
                      .filter { case (a, c) => a != c }
                      .map { case (a, _) => a }
        if (!changed.isEmpty) {
          val (ds, sft) = loadStore().get
          val added = changed.filter(_.index != IndexCoverage.NONE).map(_.name)
          val run =
            if (added.isEmpty) {
              Success(true)
            } else {
              val params = getCatalog.getDataStoreByName(workspaceName, dataStoreName)
                             .getConnectionParameters
                             .asScala
                             .toMap[String, java.io.Serializable]
                             .asInstanceOf[Map[String, String]]
              val conf = GeoMesaBasePage.getHdfsConfiguration
              Try(AttributeIndexJob.runJob(conf, params, sft.getTypeName, added))
            }

          run match {
            case Success(_) =>
              // if the job was successful, update the schema stored in the metadata
              val sftb = new SimpleFeatureTypeBuilder()
              sftb.setName(sft.getTypeName)
              sftb.addAll(attributes.map(_.toAttribute))
              val newSFT = sftb.buildFeatureType()
              ds.updateIndexedAttributes(sft.getTypeName, SimpleFeatureTypes.encodeType(newSFT))
            case Failure(e) =>
              // set error message in page for user to see
              getSession().error(s"Failed to index attributes: ${e.getMessage}")
          }
        }
        setResponsePage(new GeoMesaFeaturePage(parameters))
      }
    })
    confirmContainer.add(new AjaxLink("cancel") {
      override def onClick(target: AjaxRequestTarget) =
        setResponsePage(new GeoMesaFeaturePage(parameters))
    })
    modalWindow.setContent(confirmContainer)
    modalWindow.setResizable(false)
    // have to specify explicit heights - these were calculated from the css
    modalWindow.setInitialWidth(350)
    modalWindow.setInitialHeight(85)
    modalWindow.setTitle("Confirm Attribute Indexing Changes")
    modalWindow.setWindowClosedCallback(new WindowClosedCallback() {
      override def onClose(target: AjaxRequestTarget) = modalWaiting.show(target)
    })

    add(modalWindow)
  }
}

object GeoMesaFeaturePage {
  val FEATURE_NAME_PARAM = "feature"
  val DATASTORE_PARAM = "store"
  val WORKSPACE_PARAM = "workspace"
}


text:
define( [ 'angular', '../module' ], function( ng ) {
  'use strict';

  ng
  .module( 'auth.controllers' )
  .controller( 'UsersListController', function( $scope, Helpers, dateFilter ) {
    $scope.helpers          = Helpers;
    $scope.welcome          = 'This page lists all of the Users available in your account, you can add as many as you want';
    $scope.actionsTemplate  = '/modules/auth/views/users/table_actions.html';

    $scope.columns = [
      {
        name:       'firstname',
        title:      'First Name',
        filter:     false,
        glyph:      'user'
      },
      {
        name:       'lastname',
        title:      'Last Name',
        filter:     false,
        glyph:      'user'
      },
      {
        name:       'email',
        title:      'Email',
        filter:     false,
        glyph:      'envelope'
      },
      {
        name:       'accessedAt',
        title:      'Last Login',
        filter:     false,
        display:     function( val ) {
          if ( val ) {
            return dateFilter( val, 'short' );
          }
          return 'Never';
        }
      },
      {
        name:       'createdAt',
        title:      'Date Registered',
        filter:     false,
        glyph:      'calendar',
        width:      100,
        display: function( val ) {
          return dateFilter( val, 'short' );
        }
      }
    ];

  });
});


text:
package interfaz;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.io.Serializable;
import java.util.ArrayList;

import javax.swing.DefaultListCellRenderer;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import logica.Autor;
import logica.Genero;

public class PanelArtista extends JPanel implements ListSelectionListener{

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;
	private JList<String> jList;
	private DefaultListModel<String > defaultListModel;
	private JScrollPane jScrollPaneS;
	private ArrayList<Genero> generos;
	private PanelCancion panelCancion;
	private PanelGeneros panelGeneros;
	private JPanel pnlContenedor;
	private Font fuenteLista;
	private ImageIcon imagenfondo;
	private ListaArtistasImagen lista;

	public PanelArtista(ArrayList<Genero> generos, PanelCancion panelCancion) {

		setPreferredSize(new Dimension(333, getHeight()));
		setLayout(new GridLayout());
		setBackground(new Color (0.0f,0.0f,0.0f,0.3f));
		setOpaque(false);

		fuenteLista = new Font("Swis721 BlkEx BT", Font.PLAIN, 15);

		pnlContenedor = new JPanel();
		pnlContenedor.setLayout(new BorderLayout());
		pnlContenedor.setBackground(Color.WHITE);
		pnlContenedor.setOpaque(false);

		defaultListModel = new DefaultListModel<>();
		jList = new JList<>(defaultListModel);
		jList.setFont(fuenteLista);
		jList.setForeground(Color.WHITE);
		jList.setOpaque(false);
		jList.setBackground(new Color(0.0f,0.0f,0.0f,0.0f));
		jScrollPaneS = new JScrollPane(jList);
		DefaultListCellRenderer renderer =  (DefaultListCellRenderer)jList.getCellRenderer();
		renderer.setHorizontalAlignment(JLabel.CENTER);
		jScrollPaneS.setOpaque(false);
		jScrollPaneS.getViewport().setOpaque(false);
		jScrollPaneS.setBorder(null);
		jScrollPaneS.getViewport().setBackground (new Color (0.0f,0.0f,0.0f,0.0f));
		pnlContenedor.add(jScrollPaneS,BorderLayout.CENTER);

		this.panelCancion = panelCancion;
		this.generos = generos;

		add(pnlContenedor);
		jList.addListSelectionListener(this);
		jList.setCursor(new Cursor(Cursor.HAND_CURSOR));

	}

	public void imagenListas(ArrayList<Autor> autor) {
		if (!autor.isEmpty()) {
			lista = new ListaArtistasImagen(autor);
			this.jList.setCellRenderer(lista);
		}
	}

	public PanelGeneros getPanelGeneros() {
		return panelGeneros;
	}

	public void setPanelGeneros(PanelGeneros panelGeneros) {
		this.panelGeneros = panelGeneros;
	}

	public void actualizarListaEliminada() {
		defaultListModel.removeAllElements();
	}

	public void actualizarLista(ArrayList<Autor> listaActulizada) {
		defaultListModel.removeAllElements();
		for (Autor autores : listaActulizada) {
			defaultListModel.addElement(autores.getNombre());
		}
		jList.setModel(defaultListModel);
	}

	@Override
	public void valueChanged(ListSelectionEvent e) {
		if (e.getSource() == jList) {
			if (jList.getSelectedIndex() >= 0) {
				panelCancion.actualizarLista(generos.get(panelGeneros.getIndiceGenero()).getListaAutores().get(jList.getSelectedIndex()).getListaCanciones());
			}
		}
	}
	@Override
	public void paint(Graphics g) {
		Dimension tamanio = getSize();
		imagenfondo = new ImageIcon(getClass().getResource("/Img/Centro.png"));
		g.drawImage(imagenfondo.getImage(),0,0,tamanio.width,tamanio.height, null);
		super.paint(g);
	}

}


text:
package guest

import (
	"errors"
	"flag"

	"net/url"

	"github.com/vmware/govmomi/govc/flags"
	"github.com/vmware/govmomi/guest"
	"github.com/vmware/govmomi/object"
	"golang.org/x/net/context"
)

type GuestFlag struct {
	*flags.ClientFlag
	*flags.VirtualMachineFlag

	*AuthFlag
}

func (flag *GuestFlag) Register(f *flag.FlagSet) {}

func (flag *GuestFlag) Process() error { return nil }

func (flag *GuestFlag) FileManager() (*guest.FileManager, error) {
	c, err := flag.Client()
	if err != nil {
		return nil, err
	}

	vm, err := flag.VirtualMachine()
	if err != nil {
		return nil, err
	}

	o := guest.NewOperationsManager(c, vm.Reference())
	return o.FileManager(context.TODO())
}

func (flag *GuestFlag) ProcessManager() (*guest.ProcessManager, error) {
	c, err := flag.Client()
	if err != nil {
		return nil, err
	}

	vm, err := flag.VirtualMachine()
	if err != nil {
		return nil, err
	}

	o := guest.NewOperationsManager(c, vm.Reference())
	return o.ProcessManager(context.TODO())
}

func (flag *GuestFlag) ParseURL(urlStr string) (*url.URL, error) {
	c, err := flag.Client()
	if err != nil {
		return nil, err
	}

	return c.Client.ParseURL(urlStr)
}

func (flag *GuestFlag) VirtualMachine() (*object.VirtualMachine, error) {
	vm, err := flag.VirtualMachineFlag.VirtualMachine()
	if err != nil {
		return nil, err
	}
	if vm == nil {
		return nil, errors.New("no vm specified")
	}
	return vm, nil
}


text:
package com.netflix.exhibitor.core.config.swift;

import com.netflix.exhibitor.core.config.ConfigCollection;
import com.netflix.exhibitor.core.config.ConfigProvider;
import com.netflix.exhibitor.core.config.LoadedInstanceConfig;
import com.netflix.exhibitor.core.config.PropertyBasedInstanceConfig;
import com.netflix.exhibitor.core.config.PseudoLock;

import org.jclouds.io.Payload;
import org.jclouds.io.payloads.ByteArrayPayload;
import org.jclouds.openstack.swift.v1.SwiftApi;
import org.jclouds.openstack.swift.v1.domain.SwiftObject;
import org.jclouds.openstack.swift.v1.features.ContainerApi;
import org.jclouds.openstack.swift.v1.features.ObjectApi;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Properties;

public class SwiftConfigProvider implements ConfigProvider
{
	private final SwiftApi  swiftApi;
	private final String hostname;
	private final SwiftConfigArguments arguments;
	private final ObjectApi objectApi;
	private final Properties defaults;

	/**
	 *
	 * @param swiftApi SwiftApi
	 * @param arguments args
	 * @param hostname this VM's hostname
	 * @param defaults default props
	 * @throws Exception
	 */
    public SwiftConfigProvider(SwiftApi  swiftApi, SwiftConfigArguments arguments,String hostname, Properties defaults) throws Exception
    {
    	this.swiftApi = swiftApi;
    	this.hostname = hostname;
		this.arguments = arguments;
        this.objectApi = initialize(arguments.getContainerName());
        this.defaults = defaults;
    }

    private ObjectApi initialize (String containerName)
    {
		String region = swiftApi.getConfiguredRegions().iterator().next();

		ContainerApi containerApi = swiftApi.getContainerApi(region);
		if (containerApi.get(containerName) ==null)
			containerApi.create(containerName);

	    return swiftApi.getObjectApi(region, containerName);

    }

    @Override
    public void start() throws Exception
    {
        // NOP
    }

    @Override
    public void close() throws IOException
    {

		swiftApi.close();
    }

    @Override
    public PseudoLock newPseudoLock() throws Exception
    {
        return new SwiftPseudoLock
        (
        	objectApi,
            arguments.getLockArguments().getPrefix(),
            arguments.getLockArguments().getTimeoutMs(),
            arguments.getLockArguments().getPollingMs(),
            arguments.getLockArguments().getSettlingMs()
        );
    }

    @Override
    public LoadedInstanceConfig loadConfig() throws Exception
    {
        Date        lastModified;
        Properties  properties = new Properties();
        SwiftObject obj= objectApi.get(this.arguments.getKey());

        if (obj !=null)
        {
            lastModified = obj.getLastModified();

        	InputStream is = null;
        	try{
		    	is =  obj.getPayload().openStream();
		        properties.load(is);
		    	is.close();
        	}finally{
        		if (is !=null)
        			is.close();
        	}
        }
        else
        {
            lastModified = new Date(0L);
        }

        PropertyBasedInstanceConfig config = new PropertyBasedInstanceConfig(properties, defaults);
        return new LoadedInstanceConfig(config, lastModified.getTime());
    }

    @Override
    public LoadedInstanceConfig storeConfig(ConfigCollection config, long compareVersion) throws Exception
    {
        SwiftObject obj= objectApi.get(arguments.getKey());
        if ( obj!=null && obj.getLastModified().getTime() != compareVersion )
        {
        	return null;
        }

        PropertyBasedInstanceConfig     propertyBasedInstanceConfig = new PropertyBasedInstanceConfig(config);
        ByteArrayOutputStream           out = new ByteArrayOutputStream();
        propertyBasedInstanceConfig.getProperties().store(out, "Auto-generated by Exhibitor " + hostname);

        byte[]                          bytes = out.toByteArray();
	    Payload payload =  new ByteArrayPayload(bytes);
    	objectApi.put(arguments.getKey(), payload);
    	if (obj == null)
    	{
    		obj = objectApi.get(arguments.getKey());
    	}

        return new LoadedInstanceConfig(propertyBasedInstanceConfig, obj.getLastModified().getTime());
    }

}


text:
import json
import random

with open('__mock_btax_result.json') as f:
    data = f.read()
    data = json.loads(data)

cats = ['Major Grouping 1',
        'Major Grouping 2',
        'Major Grouping 3',
        'Major Grouping 4',
        'Major Grouping 5',
        'Major Grouping 6']

for h in list(data.keys()):
    if h.startswith('asset') or h.startswith('industry'):
        for i in list(data[h].keys()):
            for j in data[h][i]['rows']:
                j['major_grouping'] = random.choice(cats)
                j['summary_c'] = -999
                j['summary_nc'] = -999

with open('mock_btax_result.json', 'w') as f:
    f.write(json.dumps(data))


text:
A demo app that shows how to use the ExoPlayer [VP9](../../extensions/vp9) and [Opus](../../extensions/opus) Extensions to enable VP9 and Opus playback in your app by bundling native libraries along with it.

The demo app depends on the VP9 and Opus Extensions being configured built correctly.


text:
package org.springframework.boot.actuate.autoconfigure.web.server;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import org.springframework.beans.factory.annotation.Value;

/**
 * Annotation at the field or method/constructor parameter level that injects the HTTP
 * management port that got allocated at runtime. Provides a convenient alternative for
 * <code>@Value("${local.management.port}")</code>.
 *
 * @author Stephane Nicoll
 * @since 2.0.0
 */
@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Value("${local.management.port}")
public @interface LocalManagementPort {

}


text:
<?php
require_once('CreateDocument.php');

echo "Now trying to update the created document...\n";

if ($document !== null) {
    $document = $session->getObject($document);
    $properties = [\Dkd\PhpCmis\PropertyIds::DESCRIPTION => 'Updated on ' . time()];
    $document->updateProperties($properties, true);

    echo "The generated document has now been updated and the property " . \Dkd\PhpCmis\PropertyIds::DESCRIPTION
            . " should now has the value '" . $properties[\Dkd\PhpCmis\PropertyIds::DESCRIPTION]. "'.\n";
    echo "Please delete that document now by hand!\n";
} else {
    exit("Document has not been created and therefore could not be updated!\n");
}


text:
package mono.com.tencent.tencentmap.mapsdk.map;

public class TencentMap_OnMapClickListenerImplementor
	extends java.lang.Object
	implements
		mono.android.IGCUserPeer,
		com.tencent.tencentmap.mapsdk.map.TencentMap.OnMapClickListener
{
	static final String __md_methods;
	static {
		__md_methods =
			"n_onMapClick:(Lcom/tencent/mapsdk/raster/model/LatLng;)V:GetOnMapClick_Lcom_tencent_mapsdk_raster_model_LatLng_Handler:Com.Tencent.Tencentmap.Mapsdk.Map.TencentMap/IOnMapClickListenerInvoker, TencentMapBinding\n" +
			"";
		mono.android.Runtime.register ("Com.Tencent.Tencentmap.Mapsdk.Map.TencentMap/IOnMapClickListenerImplementor, TencentMapBinding, Version=0.1.0.0, Culture=neutral, PublicKeyToken=null", TencentMap_OnMapClickListenerImplementor.class, __md_methods);
	}

	public TencentMap_OnMapClickListenerImplementor () throws java.lang.Throwable
	{
		super ();
		if (getClass () == TencentMap_OnMapClickListenerImplementor.class)
			mono.android.TypeManager.Activate ("Com.Tencent.Tencentmap.Mapsdk.Map.TencentMap/IOnMapClickListenerImplementor, TencentMapBinding, Version=0.1.0.0, Culture=neutral, PublicKeyToken=null", "", this, new java.lang.Object[] {  });
	}

	public void onMapClick (com.tencent.mapsdk.raster.model.LatLng p0)
	{
		n_onMapClick (p0);
	}

	private native void n_onMapClick (com.tencent.mapsdk.raster.model.LatLng p0);

	java.util.ArrayList refList;
	public void monodroidAddReference (java.lang.Object obj)
	{
		if (refList == null)
			refList = new java.util.ArrayList ();
		refList.add (obj);
	}

	public void monodroidClearReferences ()
	{
		if (refList != null)
			refList.clear ();
	}
}


text:
class CreateTutorialGroups < ActiveRecord::Migration
  def change
    create_table :tutorial_groups do |t|
      t.integer :course_id
      t.integer :std_course_id
      t.integer :tut_course_id

      t.timestamps
    end
    add_index :tutorial_groups, [:std_course_id, :tut_course_id],unique: true
  end
end