text:
package com.tvd12.ezyfox.bean.supplier;

import com.tvd12.ezyfox.bean.EzyBeanContext;
import com.tvd12.ezyfox.bean.EzyPrototypeSupplier;

import java.util.ArrayList;
import java.util.Collection;

public final class EzyCollectionSupplier implements EzyPrototypeSupplier {

    private static final EzyCollectionSupplier INSTANCE = new EzyCollectionSupplier();

    private EzyCollectionSupplier() {}

    public static EzyCollectionSupplier getInstance() {
        return INSTANCE;
    }

    @Override
    public Object supply(EzyBeanContext context) {
        return new ArrayList<>();
    }

    @Override
    public Class<?> getObjectType() {
        return Collection.class;
    }
}

redpajama_set_name: RedPajamaGithub


text:
var _ = require('@sailshq/lodash');

module.exports = function(sails) {

    /**
     * `userhooks`
     *
     * Sails hook for loading user plugins (hooks)
     */
    return {

        defaults: { },

        initialize: function(cb) {

            if ( !sails.config.hooks.moduleloader ) {
                return cb('Cannot load user hooks without `moduleloader` hook enabled!');
            }

            // Wait for moduleloader
            sails.log.verbose('Loading user hooks...');

            // Load user hook definitions
            sails.modules.loadUserHooks(function hookDefinitionsLoaded(err, hooks) {
                if (err) return cb(err);

        // Ensure hooks is valid
        hooks = _.isObject(hooks) ? hooks : {};

        // Add the user hooks to the list of hooks to load
        _.extend(sails.hooks, hooks);

                return cb();

            });
        }
    };
};


text:
title: Not found
---

Not found :(

Sorry, but the page you were trying to view does not exist.

It looks like this was the result of either:

a mistyped address

an out-of-date link


text:
from django.core.exceptions import ValidationError
from django.db import IntegrityError
from django.utils import timezone

from consents.models import Consent, Term, TermOption
from consents.tests.base import ConsentTestBase
from workshops.models import Person

class TestQuerySet(ConsentTestBase):
    def test_term_active(self) -> None:
        term1 = Term.objects.create(
            content="term1", slug="term1", archived_at=timezone.now()
        )
        term2 = Term.objects.create(
            content="term2",
            slug="term2",
        )
        active_terms = Term.objects.active()
        self.assertNotIn(term1, active_terms)
        self.assertIn(term2, active_terms)

    def test_term_prefetch_active_options(self) -> None:
        term1 = Term.objects.create(content="term1", slug="term1")
        term2 = Term.objects.create(
            content="term2",
            slug="term2",
        )

        term1_option1 = TermOption.objects.create(
            term=term1,
            option_type="agree",
            content="option1",
        )
        TermOption.objects.create(
            term=term1,
            option_type="agree",
            content="option2",
            archived_at=timezone.now(),
        )
        term2_option1 = TermOption.objects.create(
            term=term2,
            option_type="agree",
            content="option1",
        )
        terms = Term.objects.all().prefetch_active_options()
        self.assertEqual(terms.filter(id=term1.id)[0].active_options, [term1_option1])
        self.assertEqual(terms.filter(id=term2.id)[0].active_options, [term2_option1])

    def test_consent_active(self) -> None:
        term1 = Term.objects.create(content="term1", slug="term1")
        term1_option1 = TermOption.objects.create(
            term=term1,
            option_type="agree",
            content="option1",
        )
        person1 = Person.objects.create(
            personal="Harry", family="Potter", email="hp@magic.uk"
        )
        person2 = Person.objects.create(
            personal="Ron",
            family="Weasley",
            email="rw@magic.uk",
            username="rweasley",
        )
        consent1 = self.reconsent(person1, term1, term1_option1)
        consent2 = self.reconsent(person2, term1, term1_option1)
        consents = Consent.objects.filter(
            term=term1, person__in=[person1, person2]
        ).active()

        self.assertCountEqual(consents, [consent1, consent2])

class TestConsentModel(ConsentTestBase):
    def test_unique_constraint(self) -> None:
        term1 = Term.objects.create(content="term1", slug="term1")
        TermOption.objects.create(
            term=term1,
            option_type="agree",
            content="option1",
        )
        term1_option2 = TermOption.objects.create(
            term=term1,
            option_type="agree",
            content="option2",
        )
        person1 = Person.objects.create(
            personal="Harry", family="Potter", email="hp@magic.uk"
        )
        # assert active consent exists for this term
        self.assertTrue(
            Consent.objects.filter(person=person1, term=term1).active().exists()
        )
        with self.assertRaises(IntegrityError):
            # create without archiving pre-existing active consent.
            Consent.objects.create(
                person=person1, term=term1, term_option=term1_option2
            )

    def test_term_and_term_option_should_match(self):
        """Term was added to the Consent model to avoid too many complicated joins.
        The term option should always be related to the term stored in the table."""
        term1 = Term.objects.create(content="term1", slug="term1")
        term2_option1 = TermOption.objects.create(
            term=Term.objects.create(content="term2", slug="term2"),
            option_type="agree",
            content="option1",
        )
        person = Person.objects.create(
            personal="Harry", family="Potter", email="hp@magic.uk"
        )
        with self.assertRaisesRegex(
            ValidationError, "Consent term.id must match term_option.term_id"
        ):
            Consent.objects.create(person=person, term=term1, term_option=term2_option1)

    def test_term_options(self) -> None:
        term1 = Term.objects.create(content="term1", slug="term1")
        term1_option1 = TermOption.objects.create(
            term=term1,
            option_type="agree",
            content="option1",
        )
        term1_option2 = TermOption.objects.create(
            term=term1,
            option_type="agree",
            content="option2",
        )
        term2 = Term.objects.create(content="term2", slug="term2")
        term2_option1 = TermOption.objects.create(
            term=term2,
            option_type="agree",
            content="option1",
        )
        term2_option2 = TermOption.objects.create(
            term=term2,
            option_type="agree",
            content="option2",
        )
        # Term options method is cached and requires only one
        # query even during subsequent calls
        with self.assertNumQueries(2):
            self.assertCountEqual(term1.options, [term1_option1, term1_option2])
            self.assertCountEqual(term2.options, [term2_option1, term2_option2])
            term1.options
            term2.options

        # term.options after prefetch_options does not need
        # an additional query
        terms = Term.objects.filter(
            slug__in=[term1.slug, term2.slug]
        ).prefetch_active_options()
        self.assertEqual(len(terms), 2)
        with self.assertNumQueries(0):
            self.assertCountEqual(terms[0].options, [term1_option1, term1_option2])
            self.assertCountEqual(terms[1].options, [term2_option1, term2_option2])
            self.assertCountEqual(term1.options, [term1_option1, term1_option2])
            self.assertCountEqual(term2.options, [term2_option1, term2_option2])

    def test_archive_all_for_person(self) -> None:
        """
        Archive all should archive the given consents
        then bulk create new unset consents.
        """
        terms = Term.objects.active()
        self.assertNotEqual(len(terms), 0)
        person1 = Person.objects.create(
            personal="Harry", family="Potter", email="hp@magic.uk"
        )
        person2 = Person.objects.create(
            personal="Ron",
            family="Weasley",
            email="rw@magic.uk",
            username="rweasley",
        )
        # both people consent to all terms
        self.person_consent_active_terms(person1)
        self.person_consent_active_terms(person2)
        active_consents = Consent.objects.active()
        self.assertEqual(
            len(active_consents.filter(person=person1, term_option__isnull=False)),
            len(terms),
        )
        self.assertEqual(
            len(active_consents.filter(person=person2, term_option__isnull=False)),
            len(terms),
        )

        Consent.archive_all_for_person(person1)
        active_consents = Consent.objects.active()
        # All consents for person1 is archived. And a new unset consent is active
        self.assertEqual(
            len(active_consents.filter(person=person1, term_option__isnull=False)), 0
        )
        self.assertEqual(
            len(active_consents.filter(person=person1, term_option__isnull=True)),
            len(terms),
        )
        # person2 consents remain unchanged
        self.assertEqual(
            len(active_consents.filter(person=person2, term_option__isnull=False)),
            len(terms),
        )

class TestTermModel(ConsentTestBase):
    def test_archive(self):
        """
        Term archive method should archive the term
        and all related term options and consents.
        """
        term1 = Term.objects.create(content="term1", slug="term1")
        term1_option1 = TermOption.objects.create(
            term=term1,
            option_type="agree",
            content="option1",
        )
        term1_option2 = TermOption.objects.create(
            term=term1,
            option_type="agree",
            content="option2",
        )

        person1 = Person.objects.create(
            personal="Harry", family="Potter", email="hp@magic.uk"
        )
        person2 = Person.objects.create(
            personal="Ron",
            family="Weasley",
            email="rw@magic.uk",
            username="rweasley",
        )

        consent1 = self.reconsent(person1, term1, term1_option1)
        consent2 = self.reconsent(person2, term1, term1_option2)

        # Unrelated term, option, and consent.
        # They should not appear in the queries below
        unrelated_option = TermOption.objects.create(
            term=Term.objects.create(content="unrealted", slug="unrelated"),
            option_type="agree",
            content="option",
        )
        consent3 = self.reconsent(person2, unrelated_option.term, unrelated_option)

        term1.archive()

        # Term should be archived
        archived_term_ids = [
            term.pk for term in Term.objects.filter(archived_at__isnull=False)
        ]
        self.assertEqual(
            [term1.pk],
            archived_term_ids,
        )
        # Term options should be archived
        archived_term_option_ids = [
            option.pk for option in TermOption.objects.filter(archived_at__isnull=False)
        ]
        self.assertCountEqual(
            [term1_option1.pk, term1_option2.pk],
            archived_term_option_ids,
        )
        # Consents should be archived
        archived_consent_ids = [
            consent.pk for consent in Consent.objects.filter(archived_at__isnull=False)
        ]
        self.assertIn(consent1.pk, archived_consent_ids)
        self.assertIn(consent2.pk, archived_consent_ids)
        # Unrelated consent should not be archived
        self.assertNotIn(consent3.pk, archived_consent_ids)

    def test_clean(self):
        """Ensure required terms have at least one yes term option"""
        term = Term.objects.create(
            slug="required-test-term",
            content="term content",
            required_type=Term.PROFILE_REQUIRE_TYPE,
        )
        error_message = "Required term required-test-term must have agree term option."
        with self.assertRaisesMessage(ValidationError, error_message):
            term.clean()
        # Adding a no term is not enough
        TermOption.objects.create(
            term=term,
            option_type="decline",
            content="no",
        )
        with self.assertRaisesMessage(ValidationError, error_message):
            term.clean()
        # Adding a yes term is enough
        TermOption.objects.create(
            term=term,
            option_type="agree",
            content="yes",
        )
        # no error is thrown
        term.clean()

class TestTermOptionModel(ConsentTestBase):
    def test_archive(self):
        """
        TermOption archive method should archive the TermOption
        and all related consents.
        """
        term1 = Term.objects.create(content="term1", slug="term1")
        term1_option1 = TermOption.objects.create(
            term=term1,
            option_type="agree",
            content="option1",
        )
        term1_option2 = TermOption.objects.create(
            term=term1,
            option_type="agree",
            content="option2",
        )

        person1 = Person.objects.create(
            personal="Harry", family="Potter", email="hp@magic.uk"
        )
        person2 = Person.objects.create(
            personal="Ron",
            family="Weasley",
            email="rw@magic.uk",
            username="rweasley",
        )
        consent1 = self.reconsent(person1, term1, term1_option1)
        consent2 = self.reconsent(person2, term1, term1_option2)
        # Unrelated term, option, and consent.
        # They should not appear in the queries below
        unrelated_option = TermOption.objects.create(
            term=Term.objects.create(content="unrealted", slug="unrelated"),
            option_type="agree",
            content="option",
        )
        consent3 = self.reconsent(person2, unrelated_option.term, unrelated_option)

        term1_option1.archive()

        # Term should not be archived
        archived_term_ids = [
            term.pk for term in Term.objects.filter(archived_at__isnull=False)
        ]
        self.assertEqual(len(archived_term_ids), 0)

        # Only 1 Term options should be archived
        archived_term_option_ids = [
            option.pk for option in TermOption.objects.filter(archived_at__isnull=False)
        ]
        self.assertEqual(
            [term1_option1.pk],
            archived_term_option_ids,
        )

        # Only related consents should be archived
        archived_consent_ids = [
            consent.pk for consent in Consent.objects.filter(archived_at__isnull=False)
        ]
        self.assertIn(consent1.pk, archived_consent_ids)
        # Unrelated consent should not be archived
        self.assertNotIn(consent2.pk, archived_consent_ids)
        self.assertNotIn(consent3.pk, archived_consent_ids)

    def test_cannot_archive_only_yes_option_for_required_term(self) -> None:
        """Raise an error if trying to archive the only yes option in a required term"""
        term = Term.objects.create(
            slug="required-test-term",
            content="term content",
            required_type=Term.PROFILE_REQUIRE_TYPE,
        )
        term_option = TermOption.objects.create(
            term=term,
            option_type="agree",
            content="yes",
        )
        error_message = (
            "Term option {term_option} is the only agree term option for required term"
            " required-test-term."
            " Please add an additional agree option or archive the term instead."
        )
        with self.assertRaisesMessage(
            ValidationError, error_message.format(term_option=term_option)
        ):
            term_option.archive()
        # Adding another yes term
        new_yes_term = TermOption.objects.create(
            term=term,
            option_type="agree",
            content="new yes",
        )
        # We can now archive original yes term
        term_option.archive()
        # cannot archive new yes term
        with self.assertRaisesMessage(
            ValidationError, error_message.format(term_option=new_yes_term)
        ):
            new_yes_term.archive()


text: return "hello from string.lua"


text:
import scala.xml._
import scala.io.Source

object S2ConHashTag extends Application{
    val url = "http://search.twitter.com/search.atom?q=sc2009autumn"
    val source = Source.fromURL( url )
    val xml = XML.loadString( source.getLines.mkString )
    for( entry <- xml \\ "entry" ;
         c = entry \\ "content" text ;
         user = entry \\ "author" \\ "name" text ){
     val cxml = XML.loadString("<c>" + c + "</c>" )
     println(user + ":" + cxml.child.text)
    }
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using Azure.Core;

namespace Azure.Communication
{
    [CodeGenModel("CommunicationIdentifierModel", Usage = new string[] { "output" }, Formats = new string[] { "json" })]
    internal partial class CommunicationIdentifierModel
    {
    }
}


text:
/*
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.comcast.cdn.traffic_control.traffic_router.core.router;

import com.comcast.cdn.traffic_control.traffic_router.core.edge.Cache;
import com.comcast.cdn.traffic_control.traffic_router.core.edge.CacheLocation;
import com.comcast.cdn.traffic_control.traffic_router.core.edge.CacheLocation.LocalizationMethod;
import com.comcast.cdn.traffic_control.traffic_router.core.edge.CacheRegister;
import com.comcast.cdn.traffic_control.traffic_router.core.edge.InetRecord;
import com.comcast.cdn.traffic_control.traffic_router.core.edge.Node.IPVersions;
import com.comcast.cdn.traffic_control.traffic_router.core.ds.DeliveryService;
import com.comcast.cdn.traffic_control.traffic_router.core.ds.Dispersion;
import com.comcast.cdn.traffic_control.traffic_router.core.ds.SteeringRegistry;
import com.comcast.cdn.traffic_control.traffic_router.core.hash.ConsistentHasher;
import com.comcast.cdn.traffic_control.traffic_router.core.loc.FederationRegistry;
import com.comcast.cdn.traffic_control.traffic_router.geolocation.Geolocation;
import com.comcast.cdn.traffic_control.traffic_router.core.request.DNSRequest;
import com.comcast.cdn.traffic_control.traffic_router.core.request.HTTPRequest;
import com.comcast.cdn.traffic_control.traffic_router.core.request.Request;
import com.comcast.cdn.traffic_control.traffic_router.core.router.StatTracker.Track;
import com.comcast.cdn.traffic_control.traffic_router.core.util.CidrAddress;
import org.junit.Before;
import org.junit.Test;
import org.xbill.DNS.Name;
import org.xbill.DNS.Type;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Map;
import java.util.HashMap;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.equalTo;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.doCallRealMethod;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.powermock.reflect.Whitebox.setInternalState;

public class TrafficRouterTest {
    private ConsistentHasher consistentHasher;
    private TrafficRouter trafficRouter;

    private DeliveryService deliveryService;
    private FederationRegistry federationRegistry;

    @Before
    public void before() throws Exception {
        deliveryService = mock(DeliveryService.class);
        when(deliveryService.isAvailable()).thenReturn(true);
        when(deliveryService.isCoverageZoneOnly()).thenReturn(false);
        when(deliveryService.getDispersion()).thenReturn(mock(Dispersion.class));
        when(deliveryService.isAcceptHttp()).thenReturn(true);

        consistentHasher = mock(ConsistentHasher.class);

        when(deliveryService.createURIString(any(HTTPRequest.class), any(Cache.class))).thenReturn("http://atscache.kabletown.net/index.html");

        List<InetRecord> inetRecords = new ArrayList<InetRecord>();
        InetRecord inetRecord = new InetRecord("cname1", 12345);
        inetRecords.add(inetRecord);

        federationRegistry = mock(FederationRegistry.class);
        when(federationRegistry.findInetRecords(anyString(), any(CidrAddress.class))).thenReturn(inetRecords);

        trafficRouter = mock(TrafficRouter.class);

        CacheRegister cacheRegister = mock(CacheRegister.class);
        when(cacheRegister.getDeliveryService(any(HTTPRequest.class))).thenReturn(deliveryService);

        setInternalState(trafficRouter, "cacheRegister", cacheRegister);
        setInternalState(trafficRouter, "federationRegistry", federationRegistry);
        setInternalState(trafficRouter, "consistentHasher", consistentHasher);
        setInternalState(trafficRouter, "steeringRegistry", mock(SteeringRegistry.class));

        when(trafficRouter.route(any(DNSRequest.class), any(Track.class))).thenCallRealMethod();
        when(trafficRouter.route(any(HTTPRequest.class), any(Track.class))).thenCallRealMethod();
        when(trafficRouter.singleRoute(any(HTTPRequest.class), any(Track.class))).thenCallRealMethod();
        when(trafficRouter.selectDeliveryService(any(Request.class))).thenReturn(deliveryService);
        when(trafficRouter.consistentHashDeliveryService(any(DeliveryService.class), any(HTTPRequest.class), anyString())).thenCallRealMethod();
    }

    @Test
    public void itCreatesDnsResultsFromFederationMappingHit() throws Exception {
        final Name name = Name.fromString("edge.example.com");
        DNSRequest request = new DNSRequest("example.com", name, Type.A);
        request.setClientIP("192.168.10.11");
        request.setHostname(name.relativize(Name.root).toString());

        Track track = spy(StatTracker.getTrack());

        when(deliveryService.getRoutingName()).thenReturn("edge");
        when(deliveryService.isDns()).thenReturn(true);

        DNSRouteResult result = trafficRouter.route(request, track);

        assertThat(result.getAddresses(), containsInAnyOrder(new InetRecord("cname1", 12345)));
        verify(track).setRouteType(Track.RouteType.DNS, "edge.example.com");
    }

    @Test
    public void itCreatesHttpResults() throws Exception {
        HTTPRequest httpRequest = new HTTPRequest();
        httpRequest.setClientIP("192.168.10.11");
        httpRequest.setHostname("ccr.example.com");

        Track track = spy(StatTracker.getTrack());

        Cache cache = mock(Cache.class);
        when(cache.hasDeliveryService(anyString())).thenReturn(true);
        CacheLocation cacheLocation = new CacheLocation("", new Geolocation(50,50));

        cacheLocation.addCache(cache);

        Set<CacheLocation> cacheLocationCollection = new HashSet<CacheLocation>();
        cacheLocationCollection.add(cacheLocation);

        CacheRegister cacheRegister = mock(CacheRegister.class);
        when(cacheRegister.getCacheLocations()).thenReturn(cacheLocationCollection);

        when(deliveryService.filterAvailableLocations(any(Collection.class))).thenCallRealMethod();
        when(deliveryService.isLocationAvailable(cacheLocation)).thenReturn(true);

        List<Cache> caches = new ArrayList<Cache>();
        caches.add(cache);
        when(trafficRouter.selectCaches(any(HTTPRequest.class), any(DeliveryService.class), any(Track.class))).thenReturn(caches);
        when(trafficRouter.selectCachesByGeo(anyString(), any(DeliveryService.class), any(CacheLocation.class), any(Track.class), any(IPVersions.class))).thenCallRealMethod();
        when(trafficRouter.getClientLocation(anyString(), any(DeliveryService.class), any(CacheLocation.class), any(Track.class))).thenReturn(new Geolocation(40, -100));
        when(trafficRouter.getCachesByGeo(any(DeliveryService.class), any(Geolocation.class), any(Track.class), any(IPVersions.class))).thenCallRealMethod();
        when(trafficRouter.getCacheRegister()).thenReturn(cacheRegister);
        when(trafficRouter.orderLocations(any(List.class), any(Geolocation.class))).thenCallRealMethod();

        HTTPRouteResult httpRouteResult = trafficRouter.route(httpRequest, track);

        assertThat(httpRouteResult.getUrl().toString(), equalTo("http://atscache.kabletown.net/index.html"));
    }

    @Test
    public void itFiltersByIPAvailability() throws Exception {

        DeliveryService ds = mock(DeliveryService.class);

        Cache cacheIPv4 = mock(Cache.class);
        when(cacheIPv4.hasDeliveryService(anyString())).thenReturn(true);
        when(cacheIPv4.hasAuthority()).thenReturn(true);
        when(cacheIPv4.isAvailable(any(IPVersions.class))).thenCallRealMethod();
        doCallRealMethod().when(cacheIPv4).setIsAvailable(anyBoolean());
        setInternalState(cacheIPv4, "ipv4Available", true);
        setInternalState(cacheIPv4, "ipv6Available", false);
        cacheIPv4.setIsAvailable(true);
        when(cacheIPv4.getId()).thenReturn("cache IPv4");

        Cache cacheIPv6 = mock(Cache.class);
        when(cacheIPv6.hasDeliveryService(anyString())).thenReturn(true);
        when(cacheIPv6.hasAuthority()).thenReturn(true);
        when(cacheIPv6.isAvailable(any(IPVersions.class))).thenCallRealMethod();
        doCallRealMethod().when(cacheIPv6).setIsAvailable(anyBoolean());
        setInternalState(cacheIPv6, "ipv4Available", false);
        setInternalState(cacheIPv6, "ipv6Available", true);
        cacheIPv6.setIsAvailable(true);
        when(cacheIPv6.getId()).thenReturn("cache IPv6");

        List<Cache> caches = new ArrayList<Cache>();
        caches.add(cacheIPv4);
        caches.add(cacheIPv6);

        when(trafficRouter.getSupportingCaches(any(List.class), any(DeliveryService.class), any(IPVersions.class))).thenCallRealMethod();

        List<Cache> supportingIPv4Caches = trafficRouter.getSupportingCaches(caches, ds, IPVersions.IPV4ONLY);
        assertThat(supportingIPv4Caches.size(), equalTo(1));
        assertThat(supportingIPv4Caches.get(0).getId(), equalTo("cache IPv4"));

        List<Cache> supportingIPv6Caches = trafficRouter.getSupportingCaches(caches, ds, IPVersions.IPV6ONLY);
        assertThat(supportingIPv6Caches.size(), equalTo(1));
        assertThat(supportingIPv6Caches.get(0).getId(), equalTo("cache IPv6"));

        List<Cache> supportingEitherCaches = trafficRouter.getSupportingCaches(caches, ds, IPVersions.ANY);
        assertThat(supportingEitherCaches.size(), equalTo(2));

        cacheIPv6.setIsAvailable(false);
        List<Cache> supportingAvailableCaches = trafficRouter.getSupportingCaches(caches, ds, IPVersions.ANY);
        assertThat(supportingAvailableCaches.size(), equalTo(1));
        assertThat(supportingAvailableCaches.get(0).getId(), equalTo("cache IPv4"));
    }

    @Test
    public void itChecksDefaultLocation() throws Exception {
        String ip = "1.2.3.4";
        Track track = new Track();
        Geolocation geolocation = mock(Geolocation.class);
        when(trafficRouter.getClientLocation(ip, deliveryService, null, track)).thenReturn(geolocation);
        when(geolocation.isDefaultLocation()).thenReturn(true);
        when(geolocation.getCountryCode()).thenReturn("US");
        Map<String, Geolocation> map = new HashMap<>();
        Geolocation defaultUSLocation = new Geolocation(37.751,-97.822);
        defaultUSLocation.setCountryCode("US");
        map.put("US", defaultUSLocation);
        when(trafficRouter.getDefaultGeoLocationsOverride()).thenReturn(map);
        Cache cache = mock(Cache.class);
        List<Cache> list = new ArrayList<>();
        list.add(cache);
        when(deliveryService.getMissLocation()).thenReturn(defaultUSLocation);
        when(trafficRouter.getCachesByGeo(deliveryService, deliveryService.getMissLocation(), track, IPVersions.IPV4ONLY)).thenReturn(list);
        when(trafficRouter.selectCachesByGeo(ip, deliveryService, null, track, IPVersions.IPV4ONLY)).thenCallRealMethod();
        when(trafficRouter.isValidMissLocation(deliveryService)).thenCallRealMethod();
        List<Cache> result = trafficRouter.selectCachesByGeo(ip, deliveryService, null, track, IPVersions.IPV4ONLY);
        verify(trafficRouter).getCachesByGeo(deliveryService, deliveryService.getMissLocation(), track, IPVersions.IPV4ONLY);
        assertThat(result.size(), equalTo(1));
        assertThat(result.get(0), equalTo(cache));
        assertThat(track.getResult(), equalTo(Track.ResultType.GEO_DS));
    }

    @Test
    public void itChecksMissLocation() throws Exception {
        Geolocation defaultUSLocation = new Geolocation(37.751,-97.822);
        when(deliveryService.getMissLocation()).thenReturn(defaultUSLocation);
        when(trafficRouter.isValidMissLocation(deliveryService)).thenCallRealMethod();
        boolean result = trafficRouter.isValidMissLocation(deliveryService);
        assertThat(result, equalTo(true));
        defaultUSLocation = new Geolocation(0,0);
        when(deliveryService.getMissLocation()).thenReturn(defaultUSLocation);
        result = trafficRouter.isValidMissLocation(deliveryService);
        assertThat(result, equalTo(false));
    }

    @Test
    public void itSetsResultToGeo() throws Exception {
        Cache cache = mock(Cache.class);
        when(cache.hasDeliveryService(anyString())).thenReturn(true);
        CacheLocation cacheLocation = new CacheLocation("", new Geolocation(50,50));

        cacheLocation.addCache(cache);

        Set<CacheLocation> cacheLocationCollection = new HashSet<CacheLocation>();
        cacheLocationCollection.add(cacheLocation);

        CacheRegister cacheRegister = mock(CacheRegister.class);
        when(cacheRegister.getCacheLocations()).thenReturn(cacheLocationCollection);

        when(trafficRouter.getCacheRegister()).thenReturn(cacheRegister);
        when(deliveryService.isLocationAvailable(cacheLocation)).thenReturn(true);
        when(deliveryService.filterAvailableLocations(any(Collection.class))).thenCallRealMethod();

        when(trafficRouter.selectCaches(any(HTTPRequest.class), any(DeliveryService.class), any(Track.class))).thenCallRealMethod();
        when(trafficRouter.selectCaches(any(HTTPRequest.class), any(DeliveryService.class), any(Track.class), anyBoolean())).thenCallRealMethod();
        when(trafficRouter.selectCachesByGeo(anyString(), any(DeliveryService.class), any(CacheLocation.class), any(Track.class), any(IPVersions.class))).thenCallRealMethod();

        Geolocation clientLocation = new Geolocation(40, -100);
        when(trafficRouter.getClientLocation(anyString(), any(DeliveryService.class), any(CacheLocation.class), any(Track.class))).thenReturn(clientLocation);

        when(trafficRouter.getCachesByGeo(any(DeliveryService.class), any(Geolocation.class), any(Track.class), any(IPVersions.class))).thenCallRealMethod();
        when(trafficRouter.filterEnabledLocations(any(List.class), any(LocalizationMethod.class))).thenCallRealMethod();
        when(trafficRouter.orderLocations(any(List.class), any(Geolocation.class))).thenCallRealMethod();
        when(trafficRouter.getSupportingCaches(any(List.class), any(DeliveryService.class), any(IPVersions.class))).thenCallRealMethod();

        HTTPRequest httpRequest = new HTTPRequest();
        httpRequest.setClientIP("192.168.10.11");
        httpRequest.setHostname("ccr.example.com");
        httpRequest.setPath("/some/path");

        Track track = spy(StatTracker.getTrack());

        trafficRouter.route(httpRequest, track);

        assertThat(track.getResult(), equalTo(Track.ResultType.GEO));
        assertThat(track.getResultLocation(), equalTo(new Geolocation(50, 50)));

        when(federationRegistry.findInetRecords(anyString(), any(CidrAddress.class))).thenReturn(null);
        when(deliveryService.getRoutingName()).thenReturn("edge");
        when(deliveryService.isDns()).thenReturn(true);

        final Name name = Name.fromString("edge.example.com");
        DNSRequest dnsRequest = new DNSRequest("example.com", name, Type.A);
        dnsRequest.setClientIP("10.10.10.10");
        dnsRequest.setHostname(name.relativize(Name.root).toString());

        track = StatTracker.getTrack();
        trafficRouter.route(dnsRequest, track);

        assertThat(track.getResult(), equalTo(Track.ResultType.GEO));
        assertThat(track.getResultLocation(), equalTo(new Geolocation(50, 50)));
    }

    @Test
    public void itRetainsPathElementsInURI() throws Exception {
        Cache cache = mock(Cache.class);
        when(cache.getFqdn()).thenReturn("atscache-01.kabletown.net");
        when(cache.getPort()).thenReturn(80);

        when(deliveryService.createURIString(any(HTTPRequest.class), any(Cache.class))).thenCallRealMethod();

        HTTPRequest httpRequest = new HTTPRequest();
        httpRequest.setClientIP("192.168.10.11");
        httpRequest.setHostname("tr.ds.kabletown.net");
        httpRequest.setPath("/782-93d215fcd88b/6b6ce2889-ae4c20a1584.ism/manifest(format=m3u8-aapl).m3u8");
        httpRequest.setUri("/782-93d215fcd88b/6b6ce2889-ae4c20a1584.ism;urlsig=O0U9MTQ1Ojhx74tjchm8yzfdanshdafHMNhv8vNA/manifest(format=m3u8-aapl).m3u8");

        StringBuilder dest = new StringBuilder();
        dest.append("http://");
        dest.append(cache.getFqdn().split("\\.", 2)[0]);
        dest.append(".");
        dest.append(httpRequest.getHostname().split("\\.", 2)[1]);
        dest.append(httpRequest.getUri());

        assertThat(deliveryService.createURIString(httpRequest, cache), equalTo(dest.toString()));
    }
}


text:
var app = angular.module('ganetiFront', ['ngMaterial', 'ngAnimate']).controller('mainCtrl', function($scope, $log, $http) {
	var mainNode = "192.168.0.71";
	var baseUrl = "https://" + mainNode + ":5080/2/";
	var baseUrl = "http://192.168.0.40:8888/data/";
	var tabs = [
		{ title: "Main", src:"main.html"},
		{ title: 'Nodes', src:"nodes.html"},
		{ title: 'Instances', src:"instances.html"},
		{ title: 'Networks', src:"networks.html"},
    ];
	$scope.tabs = tabs;

	var hosts = function () {return $http.get("https://" + mainNode +":5080/2/nodes")};

	$scope.reloadData = function () {
    	$http.get(baseUrl + 'instances' ).then(function(r) { $scope.instances = r.data; });
    	$http.get(baseUrl + 'networks' ).then(function(r) { $scope.networks = r.data; });
    	$http.get(baseUrl + 'nodes' ).then(function(r) { $scope.nodes = r.data; });
		console.log($scope.instances);
		console.log($scope.nodes);
	};

	$scope.reloadData();
	setInterval(function () { $scope.reloadData(); } , 10000 );

});


text: alter table ACT_HI_ATTACHMENT add TIME_ datetime(3);


text: var hash = process.env.BUDDY_ENV_INPUT_HASH;


text:
ExpressDerbyPrototype
=====================

A NodeJS server platform to explore feature development

This platform explores a variety of features, including:
- Bookmarklets for social bookmarking
- Chat rooms
- Structured conversations
- Facilities for role-playing games (quests, guilds, avatars, etc)
- Topic Maps for well-organized information resources

## Usage (at present) ##
Requires MongoDB running
The usual:
npm install
node server.js
navigate to localhost:3000

To play with the bookmarklet, create a browser bookmarklet with this code:

javascript:location.href='http://localhost:3000/bkmrk?url='+
encodeURIComponent(location.href)+'&title='+
encodeURIComponent(document.title)

Then, with the server running, visit any webpage and click that bookmarklet. At present, the console.log will show the url and page title. That has been sent to the BookmarkModel which will eventually handle the bookmark itself.


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <RelativeLayout
        android:id="@+id/rl_toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <include layout="@layout/center_toolbar" />

        <ImageView
            android:id="@+id/iv_back"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginStart="10dp"
            android:src="@mipmap/back" />

    </RelativeLayout>

    <LinearLayout
        android:id="@+id/ll_modify_password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="20dp"
        android:layout_below="@id/rl_toolbar"
        android:background="@drawable/bg_white_stroke_line_with_radius"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="10dp"
            android:orientation="horizontal">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="@android:color/black"
                android:textSize="16sp"
                android:text="@string/old_password"/>

            <EditText
                android:id="@+id/et_old_password"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@color/white"
                android:textSize="14sp"
                android:layout_marginStart="10dp"
                android:singleLine="true"
                android:hint="@string/hint_input_old_password"/>
        </LinearLayout>

        <View
            android:layout_width="match_parent"
            android:layout_height="0.5dp"
            android:background="@color/stroke_line"/>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="10dp"
            android:orientation="horizontal">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="@android:color/black"
                android:textSize="16sp"
                android:text="@string/new_password"/>

            <EditText
                android:id="@+id/et_new_password"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@color/white"
                android:textSize="14sp"
                android:layout_marginStart="10dp"
                android:singleLine="true"
                android:hint="@string/hint_input_new_password"/>
        </LinearLayout>

        <View
            android:layout_width="match_parent"
            android:layout_height="0.5dp"
            android:background="@color/stroke_line"/>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="10dp"
            android:orientation="horizontal">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="@android:color/black"
                android:textSize="16sp"
                android:text="确    认"/>

            <EditText
                android:id="@+id/et_confirm_password"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@color/white"
                android:textSize="14sp"
                android:layout_marginStart="10dp"
                android:singleLine="true"
                android:hint="@string/hint_reinput_new_password"/>
        </LinearLayout>
    </LinearLayout>

    <Button
        android:id="@+id/btn_confirm"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/ll_modify_password"
        android:layout_marginStart="20dp"
        android:background="@drawable/bg_blue_stroke_line"
        android:text="@string/confirm"
        android:textColor="@color/white"
        android:textSize="16sp"
        android:layout_marginEnd="20dp"
        />
</RelativeLayout>


text:
puppet-module-puppet
====================


text:
@interface NSURLSessionConfiguration (Doraemon)

@end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Can. J. Bot. 40: 1164 (1962)

#### Original name
Chrysosporium parvum var. parvum (C.W. Emmons & Ashburn) J.W. Carmich.

### Remarks
null


text:
"""Send + more = money.

In this model, we try to solve the following cryptarythm
SEND + MORE = MONEY
Each letter corresponds to one figure and all letters have different values.
"""

from google.apputils import app
import gflags
from ortools.constraint_solver import pywrapcp

FLAGS = gflags.FLAGS

def main(unused_argv):
  # Create the solver.
  solver = pywrapcp.Solver('SEND + MORE = MONEY')

  digits = range(0, 10)
  s = solver.IntVar(digits, 's')
  e = solver.IntVar(digits, 'e')
  n = solver.IntVar(digits, 'n')
  d = solver.IntVar(digits, 'd')
  m = solver.IntVar(digits, 'm')
  o = solver.IntVar(digits, 'o')
  r = solver.IntVar(digits, 'r')
  y = solver.IntVar(digits, 'y')

  letters = [s, e, n, d, m, o, r, y]

  solver.Add(
      1000 * s + 100 * e + 10 * n + d +
      1000 * m + 100 * o + 10 * r + e ==
      10000 * m + 1000 * o + 100 * n + 10 * e + y)

  # pylint: disable=g-explicit-bool-comparison
  solver.Add(s != 0)
  solver.Add(m != 0)

  solver.Add(solver.AllDifferent(letters))

  solver.NewSearch(solver.Phase(letters,
                                solver.INT_VAR_DEFAULT,
                                solver.INT_VALUE_DEFAULT))
  solver.NextSolution()
  print letters
  solver.EndSearch()

if __name__ == '__main__':
  app.run()


text:
<?php

defined('_JEXEC') or die;

// Include the feed functions only once
JLoader::register('ModFeedHelper', __DIR__ . '/helper.php');

$rssurl = $params->get('rssurl', '');
$rssrtl = $params->get('rssrtl', 0);

// Check if feed URL has been set
if (empty ($rssurl))
{
	echo '<div>';
	echo JText::_('MOD_FEED_ERR_NO_URL');
	echo '</div>';

	return;
}

$feed = ModFeedHelper::getFeed($params);
$moduleclass_sfx = htmlspecialchars($params->get('moduleclass_sfx'), ENT_COMPAT, 'UTF-8');

require JModuleHelper::getLayoutPath('mod_feed', $params->get('layout', 'default'));


text:
import unittest
import os
import helper
from autosign.main import checkTemplate

class TestcheckTemplate(unittest.TestCase):
    """
    tests the checkTemplate function in main module
    """
    def setUp(self):
        self.dire = os.path.dirname(__file__)
        helper.readrc(self)

    def test_correct_template_py(self):
        path = os.path.join(self.dire, 'testData/signed/py')
        for filename in os.listdir(path):
            fName = os.path.join(path, filename)
            result = checkTemplate(fName, self.options_py)
            self.assertEqual(result, True)

    def test_correct_template_c(self):
        path = os.path.join(self.dire, 'testData/signed/c')
        for filename in os.listdir(path):
            fName = os.path.join(path, filename)
            result = checkTemplate(fName, self.options_c)
            self.assertEqual(result, True)

    def test_incorrect_template(self):
        path = os.path.join(self.dire, 'testData/unsigned')
        for filename in os.listdir(path):
            fName = os.path.join(path, filename)
            self.assertEqual(checkTemplate(fName, self.options_py), False)


text:
#import "AfloatStorage.h"

#define kAfloatNamedWindowsCategoryAutosaveKey @"AfloatNamedWindowsCategoryAutosave"

#define kAfloatShouldSaveWindowKey @"AfloatShouldSaveWindow"

@interface AfloatStorage ()

// Is Afloat able to save this window? (doesn't take setShouldSave:...) into account
- (BOOL) canSaveWindow:(NSWindow*) w category:(NSString**) cat key:(NSString**) key;

// Should Afloat save this window? (setShouldSave:NO ... makes this return NO)
- (BOOL) shouldSaveWindow:(NSWindow*) w category:(NSString**) cat key:(NSString**) key;

@end

@implementation AfloatStorage

- (id) init {
	self = [super init];
	if (self != nil) {
		_backingStorage = [NSMutableDictionary new];
	}
	return self;
}

- (void) dealloc {
	[[NSNotificationCenter defaultCenter] removeObserver:self];
	[_backingStorage release];
	[super dealloc];
}

- (id) valueForWindow:(NSWindow*) w key:(NSString*) k {
	return [[_backingStorage objectForKey:[NSValue valueWithNonretainedObject:w]] objectForKey:k];
}

- (void) setValue:(id) v forWindow:(NSWindow*) w key:(NSString*) k {
	NSMutableDictionary* d = [self mutableDictionaryForWindow:w];
	[d setObject:v forKey:k];
	[self saveWindowIfRequired:w];
}

- (NSMutableDictionary*) mutableDictionaryForWindow:(NSWindow*) w {
	NSValue* value = [NSValue valueWithNonretainedObject:w];
	NSMutableDictionary* d = [_backingStorage objectForKey:value];
	if (!d) {
		d = [NSMutableDictionary dictionary];
		[_backingStorage setObject:d forKey:value];

		[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowWillClose:) name:NSWindowWillCloseNotification object:w];
	}

	return d;
}

- (void) windowWillClose:(NSNotification*) n {
	NSValue* v = [NSValue valueWithNonretainedObject:[n object]];
	NSMutableDictionary* d =
		[_backingStorage objectForKey:v];
	if (d) {
		[self.delegate storage:self willRemoveMutableDictionary:d forWindow:[n object]];
		[_backingStorage removeObjectForKey:v];
	}

	[[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowWillCloseNotification object:[n object]];
}

- (void) removeValueForWindow:(NSWindow*) w key:(NSString*) k {
	[[self mutableDictionaryForWindow:w] removeObjectForKey:k];
	[self saveWindowIfRequired:w];
}

// Takes the current state of the storage (including persistedKeys and
// setShouldSave:...) into account.
- (BOOL) shouldSaveWindow:(NSWindow*) w category:(NSString**) cat key:(NSString**) key {
	if (!self.persistedKeys || [self.persistedKeys count] == 0) return NO;

	if (![[self valueForWindow:w key:kAfloatShouldSaveWindowKey] boolValue]) return NO;

	return [self canSaveWindow:w category:cat key:key];
}

// YES if Afloat could save the window's state (returns cat/key if YES).
// NO otherwise.
- (BOOL) canSaveWindow:(NSWindow*) w category:(NSString**) cat key:(NSString**) key {
	if ([w frameAutosaveName] && ![[w frameAutosaveName] isEqual:@""]) {
		if (cat) *cat = kAfloatNamedWindowsCategoryAutosaveKey;
		if (key) *key = [w frameAutosaveName];
		return YES;
	}

	return NO;
}

- (void) setShouldSave:(BOOL) save forWindow:(NSWindow*) w {
	[self setValue:[NSNumber numberWithBool:save] forWindow:w key:kAfloatShouldSaveWindowKey];
	if (save)
		[self saveWindowIfRequired:w];
}

- (void) saveWindowIfRequired:(NSWindow*) w {
	NSString* cat = nil, * key = nil;
	BOOL canSave = [self shouldSaveWindow:w category:&cat key:&key];
	if (!canSave) return;

	cat = [NSString stringWithFormat:@"Afloat:%@:%@", cat, key];

	NSMutableDictionary* m = [NSMutableDictionary dictionary];
	for (NSString* persistedKey in self.persistedKeys)
		[m setObject:[self valueForWindow:w key:persistedKey] forKey:persistedKey];

	[[NSUserDefaults standardUserDefaults] setObject:m forKey:cat];
}

+ (void) removeSavedWindowWithCategory:(NSString*) cat identifier:(NSString*) ident {
	NSString* key = [NSString stringWithFormat:@"Afloat:%@:%@", cat, ident];
	[[NSUserDefaults standardUserDefaults] removeObjectForKey:key];
}

@synthesize persistedKeys = _persistedKeys;

+ (id) sharedStorage {
	static id myself = nil; if (!myself) myself = [self new];
	return myself;
}

+ (NSMutableDictionary*) sharedMutableDictionaryForWindow:(NSWindow*) window {
	return [[self sharedStorage] mutableDictionaryForWindow:window];
}

+ (id) sharedValueForWindow:(NSWindow*) w key:(NSString*) k {
	return [[self sharedStorage] valueForWindow:w key:k];
}

+ (void) removeSharedValueForWindow:(NSWindow*) w key:(NSString*) k {
	[[self sharedStorage] removeValueForWindow:w key:k];
}

+ (void) setSharedValue:(id) v window:(NSWindow*) w key:(NSString*) k {
	[[self sharedStorage] setValue:v forWindow:w key:k];
}

@synthesize delegate = _delegate;

@end


text:
package software.egger;

import org.junit.Test;

public class am_wait_notify {

    @Test
    public void simpleWait() throws InterruptedException {

        Object lock = new Object();

        Thread t = new Thread(() -> {
            synchronized (lock) { // wait has to be called in synchronized otherwise we get java.lang.IllegalMonitorStateException
                System.out.println("t waits");
                try {
                    lock.wait(); // the also releases the lock! Think of what happens to the sum example if we use wait() there!
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("t awake again");
            }
        });

        t.start();
        Thread.sleep(100); // Give t some time to enter wait()
        synchronized (lock) { // notify has to be called in synchronized otherwise we get java.lang.IllegalMonitorStateException
            System.out.println("calling notify");
            lock.notify();
            System.out.println("notify called");
        }
        t.join();

    }

    @Test
    public void waitAlsoExitsOnInterrupt() throws InterruptedException {

        Object lock = new Object();

        Thread t = new Thread(() -> {
            synchronized (lock) {
                System.out.println("t waits");
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    System.out.println("wait interrupted");
                    System.out.println("isInterrupted(): " + Thread.currentThread().isInterrupted());
                    System.out.println("interrupted(): " + Thread.interrupted());
                }
                System.out.println("t awake again");
            }
        });

        t.start();
        Thread.sleep(100); // Give t some time to enter wait()
        t.interrupt();
        t.join();

    }

    @SuppressWarnings("Duplicates")
    @Test
    public void notifyReleasesOneThreads() throws InterruptedException {

        Object lock = new Object();

        Thread t1 = new Thread(() -> {
            synchronized (lock) {
                System.out.println("t1 waits");
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    System.out.println("t1 wait interrupted");
                }
                System.out.println("t1 awake again");
            }
        });

        Thread t2 = new Thread(() -> {
            synchronized (lock) {
                System.out.println("t2 waits");
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    System.out.println("t2 wait interrupted");
                }
                System.out.println("t2 awake again");
            }
        });

        t1.start();
        t2.start();
        Thread.sleep(100); // Give t1, t2 some time to enter wait()

        synchronized (lock) {
            System.out.println("calling notify (1)");
            lock.notify();
            System.out.println("notify (1) called");
            System.out.println("calling notify (2)");
            lock.notify();
            System.out.println("notify (2) called");
        }

        t1.join();
        t2.join();

    }

    int counter = 0;

    @SuppressWarnings("Duplicates")
    @Test
    public void notifyAllReleasesAllThreads() throws InterruptedException {

        Object lock = new Object();

        Thread t1 = new Thread(() -> {
            synchronized (lock) {
                System.out.println("t1 waits");
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    System.out.println("t1 wait interrupted");
                }
                System.out.println("t1 awake again");
                int tmp = counter;
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                counter = tmp + 1;
                System.out.println("t1 done");
            }
        });

        Thread t2 = new Thread(() -> {
            synchronized (lock) {
                System.out.println("t2 waits");
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    System.out.println("t2 wait interrupted");
                }
                System.out.println("t2 awake again");
                int tmp = counter;
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                counter = tmp + 1;
                System.out.println("t2 done");
            }
        });

        t1.start();
        t2.start();
        Thread.sleep(100); // Give t1, t2 some time to enter wait()

        synchronized (lock) {
            System.out.println("calling notifyAll");
            lock.notifyAll(); // Note that all threads are awakened _and_ they are executed sequentially so locking is still guaranteed -> counter = 2
            System.out.println("notifyAll called");
        }

        t1.join();
        t2.join();

        System.out.println("Counter " + counter);

    }

    @Test
    public void waitCanHaveTimeOuts() throws InterruptedException {

        Object lock = new Object();

        Thread t = new Thread(() -> {
            synchronized (lock) {
                System.out.println("t waits");
                try {
                    lock.wait(100, 1); // there is also an implementation of wait without nanos. Look at the implementations of wait with nanos! timeout ++!
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("t awake again");
            }
        });

        t.start();
        t.join();

    }

    private int count = 0;

    @Test
    public void waitConditionAlwaysHasToBeCheckedInALoop() throws InterruptedException {
        // see also documentation of wait()

        Object lock = new Object();

        Thread t = new Thread(() -> {
            synchronized (lock) {
                System.out.println("t waits");
                while (count < 10) { // in very rare cases the thread can exit wait so we always have to check the condition in a loop!
                    try {
                        System.out.println("count not high enough!");
                        lock.wait();
                        System.out.println("t exited wait");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("t is done");
            }
        });

        t.start();
        Thread.sleep(10);
        synchronized (lock) {
            count = 5;
            lock.notify();
            Thread.sleep(10);
            count = 11;
            lock.notify();
        }
        t.join();

    }

}


text:
<!doctype html>

		<title>jsPlumb Documentation - </title>
		<link rel="stylesheet" href="demo-all.css">
		<link rel="stylesheet" href="gollum-template.css">

					DOCS
					DEMOS
					API
					TESTS
					CONTACT
					GITHUB
					DISCUSS
					ISSUES

Contents

Changelog

Required imports and basic setup

Browser Compatibility

Setup

Doctype

Required Imports

Initializing jsPlumb

Multiple jsPlumb Instances

Z-Index Considerations

Where does jsPlumb add elements?

Element Dragging

Performance

Zooming

Configuring Defaults

Basic Concepts

Anchors

Connectors

Endpoints

Overlays

Establishing Connections

Programmatic Connections

Reusing Common Settings

Detaching Programmatic Connections

Drag and Drop Connections

Elements as sources & targets

Element Targets

Element Sources

Specifying drag source area

Removing Connections/Endpoints

Connection & Endpoint Parameters

Connection & Endpoint Types

Events

Interceptors

Appearance

Styling via Paint Styles

Styling via CSS

Querying jsPlumb

Animation

Utility Functions

Loader Support (RequireJS)

Examples

jsPlumb.connect

Draggable Connections

Miscellaneous

Development

Which files are which?

Building jsPlumb

Documentation while developing

Overlays

Overlays are UI elements that are painted onto Connections, such as Labels or Arrows.

Introduction

Overlay Location

Adding Overlays

Overlay Types

Arrow

Plain Arrow

Diamond

Label

Custom

Hiding/Showing Overlays

Removing Overlays

Introduction

jsPlumb comes with five types of Overlays:

Arrow - a configurable arrow that is painted at some point along the connector.  You can control the length and width of the Arrow, the 'foldback' point - a point the tail points fold back into, and the direction (allowed values are 1 and -1; 1 is the default and means point in the direction of the connection)

Label - a configurable label that is painted at some point along the connector.

PlainArrow - an Arrow shaped as a triangle, with no foldback.

Diamond - as the name suggests...a diamond.

Custom - allows you to create the Overlay yourself - your Overlay may be any DOM element you like.

PlainArrow and Diamond are actually just configured instances of the generic Arrow overlay (see examples).

Overlay Location

A key concept with Overlays is that of their location.

For a Connector, the location of an Overlay refers to some point along the path inscribed by the Connector. It can be specified in one of three ways:

as a decimal in the range [0..1], which indicates some proportional amount of travel along the path inscribed by the Connector. The default value of 0.5 is in this form, and it means the default location of an Overlay on a Connector is a point halfway along the path.

as an integer greater than 1, which indicates some absolute number of pixels to travel along the Connector from the start point

as an integer less than zero, which indicates some absolute number of pixels to travel backwards along the Connector from the end point.

For an Endpoint, the same principles apply, but location is specified as an [x,y] array. For instance, this would specify an Overlay that was positioned in the center of an Endpoint:

location:[ 0.5, 0.5 ]

Whereas this would specify an Overlay that was positioned 5 pixels along the x axis from the top left corner:

location: [ 5, 0 ]

And this would specify an Overlay that was positioned 5 pixels along the x axis from the bottom right corner:

location: [ -5, 0 ]

All Overlays support these two methods for getting/setting their location:

getLocation - returns the current location

setLocation - sets the current location. For Endpoints, location is expressed in terms of an [ x, y ] array whose values are either proportional to the width/height of the Endpoint (decimals in the range 0-1 inclusive), or absolute values (decimals greater than 0).

Adding Overlays

You can specify one or more overlays when making a call to jsPlumb.connect, jsPlumb.addEndpoint or jsPlumb.makeSource (but not jsPlumb.makeTarget; overlays are always derived from what the source of a Connection defines)  The three cases are discussed below:

Specifying one or more overlays on a jsPlumb.connect call

In this example we'll create an Arrow with the default options for an Arrow, and a label with the text "foo":

jsPlumb.connect({
    ...
    overlays:[
        "Arrow",
        [ "Label", { label:"foo", location:0.25, id:"myLabel" } ]
    ],
    ...
});

This connection will have an arrow located halfway along it, and the label "foo" one quarter of the way along.  Notice the id
parameter; it can be used later if you wish to remove the Overlay or change its visibility (see below).

Another example, this time with an absolute location of 50 pixels from the source:

jsPlumb.connect({
    ...
    overlays:[
        "Arrow",
        [ "Label", { label:"foo", location:50, id:"myLabel" } ]
    ],
    ...
});

Specifying one or more overlays on a jsPlumb.addEndpoint call.

Note in this example that we use the parameter connectorOverlays and not overlays as in the last example.  This is because overlays would refer to Endpoint Overlays:

jsPlumb.addEndpoint("someDiv", {
  ...
  overlays:[
    [ "Label", { label:"foo", id:"label", location[-0.5, -0.5] } ]
  ],
  connectorOverlays:[
    [ "Arrow", { width:10, length:30, location:1, id:"arrow" } ],
    [ "Label", { label:"foo", id:"label" } ]
  ],
  ...
});

This connection will have a 10x30 Arrow located right at the head of the connection, and the label "foo" located at the halfway point. The Endpoint itself also has an overlay, located at [ -0.5  width, -0.5  height ] relative to the Endpoint's top,left corner.

Specifying one or more overlays on a jsPlumb.makeSource call.

Note in this example that we again use the parameter connectorOverlays and not overlays.  The endpoint parameter to jsPlumb.makeSource supports everything you might pass to the second argument of a jsPlumb.addEndpoint call:

jsPlumb.makeSource("someDiv", {
  ...
  endpoint:{
    connectorOverlays:[
      [ "Arrow", { width:10, length:30, location:1, id:"arrow" } ],
      [ "Label", { label:"foo", id:"label" } ]
    ]
  }
  ...
});

This connection will have a 10x30 Arrow located right at the head of the connection, and the label "foo" located at the halfway point.

Using the addOverlay method on an Endpoint or Connection

Endpoints and Connections both have an addOverlay method that takes as an argument a single Overlay definition. An example:

var e = jsPlumb.addEndpoint("someElement");
e.addOverlay([ "Arrow", { width:10, height:10, id:"arrow" }]);

Overlay Types

Arrow

Draws an arrow, using four points: the head and two tail points, and a foldback point, which permits the tail of the arrow to be indented. Available constructor arguments for this Overlay are:

width - width of the tail of the arrow

length - distance from the tail of the arrow to the head

location - where, either as a proportional value from 0 to 1 inclusive, or as an absolute value (negative values mean distance from target; positive values greater than 1 mean distance from source) the Arrow should appear on the Connector

direction - which way to point. Allowed values are 1 (the default, meaning forwards) and -1, meaning backwards

foldback - how far along the axis of the arrow the tail points foldback in to. Default is 0.623.

paintStyle - a style object in the form used for paintStyle values for Endpoints and Connectors.

PlainArrow

This is just a specialized instance of Arrow in which jsPlumb hardcodes foldback to 1, meaning the tail of the Arrow is a flat edge.  All of the constructor parameters from Arrow apply for PlainArrow.

Diamond

This is a specialized instance of Arrow in which jsPlumb hardcodes 'foldback' to 2, meaning the Arrow turns into a Diamond.  All of the constructor parameters from Arrow apply for Diamond.

Label

Provides a text label to decorate Connectors with.  The available constructor arguments are:

label - The text to display.  You can provide a function here instead of plain text: it is passed the Connection as an argument, and it should return a String.

cssClass - Optional css class to use for the Label.  This is now preferred over using the labelStyle parameter.

labelStyle - Optional arguments for the label's appearance.  Valid entries in this JS object are:

font - a font string in a format suitable for the Canvas element

fillStyle - the color to fill the label's background with. Optional.

color - the color of the label's text. Optional.

padding - optional padding for the label. This is expressed as a proportion of the width of the label, not in pixels or ems.

borderWidth - optional width in pixels for the label's border. Defaults to 0.

borderStyle - optional. The color to paint the border, if there is one.

location - As for Arrow Overlay.  Where, either proportionally from 0 to 1 inclusive, or as an absolute offset from either source or target, the label should appear.

The Label overlay offers two methods - getLabel and setLabel - for accessing/manipulating its content dynamically:

var c = jsPlumb.connect({
    source:"d1",
    target:"d2",
    overlays:[
        [ "Label", {label:"FOO", id:"label"}]
    ]
});

...

var label = c.getOverlay("label");
console.log("Label is currently", label.getLabel());
label.setLabel("BAR");
console.log("Label is now", label.getLabel());

In this example you can see that the Label Overlay is assigned an id of "label" in the connect call, and then retrieved using that id in the call to Connection's getOverlay method.

Both Connections and Endpoints support Label Overlays, and because changing labels is quite a common operation, setLabel and getLabel methods have been added to these objects:

var conn = jsPlumb.connect({
    source:"d1",
    target:"d2",
    label:"FOO"
});

...

console.log("Label is currently", conn.getLabel());
conn.setLabel("BAR");
console.log("Label is now", conn.getLabel());

These methods support passing in a Function instead of a String, and jsPlumb will create a label overlay for you if one does not yet exist when you call setLabel:

var conn = jsPlumb.connect({
    source:"d1",
    target:"d2"
});

...

conn.setLabel(function(c) {
    var s = new Date();
    return s.getTime() + "milliseconds have elapsed since 01/01/1970";
});
console.log("Label is now", conn.getLabel());

Custom

The Custom Overlay allows you to create your own Overlays, which jsPlumb will position for you.  You need to implement one method - create(component) - which is passed the component on which the Overlay is located as an argument, and which returns either a DOM element or a valid selector from the underlying library:

var conn = jsPlumb.connect({
        source:"d1",
        target:"d2",
        paintStyle:{
            strokeStyle:"red",
            lineWidth:3
        },
        overlays:[
            ["Custom", {
                create:function(component) {
                    return $("<select id='myDropDown'><option value='foo'>foo</option><option value='bar'>bar</option></select>");
                },
                location:0.7,
                id:"customOverlay"
            }]
        ]
    });

Here we have created a select box with a couple of values, assigned to it the id of 'customOverlay' and placed it at location 0.7. Note that the 'id' we assigned is distinct from the element's id. You can use the id you provided to later retrieve this Overlay using the getOverlay(id) method on a Connection or an Endpoint.

Hiding/Showing Overlays

You can control the visibility of Overlays using the setVisible method of Overlays themselves, or with showOverlay(id) or hideOverlay(id) on a Connection.

Remember the id parameter that we specified in the examples above?  This can be used to retrieve the Overlay from a Connection:

var connection = jsPlumb.connect({
    ...
    overlays:[
        "Arrow",
        [ "Label", { label:"foo", location:0.25, id:"myLabel" } ]
    ],
    ...
});

// time passes

var overlay = connection.getOverlay("myLabel");
// now you can hide this Overlay:
overlay.setVisible(false);
// there are also hide/show methods:
overlay.show();
overlay.hide();

However, Connection and Endpoint also have two convenience methods you could use instead:

var connection = jsPlumb.connect({
    ...
    overlays:[
        "Arrow",
        [ "Label", { label:"foo", location:-30 }, id:"myLabel" ]
    ],
    ...
});

// time passes

connection.hideOverlay("myLabel");

// more time passes

connection.showOverlay("myLabel");

Removing Overlays

Connection and Endpoint also have a removeOverlay method, that does what you might expect:

var connection = jsPlumb.connect({
    ...
    overlays:[
        "Arrow",
        [ "Label", { label:"foo", location:0.25 }, id:"myLabel" ]
    ],
    ...
});

// time passes

connection.removeOverlay("myLabel");


text:
Difficulty: Medium

https://leetcode.com/problems/search-suggestions-system/

Given an array of strings products and a string searchWord. We want to design a system that suggests at most three product names from products after each character of searchWord is typed. Suggested products should have common prefix with the searchWord. If there are more than three products with a common prefix return the three lexicographically minimums products.

Return list of lists of the suggested products after each character of searchWord is typed.

**Example 1:**
```
Input: products = ["mobile","mouse","moneypot","monitor","mousepad"], searchWord = "mouse"
Output: [
["mobile","moneypot","monitor"],
["mobile","moneypot","monitor"],
["mouse","mousepad"],
["mouse","mousepad"],
["mouse","mousepad"]
]
Explanation: products sorted lexicographically = ["mobile","moneypot","monitor","mouse","mousepad"]
After typing m and mo all products match and we show user ["mobile","moneypot","monitor"]
After typing mou, mous and mouse the system suggests ["mouse","mousepad"]
```

**Example 2:**
```
Input: products = ["havana"], searchWord = "havana"
Output: [["havana"],["havana"],["havana"],["havana"],["havana"],["havana"]]
```

**Example 3:**
```
Input: products = ["bags","baggage","banner","box","cloths"], searchWord = "bags"
Output: [["baggage","bags","banner"],["baggage","bags","banner"],["baggage","bags"],["bags"]]
```

**Constraints:**

* 1 <= products.length <= 1000
* There are no repeated elements in products.
* 1 <= Σ products[i].length <= 2 * 10^4
* All characters of products[i] are lower-case English letters.
* 1 <= searchWord.length <= 1000
* All characters of searchWord are lower-case English letters.


text:
import * as React from 'react';
import styles from './FeedbackForm.module.scss';
import { IFeedbackFormProps } from './IFeedbackFormProps';
import { escape } from '@microsoft/sp-lodash-subset';
import {
  TextField,
  DefaultButton,
  MessageBar,
  MessageBarType,
  MessageBarButton
} from 'office-ui-fabric-react';
import * as MicrosoftGraph from '@microsoft/microsoft-graph-types';

export interface IFeedbackFormState {
  isBusy: boolean;
  message: string;
  messageSended: boolean;
}

export default class FeedbackForm extends React.Component<IFeedbackFormProps, IFeedbackFormState> {

  constructor(props){
    super(props);

    this.state = {
      isBusy: false,
      message: '',
      messageSended: false
    };
  }

  public render(): React.ReactElement<IFeedbackFormProps> {
    return (

        {this.props.targetEmail ? '' : (
          <MessageBar messageBarType={MessageBarType.warning}>Target email is empty! Please configure this web part first.</MessageBar>
        )}
        {this.state.messageSended ? (
          <MessageBar
            actions={

                <MessageBarButton onClick={()=>{
                  this.setState({
                    messageSended:false
                  });
                }}>I want to send more!</MessageBarButton>

            }
            messageBarType={MessageBarType.success}
            isMultiline={false}
          >
            Message was sent!
          </MessageBar>
        ) :
        (
            <>
              <TextField disabled={this.state.isBusy} label="Feedback" multiline rows={3} name="text" value={this.state.message} onChange={this._onChange} />

                <DefaultButton disabled={this.state.isBusy || !this.props.targetEmail} onClick={this._sendMessage}>Send</DefaultButton>

            </>
        )}

    );
  }

  private _onChange = (event: React.ChangeEvent<HTMLInputElement>) : void => {
    this.setState({message:event.target.value});
  }

  private _sendMessage = async (event: React.MouseEvent<HTMLButtonElement, MouseEvent>) : Promise<void> => {
    this.setState({isBusy:true});

    const msg = {
      subject: escape(this.props.subject),
      importance:"low",
      body:{
          contentType:"html",
          content: escape(this.state.message)
      },
      toRecipients:[
          {
              emailAddress:{
                  address: this.props.targetEmail
              }
          }
      ]
  } as MicrosoftGraph.Message;

  await this.props.graphClient.api('/me/sendMail')
    .post({
      message : msg
    }).then(() => {
      this.setState({
        isBusy:false,
        message: '',
        messageSended: true
      });
    },(error: any) => {
      console.log(error);
    });
  }
}


text:
using System.Collections.Generic;
using System.Text.Json;
using Azure.Core;

namespace Azure.ResourceManager.Resources.Models
{
    public partial class Alias
    {
        internal static Alias DeserializeAlias(JsonElement element)
        {
            Optional<string> name = default;
            Optional<IReadOnlyList<AliasPath>> paths = default;
            Optional<AliasType> type = default;
            Optional<string> defaultPath = default;
            Optional<AliasPattern> defaultPattern = default;
            Optional<AliasPathMetadata> defaultMetadata = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("name"))
                {
                    name = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("paths"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    List<AliasPath> array = new List<AliasPath>();
                    foreach (var item in property.Value.EnumerateArray())
                    {
                        array.Add(AliasPath.DeserializeAliasPath(item));
                    }
                    paths = array;
                    continue;
                }
                if (property.NameEquals("type"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    type = property.Value.GetString().ToAliasType();
                    continue;
                }
                if (property.NameEquals("defaultPath"))
                {
                    defaultPath = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("defaultPattern"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    defaultPattern = AliasPattern.DeserializeAliasPattern(property.Value);
                    continue;
                }
                if (property.NameEquals("defaultMetadata"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    defaultMetadata = AliasPathMetadata.DeserializeAliasPathMetadata(property.Value);
                    continue;
                }
            }
            return new Alias(name.Value, Optional.ToList(paths), Optional.ToNullable(type), defaultPath.Value, defaultPattern.Value, defaultMetadata.Value);
        }
    }
}


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraController : MonoBehaviour {

    public float zoomSpeed = 40f;
    public float maxZoom = 1f;
    public float minZoom = 100f;

    public int xMargin = 10, yMargin = 10;

    public GameObject worldControllerObject;
    public WorldController worldController;

    // Use this for initialization
    void Start () {
        if (worldControllerObject == null)
        {
            Debug.LogError("No WorldControllerObject");
        }
        worldController = worldControllerObject.GetComponent<WorldController>();
        if(worldController == null)
        {
            Debug.LogError("No WorldController");
        }
        transform.position = new Vector3(worldController.world.size.x / 2, -10, -40);
        transform.rotation = Quaternion.Euler(-60, 0, 0);
	}

	// Update is called once per frame
	void Update () {
        // Camera pan map left and right
        float hscroll = Input.GetAxis("Horizontal");
        float vscroll = Input.GetAxis("Vertical");
        // Camera rotate
        float rotate = Input.GetAxis("Rotation");
        float tilt = Input.GetAxis("Tilt");
        // Camera zoom
        float zoom = zoomSpeed * Input.GetAxis("Zoom");

        // Mouse drag
        if (Input.GetKey(KeyCode.Mouse0))
        {
        }
        else if (Input.GetKey(KeyCode.Mouse1))
        {
            rotate -= Input.GetAxis("Mouse X");
            tilt -= Input.GetAxis("Mouse Y");
        }
        else if (Input.GetKey(KeyCode.Mouse2))
        {
            hscroll -= Input.GetAxis("Mouse X");
            vscroll -= Input.GetAxis("Mouse Y");
        }

        float speedScale = Mathf.Clamp(-transform.position.z / 10f, 1, 7); ;

        // Camera rotate: rotate along x axis, and tilt along vertical plane (with normal right)
        transform.rotation = Quaternion.AngleAxis(rotate, Vector3.forward) * transform.rotation;
        transform.rotation *= Quaternion.AngleAxis(-tilt, Vector3.right);

        // Horizontal translation
        transform.Translate(hscroll * speedScale, 0, 0);
        // Vertical movement, forward camera but projected onto plane (use mean to avoid corner cases)
        Vector3 position = transform.position;
        position += vscroll * speedScale * (Vector3.ProjectOnPlane(transform.forward, Vector3.forward) +
            Vector3.ProjectOnPlane(transform.up, Vector3.forward)).normalized;
        // Zoom
        position += transform.forward * zoom * speedScale;

        // Clamp to avoid too far camera
        // TODO: dynamic clamp
        position.x = Mathf.Clamp(position.x, -xMargin, worldController.world.size.x + xMargin);
        position.y = Mathf.Clamp(position.y, -yMargin, worldController.world.size.y + yMargin);
        position.z = Mathf.Clamp(position.z, -minZoom, -maxZoom);
        transform.position = position;
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="generator" content="rustdoc">
    <meta name="description" content="API documentation for the Rust `big_digit` mod in crate `num`.">
    <meta name="keywords" content="rust, rustlang, rust-lang, big_digit">

    <title>num::bigint::big_digit - Rust</title>

    <link rel="stylesheet" type="text/css" href="../../../main.css">

    <link rel="shortcut icon" href="http://www.rust-lang.org/favicon.ico">

num::<wbr>bigint

        <form class="search-form js-only">

                <input class="search-input" name="search"
                       autocomplete="off"
                       placeholder="Click or press 'S' to search, '?' for more options..."
                       type="search">

        </form>

Module num::<wbr>bigint::<wbr>big_digit

                [−]

        [src]

Constants

                        BASE

                        BITS

Functions

                        from_doublebigdigit

Split one DoubleBigDigit into two BigDigits.

                        to_doublebigdigit

Join two BigDigits into one DoubleBigDigit

Keyboard shortcuts

?

Show this help dialog

S

Focus the search field

⇤

Move up in search results

⇥

Move down in search results

⏎

Go to active search result

Search tricks

                Prefix searches with a type followed by a colon (e.g.
                fn:) to restrict the search to a given type.

                Accepted types are: fn, mod,
                struct, enum,
                trait, typedef (or
                tdef).

                Search functions by type signature (e.g.
                vec -> usize)


text:
TEST(Issue214, IsBool) {
  char json[] = "{\"ota\": {\"enabled\": true}}";
  StaticJsonBuffer<JSON_OBJECT_SIZE(1) + JSON_OBJECT_SIZE(1)> jsonBuffer;
  JsonObject& parsedJson = jsonBuffer.parseObject(json);
  ASSERT_TRUE(parsedJson["ota"]["enabled"].is<bool>());
}