text:
package org.onosproject.store.trivial;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.onosproject.net.DeviceId.deviceId;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.onlab.packet.MacAddress;
import org.onlab.packet.MplsLabel;
import org.onosproject.core.ApplicationId;
import org.onosproject.core.DefaultApplicationId;
import org.onosproject.core.GroupId;
import org.onosproject.net.DeviceId;
import org.onosproject.net.PortNumber;
import org.onosproject.net.flow.DefaultTrafficTreatment;
import org.onosproject.net.flow.TrafficTreatment;
import org.onosproject.net.group.DefaultGroup;
import org.onosproject.net.group.DefaultGroupBucket;
import org.onosproject.net.group.DefaultGroupDescription;
import org.onosproject.net.group.DefaultGroupKey;
import org.onosproject.net.group.Group;
import org.onosproject.net.group.GroupBucket;
import org.onosproject.net.group.GroupBuckets;
import org.onosproject.net.group.GroupDescription;
import org.onosproject.net.group.GroupEvent;
import org.onosproject.net.group.GroupKey;
import org.onosproject.net.group.GroupOperation;
import org.onosproject.net.group.GroupStore.UpdateType;
import org.onosproject.net.group.GroupStoreDelegate;
import org.onosproject.net.group.StoredGroupBucketEntry;
import org.onosproject.net.group.StoredGroupEntry;

import com.google.common.collect.Iterables;

/**
 * Test of the simple DeviceStore implementation.
 */
public class SimpleGroupStoreTest {

    private SimpleGroupStore simpleGroupStore;
    private final ApplicationId appId =
            new DefaultApplicationId(2, "org.groupstore.test");

    public static final DeviceId D1 = deviceId("of:1");

    @Before
    public void setUp() throws Exception {
        simpleGroupStore = new SimpleGroupStore();
        simpleGroupStore.activate();
    }

    @After
    public void tearDown() throws Exception {
        simpleGroupStore.deactivate();
    }

    private class InternalGroupStoreDelegate
                implements GroupStoreDelegate {
        private GroupId createdGroupId = null;
        private GroupKey createdGroupKey;
        private GroupBuckets createdBuckets;
        private GroupEvent.Type expectedEvent;

        public InternalGroupStoreDelegate(GroupKey key,
                                          GroupBuckets buckets,
                                          GroupEvent.Type expectedEvent) {
            this.createdBuckets = buckets;
            this.createdGroupKey = key;
            this.expectedEvent = expectedEvent;
        }
        @Override
        public void notify(GroupEvent event) {
            assertEquals(expectedEvent, event.type());
            assertEquals(Group.Type.SELECT, event.subject().type());
            assertEquals(D1, event.subject().deviceId());
            assertEquals(createdGroupKey, event.subject().appCookie());
            assertEquals(createdBuckets.buckets(), event.subject().buckets().buckets());
            if (expectedEvent == GroupEvent.Type.GROUP_ADD_REQUESTED) {
                createdGroupId = event.subject().id();
                assertEquals(Group.GroupState.PENDING_ADD,
                             event.subject().state());
            } else if (expectedEvent == GroupEvent.Type.GROUP_ADDED) {
                createdGroupId = event.subject().id();
                assertEquals(Group.GroupState.ADDED,
                             event.subject().state());
            } else if (expectedEvent == GroupEvent.Type.GROUP_UPDATED) {
                createdGroupId = event.subject().id();
                assertEquals(true,
                             event.subject().buckets().
                             buckets().containsAll(createdBuckets.buckets()));
                assertEquals(true,
                             createdBuckets.buckets().
                             containsAll(event.subject().buckets().buckets()));
                for (GroupBucket bucket:event.subject().buckets().buckets()) {
                    Optional<GroupBucket> matched = createdBuckets.buckets()
                            .stream()
                            .filter((expected) -> expected.equals(bucket))
                            .findFirst();
                    assertEquals(matched.get().packets(),
                                 bucket.packets());
                    assertEquals(matched.get().bytes(),
                                 bucket.bytes());
                }
                assertEquals(Group.GroupState.ADDED,
                             event.subject().state());
            } else if (expectedEvent == GroupEvent.Type.GROUP_UPDATE_REQUESTED) {
                assertEquals(Group.GroupState.PENDING_UPDATE,
                             event.subject().state());
                for (GroupBucket bucket:event.subject().buckets().buckets()) {
                    Optional<GroupBucket> matched = createdBuckets.buckets()
                            .stream()
                            .filter((expected) -> expected.equals(bucket))
                            .findFirst();
                    assertEquals(matched.get().weight(),
                            bucket.weight());
                    assertEquals(matched.get().watchGroup(),
                            bucket.watchGroup());
                    assertEquals(matched.get().watchPort(),
                            bucket.watchPort());
                }
            } else if (expectedEvent == GroupEvent.Type.GROUP_REMOVE_REQUESTED) {
                assertEquals(Group.GroupState.PENDING_DELETE,
                             event.subject().state());
            } else if (expectedEvent == GroupEvent.Type.GROUP_REMOVED) {
                createdGroupId = event.subject().id();
                assertEquals(Group.GroupState.PENDING_DELETE,
                             event.subject().state());
            } else if (expectedEvent == GroupEvent.Type.GROUP_ADD_FAILED) {
                createdGroupId = event.subject().id();
                assertEquals(Group.GroupState.PENDING_ADD,
                        event.subject().state());
            } else if (expectedEvent == GroupEvent.Type.GROUP_UPDATE_FAILED) {
                createdGroupId = event.subject().id();
                assertEquals(Group.GroupState.PENDING_UPDATE,
                        event.subject().state());
            } else if (expectedEvent == GroupEvent.Type.GROUP_REMOVE_FAILED) {
                createdGroupId = event.subject().id();
                assertEquals(Group.GroupState.PENDING_DELETE,
                        event.subject().state());
            }
        }

        public void verifyGroupId(GroupId id) {
            assertEquals(createdGroupId, id);
        }
    }

    /**
     * Tests group store operations. The following operations are tested:
     * a)Tests device group audit completion status change
     * b)Tests storeGroup operation
     * c)Tests getGroupCount operation
     * d)Tests getGroup operation
     * e)Tests getGroups operation
     * f)Tests addOrUpdateGroupEntry operation from southbound
     * g)Tests updateGroupDescription for ADD operation from northbound
     * h)Tests updateGroupDescription for REMOVE operation from northbound
     * i)Tests deleteGroupDescription operation from northbound
     * j)Tests removeGroupEntry operation from southbound
     */
    @Test
    public void testGroupStoreOperations() {
        // Set the Device AUDIT completed in the store
        simpleGroupStore.deviceInitialAuditCompleted(D1, true);

        // Testing storeGroup operation
        GroupKey newKey = new DefaultGroupKey("group1".getBytes());
        testStoreAndGetGroup(newKey);

        // Testing addOrUpdateGroupEntry operation from southbound
        GroupKey currKey = newKey;
        testAddGroupEntryFromSB(currKey);

        // Testing updateGroupDescription for ADD operation from northbound
        newKey = new DefaultGroupKey("group1AddBuckets".getBytes());
        testAddBuckets(currKey, newKey);

        // Testing updateGroupDescription for REMOVE operation from northbound
        currKey = newKey;
        newKey = new DefaultGroupKey("group1RemoveBuckets".getBytes());
        testRemoveBuckets(currKey, newKey);

        // Testing addOrUpdateGroupEntry operation from southbound
        currKey = newKey;
        testUpdateGroupEntryFromSB(currKey);

        // Testing deleteGroupDescription operation from northbound
        testDeleteGroup(currKey);

        // Testing removeGroupEntry operation from southbound
        testRemoveGroupFromSB(currKey);

        // Testing removing all groups on the given device by deviceid
        newKey = new DefaultGroupKey("group1".getBytes());
        testStoreAndGetGroup(newKey);
        testDeleteGroupOnDevice(newKey);

        // Testing removing all groups on the given device
        newKey = new DefaultGroupKey("group1".getBytes());
        testStoreAndGetGroup(newKey);
        testPurgeGroupEntries();
    }

    // Testing storeGroup operation
    private void testStoreAndGetGroup(GroupKey key) {
        PortNumber[] ports = {PortNumber.portNumber(31),
                              PortNumber.portNumber(32)};
        List<PortNumber> outPorts = new ArrayList<>();
        outPorts.addAll(Arrays.asList(ports));

        List<GroupBucket> buckets = new ArrayList<>();
        for (PortNumber portNumber: outPorts) {
            TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
            tBuilder.setOutput(portNumber)
                    .setEthDst(MacAddress.valueOf("00:00:00:00:00:02"))
                    .setEthSrc(MacAddress.valueOf("00:00:00:00:00:01"))
                    .pushMpls()
                    .setMpls(MplsLabel.mplsLabel(106));
            buckets.add(DefaultGroupBucket.createSelectGroupBucket(
                                                        tBuilder.build()));
        }
        GroupBuckets groupBuckets = new GroupBuckets(buckets);
        GroupDescription groupDesc = new DefaultGroupDescription(
                                                 D1,
                                                 Group.Type.SELECT,
                                                 groupBuckets,
                                                 key,
                                                 null,
                                                 appId);
        InternalGroupStoreDelegate checkStoreGroupDelegate =
                new InternalGroupStoreDelegate(key,
                                               groupBuckets,
                                               GroupEvent.Type.GROUP_ADD_REQUESTED);
        simpleGroupStore.setDelegate(checkStoreGroupDelegate);
        // Testing storeGroup operation
        simpleGroupStore.storeGroupDescription(groupDesc);

        // Testing getGroupCount operation
        assertEquals(1, simpleGroupStore.getGroupCount(D1));

        // Testing getGroup operation
        Group createdGroup = simpleGroupStore.getGroup(D1, key);
        checkStoreGroupDelegate.verifyGroupId(createdGroup.id());

        // Testing getGroups operation
        Iterable<Group> createdGroups = simpleGroupStore.getGroups(D1);
        int groupCount = 0;
        for (Group group:createdGroups) {
            checkStoreGroupDelegate.verifyGroupId(group.id());
            groupCount++;
        }
        assertEquals(1, groupCount);
        simpleGroupStore.unsetDelegate(checkStoreGroupDelegate);
    }

    // Testing addOrUpdateGroupEntry operation from southbound
    private void testAddGroupEntryFromSB(GroupKey currKey) {
        Group existingGroup = simpleGroupStore.getGroup(D1, currKey);

        InternalGroupStoreDelegate addGroupEntryDelegate =
                new InternalGroupStoreDelegate(currKey,
                                               existingGroup.buckets(),
                                               GroupEvent.Type.GROUP_ADDED);
        simpleGroupStore.setDelegate(addGroupEntryDelegate);
        simpleGroupStore.addOrUpdateGroupEntry(existingGroup);
        simpleGroupStore.unsetDelegate(addGroupEntryDelegate);
    }

    // Testing addOrUpdateGroupEntry operation from southbound
    private void testUpdateGroupEntryFromSB(GroupKey currKey) {
        Group existingGroup = simpleGroupStore.getGroup(D1, currKey);
        int totalPkts = 0;
        int totalBytes = 0;
        List<GroupBucket> newBucketList = new ArrayList<>();
        for (GroupBucket bucket:existingGroup.buckets().buckets()) {
            StoredGroupBucketEntry newBucket =
                    (StoredGroupBucketEntry)
                    DefaultGroupBucket.createSelectGroupBucket(bucket.treatment());
            newBucket.setPackets(10);
            newBucket.setBytes(10 * 256 * 8);
            totalPkts += 10;
            totalBytes += 10 * 256 * 8;
            newBucketList.add(newBucket);
        }
        GroupBuckets updatedBuckets = new GroupBuckets(newBucketList);
        Group updatedGroup = new DefaultGroup(existingGroup.id(),
                                              existingGroup.deviceId(),
                                              existingGroup.type(),
                                              updatedBuckets);
        ((StoredGroupEntry) updatedGroup).setPackets(totalPkts);
        ((StoredGroupEntry) updatedGroup).setBytes(totalBytes);

        InternalGroupStoreDelegate updateGroupEntryDelegate =
                new InternalGroupStoreDelegate(currKey,
                                               updatedBuckets,
                                               GroupEvent.Type.GROUP_UPDATED);
        simpleGroupStore.setDelegate(updateGroupEntryDelegate);
        simpleGroupStore.addOrUpdateGroupEntry(updatedGroup);
        simpleGroupStore.unsetDelegate(updateGroupEntryDelegate);
    }

    // Testing updateGroupDescription for ADD operation from northbound
    private void testAddBuckets(GroupKey currKey, GroupKey addKey) {
        Group existingGroup = simpleGroupStore.getGroup(D1, currKey);
        List<GroupBucket> buckets = new ArrayList<>();
        buckets.addAll(existingGroup.buckets().buckets());

        PortNumber[] newNeighborPorts = {PortNumber.portNumber(41),
                                         PortNumber.portNumber(42)};
        List<PortNumber> newOutPorts = new ArrayList<>();
        newOutPorts.addAll(Collections.singletonList(newNeighborPorts[0]));

        List<GroupBucket> toAddBuckets = new ArrayList<>();
        for (PortNumber portNumber: newOutPorts) {
            TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
            tBuilder.setOutput(portNumber)
                    .setEthDst(MacAddress.valueOf("00:00:00:00:00:03"))
                    .setEthSrc(MacAddress.valueOf("00:00:00:00:00:01"))
                    .pushMpls()
                    .setMpls(MplsLabel.mplsLabel(106));
            toAddBuckets.add(DefaultGroupBucket.createSelectGroupBucket(
                                                        tBuilder.build()));
        }
        GroupBuckets toAddGroupBuckets = new GroupBuckets(toAddBuckets);
        buckets.addAll(toAddBuckets);
        GroupBuckets updatedGroupBuckets = new GroupBuckets(buckets);
        InternalGroupStoreDelegate updateGroupDescDelegate =
                new InternalGroupStoreDelegate(addKey,
                                               updatedGroupBuckets,
                                               GroupEvent.Type.GROUP_UPDATE_REQUESTED);
        simpleGroupStore.setDelegate(updateGroupDescDelegate);
        simpleGroupStore.updateGroupDescription(D1,
                                                currKey,
                                                UpdateType.ADD,
                                                toAddGroupBuckets,
                                                addKey);
        simpleGroupStore.unsetDelegate(updateGroupDescDelegate);

        short weight = 5;
        toAddBuckets = new ArrayList<>();
        for (PortNumber portNumber: newOutPorts) {
            TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
            tBuilder.setOutput(portNumber)
                    .setEthDst(MacAddress.valueOf("00:00:00:00:00:03"))
                    .setEthSrc(MacAddress.valueOf("00:00:00:00:00:01"))
                    .pushMpls()
                    .setMpls(MplsLabel.mplsLabel(106));
            toAddBuckets.add(DefaultGroupBucket.createSelectGroupBucket(
                    tBuilder.build(), weight));
        }

        toAddGroupBuckets = new GroupBuckets(toAddBuckets);
        buckets = new ArrayList<>();
        buckets.addAll(existingGroup.buckets().buckets());
        buckets.addAll(toAddBuckets);
        updatedGroupBuckets = new GroupBuckets(buckets);
        updateGroupDescDelegate =
                new InternalGroupStoreDelegate(addKey,
                                               updatedGroupBuckets,
                                               GroupEvent.Type.GROUP_UPDATE_REQUESTED);
        simpleGroupStore.setDelegate(updateGroupDescDelegate);
        simpleGroupStore.updateGroupDescription(D1,
                                                addKey,
                                                UpdateType.ADD,
                                                toAddGroupBuckets,
                                                addKey);
        simpleGroupStore.unsetDelegate(updateGroupDescDelegate);
    }

    // Testing updateGroupDescription for REMOVE operation from northbound
    private void testRemoveBuckets(GroupKey currKey, GroupKey removeKey) {
        Group existingGroup = simpleGroupStore.getGroup(D1, currKey);
        List<GroupBucket> buckets = new ArrayList<>();
        buckets.addAll(existingGroup.buckets().buckets());

        List<GroupBucket> toRemoveBuckets = new ArrayList<>();

        // There should be 4 buckets in the current group
        toRemoveBuckets.add(buckets.remove(0));
        toRemoveBuckets.add(buckets.remove(1));
        GroupBuckets toRemoveGroupBuckets = new GroupBuckets(toRemoveBuckets);

        GroupBuckets remainingGroupBuckets = new GroupBuckets(buckets);
        InternalGroupStoreDelegate removeGroupDescDelegate =
                new InternalGroupStoreDelegate(removeKey,
                                               remainingGroupBuckets,
                                               GroupEvent.Type.GROUP_UPDATE_REQUESTED);
        simpleGroupStore.setDelegate(removeGroupDescDelegate);
        simpleGroupStore.updateGroupDescription(D1,
                                                currKey,
                                                UpdateType.REMOVE,
                                                toRemoveGroupBuckets,
                                                removeKey);
        simpleGroupStore.unsetDelegate(removeGroupDescDelegate);
    }

    // Testing deleteGroupDescription operation from northbound
    private void testDeleteGroup(GroupKey currKey) {
        Group existingGroup = simpleGroupStore.getGroup(D1, currKey);
        InternalGroupStoreDelegate deleteGroupDescDelegate =
                new InternalGroupStoreDelegate(currKey,
                                               existingGroup.buckets(),
                                               GroupEvent.Type.GROUP_REMOVE_REQUESTED);
        simpleGroupStore.setDelegate(deleteGroupDescDelegate);
        simpleGroupStore.deleteGroupDescription(D1, currKey);
        simpleGroupStore.unsetDelegate(deleteGroupDescDelegate);
    }

    // Testing deleteGroupDescription operation from northbound
    private void testDeleteGroupOnDevice(GroupKey currKey) {
        assertThat(simpleGroupStore.getGroupCount(D1), is(1));
        simpleGroupStore.purgeGroupEntry(D1);
        assertThat(simpleGroupStore.getGroupCount(D1), is(0));
    }

    // Testing purgeGroupEntries
    private void testPurgeGroupEntries() {
        assertThat(simpleGroupStore.getGroupCount(D1), is(1));
        simpleGroupStore.purgeGroupEntries();
        assertThat(simpleGroupStore.getGroupCount(D1), is(0));
    }

    // Testing removeGroupEntry operation from southbound
    private void testRemoveGroupFromSB(GroupKey currKey) {
        Group existingGroup = simpleGroupStore.getGroup(D1, currKey);
        InternalGroupStoreDelegate removeGroupEntryDelegate =
                new InternalGroupStoreDelegate(currKey,
                                               existingGroup.buckets(),
                                               GroupEvent.Type.GROUP_REMOVED);
        simpleGroupStore.setDelegate(removeGroupEntryDelegate);
        simpleGroupStore.removeGroupEntry(existingGroup);

        // Testing getGroup operation
        existingGroup = simpleGroupStore.getGroup(D1, currKey);
        assertEquals(null, existingGroup);
        assertEquals(0, Iterables.size(simpleGroupStore.getGroups(D1)));
        assertEquals(0, simpleGroupStore.getGroupCount(D1));

        simpleGroupStore.unsetDelegate(removeGroupEntryDelegate);
    }

    @Test
    public void testGroupOperationFailure() {

        simpleGroupStore.deviceInitialAuditCompleted(D1, true);

        ApplicationId appId =
                new DefaultApplicationId(2, "org.groupstore.test");
        GroupKey key = new DefaultGroupKey("group1".getBytes());
        PortNumber[] ports = {PortNumber.portNumber(31),
                PortNumber.portNumber(32)};
        List<PortNumber> outPorts = new ArrayList<>();
        outPorts.add(ports[0]);
        outPorts.add(ports[1]);

        List<GroupBucket> buckets = new ArrayList<>();
        for (PortNumber portNumber: outPorts) {
            TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
            tBuilder.setOutput(portNumber)
                    .setEthDst(MacAddress.valueOf("00:00:00:00:00:02"))
                    .setEthSrc(MacAddress.valueOf("00:00:00:00:00:01"))
                    .pushMpls()
                    .setMpls(MplsLabel.mplsLabel(106));
            buckets.add(DefaultGroupBucket.createSelectGroupBucket(
                    tBuilder.build()));
        }
        GroupBuckets groupBuckets = new GroupBuckets(buckets);
        GroupDescription groupDesc = new DefaultGroupDescription(
                D1,
                Group.Type.SELECT,
                groupBuckets,
                key,
                null,
                appId);
        InternalGroupStoreDelegate checkStoreGroupDelegate =
                new InternalGroupStoreDelegate(key,
                        groupBuckets,
                        GroupEvent.Type.GROUP_ADD_REQUESTED);
        simpleGroupStore.setDelegate(checkStoreGroupDelegate);
        // Testing storeGroup operation
        simpleGroupStore.storeGroupDescription(groupDesc);
        simpleGroupStore.unsetDelegate(checkStoreGroupDelegate);

        // Testing Group add operation failure
        Group createdGroup = simpleGroupStore.getGroup(D1, key);
        checkStoreGroupDelegate.verifyGroupId(createdGroup.id());

        GroupOperation groupAddOp = GroupOperation.
                createAddGroupOperation(createdGroup.id(),
                        createdGroup.type(),
                        createdGroup.buckets());
        InternalGroupStoreDelegate checkGroupAddFailureDelegate =
                new InternalGroupStoreDelegate(key,
                        groupBuckets,
                        GroupEvent.Type.GROUP_ADD_FAILED);
        simpleGroupStore.setDelegate(checkGroupAddFailureDelegate);
        simpleGroupStore.groupOperationFailed(D1, groupAddOp);

        // Testing Group modify operation failure
        simpleGroupStore.unsetDelegate(checkGroupAddFailureDelegate);
        GroupOperation groupModOp = GroupOperation.
                createModifyGroupOperation(createdGroup.id(),
                        createdGroup.type(),
                        createdGroup.buckets());
        InternalGroupStoreDelegate checkGroupModFailureDelegate =
                new InternalGroupStoreDelegate(key,
                        groupBuckets,
                        GroupEvent.Type.GROUP_UPDATE_FAILED);
        simpleGroupStore.setDelegate(checkGroupModFailureDelegate);
        simpleGroupStore.groupOperationFailed(D1, groupModOp);

        // Testing Group modify operation failure
        simpleGroupStore.unsetDelegate(checkGroupModFailureDelegate);
        GroupOperation groupDelOp = GroupOperation.
                createDeleteGroupOperation(createdGroup.id(),
                        createdGroup.type());
        InternalGroupStoreDelegate checkGroupDelFailureDelegate =
                new InternalGroupStoreDelegate(key,
                        groupBuckets,
                        GroupEvent.Type.GROUP_REMOVE_FAILED);
        simpleGroupStore.setDelegate(checkGroupDelFailureDelegate);
        simpleGroupStore.groupOperationFailed(D1, groupDelOp);
    }
}


text:
package org.metacsp.examples.multi;

import org.metacsp.framework.ConstraintNetwork;
import org.metacsp.framework.ConstraintNetworkChangeEvent;
import org.metacsp.framework.ConstraintNetworkChangeListener;
import org.metacsp.multi.activity.SymbolicVariableActivity;
import org.metacsp.multi.activity.ActivityNetworkSolver;
import org.metacsp.multi.allenInterval.AllenIntervalConstraint;
import org.metacsp.multi.symbols.SymbolicValueConstraint;
import org.metacsp.time.Bounds;

public class TestConstraintNetworkListener {

	public static void main(String[] args) {

		ConstraintNetworkChangeListener cncl = new ConstraintNetworkChangeListener() {
			private int numinvocations = 0;
			@Override
			public void stateChanged(ConstraintNetworkChangeEvent event) {
				System.out.println("Added: " + event.getAdded());
				System.out.println("Removed: " + event.getRemoved());
				System.out.println("Invocation: " + ++numinvocations);
			}
		};

		ActivityNetworkSolver solver = new ActivityNetworkSolver(0,500, new String[] {"A","B","C","D","E","F"});
		SymbolicVariableActivity act1 = (SymbolicVariableActivity)solver.createVariable();
		act1.setSymbolicDomain("A", "B", "C");
		SymbolicVariableActivity act2 = (SymbolicVariableActivity)solver.createVariable();
		act2.setSymbolicDomain("B", "C", "D");

		solver.getConstraintNetwork().addConstraintNetworkChangeListener(cncl);

		ConstraintNetwork.draw(solver.getConstraintSolvers()[1].getConstraintNetwork());

		SymbolicValueConstraint con1 = new SymbolicValueConstraint(SymbolicValueConstraint.Type.EQUALS);
		con1.setFrom(act1);
		con1.setTo(act2);

		SymbolicValueConstraint con1a = new SymbolicValueConstraint(SymbolicValueConstraint.Type.VALUESUBSET);
		con1a.setFrom(act1);
		con1a.setTo(act1);
		con1a.setValue("B","C");

		AllenIntervalConstraint con2 = new AllenIntervalConstraint(AllenIntervalConstraint.Type.Before, new Bounds(10, 20));
		con2.setFrom(act1);
		con2.setTo(act2);

		AllenIntervalConstraint con3 = new AllenIntervalConstraint(AllenIntervalConstraint.Type.Duration, new Bounds(5, 5));
		con3.setFrom(act1);
		con3.setTo(act1);

		AllenIntervalConstraint con4 = new AllenIntervalConstraint(AllenIntervalConstraint.Type.Duration, new Bounds(5, 5));
		con4.setFrom(act2);
		con4.setTo(act2);

		AllenIntervalConstraint con5 = new AllenIntervalConstraint(AllenIntervalConstraint.Type.Release, new Bounds(13, solver.getHorizon()));
		con5.setFrom(act2);
		con5.setTo(act2);

		AllenIntervalConstraint con5a = new AllenIntervalConstraint(AllenIntervalConstraint.Type.Release, new Bounds(13, solver.getHorizon()));
		con5a.setFrom(act2);
		con5a.setTo(act2);

		solver.addConstraints(con1, con1a, con2);

		solver.addConstraints(con3, con4, con5, con5a);

	}

}

redpajama_set_name: RedPajamaGithub


text:
template<class T> using VOID = void;

using std::enable_if;

template<class A, class B> using same_t = std::is_same<A, B>;
GEN_CXPR2(same)
static_assert(same<int, int>(), "same");

template<class T> using remove_cv = typename std::remove_cv<T>::type;

template<class A, class B> constexpr bool convertible() { return std::is_convertible<A,B>::value; } // B(a) valid
template<class T> constexpr bool zero_size() { return std::is_empty<T>::value; } // sizeof(T) == 0
using std::declval; // oposite of decltype

template<class... Ts> using common = typename std::common_type<Ts...>::type;
template<class A, class B> using common2_t = std::common_type<A,B>;
template<class A, class B> using common2 = typename common2_t<A, B>::type;
static_assert(same<common<int,char,short>, int>(), "common");

template<bool C, class T, class F> using cond_t = std::conditional<C,T,F>;
template<bool C, class T, class F> using cond = typename cond_t<C,T,F>::type;

template<int id, class... Args> struct select_t;
template<int id, class First, class... Rest> struct select_t<id, First, Rest...> : select_t<id-1, Rest...> {};
template<class First, class... Rest> struct select_t<0, First, Rest...> : TYPE<First> {};

template<class T, class... Args> struct callable_t {
	template<class U> static true_t f(decltype(declval<U>()(declval<Args>()...))*);
	template<class U> static false_t f(...);
	static const bool value = decltype(f<T>(0))::value;
};
template<class T, class... Args> constexpr bool callable() { return callable_t<T, Args...>::value; }

template<bool ok, class T, class R, class... Args> struct call_convertible_if_callable_t : false_t {};
template<class T, class R, class... Args> struct call_convertible_if_callable_t<true, T, R, Args...> : std::is_convertible<decltype(declval<T>()(declval<Args>()...)), R> {};
template<class T, class... Args> struct call_convertible_if_callable_t<true, T, void, Args...> : true_t {};
template<class T, class R, class... Args> struct call_convertible_args_t : call_convertible_if_callable_t<callable<T, Args...>(), T, R, Args...> {};

template<class Sig, class T> struct call_convertible_t;
template<class T, class R, class... Args> struct call_convertible_t<R(Args...), T> : call_convertible_args_t<T, R, Args...> {};
template<class Sig, class T> constexpr bool call_convertible() { return call_convertible_t<Sig,T>::value; }
template<class Sig, class T> constexpr bool call_convertible(const T &) { return call_convertible_t<Sig,T>::value; }

namespace test_callable {
	void void_void();
	using vv = decltype(void_void);
	int int_int(int);
	using ii = decltype(int_int);
	static_assert(callable<vv>(), "callable");
	static_assert(!callable<vv, bool, bool>(), "callable");
	static_assert(callable<ii, int>(), "callable");
	static_assert(callable<ii, float>(), "callable");
	static_assert(!callable<ii>(), "callable");
	static_assert(!callable<ii, int,int>(), "callable");
	static_assert(!callable<int>(), "callable");
	static_assert(!callable<bool>(), "callable");
	static_assert(call_convertible<void()>(void_void), "callable");
	static_assert(!call_convertible<int()>(void_void), "callable");
	static_assert(!call_convertible<int()>(int_int), "callable");
	static_assert(call_convertible<int(int)>(int_int), "callable");
}

#define TYPEDEF_TEST(_T_) \
	template<class T> struct has_type_ ## _T_ ## _t : TYPE<bool> { \
		template<class U> static true_t  f(typename U::_T_ *); \
		template<class U> static false_t f(...); \
		static const bool value = decltype(f<T>(0))::value; \
	}; \
	template<class T> constexpr bool has_type_ ## _T_ () { return has_type_ ## _T_ ## _t<T>::value; }

namespace test_typedef_test {
	struct x { using foo = void; };
	TYPEDEF_TEST(foo);
	static_assert(has_type_foo<x>(), "typedef test");
}

#define CONST_TEST(_F_) \
	template<class T> struct has_const_ ## _F_ ## _t : TYPE<bool> { \
		template<class U> static true_t  f(decltype(U::_F_) *); \
		template<class U> static false_t f(...); \
		static const bool value = decltype(f<T>(0))::value; \
	}; \
	template<class T> constexpr bool has_const_ ## _F_ () { return has_const_ ## _F_ ## _t<T>::value; }

namespace test_const_test {
	struct x { static const int bar = 0; };
	CONST_TEST(bar);
	static_assert(has_const_bar<x>(), "const test");
}


text:
layout: post
title:  "On Scalability"
description: ""
date:   2016-06-19 11:08
comments: true
categories: technical
---

Scalablity is often talked about in terms of raw compute power but I've rarely
heard it considered in terms of people. Your web application should be able
to handle the exponential growth in traffic if your startup becomes popular, but
can it handle the growth in software developers?

I suspect that there are plenty of people out there who already know about this,
but strangely enough I haven't heard about it talked much. The truth is that to move
forward, most projects, at some point will need lots of people to start contributing.
One person isn't enough.

## School Projects

Do you remember ever having to work with classmates on a school project? Those horrible,
time-honored group projects?

Remember how horrible they were?

Those projects were horrible because much of the time, one person ended up carrying the
project while the others fell behind and couldn't contribute anymore. These types of
projects wouldn't scale very well - adding more team members would probably make things
much, much worse.

Things get tense. People can't contribute, forget to contribute or contribute too much.
I don't think these types of projects can or should change, but they're a great example
of what happens when things go wrong. If your project or system isn't designed well
(or designed at all) it can be really difficult to do work.

## Semiconductor

The semiconductor industry has been dealing with this for years. If you have some
background in hardware from college, you might wonder how large semiconductor
companies such as AMD or Intel pull it off?  Those companies are huge - how
do you position your hardware company so that you can have that many people
contributing?

The answer is more complicated than it sounds - you split things up correctly.
You have your architects worry about the high level design. You have your designers
create the individual modules (Southbridge, Northbridge, etc). You have an
army of validation guys right beside them to make sure that changes don't break things.

The rabbit hole goes deeper but you get the picture.

## Overall

There isn't any magical formula you can follow though. The semiconductor industry spent decades
to get to the point that they are today. There was probably a ramp up period of a few decades.

But I think it's fair to consider scalablity as something beyond just compute. When you
can get a whole bunch of people to contribute as much as they individually can,
you can build something great. Sure, a smaller group of people will probably have the seed
ideas but a different challenge comes when things grow.


text:
/*
 * jQuery mmenu WordPress wrapper
 * mmenu.frebsite.nl
 */
!function(s){var e="mmenu",n="wordpress";s[e].wrappers[n]=function(){this.conf.classNames.selected="current-menu-item",s("#wpadminbar").css("position","fixed").addClass("mm-slideout")}}(jQuery);


text:
namespace hqp_controllers {

//-----------------------------------------
std::ostream& operator<<(std::ostream& str, HQPStage const& stage)
{
    str<<"HQPSTAGE"<<std::endl;
    str<<"solved: "<<stage.solved_<<std::endl;
    str<<"dim_: "<<stage.dim_<<std::endl;
    str<<"de_: "<<stage.de_->transpose()<<std::endl;
    str<<"signs: ";
    for(unsigned int i=0; i<stage.signs_->size();i++)
        str<<stage.signs_->at(i)<<" ";

    str<<std::endl<<"A_:"<<std::endl<<(*stage.A_)<<std::endl;
    str<<"x_: "<<stage.x_->transpose()<<std::endl;
    str<<"w_: "<<stage.w_->transpose()<<std::endl;
}
//-----------------------------------------
HQPStage::HQPStage() : dim_(0), solved_(false)
{
    de_.reset(new Eigen::VectorXd);
    x_.reset(new Eigen::VectorXd);
    w_.reset(new Eigen::VectorXd);
    signs_.reset(new std::vector<std::string>);
    A_.reset(new Eigen::MatrixXd);
}
//-----------------------------------------
HQPStage::HQPStage(Task const& task) : solved_(false)
{
    dim_ = task.getDimension();
    de_.reset(new Eigen::VectorXd(*task.getTaskVelocity()));
    A_.reset(new Eigen::MatrixXd(*task.getTaskJacobian()));
    signs_.reset(new std::vector<std::string>(dim_));
    std::fill(signs_->begin(), signs_->end(), task.getSign());

    x_.reset(new Eigen::VectorXd(A_->cols()));
    x_->setZero();
    w_.reset(new Eigen::VectorXd(dim_));
    w_->setZero();
}
//-----------------------------------------
void HQPStage::appendTask(Task const& task)
{
    unsigned int dim = task.getDimension();
    de_->conservativeResize(dim_ + dim);
    A_->conservativeResize(dim + dim_, Eigen::NoChange);
    de_->tail(dim) = (*task.getTaskVelocity());
    A_->bottomRows(dim) = (*task.getTaskJacobian());
    for(unsigned int i=0; i<dim; i++)
        signs_->push_back(task.getSign());

    w_->resize(dim_ + dim);
    w_->setZero();

    dim_ = dim_ +dim;
    solved_ = false;
}
//-----------------------------------------
HQPSolver::HQPSolver()
{
    env_.set(GRB_IntParam_OutputFlag, OUTPUT_FLAG);
    env_.set(GRB_IntParam_Presolve, PRESOLVE);
    env_.set(GRB_DoubleParam_OptimalityTol, OPTIMALITY_TOL);
    env_.set(GRB_IntParam_ScaleFlag, SCALE_FLAG);
    env_.set(GRB_DoubleParam_TimeLimit, TIME_LIMIT);
    env_.set(GRB_IntParam_DualReductions, DUAL_REDUCTIONS);
}
//-----------------------------------------
void HQPSolver::reset()
{
    b_.resize(0);
    w_.resize(0);
    A_.resize(0,0);
    signs_.clear();
}
//-----------------------------------------
bool HQPSolver::solve(std::map<unsigned int, boost::shared_ptr<HQPStage> > &hqp)
{
    if(hqp.empty())
        return false;

    reset();

    std::map<unsigned int, boost::shared_ptr<HQPStage> >::const_iterator it = hqp.begin();//
    unsigned int x_dim = it->second->A_->cols();
    A_.resize(Eigen::NoChange, x_dim);

    try
    {
        //iterate through all stages
        unsigned int s_count = 0; //stage counter
        for (it; it!=hqp.end(); ++it)
        {
            ROS_ASSERT(it->second->A_->cols() == x_dim); //make sure the stage jacobian column dimensions are consistent
            s_count++;
            GRBModel model(env_);
            unsigned int s_dim = it->second->dim_; //dimension of the current stage
            unsigned int s_acc_dim = b_.rows(); //accumulated dimensions of all the previously solved stages

            //append the new senses, jacobian matrix and task velocity vector to the previous ones
            for(unsigned int i = 0; i<s_dim; i++)
                signs_.push_back(it->second->signs_->at(i));

            b_.conservativeResize(s_acc_dim + s_dim);
            b_.tail(s_dim) = *(it->second->de_);
            A_.conservativeResize(s_acc_dim + s_dim,Eigen::NoChange);
            A_.bottomRows(s_dim) = *(it->second->A_);
            w_.conservativeResize(s_acc_dim + s_dim);
            w_.tail(s_dim).setZero(); //set zero for now - will be filled with the solution later

            //at each iteration, variables are x (the joint velocities) + the slack variables
            double* lb_x = new double[x_dim]; std::fill_n(lb_x, x_dim, -GRB_INFINITY);
            double* ub_x = new double[x_dim]; std::fill_n(ub_x, x_dim, GRB_INFINITY);
            GRBVar* x =model.addVars(lb_x, ub_x, NULL, NULL, NULL, x_dim);

            double* lb_w = new double[s_dim]; std::fill_n(lb_w, s_dim, -GRB_INFINITY);
            double* ub_w = new double[s_dim]; std::fill_n(ub_w, s_dim, GRB_INFINITY);
            GRBVar* w =model.addVars(lb_w, ub_w, NULL, NULL, NULL, s_dim); //slack variables
            model.update();

            GRBLinExpr* lhsides = new GRBLinExpr[s_dim + s_acc_dim];
            char* senses = new char[s_dim + s_acc_dim];
            double* rhsides = new double[s_dim + s_acc_dim];
            double* coeff_x = new double[x_dim];
            double* coeff_w = new double[s_dim];

            //========== CREATE GUROBI EXPRESSIONS ===================

            //Fill in the senses array
            for(unsigned int i=0; i<s_dim + s_acc_dim; i++)
                if(signs_[i] == "=")
                    senses[i] = GRB_EQUAL;
                else if (signs_[i] == "<=")
                    senses[i] = GRB_LESS_EQUAL;
                else if (signs_[i] == ">=")
                    senses[i] = GRB_GREATER_EQUAL;
                else
                {
                    ROS_ERROR("HQPSolver::solve(): %s is an invalid sign.",it->second->signs_->at(i).c_str());
                    ROS_BREAK();
                }

            //Fill in the constant right-hand side array
            Eigen::Map<Eigen::VectorXd>(rhsides, s_acc_dim + s_dim) = b_ + w_;

            //Fill in the left-hand side expressions
            for(unsigned int i=0; i<s_acc_dim; i++)
            {
                Eigen::Map<Eigen::VectorXd>(coeff_x, x_dim) = A_.row(i);
                lhsides[i].addTerms(coeff_x, x, x_dim);
            }
            for(unsigned int i=0; i<s_dim; i++)
            {
                Eigen::Map<Eigen::VectorXd>(coeff_x, x_dim) = A_.row(s_acc_dim+i);
                lhsides[s_acc_dim+i].addTerms(coeff_x, x, x_dim);
                if(s_count == 1)
                    lhsides[s_acc_dim+i] -= w[i]*0.0; //force the slack variables to be zero in the highest stage;
                else
                    lhsides[s_acc_dim+i] -= w[i];
            }

            //add constraints
            GRBConstr* constrs=model.addConstrs(lhsides,senses,rhsides,NULL,s_acc_dim + s_dim);

            //add objective
            GRBQuadExpr obj;
            std::fill_n(coeff_x, x_dim, TIKHONOV_FACTOR);
            std::fill_n(coeff_w, s_dim, 1.0);
            obj.addTerms(coeff_x, x, x, x_dim);
            obj.addTerms(coeff_w, w, w, s_dim);
            model.setObjective(obj, GRB_MINIMIZE);
            model.update();

            //========== SOLVE ===================
            model.optimize();
            int status = model.get(GRB_IntAttr_Status);
            double runtime = model.get(GRB_DoubleAttr_Runtime);

            if (status != GRB_OPTIMAL)
            {
                if(status == GRB_TIME_LIMIT)
                    ROS_WARN("Stage solving runtime %f sec exceeds the set time limit of %f sec.", runtime, TIME_LIMIT);
                else
                    ROS_ERROR("In HQPSolver::solve(...): No optimal solution found for stage %d. Status is %d.", s_count, status);

                delete[] lb_x;
                delete[] ub_x;
                delete[] lb_w;
                delete[] ub_w;
                delete[] x;
                delete[] w;
                delete[] lhsides;
                delete[] senses;
                delete[] rhsides;
                delete[] coeff_x;
                delete[] coeff_w;

                //model.write("/home/rkg/Desktop/model.lp");
                //model.write("/home/rkg/Desktop/model.sol");

                return false;
            }

            try
            {
                //Update the solution and put it in the current stage
                for(unsigned int i=0; i<x_dim; i++)
                    (*it->second->x_)(i) = x[i].get(GRB_DoubleAttr_X);

                for(unsigned int i=0; i<s_dim; i++)
                {
                    w_(s_acc_dim + i) = w[i].get(GRB_DoubleAttr_X);
                    (*it->second->w_)(i) = w_(s_acc_dim + i);
                }
            }
            catch(GRBException e)
            {
                ROS_ERROR("In HQPSolver::solve(...): Gurobi exception with error code %d, and error message %s when trying to extract the solution variables.", e.getErrorCode(), e.getMessage().c_str());
                //model.write("/home/rkg/Desktop/model.lp");
                //model.write("/home/rkg/Desktop/model.sol");

                return false;
            }

            it->second->solved_ = true;

//            if(s_count == hqp.size())
//            {
//                model.write("/home/rkg/Desktop/model.lp");
//                model.write("/home/rkg/Desktop/model.sol");
//            }
            //std::cout<<"SOLVED STAGE: "<<it->first<<std::endl;
            //std::cout<< *it->second<<std::endl;
            //std::cout<<"runtime: "<<runtime<<std::endl;

            delete[] lb_x;
            delete[] ub_x;
            delete[] lb_w;
            delete[] ub_w;
            delete[] x;
            delete[] w;
            delete[] lhsides;
            delete[] senses;
            delete[] rhsides;
            delete[] coeff_x;
            delete[] coeff_w;
        }
    }
    catch(GRBException e)
    {
        ROS_ERROR("In HQPSolver::solve(...): Gurobi exception with error code %d, and error message %s.", e.getErrorCode(), e.getMessage().c_str());
        return false;
    }

    //    std::cout<<"Solved HQP! Yay!"<<std::endl;
    return true;
}
//-----------------------------------------
}//end namespace hqp_controllers


text:
// File generated from our OpenAPI spec

declare module 'stripe' {
  namespace Stripe {
    namespace Treasury {
      /**
       * ReceivedCredits represent funds sent to a [FinancialAccount](https://stripe.com/docs/api#financial_accounts) (for example, via ACH or wire). These money movements are not initiated from the FinancialAccount.
       */
      interface ReceivedCredit {
        /**
         * Unique identifier for the object.
         */
        id: string;

        /**
         * String representing the object's type. Objects of the same type share the same value.
         */
        object: 'treasury.received_credit';

        /**
         * Amount (in cents) transferred.
         */
        amount: number;

        /**
         * Time at which the object was created. Measured in seconds since the Unix epoch.
         */
        created: number;

        /**
         * Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies).
         */
        currency: string;

        /**
         * An arbitrary string attached to the object. Often useful for displaying to users.
         */
        description: string;

        /**
         * Reason for the failure. A ReceivedCredit might fail because the receiving FinancialAccount is closed or frozen.
         */
        failure_code: ReceivedCredit.FailureCode | null;

        /**
         * The FinancialAccount that received the funds.
         */
        financial_account: string | null;

        /**
         * A [hosted transaction receipt](https://stripe.com/docs/treasury/moving-money/regulatory-receipts) URL that is provided when money movement is considered regulated under Stripe's money transmission licenses.
         */
        hosted_regulatory_receipt_url: string | null;

        initiating_payment_method_details: ReceivedCredit.InitiatingPaymentMethodDetails;

        linked_flows: ReceivedCredit.LinkedFlows;

        /**
         * Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode.
         */
        livemode: boolean;

        /**
         * The rails used to send the funds.
         */
        network: ReceivedCredit.Network;

        /**
         * Details describing when a ReceivedCredit may be reversed.
         */
        reversal_details: ReceivedCredit.ReversalDetails | null;

        /**
         * Status of the ReceivedCredit. ReceivedCredits are created either `succeeded` (approved) or `failed` (declined). If a ReceivedCredit is declined, the failure reason can be found in the `failure_code` field.
         */
        status: ReceivedCredit.Status;

        /**
         * The Transaction associated with this object.
         */
        transaction: string | Stripe.Treasury.Transaction | null;
      }

      namespace ReceivedCredit {
        type FailureCode = 'account_closed' | 'account_frozen' | 'other';

        interface InitiatingPaymentMethodDetails {
          /**
           * Set when `type` is `balance`.
           */
          balance?: 'payments';

          billing_details: InitiatingPaymentMethodDetails.BillingDetails;

          financial_account?: InitiatingPaymentMethodDetails.FinancialAccount;

          /**
           * Set when `type` is `issuing_card`. This is an [Issuing Card](https://stripe.com/docs/api#issuing_cards) ID.
           */
          issuing_card?: string;

          /**
           * Polymorphic type matching the originating money movement's source. This can be an external account, a Stripe balance, or a FinancialAccount.
           */
          type: InitiatingPaymentMethodDetails.Type;

          us_bank_account?: InitiatingPaymentMethodDetails.UsBankAccount;
        }

        namespace InitiatingPaymentMethodDetails {
          interface BillingDetails {
            address: Stripe.Address;

            /**
             * Email address.
             */
            email: string | null;

            /**
             * Full name.
             */
            name: string | null;
          }

          interface FinancialAccount {
            /**
             * The FinancialAccount ID.
             */
            id: string;

            /**
             * The rails the ReceivedCredit was sent over. A FinancialAccount can only send funds over `stripe`.
             */
            network: 'stripe';
          }

          type Type =
            | 'balance'
            | 'financial_account'
            | 'issuing_card'
            | 'stripe'
            | 'us_bank_account';

          interface UsBankAccount {
            /**
             * Bank name.
             */
            bank_name: string | null;

            /**
             * The last four digits of the bank account number.
             */
            last4: string | null;

            /**
             * The routing number for the bank account.
             */
            routing_number: string | null;
          }
        }

        interface LinkedFlows {
          /**
           * The CreditReversal created as a result of this ReceivedCredit being reversed.
           */
          credit_reversal: string | null;

          /**
           * Set if the ReceivedCredit was created due to an [Issuing Authorization](https://stripe.com/docs/api#issuing_authorizations) object.
           */
          issuing_authorization: string | null;

          /**
           * Set if the ReceivedCredit is also viewable as an [Issuing transaction](https://stripe.com/docs/api#issuing_transactions) object.
           */
          issuing_transaction: string | null;

          /**
           * ID of the source flow. Set if `network` is `stripe` and the source flow is visible to the user. Examples of source flows include OutboundPayments, payouts, or CreditReversals.
           */
          source_flow: string | null;

          /**
           * The expandable object of the source flow.
           */
          source_flow_details: LinkedFlows.SourceFlowDetails | null;

          /**
           * The type of flow that originated the ReceivedCredit (for example, `outbound_payment`).
           */
          source_flow_type: string | null;
        }

        namespace LinkedFlows {
          interface SourceFlowDetails {
            /**
             * You can reverse some [ReceivedCredits](https://stripe.com/docs/api#received_credits) depending on their network and source flow. Reversing a ReceivedCredit leads to the creation of a new object known as a CreditReversal.
             */
            credit_reversal?: Stripe.Treasury.CreditReversal;

            /**
             * Use OutboundPayments to send funds to another party's external bank account or [FinancialAccount](https://stripe.com/docs/api#financial_accounts). To send money to an account belonging to the same user, use an [OutboundTransfer](https://stripe.com/docs/api#outbound_transfers).
             *
             * Simulate OutboundPayment state changes with the `/v1/test_helpers/treasury/outbound_payments` endpoints. These methods can only be called on test mode objects.
             */
            outbound_payment?: Stripe.Treasury.OutboundPayment;

            /**
             * A `Payout` object is created when you receive funds from Stripe, or when you
             * initiate a payout to either a bank account or debit card of a [connected
             * Stripe account](https://stripe.com/docs/connect/bank-debit-card-payouts). You can retrieve individual payouts,
             * as well as list all payouts. Payouts are made on [varying
             * schedules](https://stripe.com/docs/connect/manage-payout-schedule), depending on your country and
             * industry.
             *
             * Related guide: [Receiving Payouts](https://stripe.com/docs/payouts).
             */
            payout?: Stripe.Payout;

            /**
             * The type of the source flow that originated the ReceivedCredit.
             */
            type: SourceFlowDetails.Type;
          }

          namespace SourceFlowDetails {
            type Type =
              | 'credit_reversal'
              | 'other'
              | 'outbound_payment'
              | 'payout';
          }
        }

        type Network = 'ach' | 'card' | 'stripe' | 'us_domestic_wire';

        interface ReversalDetails {
          /**
           * Time before which a ReceivedCredit can be reversed.
           */
          deadline: number | null;

          /**
           * Set if a ReceivedCredit cannot be reversed.
           */
          restricted_reason: ReversalDetails.RestrictedReason | null;
        }

        namespace ReversalDetails {
          type RestrictedReason =
            | 'already_reversed'
            | 'deadline_passed'
            | 'network_restricted'
            | 'other'
            | 'source_flow_restricted';
        }

        type Status = 'failed' | 'succeeded';
      }
    }
  }
}


text:
{{ application.name }}
			{{ application.url }}

			Details
			Logging
			JMX
			Threads


text: OpenLayers 3 example with KML data as polygons.


text:
package org.springframework.security.oauth2.client.userinfo;

import org.springframework.security.core.AuthenticatedPrincipal;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.user.OAuth2User;
import reactor.core.publisher.Mono;

/**
 * Implementations of this interface are responsible for obtaining the user attributes
 * of the End-User (Resource Owner) from the UserInfo Endpoint
 * using the {@link OAuth2UserRequest#getAccessToken() Access Token}
 * granted to the {@link OAuth2UserRequest#getClientRegistration() Client}
 * and returning an {@link AuthenticatedPrincipal} in the form of an {@link OAuth2User}.
 *
 * @author Rob Winch
 * @since 5.1
 * @see OAuth2UserRequest
 * @see OAuth2User
 * @see AuthenticatedPrincipal
 *
 * @param <R> The type of OAuth 2.0 User Request
 * @param <U> The type of OAuth 2.0 User
 */
public interface ReactiveOAuth2UserService<R extends OAuth2UserRequest, U extends OAuth2User> {

	/**
	 * Returns an {@link OAuth2User} after obtaining the user attributes of the End-User from the UserInfo Endpoint.
	 *
	 * @param userRequest the user request
	 * @return an {@link OAuth2User}
	 * @throws OAuth2AuthenticationException if an error occurs while attempting to obtain the user attributes from the UserInfo Endpoint
	 */
	Mono<U> loadUser(R userRequest) throws OAuth2AuthenticationException;

}


text:
<!DOCTYPE html>

    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='css/reset.css') }}">
    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='css/style.css') }}">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

    <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
    <link rel="icon" href="{{ url_for('static', filename='img/c_mon9.png') }}">
    <title>Cody's Portfolio</title>

            {% if request.path == '/' %}
                About Me
                Projects
                Contact
            {% elif request.path == '/about' %}
                Home
                Projects
                Contact
            {% elif request.path == '/projects' %}
                Home
                About Me
                Contact
            {% elif request.path == '/contact' %}
                Home
                About Me
                Projects
            {% elif request.path == '/knightdefense' %}
                Home
                About Me
                Projects
                Contact
            {% endif %}

    {% block content %}{% endblock %}


text:
package org.apache.accumulo.core.file.streams;

import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.accumulo.core.util.ratelimit.NullRateLimiter;
import org.apache.accumulo.core.util.ratelimit.RateLimiter;
import org.apache.hadoop.fs.Seekable;

/**
 * A decorator for an {@code InputStream} which limits the rate at which reads are performed.
 */
public class RateLimitedInputStream extends FilterInputStream implements Seekable {
  private final RateLimiter rateLimiter;

  public <StreamType extends InputStream & Seekable> RateLimitedInputStream(StreamType stream, RateLimiter rateLimiter) {
    super(stream);
    this.rateLimiter = rateLimiter == null ? NullRateLimiter.INSTANCE : rateLimiter;
  }

  @Override
  public int read() throws IOException {
    int val = in.read();
    if (val >= 0) {
      rateLimiter.acquire(1);
    }
    return val;
  }

  @Override
  public int read(byte[] buffer, int offset, int length) throws IOException {
    int count = in.read(buffer, offset, length);
    if (count > 0) {
      rateLimiter.acquire(count);
    }
    return count;
  }

  @Override
  public void seek(long pos) throws IOException {
    ((Seekable) in).seek(pos);
  }

  @Override
  public long getPos() throws IOException {
    return ((Seekable) in).getPos();
  }

  @Override
  public boolean seekToNewSource(long targetPos) throws IOException {
    return ((Seekable) in).seekToNewSource(targetPos);
  }
}


text:
package de.zib.scalaris.examples.wikipedia.bliki;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import de.zib.scalaris.Connection;
import de.zib.scalaris.examples.wikipedia.RevisionResult;
import de.zib.scalaris.examples.wikipedia.ScalarisDataHandler;

/**
 * Wiki model using Scalaris to fetch (new) data, e.g. templates.
 *
 * @author Nico Kruber, kruber@zib.de
 */
public class MyScalarisWikiModel extends MyWikiModel {
    protected Connection connection;
    protected Map<String, String> pageCache = new HashMap<String, String>();
    // e.g. "#REDIRECT [[France]]", "#REDIRECT:[[France]]"
    private static final Pattern MATCH_WIKI_REDIRECT =
            Pattern.compile("^#REDIRECT[^\\[]?\\[\\[:?([^\\]]*)\\]\\]$", Pattern.CASE_INSENSITIVE);

    /**
     * Creates a new wiki model to render wiki text using the given connection
     * to Scalaris.
     *
     * @param imageBaseURL
     *            base url pointing to images - can contain ${image} for
     *            replacement
     * @param linkBaseURL
     *            base url pointing to links - can contain ${title} for
     *            replacement
     * @param connection
     *            connection to Scalaris
     * @param namespace
     *            namespace of the wiki
     */
    public MyScalarisWikiModel(String imageBaseURL, String linkBaseURL, Connection connection, MyNamespace namespace) {
        super(imageBaseURL, linkBaseURL, namespace);
        this.connection = connection;
    }

    /**
     * Determines if a template name corresponds to a magic word using
     * {@link MyScalarisMagicWord#isMagicWord(String)}.
     *
     * @param name
     *            the template name
     *
     * @return whether the template is a magic word or not
     */
    @Override
    protected boolean isMagicWord(String name) {
        return MyScalarisMagicWord.isMagicWord(name);
    }

    /**
     * Retrieves the contents of the given magic word from Scalaris.
     *
     * @param templateName
     *            the template's name without the namespace, e.g. a magic word
     *            including its parameters
     * @param magicWord
     *            the magic word alone
     * @param parameter
     *            the parameters of the magic word
     *
     * @return the contents of the magic word (see
     *         {@link MyScalarisMagicWord#processMagicWord(String, String, info.bliki.wiki.model.IWikiModel)})
     */
    @Override
    protected String retrieveMagicWord(String articleName, String magicWord,
            String parameter) {
        return MyScalarisMagicWord.processMagicWord(magicWord, parameter, this);
    }

    /**
     * Retrieves the contents of the given page from Scalaris.
     * Caches retrieved pages in {@link #pageCache}.
     *
     * @param namespace
     *            the namespace of the page
     * @param articleName
     *            the page's name without the namespace
     * @param templateParameters
     *            template parameters if the page is a template, <tt>null</tt>
     *            otherwise
     *
     * @return the page's contents or <tt>null</tt> if no connection exists
     */
    @Override
    protected String retrievePage(String namespace, String articleName,
            Map<String, String> templateParameters) {
        return retrievePage(namespace, articleName, templateParameters, true);
    }

    /**
     * Retrieves the contents of the given page from Scalaris. Caches retrieved
     * pages in {@link #pageCache}.
     *
     * @param namespace
     *            the namespace of the page
     * @param articleName
     *            the page's name without the namespace
     * @param templateParameters
     *            template parameters if the page is a template, <tt>null</tt>
     *            otherwise
     * @param followRedirect
     *            whether to follow a redirect or not (at most one redirect
     *            should be followed)
     *
     * @return the page's contents or <tt>null</tt> if no connection exists
     */
    protected String retrievePage(String namespace, String articleName,
            Map<String, String> templateParameters, boolean followRedirect) {
        if (connection != null) {
            String pageName = createFullPageName(namespace, articleName);
            if (pageCache.containsKey(pageName)) {
                return pageCache.get(pageName);
            } else {
                String text = null;
                // System.out.println("retrievePage(" + namespace + ", " + articleName + ")");
                RevisionResult getRevResult = ScalarisDataHandler.getRevision(connection, pageName);
                if (getRevResult.success) {
                    text = getRevResult.revision.getText();
                    final Matcher matcher = MATCH_WIKI_REDIRECT.matcher(text);
                    if (getRevResult.page.isRedirect() && matcher.matches()) {
                        // see https://secure.wikimedia.org/wikipedia/en/wiki/Help:Redirect#Transclusion
                        String[] redirFullName = splitNsTitle(matcher.group(1));
                        String redirText = retrievePage(redirFullName[0], redirFullName[1], templateParameters, false);
                        if (redirText != null && !redirText.isEmpty()) {
                            text = redirText;
                        }
                    }
                } else {
                    // System.err.println(getRevResult.message);
                    // text = "ERROR: template " + pageName + " not available: " + getRevResult.message + "";
                }
                pageCache.put(pageName, text);
                return text;
            }
        }
        return null;
    }

    /**
     * Gets the contents of the newest revision of the page redirected to.
     *
     * @param pageName
     *            the name of the page redirected to
     *
     * @return the contents of the newest revision of that page or a placeholder
     *         string for the redirect
     */
    @Override
    public String getRedirectContent(String pageName) {
        if (connection != null) {
            RevisionResult getRevResult = ScalarisDataHandler.getRevision(connection, pageName);
            if (getRevResult.success) {
                // make PAGENAME in the redirected content work as expected
                setPageName(pageName);
                return getRevResult.revision.getText();
            } else {
//                System.err.println(getRevResult.message);
//                return "ERROR: redirect to " + getRedirectLink() + " failed: " + getRevResult.message + "";
            }
        }
        return "#redirect [[" + pageName + "]]";
    }

    /* (non-Javadoc)
     * @see de.zib.scalaris.examples.wikipedia.bliki.MyWikiModel#setUp()
     */
    @Override
    public void setUp() {
        super.setUp();
        pageCache = new HashMap<String, String>();
    }
}


text:
/*
** $Id: //Department/DaVinci/BRANCHES/MT6620_WIFI_DRIVER_V2_3/include/mgmt/cnm_timer.h#1 $
*/

/*! \file   cnm_timer.h
    \brief  Declaration of timer obj and related timer macro for setup time out
	    event.

    In this file we declare the timer object and provide several macro for
    Protocol functional blocks to setup their own time out event.
*/

/*
** $Log: cnm_timer.h $
 *
 * 12 13 2011 cm.chang
 * [WCXRP00001136] [All Wi-Fi][Driver] Add wake lock for pending timer
 * Add wake lock if timer timeout value is smaller than 5 seconds
 *
 * 09 03 2010 kevin.huang
 * NULL
 * Refine #include sequence and solve recursive/nested #include issue
 *
 * 07 08 2010 cp.wu
 *
 * [WPD00003833] [MT6620 and MT5931] Driver migration - move to new repository.
 *
 * 06 08 2010 cp.wu
 * [WPD00003833][MT6620 and MT5931] Driver migration
 * cnm_timer has been migrated.
 *
 * 06 08 2010 cp.wu
 * [WPD00003833][MT6620 and MT5931] Driver migration
 * add hem_mbox.c and cnm_mem.h (but disabled some feature) for further migration
 *
 * 06 07 2010 cp.wu
 * [WPD00003833][MT6620 and MT5931] Driver migration
 * merge cnm_scan.h and hem_mbox.h
 *
 * 06 07 2010 cp.wu
 * [WPD00003833][MT6620 and MT5931] Driver migration
 * merge wifi_var.h, precomp.h, cnm_timer.h (data type only)
 *
 * 06 04 2010 george.huang
 * [BORA00000678][MT6620]WiFi LP integration
 * [PM] Support U-APSD for STA mode
 *
 * 04 24 2010 cm.chang
 * [BORA00000018]Integrate WIFI part into BORA for the 1st time
 * Return timer token back to COS when entering wait off state
 *
 * 01 08 2010 cm.chang
 * [BORA00000018]Integrate WIFI part into BORA for the 1st time
 * Support longer timeout interval to 45 days from 65secu1rwduu`wvpghlqg|fh+fmdkb
 *
 * 01 06 2010 cm.chang
 * [BORA00000018]Integrate WIFI part into BORA for the 1st time
 * Fix system time is 32KHz instead of 1ms
 *
 * Nov 23 2009 mtk01088
 * [BORA00000476] [Wi-Fi][firmware] Add the security module initialize code
 * add the copy time function
 *
 * Nov 5 2009 mtk01461
 * [BORA00000018] Integrate WIFI part into BORA for the 1st time
 * Fix LINT warnning
 *
 * Oct 28 2009 mtk01104
 * [BORA00000018] Integrate WIFI part into BORA for the 1st time
 *
**
*/

#ifndef _CNM_TIMER_H
#define _CNM_TIMER_H

/*******************************************************************************
*                         C O M P I L E R   F L A G S
********************************************************************************
*/

/*******************************************************************************
*                    E X T E R N A L   R E F E R E N C E S
********************************************************************************
*/

/*******************************************************************************
*                              C O N S T A N T S
********************************************************************************
*/
#undef MSEC_PER_SEC
#define MSEC_PER_SEC                    1000
#undef USEC_PER_MSEC
#define USEC_PER_MSEC                   1000
#define USEC_PER_TU                     1024	/* microsecond */

#define MSEC_PER_MIN                    (60 * MSEC_PER_SEC)

#define MGMT_MAX_TIMEOUT_INTERVAL       ((UINT_32)0x7fffffff)

#define WAKE_LOCK_MAX_TIME              5	/* Unit: sec */

/* If WAKE_LOCK_MAX_TIME is too large, the whole system may always keep awake
 * because of periodic timer of OBSS scanning
 */
#if (WAKE_LOCK_MAX_TIME >= OBSS_SCAN_MIN_INTERVAL)
#error WAKE_LOCK_MAX_TIME is too large
#endif

/*******************************************************************************
*                             D A T A   T Y P E S
********************************************************************************
*/
typedef VOID(*PFN_MGMT_TIMEOUT_FUNC) (P_ADAPTER_T, UINT_32);

typedef struct _TIMER_T {
	LINK_ENTRY_T rLinkEntry;
	OS_SYSTIME rExpiredSysTime;
	UINT_16 u2Minutes;
	UINT_16 u2Reserved;
	UINT_32 u4Data;
	PFN_MGMT_TIMEOUT_FUNC pfMgmtTimeOutFunc;
} TIMER_T, *P_TIMER_T;

/*******************************************************************************
*                            P U B L I C   D A T A
********************************************************************************
*/

/*******************************************************************************
*                           P R I V A T E   D A T A
********************************************************************************
*/

/*******************************************************************************
*                                 M A C R O S
********************************************************************************
*/
/* Check if time "a" is before time "b" */
/* In 32-bit variable, 0x00000001~0x7fffffff -> positive number,
 *                     0x80000000~0xffffffff -> negative number
 */
#define TIME_BEFORE_64bit(a, b)       (a < b)

#define TIME_BEFORE(a, b)        ((UINT_32)((UINT_32)(a) - (UINT_32)(b)) > 0x7fffffff)

/* #define TIME_BEFORE(a,b)        ((INT_32)((INT_32)(b) - (INT_32)(a)) > 0)
 * may cause UNexpect result between Free build and Check build for WinCE
 */

#define TIME_AFTER(a, b)         TIME_BEFORE(b, a)

#define SYSTIME_TO_SEC(_systime)            ((_systime) / KAL_HZ)
#define SEC_TO_SYSTIME(_sec)                ((_sec) * KAL_HZ)

/* The macros to convert second & millisecond */
#define MSEC_TO_SEC(_msec)                  ((_msec) / MSEC_PER_SEC)
#define SEC_TO_MSEC(_sec)                   ((UINT_32)(_sec) * MSEC_PER_SEC)

/* The macros to convert millisecond & microsecond */
#define USEC_TO_MSEC(_usec)                 ((_usec) / USEC_PER_MSEC)
#define MSEC_TO_USEC(_msec)                 ((UINT_32)(_msec) * USEC_PER_MSEC)

/* The macros to convert TU & microsecond, TU & millisecond */
#define TU_TO_USEC(_tu)                     ((_tu) * USEC_PER_TU)
#define TU_TO_MSEC(_tu)                     USEC_TO_MSEC(TU_TO_USEC(_tu))

/* The macros to convert TU & & OS system time, round up by 0.5 */
#define TU_TO_SYSTIME(_tu)                  MSEC_TO_SYSTIME(TU_TO_MSEC(_tu))
#define SYSTIME_TO_TU(_systime)             \
    ((SYSTIME_TO_USEC(_systime) + ((USEC_PER_TU / 2) - 1)) / USEC_PER_TU)

/* The macros to convert OS system time & microsecond */
#define SYSTIME_TO_USEC(_systime)           (SYSTIME_TO_MSEC(_systime) * USEC_PER_MSEC)

/* The macro to get the current OS system time */
#define GET_CURRENT_SYSTIME(_systime_p)     {*(_systime_p) = kalGetTimeTick(); }

/* The macro to copy the system time */
#define COPY_SYSTIME(_destTime, _srcTime)   (_destTime) = (_srcTime)

/* The macro to get the system time difference between t1 and t2 (t1 - t2) */
/* #define GET_SYSTIME_DIFFERENCE(_time1, _time2, _diffTime) \
	(_diffTime) = (_time1) - (_time2) */

/* The macro to check for the expiration, if TRUE means _currentTime >= _expirationTime */
#define CHECK_FOR_EXPIRATION(_currentTime, _expirationTime) \
	(((UINT_32)(_currentTime) - (UINT_32)(_expirationTime)) <= 0x7fffffffUL)

/* The macro to check for the timeout */
#define CHECK_FOR_TIMEOUT(_currentTime, _timeoutStartingTime, _timeout) \
    CHECK_FOR_EXPIRATION((_currentTime), ((_timeoutStartingTime) + (_timeout)))

								   /* The macro to set the expiration time with a specified timeout *//* Watch out for round up. */
#define SET_EXPIRATION_TIME(_expirationTime, _timeout) \
	{ \
	    GET_CURRENT_SYSTIME(&(_expirationTime)); \
	    (_expirationTime) += (OS_SYSTIME)(_timeout); \
	}

#define timerRenewTimer(adapter, tmr, interval) \
        timerStartTimer(adapter, tmr, interval, (tmr)->function, (tmr)->data)

#define MGMT_INIT_TIMER(_adapter_p, _timer, _callbackFunc) \
	timerInitTimer(_adapter_p, &(_timer), (UINT_32)(_callbackFunc))

/*******************************************************************************
*                  F U N C T I O N   D E C L A R A T I O N S
********************************************************************************
*/
VOID cnmTimerInitialize(IN P_ADAPTER_T prAdapter);

VOID cnmTimerDestroy(IN P_ADAPTER_T prAdapter);

VOID
cnmTimerInitTimer(IN P_ADAPTER_T prAdapter,
		  IN P_TIMER_T prTimer, IN PFN_MGMT_TIMEOUT_FUNC pfFunc, IN UINT_32 u4Data);

VOID cnmTimerStopTimer(IN P_ADAPTER_T prAdapter, IN P_TIMER_T prTimer);

VOID cnmTimerStartTimer(IN P_ADAPTER_T prAdapter, IN P_TIMER_T prTimer, IN UINT_32 u4TimeoutMs);

VOID cnmTimerDoTimeOutCheck(IN P_ADAPTER_T prAdapter);

/*******************************************************************************
*                              F U N C T I O N S
********************************************************************************
*/
__KAL_INLINE__ INT_32 timerPendingTimer(IN P_TIMER_T prTimer)
{
	ASSERT(prTimer);

	return prTimer->rLinkEntry.prNext != NULL;
}

#endif				/* _CNM_TIMER_H */


text:
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
 * @unrestricted
 * @extends {DataGrid.DataGrid<!NODE_TYPE>}
 * @template NODE_TYPE
 */
DataGrid.ViewportDataGrid = class extends DataGrid.DataGrid {
  /**
   * @param {!Array.<!DataGrid.DataGrid.ColumnDescriptor>} columnsArray
   * @param {function(!NODE_TYPE, string, string, string)=} editCallback
   * @param {function(!NODE_TYPE)=} deleteCallback
   * @param {function()=} refreshCallback
   */
  constructor(columnsArray, editCallback, deleteCallback, refreshCallback) {
    super(columnsArray, editCallback, deleteCallback, refreshCallback);

    this._onScrollBound = this._onScroll.bind(this);
    this._scrollContainer.addEventListener('scroll', this._onScrollBound, true);

    // This is not in setScrollContainer because mouse wheel needs to detect events on the content not the scrollbar itself.
    this._scrollContainer.addEventListener('mousewheel', this._onWheel.bind(this), true);
    /** @type {!Array.<!DataGrid.ViewportDataGridNode>} */
    this._visibleNodes = [];
    /** @type {boolean} */
    this._inline = false;

    // Wheel target shouldn't be removed from DOM to preserve native kinetic scrolling.
    /** @type {?Node} */
    this._wheelTarget = null;

    // Element that was hidden earlier, but hasn't been removed yet.
    /** @type {?Node} */
    this._hiddenWheelTarget = null;

    /** @type {boolean} */
    this._stickToBottom = false;
    /** @type {boolean} */
    this._atBottom = true;
    /** @type {number} */
    this._lastScrollTop = 0;

    this.setRootNode(new DataGrid.ViewportDataGridNode());
  }

  /**
   * @param {!Element} scrollContainer
   */
  setScrollContainer(scrollContainer) {
    this._scrollContainer.removeEventListener('scroll', this._onScrollBound, true);
    this._scrollContainer = scrollContainer;
    this._scrollContainer.addEventListener('scroll', this._onScrollBound, true);
  }

  /**
   * @override
   */
  onResize() {
    if (this._stickToBottom && this._atBottom)
      this._scrollContainer.scrollTop = this._scrollContainer.scrollHeight - this._scrollContainer.clientHeight;
    this.scheduleUpdate();
    super.onResize();
  }

  /**
   * @param {boolean} stick
   */
  setStickToBottom(stick) {
    this._stickToBottom = stick;
  }

  /**
   * @param {?Event} event
   */
  _onWheel(event) {
    this._wheelTarget = event.target ? event.target.enclosingNodeOrSelfWithNodeName('tr') : null;
  }

  /**
   * @param {?Event} event
   */
  _onScroll(event) {
    this._atBottom = this._scrollContainer.isScrolledToBottom();
    if (this._lastScrollTop !== this._scrollContainer.scrollTop)
      this.scheduleUpdate();
  }

  /**
   * @protected
   */
  scheduleUpdateStructure() {
    this.scheduleUpdate();
  }

  scheduleUpdate() {
    if (this._updateAnimationFrameId)
      return;
    this._updateAnimationFrameId = this.element.window().requestAnimationFrame(this._update.bind(this));
  }

  updateInstantlyForTests() {
    if (!this._updateAnimationFrameId)
      return;
    this.element.window().cancelAnimationFrame(this._updateAnimationFrameId);
    this._update();
  }

  /**
   * @override
   */
  renderInline() {
    this._inline = true;
    super.renderInline();
    this._update();
  }

  /**
   * @param {number} clientHeight
   * @param {number} scrollTop
   * @return {{topPadding: number, bottomPadding: number, contentHeight: number, visibleNodes: !Array.<!DataGrid.ViewportDataGridNode>, offset: number}}
   */
  _calculateVisibleNodes(clientHeight, scrollTop) {
    var nodes = this.rootNode().flatChildren();
    if (this._inline)
      return {topPadding: 0, bottomPadding: 0, contentHeight: 0, visibleNodes: nodes, offset: 0};

    var size = nodes.length;
    var i = 0;
    var y = 0;

    for (; i < size && y + nodes[i].nodeSelfHeight() < scrollTop; ++i)
      y += nodes[i].nodeSelfHeight();
    var start = i;
    var topPadding = y;

    for (; i < size && y < scrollTop + clientHeight; ++i)
      y += nodes[i].nodeSelfHeight();
    var end = i;

    var bottomPadding = 0;
    for (; i < size; ++i)
      bottomPadding += nodes[i].nodeSelfHeight();

    return {
      topPadding: topPadding,
      bottomPadding: bottomPadding,
      contentHeight: y - topPadding,
      visibleNodes: nodes.slice(start, end),
      offset: start
    };
  }

  /**
   * @return {number}
   */
  _contentHeight() {
    var nodes = this.rootNode().flatChildren();
    var result = 0;
    for (var i = 0, size = nodes.length; i < size; ++i)
      result += nodes[i].nodeSelfHeight();
    return result;
  }

  _update() {
    if (this._updateAnimationFrameId) {
      this.element.window().cancelAnimationFrame(this._updateAnimationFrameId);
      delete this._updateAnimationFrameId;
    }

    var clientHeight = this._scrollContainer.clientHeight;
    var scrollTop = this._scrollContainer.scrollTop;
    var currentScrollTop = scrollTop;
    var maxScrollTop = Math.max(0, this._contentHeight() - clientHeight);
    if (this._stickToBottom && this._atBottom)
      scrollTop = maxScrollTop;
    scrollTop = Math.min(maxScrollTop, scrollTop);
    this._atBottom = scrollTop === maxScrollTop;

    var viewportState = this._calculateVisibleNodes(clientHeight, scrollTop);
    var visibleNodes = viewportState.visibleNodes;
    var visibleNodesSet = new Set(visibleNodes);

    if (this._hiddenWheelTarget && this._hiddenWheelTarget !== this._wheelTarget) {
      this._hiddenWheelTarget.remove();
      this._hiddenWheelTarget = null;
    }

    for (var i = 0; i < this._visibleNodes.length; ++i) {
      var oldNode = this._visibleNodes[i];
      if (!visibleNodesSet.has(oldNode) && oldNode.attached()) {
        var element = oldNode.existingElement();
        if (element === this._wheelTarget)
          this._hiddenWheelTarget = oldNode.abandonElement();
        else
          element.remove();
        oldNode.wasDetached();
      }
    }

    var previousElement = this.topFillerRowElement();
    if (previousElement.nextSibling === this._hiddenWheelTarget)
      previousElement = this._hiddenWheelTarget;
    var tBody = this.dataTableBody;
    var offset = viewportState.offset;
    for (var i = 0; i < visibleNodes.length; ++i) {
      var node = visibleNodes[i];
      var element = node.element();
      node.willAttach();
      element.classList.toggle('odd', (offset + i) % 2 === 0);
      tBody.insertBefore(element, previousElement.nextSibling);
      node.revealed = true;
      previousElement = element;
    }

    this.setVerticalPadding(viewportState.topPadding, viewportState.bottomPadding);
    this._lastScrollTop = scrollTop;
    if (scrollTop !== currentScrollTop)
      this._scrollContainer.scrollTop = scrollTop;
    var contentFits =
        viewportState.contentHeight <= clientHeight && viewportState.topPadding + viewportState.bottomPadding === 0;
    if (contentFits !== this.element.classList.contains('data-grid-fits-viewport')) {
      this.element.classList.toggle('data-grid-fits-viewport', contentFits);
      this.updateWidths();
    }
    this._visibleNodes = visibleNodes;
    this.dispatchEventToListeners(DataGrid.ViewportDataGrid.Events.ViewportCalculated);
  }

  /**
   * @param {!DataGrid.ViewportDataGridNode} node
   */
  _revealViewportNode(node) {
    var nodes = this.rootNode().flatChildren();
    var index = nodes.indexOf(node);
    if (index === -1)
      return;
    var fromY = 0;
    for (var i = 0; i < index; ++i)
      fromY += nodes[i].nodeSelfHeight();
    var toY = fromY + node.nodeSelfHeight();

    var scrollTop = this._scrollContainer.scrollTop;
    if (scrollTop > fromY) {
      scrollTop = fromY;
      this._atBottom = false;
    } else if (scrollTop + this._scrollContainer.offsetHeight < toY) {
      scrollTop = toY - this._scrollContainer.offsetHeight;
    }
    this._scrollContainer.scrollTop = scrollTop;
  }
};

DataGrid.ViewportDataGrid.Events = {
  ViewportCalculated: Symbol('ViewportCalculated')
};

/**
 * @unrestricted
 * @this {NODE_TYPE}
 * @extends {DataGrid.DataGridNode<!NODE_TYPE>}
 * @template NODE_TYPE
 */
DataGrid.ViewportDataGridNode = class extends DataGrid.DataGridNode {
  /**
   * @param {?Object.<string, *>=} data
   * @param {boolean=} hasChildren
   */
  constructor(data, hasChildren) {
    super(data, hasChildren);
    /** @type {boolean} */
    this._stale = false;
    /** @type {?Array<!DataGrid.ViewportDataGridNode>} */
    this._flatNodes = null;
  }

  /**
   * @override
   * @return {!Element}
   */
  element() {
    var existingElement = this.existingElement();
    var element = existingElement || this.createElement();
    if (!existingElement || this._stale) {
      this.createCells(element);
      this._stale = false;
    }
    return element;
  }

  _clearFlatNodes() {
    this._flatNodes = null;
    var parent = /** @type {!DataGrid.ViewportDataGridNode} */ (this.parent);
    if (parent)
      parent._clearFlatNodes();
  }

  /**
   * @return {!Array<!DataGrid.ViewportDataGridNode>}
   */
  flatChildren() {
    if (this._flatNodes)
      return this._flatNodes;
    /** @type {!Array<!DataGrid.ViewportDataGridNode>} */
    var flatNodes = [];
    /** @type {!Array<!Array<!DataGrid.ViewportDataGridNode>>} */
    var children = [this.children];
    /** @type {!Array<number>} */
    var counters = [0];
    var depth = 0;
    while (depth >= 0) {
      if (children[depth].length <= counters[depth]) {
        depth--;
        continue;
      }
      var node = children[depth][counters[depth]++];
      flatNodes.push(node);
      if (node._expanded && node.children.length) {
        depth++;
        children[depth] = node.children;
        counters[depth] = 0;
      }
    }

    this._flatNodes = flatNodes;
    return flatNodes;
  }

  /**
   * @override
   * @param {!NODE_TYPE} child
   * @param {number} index
   */
  insertChild(child, index) {
    this._clearFlatNodes();
    if (child.parent === this) {
      var currentIndex = this.children.indexOf(child);
      if (currentIndex < 0)
        console.assert(false, 'Inconsistent DataGrid state');
      if (currentIndex === index)
        return;
      if (currentIndex < index)
        --index;
    }
    child.remove();
    child.parent = this;
    child.dataGrid = this.dataGrid;
    if (!this.children.length)
      this.setHasChildren(true);
    this.children.splice(index, 0, child);
    child.recalculateSiblings(index);
    if (this._expanded)
      this.dataGrid.scheduleUpdateStructure();
  }

  /**
   * @override
   * @param {!NODE_TYPE} child
   */
  removeChild(child) {
    this._clearFlatNodes();
    if (this.dataGrid)
      this.dataGrid.updateSelectionBeforeRemoval(child, false);
    if (child.previousSibling)
      child.previousSibling.nextSibling = child.nextSibling;
    if (child.nextSibling)
      child.nextSibling.previousSibling = child.previousSibling;
    if (child.parent !== this)
      throw 'removeChild: Node is not a child of this node.';

    child._unlink();
    this.children.remove(child, true);
    if (!this.children.length)
      this.setHasChildren(false);
    if (this._expanded)
      this.dataGrid.scheduleUpdateStructure();
  }

  /**
   * @override
   */
  removeChildren() {
    this._clearFlatNodes();
    if (this.dataGrid)
      this.dataGrid.updateSelectionBeforeRemoval(this, true);
    for (var i = 0; i < this.children.length; ++i)
      this.children[i]._unlink();
    this.children = [];

    if (this._expanded)
      this.dataGrid.scheduleUpdateStructure();
  }

  _unlink() {
    if (this.attached()) {
      this.existingElement().remove();
      this.wasDetached();
    }
    this.dataGrid = null;
    this.parent = null;
    this.nextSibling = null;
    this.previousSibling = null;
  }

  /**
   * @override
   */
  collapse() {
    if (!this._expanded)
      return;
    this._clearFlatNodes();
    this._expanded = false;
    if (this.existingElement())
      this.existingElement().classList.remove('expanded');
    this.dataGrid.scheduleUpdateStructure();
  }

  /**
   * @override
   */
  expand() {
    if (this._expanded)
      return;
    this._clearFlatNodes();
    super.expand();
    this.dataGrid.scheduleUpdateStructure();
  }

  /**
   * @protected
   */
  willAttach() {
  }

  /**
   * @protected
   * @return {boolean}
   */
  attached() {
    return !!(this.dataGrid && this.existingElement() && this.existingElement().parentElement);
  }

  /**
   * @override
   */
  refresh() {
    if (this.attached()) {
      this._stale = true;
      this.dataGrid.scheduleUpdate();
    } else {
      this.resetElement();
    }
  }

  /**
   * @return {?Element}
   */
  abandonElement() {
    var result = this.existingElement();
    if (result)
      result.style.display = 'none';
    this.resetElement();
    return result;
  }

  /**
   * @override
   */
  reveal() {
    this.dataGrid._revealViewportNode(this);
  }

  /**
   * @override
   * @param {number} index
   */
  recalculateSiblings(index) {
    this._clearFlatNodes();
    super.recalculateSiblings(index);
  }
};


text:
namespace ppapi {

namespace {

void CallAddRef(const PP_Var& v) {
  PpapiGlobals::Get()->GetVarTracker()->AddRefVar(v);
}

void CallRelease(const PP_Var& v) {
  PpapiGlobals::Get()->GetVarTracker()->ReleaseVar(v);
}

}  // namespace

ScopedPPVar::ScopedPPVar() : var_(PP_MakeUndefined()) {
}

ScopedPPVar::ScopedPPVar(const PP_Var& v) : var_(v) {
  CallAddRef(var_);
}

ScopedPPVar::ScopedPPVar(const PassRef&, const PP_Var& v) : var_(v) {
}

ScopedPPVar::ScopedPPVar(const ScopedPPVar& other)
    : var_(other.var_) {
  CallAddRef(var_);
}

ScopedPPVar::~ScopedPPVar() {
  CallRelease(var_);
}

ScopedPPVar& ScopedPPVar::operator=(const PP_Var& v) {
  CallAddRef(v);
  CallRelease(var_);
  var_ = v;
  return *this;
}

PP_Var ScopedPPVar::Release() {
  PP_Var result = var_;
  var_ = PP_MakeUndefined();
  return result;
}

}  // namespace ppapi


text:
package org.napile.idea.plugin.structureView;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.napile.compiler.lang.psi.NapileFile;
import com.intellij.ide.structureView.StructureViewBuilder;
import com.intellij.ide.structureView.StructureViewModel;
import com.intellij.ide.structureView.TreeBasedStructureViewBuilder;
import com.intellij.lang.PsiStructureViewFactory;
import com.intellij.openapi.editor.Editor;
import com.intellij.psi.PsiFile;

/**
 * @author yole
 */
public class NapileStructureViewFactory implements PsiStructureViewFactory
{
	@Override
	public StructureViewBuilder getStructureViewBuilder(final PsiFile psiFile)
	{
		if(psiFile instanceof NapileFile)
		{
			final NapileFile file = (NapileFile) psiFile;

			return new TreeBasedStructureViewBuilder()
			{
				@NotNull
				@Override
				public StructureViewModel createStructureViewModel(@Nullable Editor editor)
				{
					return new NapileStructureViewModel(file);
				}
			};
		}

		return null;
	}
}


text:
/**
 * Created by alexandr.dascal on 2/24/2015.
 */

(function () {
    'use strict';

    angular.module('angular-m-validation', [
        'angular-m-validation.rules',
        'angular-m-validation.providers',
        'angular-m-validation.directives'
    ]);

    angular.module('angular-m-validation.rules', []);
    angular.module('angular-m-validation.providers', []);
    angular.module('angular-m-validation.directives', [
        'angular-m-validation.rules',
        'angular-m-validation.providers'
    ]);
})();


text:
Written in Java, built on NetBeans and using SQLite, it helps the user find the cartridge for any specific printer.

# Dependencies:
[sqlite-jdbc]

#SQLite Table Structure

- Table names based on their brands: Canon, Epson, HP, Lexmark.

- Model TEXT PRIMARY KEY

- Cartridges TEXT

[sqlite-jdbc]:https://github.com/xerial/sqlite-jdbc


text:
"""Tests for VectorDiffeomixture."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import numpy as np

from tensorflow.contrib.distributions.python.ops import test_util
from tensorflow.contrib.distributions.python.ops import vector_diffeomixture as vector_diffeomixture_lib
from tensorflow.python.framework import dtypes
from tensorflow.python.ops import array_ops
from tensorflow.python.ops.distributions import normal as normal_lib
from tensorflow.python.ops.linalg import linear_operator_diag as linop_diag_lib
from tensorflow.python.ops.linalg import linear_operator_identity as linop_identity_lib
from tensorflow.python.platform import test

class VectorDiffeomixtureTest(
    test_util.VectorDistributionTestHelpers, test.TestCase):
  """Tests the VectorDiffeomixture distribution."""

  def testSampleProbConsistentBroadcastMixNoBatch(self):
    with self.test_session() as sess:
      dims = 4
      vdm = vector_diffeomixture_lib.VectorDiffeomixture(
          mix_loc=[[0.], [1.]],
          mix_scale=[1.],
          distribution=normal_lib.Normal(0., 1.),
          loc=[
              None,
              np.float32([2.]*dims),
          ],
          scale=[
              linop_identity_lib.LinearOperatorScaledIdentity(
                  num_rows=dims,
                  multiplier=np.float32(1.1),
                  is_positive_definite=True),
              linop_diag_lib.LinearOperatorDiag(
                  diag=np.linspace(2.5, 3.5, dims, dtype=np.float32),
                  is_positive_definite=True),
          ],
          validate_args=True)
      # Ball centered at component0's mean.
      self.run_test_sample_consistent_log_prob(
          sess.run, vdm, radius=2., center=0., rtol=0.005)
      # Larger ball centered at component1's mean.
      self.run_test_sample_consistent_log_prob(
          sess.run, vdm, radius=4., center=2., rtol=0.005)

  def testSampleProbConsistentBroadcastMixNonStandardBase(self):
    with self.test_session() as sess:
      dims = 4
      vdm = vector_diffeomixture_lib.VectorDiffeomixture(
          mix_loc=[[0.], [1.]],
          mix_scale=[1.],
          distribution=normal_lib.Normal(1., 1.5),
          loc=[
              None,
              np.float32([2.]*dims),
          ],
          scale=[
              linop_identity_lib.LinearOperatorScaledIdentity(
                  num_rows=dims,
                  multiplier=np.float32(1.1),
                  is_positive_definite=True),
              linop_diag_lib.LinearOperatorDiag(
                  diag=np.linspace(2.5, 3.5, dims, dtype=np.float32),
                  is_positive_definite=True),
          ],
          validate_args=True)
      # Ball centered at component0's mean.
      self.run_test_sample_consistent_log_prob(
          sess.run, vdm, radius=2., center=1., rtol=0.006)
      # Larger ball centered at component1's mean.
      self.run_test_sample_consistent_log_prob(
          sess.run, vdm, radius=4., center=3., rtol=0.009)

  def testSampleProbConsistentBroadcastMixBatch(self):
    with self.test_session() as sess:
      dims = 4
      vdm = vector_diffeomixture_lib.VectorDiffeomixture(
          mix_loc=[[0.], [1.]],
          mix_scale=[1.],
          distribution=normal_lib.Normal(0., 1.),
          loc=[
              None,
              np.float32([2.]*dims),
          ],
          scale=[
              linop_identity_lib.LinearOperatorScaledIdentity(
                  num_rows=dims,
                  multiplier=[np.float32(1.1)],
                  is_positive_definite=True),
              linop_diag_lib.LinearOperatorDiag(
                  diag=np.stack([
                      np.linspace(2.5, 3.5, dims, dtype=np.float32),
                      np.linspace(2.75, 3.25, dims, dtype=np.float32),
                  ]),
                  is_positive_definite=True),
          ],
          validate_args=True)
      # Ball centered at component0's mean.
      self.run_test_sample_consistent_log_prob(
          sess.run, vdm, radius=2., center=0., rtol=0.005)
      # Larger ball centered at component1's mean.
      self.run_test_sample_consistent_log_prob(
          sess.run, vdm, radius=4., center=2., rtol=0.005)

  def testMeanCovarianceNoBatch(self):
    with self.test_session() as sess:
      dims = 3
      vdm = vector_diffeomixture_lib.VectorDiffeomixture(
          mix_loc=[[0.], [4.]],
          mix_scale=[10.],
          distribution=normal_lib.Normal(0., 1.),
          loc=[
              np.float32([-2.]),
              None,
          ],
          scale=[
              linop_identity_lib.LinearOperatorScaledIdentity(
                  num_rows=dims,
                  multiplier=np.float32(1.5),
                  is_positive_definite=True),
              linop_diag_lib.LinearOperatorDiag(
                  diag=np.linspace(2.5, 3.5, dims, dtype=np.float32),
                  is_positive_definite=True),
          ],
          validate_args=True)
      self.run_test_sample_consistent_mean_covariance(
          sess.run, vdm, rtol=0.02, cov_rtol=0.06)

  def testMeanCovarianceNoBatchUncenteredNonStandardBase(self):
    with self.test_session() as sess:
      dims = 3
      vdm = vector_diffeomixture_lib.VectorDiffeomixture(
          mix_loc=[[0.], [4.]],
          mix_scale=[10.],
          distribution=normal_lib.Normal(-1., 1.5),
          loc=[
              np.float32([-2.]),
              np.float32([0.]),
          ],
          scale=[
              linop_identity_lib.LinearOperatorScaledIdentity(
                  num_rows=dims,
                  multiplier=np.float32(1.5),
                  is_positive_definite=True),
              linop_diag_lib.LinearOperatorDiag(
                  diag=np.linspace(2.5, 3.5, dims, dtype=np.float32),
                  is_positive_definite=True),
          ],
          validate_args=True)
      self.run_test_sample_consistent_mean_covariance(
          sess.run, vdm, num_samples=int(1e6), rtol=0.01, cov_atol=0.025)

  def testMeanCovarianceBatch(self):
    with self.test_session() as sess:
      dims = 3
      vdm = vector_diffeomixture_lib.VectorDiffeomixture(
          mix_loc=[[0.], [4.]],
          mix_scale=[10.],
          distribution=normal_lib.Normal(0., 1.),
          loc=[
              np.float32([[-2.]]),
              None,
          ],
          scale=[
              linop_identity_lib.LinearOperatorScaledIdentity(
                  num_rows=dims,
                  multiplier=[np.float32(1.5)],
                  is_positive_definite=True),
              linop_diag_lib.LinearOperatorDiag(
                  diag=np.stack([
                      np.linspace(2.5, 3.5, dims, dtype=np.float32),
                      np.linspace(0.5, 1.5, dims, dtype=np.float32),
                  ]),
                  is_positive_definite=True),
          ],
          validate_args=True)
      self.run_test_sample_consistent_mean_covariance(
          sess.run, vdm, rtol=0.02, cov_rtol=0.06)

  def testSampleProbConsistentDynamicQuadrature(self):
    with self.test_session() as sess:
      qgrid = array_ops.placeholder(dtype=dtypes.float32)
      qprobs = array_ops.placeholder(dtype=dtypes.float32)
      g, p = np.polynomial.hermite.hermgauss(deg=8)
      dims = 4
      vdm = vector_diffeomixture_lib.VectorDiffeomixture(
          mix_loc=[[0.], [1.]],
          mix_scale=[1.],
          distribution=normal_lib.Normal(0., 1.),
          loc=[
              None,
              np.float32([2.]*dims),
          ],
          scale=[
              linop_identity_lib.LinearOperatorScaledIdentity(
                  num_rows=dims,
                  multiplier=np.float32(1.1),
                  is_positive_definite=True),
              linop_diag_lib.LinearOperatorDiag(
                  diag=np.linspace(2.5, 3.5, dims, dtype=np.float32),
                  is_positive_definite=True),
          ],
          quadrature_grid_and_probs=(g, p),
          validate_args=True)
      # Ball centered at component0's mean.
      sess_run_fn = lambda x: sess.run(x, feed_dict={qgrid: g, qprobs: p})
      self.run_test_sample_consistent_log_prob(
          sess_run_fn, vdm, radius=2., center=0., rtol=0.005)
      # Larger ball centered at component1's mean.
      self.run_test_sample_consistent_log_prob(
          sess_run_fn, vdm, radius=4., center=2., rtol=0.005)

  # TODO(jvdillon): We've tested that (i) .sample and .log_prob are consistent,
  # (ii) .mean, .stddev etc... and .sample are consistent. However, we haven't
  # tested that the quadrature approach well-approximates the integral.
  #
  # To that end, consider adding these tests:
  #
  # Test1: In the limit of high mix_scale, this approximates a discrete mixture,
  # and there are many discrete mixtures where we can explicitly compute
  # mean/var, etc... So test1 would choose one of those discrete mixtures and
  # show our mean/var/etc... is close to that.
  #
  # Test2:  In the limit of low mix_scale, the a diffeomixture of Normal(-5, 1),
  # Normal(5, 1) should (I believe...must check) should look almost like
  # Uniform(-5, 5), and thus (i) .prob(x) should be about 1/10 for x in (-5, 5),
  # and (ii) the first few moments should approximately match that of
  # Uniform(-5, 5)
  #
  # Test3:  If mix_loc is symmetric, then for any mix_scale, our
  # quadrature-based diffeomixture of Normal(-1, 1), Normal(1, 1) should have
  # mean zero, exactly.

  # TODO(jvdillon): Add more tests which verify broadcasting.

if __name__ == "__main__":
  test.main()