text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Runtime.InteropServices;
using System;
using System.IO;

namespace Microsoft.Build.Framework
{
    /// <summary>
    /// Arguments for target started events
    /// </summary>
    /// <remarks>
    /// WARNING: marking a type [Serializable] without implementing
    /// ISerializable imposes a serialization contract -- it is a
    /// promise to never change the type's fields i.e. the type is
    /// immutable; adding new fields in the next version of the type
    /// without following certain special FX guidelines, can break both
    /// forward and backward compatibility
    /// </remarks>
    [Serializable]
    public class TargetStartedEventArgs : BuildStatusEventArgs
    {
        /// <summary>
        /// Default constructor
        /// </summary>
        protected TargetStartedEventArgs()
            : base()
        {
            // do nothing
        }

        /// <summary>
        /// This constructor allows event data to be initialized.
        /// Sender is assumed to be "MSBuild".
        /// </summary>
        /// <param name="message">text message</param>
        /// <param name="helpKeyword">help keyword </param>
        /// <param name="targetName">target name</param>
        /// <param name="projectFile">project file</param>
        /// <param name="targetFile">file in which the target is defined</param>
        public TargetStartedEventArgs
        (
            string message,
            string helpKeyword,
            string targetName,
            string projectFile,
            string targetFile
        )
            : this(message, helpKeyword, targetName, projectFile, targetFile, String.Empty, DateTime.UtcNow)
        {
        }

        /// <summary>
        /// This constructor allows event data to be initialized including the timestamp when the event was created.
        /// </summary>
        /// <param name="message">text message</param>
        /// <param name="helpKeyword">help keyword </param>
        /// <param name="targetName">target name</param>
        /// <param name="projectFile">project file</param>
        /// <param name="targetFile">file in which the target is defined</param>
        /// <param name="eventTimestamp">Timestamp when the event was created</param>
        public TargetStartedEventArgs
        (
            string message,
            string helpKeyword,
            string targetName,
            string projectFile,
            string targetFile,
            string parentTarget,
            DateTime eventTimestamp
        )
            : base(message, helpKeyword, "MSBuild", eventTimestamp)
        {
            _targetName = targetName;
            _projectFile = projectFile;
            _targetFile = targetFile;
            _parentTarget = parentTarget;
        }

        private string _targetName;
        private string _projectFile;
        private string _targetFile;
        private string _parentTarget;

        #region CustomSerializationToStream
        /// <summary>
        /// Serializes to a stream through a binary writer
        /// </summary>
        /// <param name="writer">Binary writer which is attached to the stream the event will be serialized into</param>
        internal override void WriteToStream(BinaryWriter writer)
        {
            base.WriteToStream(writer);
            #region TargetName
            if (_targetName == null)
            {
                writer.Write((byte)0);
            }
            else
            {
                writer.Write((byte)1);
                writer.Write(_targetName);
            }
            #endregion
            #region ProjectFile
            if (_projectFile == null)
            {
                writer.Write((byte)0);
            }
            else
            {
                writer.Write((byte)1);
                writer.Write(_projectFile);
            }
            #endregion
            #region TargetFile
            if (_targetFile == null)
            {
                writer.Write((byte)0);
            }
            else
            {
                writer.Write((byte)1);
                writer.Write(_targetFile);
            }
            #endregion
            #region ParentTarget
            if (_parentTarget == null)
            {
                writer.Write((byte)0);
            }
            else
            {
                writer.Write((byte)1);
                writer.Write(_parentTarget);
            }
            #endregion
        }

        /// <summary>
        /// Deserializes from a stream through a binary reader
        /// </summary>
        /// <param name="reader">Binary reader which is attached to the stream the event will be deserialized from</param>
        /// <param name="version">The version of the runtime the message packet was created from</param>
        internal override void CreateFromStream(BinaryReader reader, int version)
        {
            base.CreateFromStream(reader, version);
            #region TargetName
            if (reader.ReadByte() == 0)
            {
                _targetName = null;
            }
            else
            {
                _targetName = reader.ReadString();
            }
            #endregion
            #region ProjectFile
            if (reader.ReadByte() == 0)
            {
                _projectFile = null;
            }
            else
            {
                _projectFile = reader.ReadString();
            }
            #endregion
            #region TargetFile
            if (reader.ReadByte() == 0)
            {
                _targetFile = null;
            }
            else
            {
                _targetFile = reader.ReadString();
            }
            #endregion
            #region ParentTarget
            if (version > 20)
            {
                if (reader.ReadByte() == 0)
                {
                    _parentTarget = null;
                }
                else
                {
                    _parentTarget = reader.ReadString();
                }
            }
            #endregion
        }
        #endregion

        /// <summary>
        /// target name
        /// </summary>
        public string TargetName
        {
            get
            {
                return _targetName;
            }
        }

        /// <summary>
        /// Target which caused this target to build
        /// </summary>
        public string ParentTarget
        {
            get
            {
                return _parentTarget;
            }
        }

        /// <summary>
        /// Project file associated with event.
        /// </summary>
        public string ProjectFile
        {
            get
            {
                return _projectFile;
            }
        }

        /// <summary>
        /// File where this target was declared.
        /// </summary>
        public string TargetFile
        {
            get
            {
                return _targetFile;
            }
        }
    }
}


text:
namespace extensions {

namespace {

void ShowSettingsApiBubble(SettingsApiOverrideType type,
                           Browser* browser,
                           views::View* anchor_view,
                           views::BubbleBorder::Arrow arrow) {
  scoped_ptr<SettingsApiBubbleController> settings_api_bubble(
      new SettingsApiBubbleController(browser, type));
  if (!settings_api_bubble->ShouldShow())
    return;

  SettingsApiBubbleController* controller = settings_api_bubble.get();
  ExtensionMessageBubbleView* bubble_delegate = new ExtensionMessageBubbleView(
      anchor_view, arrow, settings_api_bubble.Pass());
  views::BubbleDelegateView::CreateBubble(bubble_delegate);
  controller->Show(bubble_delegate);
}

}  // namespace

void MaybeShowExtensionControlledHomeNotification(Browser* browser) {
#if !defined(OS_WIN)
  return;
#endif

  // The bubble will try to anchor itself against the home button
  views::View* anchor_view = BrowserView::GetBrowserViewForBrowser(browser)->
      toolbar()->home_button();
  ShowSettingsApiBubble(BUBBLE_TYPE_HOME_PAGE,
                        browser,
                        anchor_view,
                        views::BubbleBorder::TOP_LEFT);
}

void MaybeShowExtensionControlledSearchNotification(
    Profile* profile,
    content::WebContents* web_contents,
    const AutocompleteMatch& match) {
#if !defined(OS_WIN)
  return;
#endif

  if (AutocompleteMatch::IsSearchType(match.type) &&
      match.type != AutocompleteMatchType::SEARCH_OTHER_ENGINE) {
    Browser* browser = chrome::FindBrowserWithWebContents(web_contents);
    ToolbarView* toolbar =
        BrowserView::GetBrowserViewForBrowser(browser)->toolbar();
    ShowSettingsApiBubble(BUBBLE_TYPE_SEARCH_ENGINE,
                          browser,
                          toolbar->app_menu(),
                          views::BubbleBorder::TOP_RIGHT);
  }
}

void MaybeShowExtensionControlledNewTabPage(
    Browser* browser, content::WebContents* web_contents) {
#if !defined(OS_WIN)
  return;
#endif

  content::NavigationEntry* entry =
      web_contents->GetController().GetActiveEntry();
  if (!entry)
    return;
  GURL active_url = entry->GetURL();
  if (!active_url.SchemeIs("chrome-extension"))
    return;  // Not a URL that we care about.

  // See if the current active URL matches a transformed NewTab URL.
  GURL ntp_url(chrome::kChromeUINewTabURL);
  bool ignored_param;
  content::BrowserURLHandler::GetInstance()->RewriteURLIfNecessary(
      &ntp_url,
      web_contents->GetBrowserContext(),
      &ignored_param);
  if (ntp_url != active_url)
    return;  // Not being overridden by an extension.

  scoped_ptr<NtpOverriddenBubbleController> ntp_overridden_bubble(
      new NtpOverriddenBubbleController(browser));
  if (!ntp_overridden_bubble->ShouldShow(ntp_url.host()))
    return;

  NtpOverriddenBubbleController* controller = ntp_overridden_bubble.get();
  ExtensionMessageBubbleView* bubble_delegate = new ExtensionMessageBubbleView(
      BrowserView::GetBrowserViewForBrowser(browser)->toolbar()->app_menu(),
      views::BubbleBorder::TOP_RIGHT,
      ntp_overridden_bubble.Pass());
  views::BubbleDelegateView::CreateBubble(bubble_delegate);
  controller->Show(bubble_delegate);
}

}  // namespace extensions

redpajama_set_name: RedPajamaGithub


text:
package org.codehaus.enunciate.modules.gwt;

import java.util.Collection;

/**
 * @author Ryan Heaton
 */
public class GWTBeanOneDotTwo extends GWTBeanOneDotOne {
  private String property3;
  private Collection property4;

  public String getProperty3() {
    return property3;
  }

  public void setProperty3(String property3) {
    this.property3 = property3;
  }

  public Collection getProperty4() {
    return property4;
  }

  public void setProperty4(Collection property4) {
    this.property4 = property4;
  }

}


text:
404

Whoops. Looks like what you're looking for can't be found.


text:
"""Tests for vectorized_base."""

import datetime
import time

import mock
import numpy as np
from vizier import pyvizier as vz
from vizier._src.algorithms.optimizers import vectorized_base as vb
from vizier.pyvizier import converters

from absl.testing import absltest
from absl.testing import parameterized

class FakeVectorizedStrategy(vb.VectorizedStrategy):

  def __init__(self):
    self._iter = 0

  def suggest(self) -> np.ndarray:
    # The following structure allows to test the top K results.
    suggestions = np.array([
        [self._iter % 10, self._iter % 10],
        [(self._iter + 1) % 10, (self._iter + 1) % 10],
        [(self._iter + 2) % 10, (self._iter + 2) % 10],
        [(self._iter + 3) % 10, (self._iter + 3) % 10],
        [(self._iter + 4) % 10, (self._iter + 4) % 10],
    ]) / 10
    self._iter += 5
    return suggestions

  @property
  def suggestion_batch_size(self) -> int:
    return 5

  def update(self, rewards: np.ndarray) -> None:
    pass

class VectorizedBaseTest(parameterized.TestCase):

  @parameterized.parameters(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
  def test_optimize_candidates_len(self, count):
    problem = vz.ProblemStatement()
    problem.search_space.root.add_float_param('f1', 0.0, 10.0)
    problem.search_space.root.add_float_param('f2', 0.0, 10.0)
    converter = converters.TrialToArrayConverter.from_study_config(problem)
    score_fn = lambda x: np.sum(x, axis=-1)
    strategy_factory = lambda converter, batch, seed: FakeVectorizedStrategy()
    optimizer = vb.VectorizedOptimizer(
        strategy_factory=strategy_factory,
        max_evaluations=100,
    )
    res = optimizer.optimize(
        converter=converter, score_fn=score_fn, count=count)
    self.assertLen(res, count)

  @parameterized.parameters([None, datetime.timedelta(minutes=10)])
  def test_should_stop_max_evaluations(self, max_duration):
    problem = vz.ProblemStatement()
    problem.search_space.root.add_float_param('f1', 0.0, 10.0)
    problem.search_space.root.add_float_param('f2', 0.0, 10.0)
    converter = converters.TrialToArrayConverter.from_study_config(problem)
    score_fn = mock.Mock()
    score_fn.side_effect = lambda x: np.sum(x, axis=-1)
    strategy_factory = lambda converter, batch, seed: FakeVectorizedStrategy()
    optimizer = vb.VectorizedOptimizer(
        strategy_factory=strategy_factory,
        max_evaluations=100,
        max_duration=max_duration,
    )
    optimizer.optimize(converter=converter, score_fn=score_fn, count=3)
    # The batch size is 5, so we expect 100/5 = 20 calls
    self.assertEqual(score_fn.call_count, 20)

  def test_best_candidates(self):
    problem = vz.ProblemStatement()
    problem.search_space.root.add_float_param('f1', 0.0, 1.0)
    problem.search_space.root.add_float_param('f2', 0.0, 1.0)
    converter = converters.TrialToArrayConverter.from_study_config(problem)
    score_fn = lambda x: -np.max(np.square(x - 0.52), axis=-1)
    strategy_factory = lambda converter, batch, seed: FakeVectorizedStrategy()
    optimizer = vb.VectorizedOptimizer(
        strategy_factory=strategy_factory, max_evaluations=10)
    best_candidates = optimizer.optimize(
        converter=converter, score_fn=score_fn, count=3)
    # check 1st best candidate
    self.assertEqual(best_candidates[0].parameters['f1'].value, 0.5)
    self.assertEqual(best_candidates[0].parameters['f2'].value, 0.5)
    self.assertEqual(
        best_candidates[0].final_measurement.metrics['acquisition'].value,
        -(0.5 - 0.52)**2)
    # check 2nd best candidate
    self.assertEqual(best_candidates[1].parameters['f1'].value, 0.6)
    self.assertEqual(best_candidates[1].parameters['f2'].value, 0.6)
    self.assertEqual(
        best_candidates[1].final_measurement.metrics['acquisition'].value,
        -(0.6 - 0.52)**2)
    # check 3rd best candidate
    self.assertEqual(best_candidates[2].parameters['f1'].value, 0.4)
    self.assertEqual(best_candidates[2].parameters['f2'].value, 0.4)
    self.assertEqual(
        best_candidates[2].final_measurement.metrics['acquisition'].value,
        -(0.4 - 0.52)**2)

  def test_should_stop_max_duration(self):
    problem = vz.ProblemStatement()
    problem.search_space.root.add_float_param('f1', 0.0, 10.0)
    problem.search_space.root.add_float_param('f2', 0.0, 10.0)
    converter = converters.TrialToArrayConverter.from_study_config(problem)
    score_fn = mock.Mock()

    def slow_score_fn(x):
      time.sleep(1)
      return np.sum(x, axis=-1)

    score_fn.side_effect = slow_score_fn
    strategy_factory = lambda converter, batch, seed: FakeVectorizedStrategy()
    optimizer = vb.VectorizedOptimizer(
        strategy_factory=strategy_factory,
        max_evaluations=100,
        max_duration=datetime.timedelta(seconds=3))
    optimizer.optimize(converter=converter, score_fn=score_fn)
    # Test the optimization stopped after ~3 seconds based on function calls.
    self.assertLess(score_fn.call_count, 4)

  def test_vectorized_optimizer_factory(self):
    strategy_factory = lambda converter, batch, seed: FakeVectorizedStrategy()
    optimizer_factory = vb.VectorizedOptimizerFactory(
        strategy_factory=strategy_factory)
    optimizer = optimizer_factory(suggestion_batch_size=5, max_evaluations=1000)
    self.assertEqual(optimizer.max_evaluations, 1000)
    self.assertEqual(optimizer.suggestion_batch_size, 5)

if __name__ == '__main__':
  absltest.main()


text:
The wiring of Maarten's RPM meter

## Introduction
This project consists of a sensor, a LED matrix and an ESP8266.
See the [main](../README.md) page for details on these components.
This page explains how to connect them.

The sensor and the matrix need to be connected to the ESP8266.
 - The _sensor_ has three pins: power (VCC 5V, GND) and a digital out (DO).
 - The _LED matrix_ is more complicated with its 5 pins; it has power (VCC 3V3, GND), data in (DIN), clock (CLK) and chip select (CS).

## Power
The ESP8266 is typically powered over USB (5V) from a power bank; the matrix and sensor are powered from the ESP8266 board.
The ESP8266 board has an LDO to convert 5V to 3V3 and it has some pins to output 3V3, one of which connects to the LED matrix.
The sensor needs 5V. Unfortunately, the chosen ESP8266 board does not have a 5V out (directly form the USB).
It does have a VIN which is connected to VUSB via a Schottky, so we use that instead.

  ![VUSB to VIN](VIN.png)

Some ESP8266 boards do have VUSB out.

  ![VUSB out pin](VU.jpg)

## Schematics
The overall schematics are as follows

  ![Schematics](1schematics.jpg)

The wiring instructions are also described in a [text file](2wiring.txt).

## ESP8266 to matrix
The connection between the ESP8266 and the matrix is shown in two photos, ESP8266 side and matrix side:

  ![ESP8266 to Matrix connection](3esp-matrix.jpg)

  ![Matrix to ESP8266 connection](3matrix-esp.jpg)

## ESP8266 to sensor
The connection between the ESP8266 and the sensor is shown in two photos, ESP8266 side and sensor side:

  ![ESP8266 to Matrix connection](4esp-sensor.jpg)

  ![Matrix to ESP8266 connection](4sensor-esp.jpg)

## Matrix not working
Some of the LED matrices appeared not to work.
They show a blocky pattern like in the photo below.

  ![LED matrix not working](MatrixError.jpg)

It turned out that the 8x8 modules are inserted up-side-down.
When the LEDs are facing upwards, and the input is on the right hand side,
the printed serial number on the module should be at the bottom as shown in the photo below.

  ![LED matrix not working](MatrixOrientation.jpg)

## Firmware
Next step is to flash the [firmware](../arduino) via the Arduino IDE.

(end of doc)


text:
package org.redisson;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

import org.redisson.api.RFuture;
import org.redisson.api.RTopic;
import org.redisson.api.listener.BaseStatusListener;
import org.redisson.api.listener.MessageListener;
import org.redisson.connection.ConnectionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.util.Timeout;
import io.netty.util.TimerTask;
import io.netty.util.concurrent.FutureListener;

/**
 *
 * @author Nikita Koksharov
 *
 */
public abstract class QueueTransferTask {

    private static final Logger log = LoggerFactory.getLogger(QueueTransferTask.class);

    private int usage = 1;
    private final AtomicReference<Timeout> timeoutReference = new AtomicReference<Timeout>();
    private final ConnectionManager connectionManager;

    public QueueTransferTask(ConnectionManager connectionManager) {
        super();
        this.connectionManager = connectionManager;
    }

    public void incUsage() {
        usage++;
    }

    public int decUsage() {
        usage--;
        return usage;
    }

    private int messageListenerId;
    private int statusListenerId;

    public void start() {
        RTopic<Long> schedulerTopic = getTopic();
        statusListenerId = schedulerTopic.addListener(new BaseStatusListener() {
            @Override
            public void onSubscribe(String channel) {
                pushTask();
            }
        });

        messageListenerId = schedulerTopic.addListener(new MessageListener<Long>() {
            @Override
            public void onMessage(String channel, Long startTime) {
                scheduleTask(startTime);
            }
        });
    }

    public void stop() {
        RTopic<Long> schedulerTopic = getTopic();
        schedulerTopic.removeListener(messageListenerId);
        schedulerTopic.removeListener(statusListenerId);
    }

    private void scheduleTask(final Long startTime) {
        if (startTime == null) {
            return;
        }

        Timeout oldTimeout = timeoutReference.get();
        if (oldTimeout != null) {
            oldTimeout.cancel();
            timeoutReference.compareAndSet(oldTimeout, null);
        }

        long delay = startTime - System.currentTimeMillis();
        if (delay > 10) {
            Timeout timeout = connectionManager.newTimeout(new TimerTask() {
                @Override
                public void run(Timeout timeout) throws Exception {
                    pushTask();
                }
            }, delay, TimeUnit.MILLISECONDS);
            timeoutReference.set(timeout);
        } else {
            pushTask();
        }
    }

    protected abstract RTopic<Long> getTopic();

    protected abstract RFuture<Long> pushTaskAsync();

    private void pushTask() {
        RFuture<Long> startTimeFuture = pushTaskAsync();
        addListener(startTimeFuture);
    }

    private void addListener(RFuture<Long> startTimeFuture) {
        startTimeFuture.addListener(new FutureListener<Long>() {
            @Override
            public void operationComplete(io.netty.util.concurrent.Future<Long> future) throws Exception {
                if (!future.isSuccess()) {
                    if (future.cause() instanceof RedissonShutdownException) {
                        return;
                    }
                    log.error(future.cause().getMessage(), future.cause());
                    scheduleTask(System.currentTimeMillis() + 5 * 1000L);
                    return;
                }

                if (future.getNow() != null) {
                    scheduleTask(future.getNow());
                }
            }
        });
    }

}


text:
import AutoCompleteComboBox from "../src/AutoCompleteComboBox.js";
export default class ElixAutoCompleteComboBox extends AutoCompleteComboBox {}
customElements.define("elix-auto-complete-combo-box", ElixAutoCompleteComboBox);


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

// This code file is heavily inspired from the Kerberos.NET library,
// which is Copyright (c) 2017 Steve Syfuhs and released under the MIT
// license at
//
// https://github.com/SteveSyfuhs/Kerberos.NET
//

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.InteropServices;
using static Hazelcast.Security.Win32.NativeMethods;

namespace Hazelcast.Security.Win32
{
    internal partial class SspiSecurityContext : IDisposable
    {
        private const int SECPKG_CRED_BOTH = 0x00000003;
        private const int SECURITY_NETWORK_DREP = 0x00;

        private const int MaxTokenSize = 16 * 1024;

        private const ContextFlag DefaultRequiredFlags =
                                    ContextFlag.Connection |
                                    ContextFlag.ReplayDetect |
                                    ContextFlag.SequenceDetect |
                                    ContextFlag.Confidentiality |
                                    ContextFlag.AllocateMemory |
                                    ContextFlag.Delegate |
                                    ContextFlag.InitExtendedError;

        private const ContextFlag DefaultServerRequiredFlags =
                                    DefaultRequiredFlags |
                                    ContextFlag.AcceptStream |
                                    ContextFlag.AcceptExtendedError;

        private SECURITY_HANDLE credentialsHandle = new SECURITY_HANDLE();
        private SECURITY_HANDLE securityContext = new SECURITY_HANDLE();

        private readonly HashSet<object> disposable = new HashSet<object>();

        private readonly Credential credential;
        private readonly ContextFlag clientFlags;
        private readonly ContextFlag serverFlags;

        public SspiSecurityContext(
            Credential credential,
            string package,
            ContextFlag clientFlags = DefaultRequiredFlags,
            ContextFlag serverFlags = DefaultServerRequiredFlags
        )
        {
            this.credential = credential;
            this.clientFlags = clientFlags;
            this.serverFlags = serverFlags;

            Package = package;
        }

        public bool Impersonating { get; private set; }

        public string Package { get; }

        public string UserName { get { return QueryContextAttributeAsString(SecurityContextAttribute.SECPKG_ATTR_NAMES); } }

        public unsafe string QueryContextAttributeAsString(SecurityContextAttribute attr)
        {
            SecPkgContext_SecString pBuffer = default(SecPkgContext_SecString);
            SecStatus status;
            string strValue = null;

            // see https://github.com/dotnet/docs/blob/main/docs/fundamentals/syslib-diagnostics/syslib0004.md
            // this only exists in .NET Framework and has been obsoleted
#if NETFRAMEWORK
            RuntimeHelpers.PrepareConstrainedRegions();
#endif
            try { }
            finally
            {
                status = QueryContextAttributesString(ref this.securityContext, attr, ref pBuffer);

                if (status == SecStatus.SEC_E_OK)
                {
                    try
                    {
                        strValue = Marshal.PtrToStringUni((IntPtr)pBuffer.sValue);
                    }
                    finally
                    {
                        FreeContextBuffer(pBuffer.sValue);
                    }
                }

                if (status != SecStatus.SEC_E_UNSUPPORTED_FUNCTION && status > SecStatus.SEC_E_ERROR)
                {
                    throw new Win32Exception((int)status);
                }
            }

            return strValue;
        }

        public ContextStatus InitializeSecurityContext(string targetName, byte[] serverResponse, out byte[] clientRequest)
        {
            var targetNameNormalized = targetName.ToLowerInvariant();

            clientRequest = null;

            // 1. acquire
            // 2. initialize
            // 3. ??

            SecStatus result = 0;

            int tokenSize = 0;

            SecBufferDesc clientToken = default(SecBufferDesc);

            try
            {
                do
                {
                    clientToken = new SecBufferDesc(tokenSize);

                    if (!credentialsHandle.IsSet || result == SecStatus.SEC_I_CONTINUE_NEEDED)
                    {
                        AcquireCredentials();
                    }

                    if (serverResponse == null)
                    {
                        result = InitializeSecurityContext_0(
                            ref credentialsHandle,
                            IntPtr.Zero,
                            targetNameNormalized,
                            clientFlags,
                            0,
                            SECURITY_NETWORK_DREP,
                            IntPtr.Zero,
                            0,
                            ref securityContext,
                            ref clientToken,
                            out ContextFlag ContextFlags,
                            IntPtr.Zero
                        );
                    }
                    else
                    {
                        var pInputBuffer = new SecBufferDesc(serverResponse);
                        {
                            IntPtr pExpiry = IntPtr.Zero;

                            result = InitializeSecurityContext_1(
                                ref credentialsHandle,
                                ref securityContext,
                                targetNameNormalized,
                                clientFlags,
                                0,
                                SECURITY_NETWORK_DREP,
                                ref pInputBuffer,
                                0,
                                ref securityContext,
                                ref clientToken,
                                out ContextFlag ContextFlags,
                                ref pExpiry
                            );
                        }
                    }

                    if (result == SecStatus.SEC_E_INSUFFICENT_MEMORY)
                    {
                        if (tokenSize > MaxTokenSize)
                        {
                            break;
                        }

                        tokenSize += 1000;
                    }
                }
                while (result == SecStatus.SEC_I_INCOMPLETE_CREDENTIALS || result == SecStatus.SEC_E_INSUFFICENT_MEMORY);

                if (result > SecStatus.SEC_E_ERROR)
                {
                    throw new Win32Exception((int)result);
                }

                clientRequest = clientToken.ReadBytes();

                if (result == SecStatus.SEC_I_CONTINUE_NEEDED)
                {
                    return ContextStatus.RequiresContinuation;
                }

                return ContextStatus.Accepted;
            }
            finally
            {
                clientToken.Dispose();
            }
        }

        public ContextStatus AcceptSecurityContext(byte[] clientRequest, out byte[] serverResponse)
        {
            serverResponse = null;

            if (!credentialsHandle.IsSet)
            {
                AcquireCredentials();
            }

            var pInput = new SecBufferDesc(clientRequest);

            var tokenSize = 0;
            SecBufferDesc pOutput = default(SecBufferDesc);

            try
            {
                SecStatus result;

                do
                {
                    pOutput = new SecBufferDesc(tokenSize);

                    if (!securityContext.IsSet)
                    {
                        result = AcceptSecurityContext_0(
                            ref credentialsHandle,
                            IntPtr.Zero,
                            ref pInput,
                            serverFlags,
                            SECURITY_NETWORK_DREP,
                            ref securityContext,
                            out pOutput,
                            out ContextFlag pfContextAttr,
                            out SECURITY_INTEGER ptsTimeStamp
                        );
                    }
                    else
                    {
                        result = AcceptSecurityContext_1(
                            ref credentialsHandle,
                            ref securityContext,
                            ref pInput,
                            serverFlags,
                            SECURITY_NETWORK_DREP,
                            ref securityContext,
                            out pOutput,
                            out ContextFlag pfContextAttr,
                            out SECURITY_INTEGER ptsTimeStamp
                        );
                    }

                    if (result == SecStatus.SEC_E_INSUFFICENT_MEMORY)
                    {
                        if (tokenSize > MaxTokenSize)
                        {
                            break;
                        }

                        tokenSize += 1000;
                    }
                }
                while (result == SecStatus.SEC_I_INCOMPLETE_CREDENTIALS || result == SecStatus.SEC_E_INSUFFICENT_MEMORY);

                TrackUnmanaged(securityContext);

                if (result > SecStatus.SEC_E_ERROR)
                {
                    throw new Win32Exception((int)result);
                }

                serverResponse = pOutput.ReadBytes();

                if (result == SecStatus.SEC_I_CONTINUE_NEEDED)
                {
                    return ContextStatus.RequiresContinuation;
                }

                return ContextStatus.Accepted;
            }
            finally
            {
                pInput.Dispose();
                pOutput.Dispose();
            }
        }

        private void TrackUnmanaged(object thing)
        {
            disposable.Add(thing);
        }

        private unsafe void AcquireCredentials()
        {
            CredentialHandle creds = credential.Structify();

            TrackUnmanaged(creds);

            SecStatus result;

// see https://github.com/dotnet/docs/blob/main/docs/fundamentals/syslib-diagnostics/syslib0004.md
// this only exists in .NET Framework and has been obsoleted
#if NETFRAMEWORK
            RuntimeHelpers.PrepareConstrainedRegions();
#endif
            try { }
            finally
            {
                result = AcquireCredentialsHandle(
                    null,
                    Package,
                    SECPKG_CRED_BOTH,
                    IntPtr.Zero,
                    (void*)creds.DangerousGetHandle(),
                    IntPtr.Zero,
                    IntPtr.Zero,
                    ref credentialsHandle,
                    IntPtr.Zero
               );
            }

            if (result != SecStatus.SEC_E_OK)
            {
                throw new Win32Exception((int)result);
            }

            TrackUnmanaged(credentialsHandle);
        }

        public unsafe void Dispose()
        {
            foreach (var thing in disposable)
            {
                if (thing is IDisposable managedDispose)
                {
                    managedDispose.Dispose();
                }
                else if (thing is SECURITY_HANDLE handle)
                {
                    DeleteSecurityContext(&handle);
                    FreeCredentialsHandle(&handle);
                }
                else if (thing is IntPtr pThing)
                {
                    Marshal.FreeHGlobal(pThing);
                }
            }
        }
    }
}


text:
/**
 * ng-SignalR
 * @author danielfoord
 * @license MIT License
 * SignalR - http://signalr.net/
 * AngularJS - https://angularjs.org/
 */
angular.module('ngSignalR', [])
.constant('$', window.$)
.provider('signalr', [function () {

  //Transport methods used by SignalR
  this.transports = ['webSockets', 'serverSentEvents', 'foreverFrame', 'longPolling'];

  var errmsg = {
    callback: 'Callback function is not a function',
    errCallback: 'errorCallback function is not a function'
  };

  this.setTransports = function (transports) {
    if (!angular.isArray(transports)) {
      throw new Error('setTransports expects an \'Array\'');
    } else {
      this.transports = transports;
    }
  };

  this.getTransports = function () {
    return this.transports;
  };

  this.$get = ['$rootScope', '$q', '$', function ($rootScope, $q, $) {

    //Get provided transports to use in connections.
    var transports = this.transports;

    //Global collection of all active connections.
    var connections = [];

    return {
      /**
       * Creates a Connection to a SignalR Hub without the generated proxy.
       * @param  {String} channel - Camel case reference to SingalR hub class.
       * @returns {Object} - Returns Proxy and Connection.
       */
      createHubConnection: function (channel) {

        if (angular.isDefined(channel)) {
          var connection = $.hubConnection(),
            cons = connections;

          cons.push(connection);

          var proxy = connection.createHubProxy(channel);
          return {
            connection: connection,
            proxy: proxy
          };
        } else {
          throw new Error('channel is undefined');
        }

      },

      /**
       * Creates socket connection using the generated proxy.
       * @param  {String} channel - Camel case reference to SingalR hub class.
       * @returns {Object} - Returns Connection.
       */
      createConnection: function (channel) {

        if(angular.isDefined(channel)) {
          var connection = $.connection[channel],
            cons = connections;

          cons.push(connection);

          return connection;
        } else {
          throw new Error('channel is undefined');
        }

      },

      /**
       * Stops the hubs API Connection to a SignalR Hub.
       * @returns {Promise} - Returns a promise that is resolved when the connection is terminated.
       */
      stopConnection: function (connection) {

        var deferred = $q.defer(),
          cons = connections;

        try {
          cons.splice(cons.indexOf(connection), 1);
          connection.stop();
          deferred.resolve();
        } catch (ex) {
          deferred.reject(ex);
        }

        return deferred.promise;

      },

      /**
       * Stops all active connections to the server.
       * @returns {Promise} - Returns a promise that is resolved when all the connections are terminated.
       */
      stopAllConnections: function () {

        var deferred = $q.defer(),
          cons = connections;

        try {
          for (var i in cons) {
            cons[i].stop();
          }
          connections = [];
          deferred.resolve();
        } catch (ex) {
          deferred.reject(ex);
        }

        return deferred.promise;

      },

      /**
       * Function that executes when a connection is made without the generated proxy.
       * @param {Object} connection - Connection on which to execute the callback.
       * @returns {Promise} - Returns a promise that is resolved when the connection is made.
       */
      startHubConnection: function (connection) {

        if(angular.isDefined(connection)) {
          var deferred = $q.defer();

          connection.start({
            transport: transports
          })
          .done(function () {
            deferred.resolve();
          });

          return deferred.promise;
        } else {
          throw new Error('connection is undefined');
        }

      },

      /**
       * Function that executes when a connection is made using the generated proxy.
       * @returns {Promise} - Returns a promise when the connection is made.
       */
      startConnection: function () {

        var deferred = $q.defer();

        $.connection.hub.start({
          transport: transports
        }).done(function () {
          deferred.resolve();
        });

        return deferred.promise;

      },

      /**
       * Recevies a payload from the Server from the specified hub without the generated proxy.
       * @param {Object} proxy - The proxy returned from the hub.
       * @param {String} fnName - Camel Case reference to the SignalR funciton that sends the payload.
       * @param {Function} callback - The callback that Executes when a payload is received.
       */
      receiveProxy: function (proxy, fnName, callback) {

        if (callback && !angular.isFunction(callback)) {
          throw TypeError(errmsg.callback);
        }
        proxy.on(fnName, callback);

      },

      /**
       * Recevies a payload from Hub using with the generated proxy.
       * @param {Object} connection - The connection from the hub
       * @param {String} fnName - Camel Case reference to the SignalR funciton that sends payload to the client.
       * @param {Function} callback - The callback that Executes when a payload is received.
       */
      receive: function (connection, fnName, callback) {

        if (callback && angular.isFunction(callback)) {
          connection.client[fnName] = callback;
        } else if (callback && !angular.isFunction(callback)) {
          throw new TypeError(errmsg.callback);
        }

      },

      /**
       * Sends a payload to the specfied SignalR Hub without the generated proxy.
       * @param {Object} proxy - The proxy on which to send.
       * @param {String} fnName - Camel Case reference to the SignalR funciton that receives the client payload.
       * @param {Object} data - The payload to send to the server.
       * @param {Function} [errorCallback] - fires if invocation fails.
       */
      sendProxy: function (proxy, fnName, data, errorCallback) {

        if (errorCallback && !angular.isFunction(errorCallback)) {
          throw new TypeError(errmsg.errCallback);
        } else if (errorCallback) {
          proxy.invoke(fnName, data).fail(errorCallback);
        } else {
          proxy.invoke(fnName, data);
        }

      },

      /**
       * Sends a payload to the specfied SignalR Hub.
       * @param {Object} connection - The connection from the hub.
       * @param {String} fnName - Camel Case reference to the SignalR funciton that receives the client payload.
       * @param {Object} data - The payload to send to the server.
       * @param {Function} [errorCallback] - fires if invocation fails.
       */
      send: function (connection, fnName, data, errorCallback) {

        if (errorCallback && !angular.isFunction(errorCallback)) {
          throw new TypeError(errmsg.errCallback);
        } else if (errorCallback) {
          connection.server[fnName](data).fail(errorCallback);
        } else {
          connection.server[fnName](data);
        }

      },

      /**
       * Sets Client logging.
       * @param {Boolean} enable - Specifies if client logging should be enabled.
       * @param {Object} [connection] - The connection to log: If not given will use generated proxy.
       */
      logging: function (enable, connection) {

        if (angular.isUndefined(connection)) {
          $.connection.hub.logging = enable;
        } else {
          connection.logging = enable;
        }

      },

      /**
       * starting Lifetime event with proxy connection.
       * @param {Function} callback - Executes when starting Lifetime event fires.
       * @param {Object} [connection] - The connection to log: If not given will use generated proxy.
       */
      starting: function (callback, connection) {

        if (angular.isFunction(callback) && angular.isDefined(connection)) {
          connection.starting(callback);
        } else if (angular.isFunction(callback) && angular.isUndefined(connection)) {
           $.connection.hub.starting(callback);
        }  else if (!angular.isFunction(callback)) {
          throw new TypeError(errmsg.callback);
        }

      },

      /**
       * received Lifetime event.
       * @param {Function} callback - Executes when received Lifetime event fires.
       * @param {Object} [connection] - The connection on which the Lifetime event will fire: if not specified, will use generated proxy.
       */
      received: function (callback, connection) {

        if (angular.isFunction(callback) && angular.isDefined(connection)) {
          connection.received(callback);
        } else if (angular.isFunction(callback) && angular.isUndefined(connection)) {
           $.connection.hub.received(callback);
        }  else if (!angular.isFunction(callback)) {
          throw new TypeError(errmsg.callback);
        }

      },

      /**
       * connectionSlow Lifetime event.
       * @param {Function} callback - Executes when connectionSlow Lifetime event fires.
       * @param {Object} [connection] - The connection on which the Lifetime event will fire: if not specified, will use generated proxy.
       */
      connectionSlow: function (callback, connection) {

        if (angular.isFunction(callback) && angular.isDefined(connection)) {
          connection.connectionSlow(callback);
        } else if (angular.isFunction(callback) && angular.isUndefined(connection)) {
           $.connection.hub.connectionSlow(callback);
        }  else if (!angular.isFunction(callback)) {
          throw new TypeError(errmsg.callback);
        }

      },

      /**
       * reconnecting Lifetime event.
       * @param {Function} callback - Executes when reconnecting Lifetime event fires.
       * @param {Object} [connection] - The connection on which the Lifetime event will fire: if not specified, will use generated proxy.
       */
      reconnecting: function (callback, connection) {

        if (angular.isFunction(callback) && angular.isDefined(connection)) {
          connection.reconnecting(callback);
        } else if (angular.isFunction(callback) && angular.isUndefined(connection)) {
           $.connection.hub.reconnecting(callback);
        }  else if (!angular.isFunction(callback)) {
          throw new TypeError(errmsg.callback);
        }

      },

      /**
       * reconnected Lifetime event.
       * @param {Function} callback - Executes when reconnected Lifetime event fires.
       * @param {Object} [connection] - The connection on which the Lifetime event will fire: if not specified, will use generated proxy.
       */
      reconnected: function (callback, connection) {

        if (angular.isFunction(callback) && angular.isDefined(connection)) {
          connection.reconnected(callback);
        } else if (angular.isFunction(callback) && angular.isUndefined(connection)) {
           $.connection.hub.reconnected(callback);
        }  else if (!angular.isFunction(callback)) {
          throw new TypeError(errmsg.callback);
        }

      },

      /**
       * stateChanged Lifetime event.
       * @param {Function} callback - Executes when stateChanged Lifetime event fires.
       * @param {Object} [connection] - The connection on which the Lifetime event will fire: if not specified, will use generated proxy.
       */
      stateChanged: function (callback, connection) {

        if (angular.isFunction(callback) && angular.isDefined(connection)) {
          connection.stateChanged(callback);
        } else if (angular.isFunction(callback) && angular.isUndefined(connection)) {
           $.connection.hub.stateChanged(callback);
        }  else if (!angular.isFunction(callback)) {
          throw new TypeError(errmsg.callback);
        }

      },

      /**
       * disconnected Lifetime event.
       * @param {Function} callback - Executes when disconnected Lifetime event fires.
       * @param {Object} [connection] - The connection on which the Lifetime event will fire: if not specified, will use generated proxy.
       */
      disconnected: function (callback, connection) {

        if (angular.isFunction(callback) && angular.isDefined(connection)) {
          connection.disconnected(callback);
        } else if (angular.isFunction(callback) && angular.isUndefined(connection)) {
           $.connection.hub.disconnected(callback);
        }  else if (!angular.isFunction(callback)) {
          throw new TypeError(errmsg.callback);
        }

      },

      /**
       * Error handler for connection.
       * @param {Function} callback - fires on conneciton error.
       * @param {Object} [connection] - the connection returned from hubs connection: if not specified, will use generated proxy.
       */
      error: function (callback, connection) {

        if (angular.isFunction(callback) && angular.isDefined(connection)) {
          connection.error(callback);
        } else if (angular.isFunction(callback) && angular.isUndefined(connection)) {
           $.connection.hub.error(callback);
        }  else if (!angular.isFunction(callback)) {
          throw new TypeError(errmsg.callback);
        }

      }

    };
  }];
}
]);


text:
package io.skyfii.mandrill.model

object MergeLanguage extends Enumeration {
  type MergeLanguage = Value
  val mailchimp, handlebars = Value
}


text:
import React from 'react'

import Paper from 'material-ui/Paper'
import List from 'material-ui/List'

import DebaterListItem from './DebaterListItem'

export default ({
  sortedDebaters,
  lastRound
}) =>
  <Paper>
    <List>
      {sortedDebaters.map((debater, index) =>
        <DebaterListItem
          key={debater._id}
          debater={debater}
          rank={index + 1}
          lastRound={lastRound}
        />
      )}
    </List>
  </Paper>


text:
"""Convolutional LSTM implementation."""

import tensorflow as tf

from tensorflow.contrib.slim import add_arg_scope
from tensorflow.contrib.slim import layers

def init_state(inputs,
               state_shape,
               state_initializer=tf.zeros_initializer(),
               dtype=tf.float32):
  """Helper function to create an initial state given inputs.

  Args:
    inputs: input Tensor, at least 2D, the first dimension being batch_size
    state_shape: the shape of the state.
    state_initializer: Initializer(shape, dtype) for state Tensor.
    dtype: Optional dtype, needed when inputs is None.
  Returns:
     A tensors representing the initial state.
  """
  if inputs is not None:
    # Handle both the dynamic shape as well as the inferred shape.
    inferred_batch_size = inputs.get_shape().with_rank_at_least(1)[0]
    batch_size = tf.shape(inputs)[0]
    dtype = inputs.dtype
  else:
    inferred_batch_size = 0
    batch_size = 0

  initial_state = state_initializer(
      tf.stack([batch_size] + state_shape),
      dtype=dtype)
  initial_state.set_shape([inferred_batch_size] + state_shape)

  return initial_state

@add_arg_scope
def basic_conv_lstm_cell(inputs,
                         state,
                         num_channels,
                         filter_size=5,
                         forget_bias=1.0,
                         scope=None,
                         reuse=None):
  """Basic LSTM recurrent network cell, with 2D convolution connctions.

  We add forget_bias (default: 1) to the biases of the forget gate in order to
  reduce the scale of forgetting in the beginning of the training.

  It does not allow cell clipping, a projection layer, and does not
  use peep-hole connections: it is the basic baseline.

  Args:
    inputs: input Tensor, 4D, batch x height x width x channels.
    state: state Tensor, 4D, batch x height x width x channels.
    num_channels: the number of output channels in the layer.
    filter_size: the shape of the each convolution filter.
    forget_bias: the initial value of the forget biases.
    scope: Optional scope for variable_scope.
    reuse: whether or not the layer and the variables should be reused.

  Returns:
     a tuple of tensors representing output and the new state.
  """
  spatial_size = inputs.get_shape()[1:3]
  if state is None:
    state = init_state(inputs, list(spatial_size) + [2 * num_channels])
  with tf.variable_scope(scope,
                         'BasicConvLstmCell',
                         [inputs, state],
                         reuse=reuse):
    inputs.get_shape().assert_has_rank(4)
    state.get_shape().assert_has_rank(4)
    c, h = tf.split(axis=3, num_or_size_splits=2, value=state)
    inputs_h = tf.concat(axis=3, values=[inputs, h])
    # Parameters of gates are concatenated into one conv for efficiency.
    i_j_f_o = layers.conv2d(inputs_h,
                            4 * num_channels, [filter_size, filter_size],
                            stride=1,
                            activation_fn=None,
                            scope='Gates')

    # i = input_gate, j = new_input, f = forget_gate, o = output_gate
    i, j, f, o = tf.split(axis=3, num_or_size_splits=4, value=i_j_f_o)

    new_c = c * tf.sigmoid(f + forget_bias) + tf.sigmoid(i) * tf.tanh(j)
    new_h = tf.tanh(new_c) * tf.sigmoid(o)

    return new_h, tf.concat(axis=3, values=[new_c, new_h])


text:
namespace views {

class HighlightPathGenerator;

// FocusRing is a View that is designed to act as an indicator of focus for its
// parent. It is a view that paints to a layer which extends beyond the bounds
// of its parent view.
// If MyView should show a rounded rectangular focus ring when it has focus and
// hide the ring when it loses focus, no other configuration is necessary. In
// other cases, it might be necessary to use the Set*() functions on FocusRing;
// these take care of repainting it when the state changes.
// TODO(tluk): FocusRing should not be a view but instead a new concept which
// only participates in view painting ( https://crbug.com/840796 ).
class VIEWS_EXPORT FocusRing : public View, public ViewObserver {
 public:
  METADATA_HEADER(FocusRing);

  using ViewPredicate = std::function<bool(View* view)>;

  // The default thickness and inset amount of focus ring halos. If you need
  // the thickness of a specific focus ring, call halo_thickness() instead.
  static constexpr float kDefaultHaloThickness = 2.0f;

  // The default inset for the focus ring. Moves the ring slightly out from the
  // edge of the host view, so that the halo doesn't significantly overlap the
  // host view's contents. If you need a value for a specific focus ring, call
  // halo_inset() instead.
  static constexpr float kDefaultHaloInset = kDefaultHaloThickness * -0.5f;

  // Creates a FocusRing and adds it to `host`.
  static void Install(View* host);

  // Gets the FocusRing, if present, from `host`.
  static FocusRing* Get(View* host);
  static const FocusRing* Get(const View* host);

  // Removes the FocusRing, if present, from `host`.
  static void Remove(View* host);

  FocusRing(const FocusRing&) = delete;
  FocusRing& operator=(const FocusRing&) = delete;

  ~FocusRing() override;

  // Sets the HighlightPathGenerator to draw this FocusRing around.
  // Note: This method should only be used if the focus ring needs to differ
  // from the highlight shape used for InkDrops.
  // Otherwise install a HighlightPathGenerator on the parent and FocusRing will
  // use it as well.
  void SetPathGenerator(std::unique_ptr<HighlightPathGenerator> generator);

  // Sets whether the FocusRing should show an invalid state for the View it
  // encloses.
  void SetInvalid(bool invalid);

  // Sets the predicate function used to tell when the parent has focus. The
  // parent is passed into this predicate; it should return whether the parent
  // should be treated as focused. This is useful when, for example, the parent
  // wraps an inner view and the inner view is the one that actually receives
  // focus, but the FocusRing sits on the parent instead of the inner view.
  void SetHasFocusPredicate(const ViewPredicate& predicate);

  absl::optional<ui::ColorId> GetColorId() const;
  void SetColorId(absl::optional<ui::ColorId> color_id);

  float GetHaloThickness() const;
  float GetHaloInset() const;
  void SetHaloThickness(float halo_thickness);
  void SetHaloInset(float halo_inset);

  bool ShouldPaintForTesting();

  // View:
  void Layout() override;
  void ViewHierarchyChanged(
      const ViewHierarchyChangedDetails& details) override;
  void OnPaint(gfx::Canvas* canvas) override;
  void GetAccessibleNodeData(ui::AXNodeData* node_data) override;
  void OnThemeChanged() override;

  // ViewObserver:
  void OnViewFocused(View* view) override;
  void OnViewBlurred(View* view) override;

 private:
  FocusRing();

  SkPath GetPath() const;
  SkRRect GetRingRoundRect() const;

  void RefreshLayer();

  bool ShouldPaint();

  // Translates the provided SkRect or SkRRect, which is in the parent's
  // coordinate system, into this view's coordinate system, then insets it
  // appropriately to produce the focus ring "halo" effect. If the supplied rect
  // is an SkRect, it will have the default focus ring corner radius applied as
  // well.
  SkRRect RingRectFromPathRect(const SkRect& rect) const;
  SkRRect RingRectFromPathRect(const SkRRect& rect) const;

  // The path generator used to draw this focus ring.
  std::unique_ptr<HighlightPathGenerator> path_generator_;

  // Whether the enclosed View is in an invalid state, which controls whether
  // the focus ring shows an invalid appearance (usually a different color).
  bool invalid_ = false;

  // Overriding color_id for the focus ring.
  absl::optional<ui::ColorId> color_id_;

  // The predicate used to determine whether the parent has focus.
  absl::optional<ViewPredicate> has_focus_predicate_;

  // The thickness of the focus ring halo, in DIP.
  float halo_thickness_ = kDefaultHaloThickness;

  // The adjustment from the visible border of the host view to render the
  // focus ring.
  //
  // At -0.5 * halo_thickness_ (the default), the inner edge of the focus
  // ring will align with the outer edge of the default inkdrop. For very thin
  // focus rings, a zero value may provide better visual results.
  float halo_inset_ = kDefaultHaloInset;

  base::ScopedObservation<View, ViewObserver> view_observation_{this};
};

VIEWS_EXPORT SkPath
GetHighlightPath(const View* view,
                 float halo_thickness = FocusRing::kDefaultHaloThickness);

// Set this on the FocusRing host to have the FocusRing paint an outline around
// itself. This ensures that the FocusRing has sufficient contrast with its
// surroundings (this is used for prominent MdTextButtons because they are blue,
// while the background is light/dark, and the FocusRing doesn't contrast well
// with both the interior and exterior of the button). This may need some polish
// (such as blur?) in order to be expandable to all controls. For now it solves
// color contrast on prominent buttons which is an a11y issue. See
// https://crbug.com/1197631.
// TODO(pbos): Consider polishing this well enough that this can be
// unconditional. This may require rolling out `kCascadingBackgroundColor` to
// more surfaces to have an accurate background color.
VIEWS_EXPORT extern const ui::ClassProperty<bool>* const
    kDrawFocusRingBackgroundOutline;

}  // namespace views

#endif  // UI_VIEWS_CONTROLS_FOCUS_RING_H_


text:
/* SCANNER TEST */

#ifndef SMALL_TEST_CLIENT_PROTOCOL_H
#define SMALL_TEST_CLIENT_PROTOCOL_H

#include <stdint.h>
#include <stddef.h>
#include "wayland-client-core.h"

#ifdef  __cplusplus
extern "C" {
#endif

/**
 * @page page_small_test The small_test protocol
 * @section page_ifaces_small_test Interfaces
 * - @subpage page_iface_intf_A - the thing A
 * @section page_copyright_small_test Copyright
 * <pre>
 *
 * Copyright © 2016 Collabora, Ltd.
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation files
 * (the "Software"), to deal in the Software without restriction,
 * including without limitation the rights to use, copy, modify, merge,
 * publish, distribute, sublicense, and/or sell copies of the Software,
 * and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice (including the
 * next paragraph) shall be included in all copies or substantial
 * portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 * </pre>
 */
struct another_intf;
struct intf_A;
struct intf_not_here;

/**
 * @page page_iface_intf_A intf_A
 * @section page_iface_intf_A_desc Description
 *
 * A useless example trying to tickle the scanner.
 * @section page_iface_intf_A_api API
 * See @ref iface_intf_A.
 */
/**
 * @defgroup iface_intf_A The intf_A interface
 *
 * A useless example trying to tickle the scanner.
 */
extern const struct wl_interface intf_A_interface;

#ifndef INTF_A_FOO_ENUM
#define INTF_A_FOO_ENUM
enum intf_A_foo {
	/**
	 * this is the first
	 */
	INTF_A_FOO_FIRST = 0,
	/**
	 * this is the second
	 */
	INTF_A_FOO_SECOND = 1,
	/**
	 * this is the third
	 * @since 2
	 */
	INTF_A_FOO_THIRD = 2,
};
/**
 * @ingroup iface_intf_A
 */
#define INTF_A_FOO_THIRD_SINCE_VERSION 2
#endif /* INTF_A_FOO_ENUM */

/**
 * @ingroup iface_intf_A
 * @struct intf_A_listener
 */
struct intf_A_listener {
	/**
	 */
	void (*hey)(void *data,
		    struct intf_A *intf_A);
};

/**
 * @ingroup iface_intf_A
 */
static inline int
intf_A_add_listener(struct intf_A *intf_A,
		    const struct intf_A_listener *listener, void *data)
{
	return wl_proxy_add_listener((struct wl_proxy *) intf_A,
				     (void (**)(void)) listener, data);
}

#define INTF_A_RQ1 0
#define INTF_A_RQ2 1
#define INTF_A_DESTROY 2

/**
 * @ingroup iface_intf_A
 */
#define INTF_A_HEY_SINCE_VERSION 1

/**
 * @ingroup iface_intf_A
 */
#define INTF_A_RQ1_SINCE_VERSION 1
/**
 * @ingroup iface_intf_A
 */
#define INTF_A_RQ2_SINCE_VERSION 1
/**
 * @ingroup iface_intf_A
 */
#define INTF_A_DESTROY_SINCE_VERSION 1

/** @ingroup iface_intf_A */
static inline void
intf_A_set_user_data(struct intf_A *intf_A, void *user_data)
{
	wl_proxy_set_user_data((struct wl_proxy *) intf_A, user_data);
}

/** @ingroup iface_intf_A */
static inline void *
intf_A_get_user_data(struct intf_A *intf_A)
{
	return wl_proxy_get_user_data((struct wl_proxy *) intf_A);
}

static inline uint32_t
intf_A_get_version(struct intf_A *intf_A)
{
	return wl_proxy_get_version((struct wl_proxy *) intf_A);
}

/**
 * @ingroup iface_intf_A
 */
static inline void *
intf_A_rq1(struct intf_A *intf_A, const struct wl_interface *interface, uint32_t version)
{
	struct wl_proxy *untyped_new;

	untyped_new = wl_proxy_marshal_constructor_versioned((struct wl_proxy *) intf_A,
			 INTF_A_RQ1, interface, version, interface->name, version, NULL);

	return (void *) untyped_new;
}

/**
 * @ingroup iface_intf_A
 */
static inline struct intf_not_here *
intf_A_rq2(struct intf_A *intf_A, const char *str, int32_t i, uint32_t u, wl_fixed_t f, int32_t fd, struct another_intf *obj)
{
	struct wl_proxy *typed_new;

	typed_new = wl_proxy_marshal_constructor((struct wl_proxy *) intf_A,
			 INTF_A_RQ2, &intf_not_here_interface, NULL, str, i, u, f, fd, obj);

	return (struct intf_not_here *) typed_new;
}

/**
 * @ingroup iface_intf_A
 */
static inline void
intf_A_destroy(struct intf_A *intf_A)
{
	wl_proxy_marshal((struct wl_proxy *) intf_A,
			 INTF_A_DESTROY);

	wl_proxy_destroy((struct wl_proxy *) intf_A);
}

#ifdef  __cplusplus
}
#endif

#endif


text:
define('ts/common/EditHostIP', [
    'ts/widgets/CommonWidget',
    'ts/widgets/CommonFormField',
    'dojo/text!ts/common/EditHostIP.html',
    'dojo/css!ts/common/EditHostIP.css',
    'dojo/nls!ts/common/dataCenter.json'
], function(CommonWidget, CommonFormField, html, css, json){
    'use strict';

    var i18n = null;
    function EditHostIP(opts){
        CommonWidget.call(this, {html: html, css: css, json: json});
        i18n = this.i18n;
        this.opts = null;
        this.container = null;
        this.initialize.apply(this, arguments);
    }

    var methods = {
        initialize: function(opts){
            var that = this,
                $container = this.container = $(this.rootElement),
                $listItems = null;

            this.opts = $.extend({}, opts);

            ko.validation.configure({
                decorateInputElement: true,
                registerExtenders: true,
                messagesOnModified: true,
                insertMessages: false,
                parseInputAttributes: true,
                errorClass: 'has-error'
//                errorMessageClass: 'error-message'
            });

            ko.validation.configuration.insertMessages = false;

            function ViewModel(){
                var self = this;
//                self.checkedAllBtn = ko.observable(false);
                self.hostList = ko.observableArray([]);
//                self.hostList = ko.mapping.fromJS(data);

                self.checkedAll = ko.observable(false);
                self.isItem = ko.observable(true);

                self.selectedCount = function(){
                    var node = self.hostList();
                    var selectedCount = 0;
                    var totalCount = node.length;

                    node.forEach(function(o){
                        if(o.checked() === true){
                            selectedCount++;
                        }
                    });
                    return '(' + selectedCount + '/'+ totalCount + ')';
                };
                self.allCheck = ko.computed(function(){
                    var flag = self.checkedAll();

                    if(self.isItem()){
                        return ;
                    }
                    self.hostList().forEach(function(o){
                        o.checked(flag);
                    });
                });
                self.itemCheck = ko.computed(function(){
                    var result = true;

                    self.hostList().forEach(function(o){
                        if(o.checked() === false){
                            result = false;
                            return ;
                        }
                    });

                    self.checkedAll(result);
                });

                self.clickAll = function(){
                    self.isItem(false);
                };

                self.clickItem = function(itemData){
                    self.isItem(true);
                };

                self.save = function(){
                    that.req();
                }

                return self;
            }

//            this.vm = new ViewModel();

            this.vm = ko.mapping.fromJS({});
            this.vm = ViewModel.call(this.vm);

            window.vm = this.vm;
//            window.vmRL = vm;

            $container.on('blur', 'input.ip', function(e){
                var $this = $(this);
                var val = $this.val();
                var reg = /((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)/;
                if(!reg.test(val)){
                    $this.addClass('has-error');
                    Dialog.alert(i18n.getMsg('please enter the IP the correct format'));
//                    $this.focus();
                }else{
                    $this.removeClass('has-error');
                }
            });

        },

        validate: function(){
            var result = false;
            var reg = /((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)/;

            ko.mapping.toJS(this.vm).hostList.forEach(function(host){
                if(host.checked === true){
                    result = true;
                    return false;
                }
            });

            if(result === false){
                Dialog.alert(i18n.getMsg('please select to edit the host'));
                return false;
            }

            //ip验证
            result && this.container.find('input.ip').each(function(){
                var $this = $(this);
                if(!reg.test(this.value)){
                    result = false;
                    $this.addClass('has-error');
                }else{
                    $this.removeClass('has-error');
                }
            });

            if(result === false){
               Dialog.alert(i18n.getMsg('please enter the IP the correct format'));
                return false;
            }

            return result;
        },
        createCompleteCallback: function(){
            var originData = this.opts.data;
            ko.applyBindings(this.vm, this.container[0]);

            this.loadData(originData);
        },

        loadData: function(data){
            if($.type(data) === 'array'){
                data.forEach(function(node){
                    node.checked = true;
                });
                ko.mapping.fromJS({hostList: data}, this.vm);

            }else{
                this.vm.hostList.push(data);
            }
        },
        getData: function(){
            var data = [];
            data = ko.mapping.toJS(this.vm).hostList.filter(function(host){
                return host.checked;
            });

            return data;
        },
        load: function(url, callback){

        },
        req: function(){
            var that = this;
            var jsonData = this.getData();

            if(!this.validate()) return ;

            $.post(that.opts.url, jsonData, function(data){
                if(data.flag === '1'){
                    Dialog.close();
                    Dialog.alert(i18n.getMsg('editHostIPSucc'));
                }else{
                    Dialog.alert(data.msg);
                }
            });
        }
    }

    ExtendClass(EditHostIP, CommonWidget);
    InstallFunctions(EditHostIP.prototype, DONT_ENUM, GUtil.obj2Arr(methods));

    return EditHostIP;
});


text:
var _ = require('lodash')
var fs = require('fs-extra')
var path = require('path')
var assert = require('chai').assert
var fsAssert = require('./helpers/fs-assert')

var Globcp = require('../lib/globcp')

describe('globcp', function() {

    var tmpDir
    var fixturesDir

    var globcp

    function checkResult(destDir, expectedFiles, done) {
        return function(err) {
            if (err) { return done(err) }
            _.each(expectedFiles, function(relPath) {
                var destPath = path.resolve(destDir, relPath)
                assert(fs.existsSync(destPath), 'file exists: ' + destPath)
            })
            done()
        }
    }

    before(function() {
        tmpDir = '/tmp/globcp'
        fs.ensureDirSync(tmpDir)

        fixturesDir = path.resolve(__dirname, 'fixtures')

        globcp = new Globcp({ debug: true })
    })

    beforeEach(function() {
        fs.emptyDirSync(tmpDir)
    })

    after(function() {
        // fs.removeSync(tmpDir)
    })

    describe('flat copy to dest dir', function() {
        it('**', function(done) {
            var srcDir = path.resolve(fixturesDir, 'flat_01')
            var destDir = path.resolve(tmpDir, 'dest')
            globcp.copyFlat(srcDir, '**', destDir, checkResult(destDir, [
                'a.html', 'a.txt', 'b.txt', 'c.txt'
            ], done))
        })

        it('*.txt', function(done) {
            var srcDir = path.resolve(fixturesDir, 'flat_01')
            var destDir = path.resolve(tmpDir, 'dest')
            globcp.copyFlat(srcDir, '**', destDir, checkResult(destDir, [
                'a.txt', 'b.txt', 'c.txt'
            ], done))
        })

        it('a.*', function(done) {
            var srcDir = path.resolve(fixturesDir, 'flat_01')
            var destDir = path.resolve(tmpDir, 'dest')
            globcp.copyFlat(srcDir, 'a.*', destDir, checkResult(destDir, [
                'a.html', 'a.txt'
            ], done))
        })

        it('nested src, **/*.txt', function(done) {
            var srcDir = path.resolve(fixturesDir, 'tree_01')
            var destDir = path.resolve(tmpDir, 'dest')
            globcp.copyFlat(srcDir, '**/*.txt', destDir, checkResult(destDir, [
                'a.txt', 'b.txt', 'c.txt'
            ], done))
        })

        it('nested src, **/b*', function(done) {
            var srcDir = path.resolve(fixturesDir, 'tree_01')
            var destDir = path.resolve(tmpDir, 'dest')
            globcp.copyFlat(srcDir, '**/*.txt', destDir, checkResult(destDir, [
                'b.txt'
            ], done))
        })
    })

    describe('copy and preserve tree with base dir', function() {
        it('**', function(done) {
            var srcDir = path.resolve(fixturesDir, 'flat_01')
            var destDir = path.resolve(tmpDir, 'dest')
            globcp.copyTree(srcDir, '**', destDir, checkResult(destDir, [
                'a.html', 'a.txt', 'b.txt', 'c.txt'
            ], done))
        })

        it('nested src, **', function(done) {
            var srcDir = path.resolve(fixturesDir, 'tree_01')
            var destDir = path.resolve(tmpDir, 'dest')
            globcp.copyTree(srcDir, '**', destDir, checkResult(destDir, [
                'a/a.txt', 'a/b/b.txt', 'a/b/c/c.txt'
            ], done))
        })
    })
})


text:
package org.apach3.http.conn.params;

import java.net.InetAddress;

import org.apach3.http.annotation.Immutable;

import org.apach3.http.HttpHost;
import org.apach3.http.params.HttpParams;
import org.apach3.http.conn.routing.HttpRoute;

/**
 * An adaptor for manipulating HTTP routing parameters
 * in {@link HttpParams}.
 *
 * @since 4.0
 */
@Immutable
public class ConnRouteParams implements ConnRoutePNames {

    /**
     * A special value indicating "no host".
     * This relies on a nonsense scheme name to avoid conflicts
     * with actual hosts. Note that this is a valid host.
     */
    public static final HttpHost NO_HOST =
        new HttpHost("127.0.0.255", 0, "no-host"); // Immutable

    /**
     * A special value indicating "no route".
     * This is a route with {@link #NO_HOST} as the target.
     */
    public static final HttpRoute NO_ROUTE = new HttpRoute(NO_HOST); // Immutable

    /** Disabled default constructor. */
    private ConnRouteParams() {
        // no body
    }

    /**
     * Obtains the {@link ConnRoutePNames#DEFAULT_PROXY DEFAULT_PROXY}
     * parameter value.
     * {@link #NO_HOST} will be mapped to null,
     * to allow unsetting in a hierarchy.
     *
     * @param params    the parameters in which to look up
     *
     * @return  the default proxy set in the argument parameters, or
     *          null if not set
     */
    public static HttpHost getDefaultProxy(HttpParams params) {
        if (params == null) {
            throw new IllegalArgumentException("Parameters must not be null.");
        }
        HttpHost proxy = (HttpHost)
            params.getParameter(DEFAULT_PROXY);
        if ((proxy != null) && NO_HOST.equals(proxy)) {
            // value is explicitly unset
            proxy = null;
        }
        return proxy;
    }

    /**
     * Sets the {@link ConnRoutePNames#DEFAULT_PROXY DEFAULT_PROXY}
     * parameter value.
     *
     * @param params    the parameters in which to set the value
     * @param proxy     the value to set, may be null.
     *                  Note that {@link #NO_HOST} will be mapped to
     *                  null by {@link #getDefaultProxy},
     *                  to allow for explicit unsetting in hierarchies.
     */
    public static void setDefaultProxy(HttpParams params,
                                             HttpHost proxy) {
        if (params == null) {
            throw new IllegalArgumentException("Parameters must not be null.");
        }
        params.setParameter(DEFAULT_PROXY, proxy);
    }

    /**
     * Obtains the {@link ConnRoutePNames#FORCED_ROUTE FORCED_ROUTE}
     * parameter value.
     * {@link #NO_ROUTE} will be mapped to null,
     * to allow unsetting in a hierarchy.
     *
     * @param params    the parameters in which to look up
     *
     * @return  the forced route set in the argument parameters, or
     *          null if not set
     */
    public static HttpRoute getForcedRoute(HttpParams params) {
        if (params == null) {
            throw new IllegalArgumentException("Parameters must not be null.");
        }
        HttpRoute route = (HttpRoute)
            params.getParameter(FORCED_ROUTE);
        if ((route != null) && NO_ROUTE.equals(route)) {
            // value is explicitly unset
            route = null;
        }
        return route;
    }

    /**
     * Sets the {@link ConnRoutePNames#FORCED_ROUTE FORCED_ROUTE}
     * parameter value.
     *
     * @param params    the parameters in which to set the value
     * @param route     the value to set, may be null.
     *                  Note that {@link #NO_ROUTE} will be mapped to
     *                  null by {@link #getForcedRoute},
     *                  to allow for explicit unsetting in hierarchies.
     */
    public static void setForcedRoute(HttpParams params,
                                            HttpRoute route) {
        if (params == null) {
            throw new IllegalArgumentException("Parameters must not be null.");
        }
        params.setParameter(FORCED_ROUTE, route);
    }

    /**
     * Obtains the {@link ConnRoutePNames#LOCAL_ADDRESS LOCAL_ADDRESS}
     * parameter value.
     * There is no special value that would automatically be mapped to
     * null. You can use the wildcard address (0.0.0.0 for IPv4,
     * :: for IPv6) to override a specific local address in a hierarchy.
     *
     * @param params    the parameters in which to look up
     *
     * @return  the local address set in the argument parameters, or
     *          null if not set
     */
    public static InetAddress getLocalAddress(HttpParams params) {
        if (params == null) {
            throw new IllegalArgumentException("Parameters must not be null.");
        }
        InetAddress local = (InetAddress)
            params.getParameter(LOCAL_ADDRESS);
        // no explicit unsetting
        return local;
    }

    /**
     * Sets the {@link ConnRoutePNames#LOCAL_ADDRESS LOCAL_ADDRESS}
     * parameter value.
     *
     * @param params    the parameters in which to set the value
     * @param local     the value to set, may be null
     */
    public static void setLocalAddress(HttpParams params,
                                             InetAddress local) {
        if (params == null) {
            throw new IllegalArgumentException("Parameters must not be null.");
        }
        params.setParameter(LOCAL_ADDRESS, local);
    }

}


text:
package pgmr.com.banjocreek.riverbed.builder.json;

import static org.junit.Assert.*;

import java.math.BigDecimal;
import java.math.BigInteger;

import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonValue;

import org.junit.Before;
import org.junit.Test;

import com.banjocreek.riverbed.builder.json.immutable.ImmutableJsonBuilders;
import com.banjocreek.riverbed.builder.json.immutable.JObj;

public class ImmutableObjectBuilderOpTest {

    private JObj<JsonObject, JsonObject> builder;

    @Before
    public void setup() {
        this.builder = ImmutableJsonBuilders.object();
    }

    @Test
    public void testClear() {

        /*
         * given a builder with defaults and values
         */
        // SETUP
        final JObj<?, JsonObject> b = this.builder.withValue(
                Json.createObjectBuilder().add("b", "BB").add("c", "CC")
                        .build())
                .withDefault(
                        Json.createObjectBuilder().add("a", "A").add("b", "BB")
                                .build());

        /*
         * when clear is invoked
         */
        final JObj<?, JsonObject> b1 = b.clear();

        /*
         * the builder will create an empty instance
         */
        assertTrue(b1.done().isEmpty());

    }

    @Test
    public void testDefault() {

        /*
         * given a builder and an object
         */
        // SETUP
        final JsonObject jdef = Json.createObjectBuilder().add("a", "A")
                .add("b", "B").build();

        /*
         * when object is used as default
         */
        final JObj<?, JsonObject> b = this.builder.withDefault(jdef);

        /*
         * the created object has the defaults.
         */
        assertEquals(jdef, b.done());

    }

    @Test
    public void testDefaultDoesNotOverrideValue() {

        /*
         * given a builder with values
         */
        // SETUP
        final JsonObject jval = Json.createObjectBuilder().add("b", "BB")
                .add("c", "CC").build();
        final JObj<?, JsonObject> b = this.builder.withValue(jval);

        /*
         * when overlapping defaults are set
         */
        final JObj<?, JsonObject> b1 = b.withDefault(Json.createObjectBuilder()
                .add("a", "A").add("b", "B").build());

        /*
         * the builder will create an instance overlapping values taking
         * precedence.
         */
        final JsonObject actual = b1.done();
        final JsonObject expected = Json.createObjectBuilder().add("a", "A")
                .add("b", "BB").add("c", "CC").build();
        assertEquals(expected, actual);

    }

    @Test
    public void testRemove() {

        /*
         * given keys, values and builder with values at keys
         */
        // SETUP
        final String k1 = "Key1", k2 = "Key2";
        final String v1 = "Value1", v2 = "Value2";
        final JObj<?, JsonObject> b = this.builder.set(k1, v1).set(k2, v2);
        /*
         * when a key is unset
         */
        final JObj<?, JsonObject> b1 = b.remove(k1);

        /*
         * the builder will emit an instance without the key but with the
         * others.
         */
        final JsonObject actual = b1.done();
        final JsonObject expected = Json.createObjectBuilder().add(k2, v2)
                .build();
        assertEquals(expected, actual);

    }

    @Test
    public void testReset() {

        /*
         * given defaults and a builder with the defaults and some other values
         */
        // SETUP
        final JsonObject jdef = Json.createObjectBuilder().add("a", "A")
                .add("b", "BB").build();
        final JObj<?, JsonObject> b = this.builder.withValue(
                Json.createObjectBuilder().add("b", "BB").add("c", "CC")
                        .build()).withDefault(jdef);

        /*
         * when reset is invoked
         */
        final JObj<?, JsonObject> b1 = b.reset();

        /*
         * the builder will create an instance with just the defaults
         */
        assertEquals(jdef, b1.done());

    }

    @Test
    public void testSetBigDecimal() {

        /*
         * given a builder, a key, and a value
         */
        // SETUP
        final String k = "Key";
        final BigDecimal v = BigDecimal.valueOf(109.3);

        /*
         * when set is invoked with the key and value
         */
        final JObj<?, JsonObject> mutated = this.builder.set(k, v);

        /*
         * the builder is mutated with the parameters
         */
        final JsonObject actual = mutated.done();
        final JsonObject expected = Json.createObjectBuilder().add(k, v)
                .build();

        assertEquals(expected, actual);

    }

    @Test
    public void testSetBigInteger() {

        /*
         * given a builder, a key, and a value
         */
        // SETUP
        final String k = "Key";
        final BigInteger v = BigInteger.valueOf(100902L);

        /*
         * when set is invoked with the key and value
         */
        final JObj<?, JsonObject> mutated = this.builder.set(k, v);

        /*
         * the builder is mutated with the parameters
         */
        final JsonObject actual = mutated.done();
        final JsonObject expected = Json.createObjectBuilder().add(k, v)
                .build();

        assertEquals(expected, actual);

    }

    @Test
    public void testSetBoolean() {

        /*
         * given a builder, a key, and a value
         */
        // SETUP
        final String k = "Key";
        final boolean v = true;

        /*
         * when set is invoked with the key and value
         */
        final JObj<?, JsonObject> mutated = this.builder.set(k, v);

        /*
         * the builder is mutated with the parameters
         */
        final JsonObject actual = mutated.done();
        final JsonObject expected = Json.createObjectBuilder().add(k, v)
                .build();

        assertEquals(expected, actual);

    }

    @Test
    public void testSetDouble() {

        /*
         * given a builder, a key, and a value
         */
        // SETUP
        final String k = "Key";
        final double v = 109.3;

        /*
         * when set is invoked with the key and value
         */
        final JObj<?, JsonObject> mutated = this.builder.set(k, v);

        /*
         * the builder is mutated with the parameters
         */
        final JsonObject actual = mutated.done();
        final JsonObject expected = Json.createObjectBuilder().add(k, v)
                .build();

        assertEquals(expected, actual);

    }

    @Test
    public void testSetInt() {

        /*
         * given a builder, a key, and a value
         */
        // SETUP
        final String k = "Key";
        final int v = 19003;

        /*
         * when set is invoked with the key and value
         */
        final JObj<?, JsonObject> mutated = this.builder.set(k, v);

        /*
         * the builder is mutated with the parameters
         */
        final JsonObject actual = mutated.done();
        final JsonObject expected = Json.createObjectBuilder().add(k, v)
                .build();

        assertEquals(expected, actual);

    }

    @Test
    public void testSetJsonValue() {

        /*
         * given a builder, a key, and a value
         */
        // SETUP
        final String k = "Key";
        final JsonValue v = Json.createObjectBuilder().add("key", 100).build()
                .get("key");

        /*
         * when set is invoked with the key and value
         */
        final JObj<?, JsonObject> mutated = this.builder.set(k, v);

        /*
         * the builder is mutated with the parameters
         */
        final JsonObject actual = mutated.done();
        final JsonObject expected = Json.createObjectBuilder().add(k, v)
                .build();

        assertEquals(expected, actual);

    }

    @Test
    public void testSetLong() {

        /*
         * given a builder, a key, and a value
         */
        // SETUP
        final String k = "Key";
        final long v = 19003L;

        /*
         * when set is invoked with the key and value
         */
        final JObj<?, JsonObject> mutated = this.builder.set(k, v);

        /*
         * the builder is mutated with the parameters
         */
        final JsonObject actual = mutated.done();
        final JsonObject expected = Json.createObjectBuilder().add(k, v)
                .build();

        assertEquals(expected, actual);

    }

    @Test
    public void testSetNull() {

        /*
         * given a builder and a key
         */
        // SETUP
        final String k = "Key";

        /*
         * when set is invoked with the key and value
         */
        final JObj<?, JsonObject> mutated = this.builder.setNull(k);

        /*
         * the builder is mutated with the parameters
         */
        final JsonObject actual = mutated.done();
        final JsonObject expected = Json.createObjectBuilder().addNull(k)
                .build();

        assertEquals(expected, actual);

    }

    @Test
    public void testSetString() {

        /*
         * given a builder, a key, and a value
         */
        // SETUP
        final String k = "Key";
        final String v = "Value";

        /*
         * when set is invoked with the key and value
         */
        final JObj<?, JsonObject> mutated = this.builder.set(k, v);

        /*
         * the builder is mutated with the parameters
         */
        final JsonObject actual = mutated.done();
        final JsonObject expected = Json.createObjectBuilder().add(k, v)
                .build();

        assertEquals(expected, actual);

    }

    @Test
    public void testUpdateArray() {

        /*
         * given a key and builder with a json array value for the key
         */
        final String k = "Key";
        final JObj<?, JsonObject> b1 = this.builder.set(k, Json
                .createArrayBuilder().add("A").add("B").build());

        /*
         * when update is invoked with an array
         */
        final JObj<?, JsonObject> b2 = b1.update(k, Json.createArrayBuilder()
                .add("C").add("D").build());

        /*
         * the builder produces an instance with the combined values at the key,
         * the second after the first.
         */
        final JsonObject actual = b2.done();
        final JsonObject expected = Json
                .createObjectBuilder()
                .add(k,
                        Json.createArrayBuilder().add("A").add("B").add("C")
                                .add("D").build()).build();
        assertEquals(expected, actual);

    }

    @Test
    public void testUpdateObject() {

        /*
         * given a key and builder with a json object value for the key
         */
        final String k = "Key";
        final JsonObject v = Json.createObjectBuilder().add("a", "A")
                .add("b", "B").build();
        final JObj<?, JsonObject> b1 = this.builder.set(k, v);

        /*
         * when update is invoked with an overlapping value for the same key
         */
        final JObj<?, JsonObject> b2 = b1.update(k, Json.createObjectBuilder()
                .add("c", "C").add("b", "BB").build());

        /*
         * the builder produces an instance with the combined values at the key,
         * the second overriding the first.
         */
        final JsonObject actual = b2.done();
        final JsonObject expected = Json
                .createObjectBuilder()
                .add(k,
                        Json.createObjectBuilder().add("a", "A").add("c", "C")
                                .add("b", "BB").build()).build();
        assertEquals(expected, actual);

    }

    @Test
    public void testValue() {

        /*
         * given a builder and an object
         */
        // SETUP
        final JsonObject jval = Json.createObjectBuilder().add("b", "BB")
                .add("c", "CC").build();

        /*
         * when object is used as values
         */
        final JObj<?, JsonObject> b = this.builder.withValue(jval);

        /*
         * the created object has the defaults.
         */
        assertEquals(jval, b.done());

    }

}