text:
declare const chrome;

//
// Imports
//

import { Settings, ScrollAxis } from './types';
import defaultSettings from './settings/default-settings';
import { urlMatchesAnyGlobOf } from './settings/ignored-urls';

//
// Variables
//

let pressedKeys = new Set<String>();
let settings: Settings;
let triggerKeyIsPressed = false;

const overflowValuesThatEnableScrollbarsOnContentElements = ['auto', 'overlay', 'scroll'];

//
// Init
//

loadSettings(() => {
  attachPageFocusLossListener();
  attachKeysListeners();
  attachWheelListener();
  console.debug('[fast-scroll] ready', window.location.href);
});

//
// Helpers
//

function attachPageFocusLossListener() {
  /* clear pressed keys when the page loses focus, because by default they stay pressed when tab-switching to another
  OS window, which causes unexpected scrolling behavior when returning to the browser */
  window.addEventListener('blur', () => {
    pressedKeys.clear();
    triggerKeyIsPressed = false;
  });
}

function attachKeysListeners() {
  window.addEventListener('keydown', event => {
    pressedKeys.add(event.code);
    triggerKeyIsPressed = pressedKeys.has(settings.triggerKey);
  });
  window.addEventListener('keyup', event => {
    pressedKeys.delete(event.code);
    triggerKeyIsPressed = pressedKeys.has(settings.triggerKey);
  });

  /* By default, on Windows (but not on Linux), Google Chrome uses the Alt Left key to focus the browser's menu button,
  which interferes with Fast Scroll because the web page loses focus when Alt Left is released so you can't press it
  multiple times in a row to scroll faster, you have to click on the page so it regains focus everytime. So we're
  preventing this default behavior when Alt Left is used as the trigger key. */
  const preventAltLeftDefault = settings.triggerKey === Settings.TriggerKey.AltLeft;
  if (preventAltLeftDefault) {
    window.addEventListener('keyup', event => {
      if (event.code === Settings.TriggerKey.AltLeft)
        event.preventDefault();
    }, { passive: false });
  }
}

function attachWheelListener() {
  if (settings.mode === Settings.Mode.OnTriggerKeyPressed)
    window.addEventListener('wheel', onWheelModeOnTriggerKeyPressed, { passive: false });
  else if (settings.mode === Settings.Mode.Always)
    window.addEventListener('wheel', onWheelModeAlways, { passive: false });
  else
    throw new Error(`Unknown mode '${settings.mode}'`);
}

function elementIsScrollable(element, axis: ScrollAxis): boolean {
  const elementComputedStyle = window.getComputedStyle(element);

  if (axis === 'horizontal') {
    // if the element is as big as its content, it can't be scrolled (and doesn't need to)
    if (element.scrollWidth === element.clientWidth)
      return false;

    // <body> and <html> elements are scrollable as long as their overflow content isn't hidden
    if (element instanceof HTMLBodyElement || element instanceof HTMLHtmlElement)
      return true;

    // other elements are scrollable only when their 'overflow-<axis>' CSS attr has a value that enables scrollbars
    return overflowValuesThatEnableScrollbarsOnContentElements.includes(elementComputedStyle.overflowX);
  }
  else {
    // if the element is as big as its content, it can't be scrolled (and doesn't need to)
    if (element.scrollHeight === element.clientHeight)
      return false;

    // <body> and <html> elements are scrollable as long as their overflow content isn't hidden
    if (element instanceof HTMLBodyElement || element instanceof HTMLHtmlElement)
      return true;

    // other elements are scrollable only when their 'overflow-<axis>' CSS attr has a value that enables scrollbars
    return overflowValuesThatEnableScrollbarsOnContentElements.includes(elementComputedStyle.overflowY);
  }
}

/**
 * @returns The first element in the `element`'s hierarchy (including the element itself) that has a scrollbar for the
 * given `axis`, or `null` if none has any.
 */
function findScrollTarget(element, axis: ScrollAxis) {
  if (element === document.body) {
    /* On some websites the <body> element is seen as scrollable by Fast Scroll but `body.scrollBy()` does nothing,
    however as per my tests in all these cases `document.scrollingElement.scrollBy()` does work (with `scrollingElement`
    being the <html> element). That's why we check if `document.scrollingElement` is scrollable before checking the
    <body>. */
    if (elementIsScrollable(document.scrollingElement, axis))
      return document.scrollingElement;
  }

  if (elementIsScrollable(element, axis))
    return element;
  else if (element.parentElement)
    return findScrollTarget(element.parentElement, axis);
  return null;
}

function handleScroll(event: WheelEvent, speed: 'custom' | 'default') {
  event.preventDefault();

  const scrollAmount = (() => {
    /* When scrolling to the bottom or to the right, `event.deltaY` will be a positive int ; when scrolling to the top or
    to the left, it will be a negative int.
    During my tests `event.deltaX` never changed and was always `0`, but I think that's because my mouse has a
    unidirectional wheel, while some other mouses can be have a bidirectional wheel, that's why I'm checking it ‒ to
    [hopefully] support all possible use cases */
    const scrollAmountDefault = event.deltaY || event.deltaX;

    if (speed === 'custom')
      return scrollAmountDefault * settings.scrollSpeedMultiplier;
    else if (speed === 'default')
      return scrollAmountDefault;
  })();

  /* Use the first scrollable element in the target's hierachy's instead of `window` to allow to scroll faster not only
  in the page itself but also in inner elements, like text areas or divs with overflow content. This also allows the
  extension to work on websites like Trello where the scrollable area isn't the <body> nor <html> element but a child
  element. */

  const axis: ScrollAxis = (settings.triggerKey !== Settings.TriggerKey.ShiftLeft
      && (pressedKeys.has('ShiftLeft') || pressedKeys.has('ShiftRight')))
    ? 'horizontal' : 'vertical';
  const scrollTarget = findScrollTarget(event.target, axis) || window; // if no scrollable element is found fallback to `window`

  if (axis === 'horizontal')
    scrollTarget.scrollBy(scrollAmount, 0);
  else
    scrollTarget.scrollBy(0, scrollAmount);
}

function loadSettings(callback: () => void) {
  // load saved settings
  chrome.storage.sync.get(defaultSettings, savedSettings => {
    settings = savedSettings;

    // if current URL doesn't match any ignore glob
    if (!urlMatchesAnyGlobOf(window.location.href, settings.ignoredUrls))
      callback();
  });

  // listen to changes
  chrome.storage.onChanged.addListener(changes => {
    if (changes.mode)
      settings.mode = changes.mode.newValue;
    if (changes.scrollSpeedMultiplier)
      settings.scrollSpeedMultiplier = changes.scrollSpeedMultiplier.newValue;
    if (changes.triggerKey)
      settings.triggerKey = changes.triggerKey.newValue;
  });
}

function onWheelModeAlways(event: WheelEvent) {
  // brackets are important here because of this: https://gist.github.com/flawyte/e7e39d1d48aa1d5e7512b21bb8429b1f
  if (triggerKeyIsPressed) {
    if (settings.triggerKey === Settings.TriggerKey.ControlLeft)
      handleScroll(event, 'default'); // handle normal scroll by ourself since by default ControlLeft is used to zoom in/out on the page
    else if (settings.triggerKey === Settings.TriggerKey.ShiftLeft)
      handleScroll(event, 'default'); // handle normal scroll by ourself since by default ShiftLeft is used to scroll horizontally
  }
  else if (!pressedKeys.has('ControlLeft')) // pass if ControlLeft is pressed to preserve default zoom in/out behavior
    handleScroll(event, 'custom');
}

function onWheelModeOnTriggerKeyPressed(event: WheelEvent) {
  if (triggerKeyIsPressed)
    handleScroll(event, 'custom');
}


text:
{:data-section="shell"}
{:data-date="February 03, 2019"}
{:data-extra="Um Pages"}

## EXAMPLES

`ssh -D 1080 -CT user@remote`
: SOCKS proxy on localhost:1080

`ssh -L 3000:localhost:3000 -NT user@remote`
: Forward remote:3000 to localhost:3000

`ssh -o "UserKnownHostsFile /dev/null"`
: Ignore known_hosts

`ssh -J host1 host2`
: Host jumping

## OPTIONS

`-D`
: Bind port for port forwarding

`-L [bind_address:]port:host:hostport`
: Forward specific ports

`-C`
: Compress data

`-T`
: Disable tty

`-i /path/to/keyfile`
: Specify private key

`-o option`
: Override config file

`-J host1 host2`
: Host jumping

## KEYBINDS

`~.<ENTER>`
: Force exit out of session

redpajama_set_name: RedPajamaGithub


text:
#ifndef XMLHttpRequestProgressEventThrottle_h
#define XMLHttpRequestProgressEventThrottle_h

#include "platform/Timer.h"
#include "platform/heap/Handle.h"
#include "wtf/PassRefPtr.h"
#include "wtf/Vector.h"
#include "wtf/text/AtomicString.h"

namespace blink {

class Event;
class EventTarget;

enum ProgressEventAction {
    DoNotFlushProgressEvent,
    FlushDeferredProgressEvent,
    FlushProgressEvent
};

// This implements the XHR2 progress event dispatching: "dispatch a progress event called progress
// about every 50ms or for every byte received, whichever is least frequent".
class XMLHttpRequestProgressEventThrottle FINAL : public TimerBase {
    DISALLOW_ALLOCATION();
public:
    explicit XMLHttpRequestProgressEventThrottle(EventTarget*);
    virtual ~XMLHttpRequestProgressEventThrottle();

    // Dispatches a ProgressEvent.
    //
    // Special treatment for events named "progress" is implemented to dispatch
    // them at the required frequency. If this object is suspended, the given
    // ProgressEvent overwrites the existing. I.e. only the latest one gets
    // queued. If the timer is running, this method just updates
    // m_lengthComputable, m_loaded and m_total. They'll be used on next
    // fired() call.
    void dispatchProgressEvent(const AtomicString&, bool lengthComputable, unsigned long long loaded, unsigned long long total);
    void dispatchReadyStateChangeEvent(PassRefPtrWillBeRawPtr<Event>, ProgressEventAction = DoNotFlushProgressEvent);

    void suspend();
    void resume();

    void trace(Visitor*);

private:
    static const double minimumProgressEventDispatchingIntervalInSeconds;

    // Dispatches an event. If suspended, just queues the given event.
    void dispatchEvent(PassRefPtrWillBeRawPtr<Event>);

    virtual void fired() OVERRIDE;
    void dispatchDeferredEvents(Timer<XMLHttpRequestProgressEventThrottle>*);
    bool flushDeferredProgressEvent();
    void deliverProgressEvent();

    bool hasEventToDispatch() const;

    // Non-Oilpan, keep a weak pointer to our XMLHttpRequest object as it is
    // the one holding us. With Oilpan, a simple strong Member can be used -
    // this XMLHttpRequestProgressEventThrottle (part) object dies together
    // with the XMLHttpRequest object.
    RawPtrWillBeMember<EventTarget> m_target;

    bool m_lengthComputable;
    unsigned long long m_loaded;
    unsigned long long m_total;

    bool m_deferEvents;
    RefPtrWillBeMember<Event> m_deferredProgressEvent;
    WillBeHeapVector<RefPtrWillBeMember<Event> > m_deferredEvents;
    Timer<XMLHttpRequestProgressEventThrottle> m_dispatchDeferredEventsTimer;
};

} // namespace blink

#endif // XMLHttpRequestProgressEventThrottle_h


text:
from __future__ import unicode_literals

from django.db import models, migrations
import board.utils

class Migration(migrations.Migration):

    dependencies = [
        ('board', '0006_auto_20150109_2254'),
    ]

    operations = [
        migrations.CreateModel(
            name='FileAttachment',
            fields=[
                ('id', models.AutoField(auto_created=True, serialize=False, verbose_name='ID', primary_key=True)),
                ('name', models.CharField(max_length=128)),
                ('file', models.FileField(max_length=256, upload_to=board.utils.get_upload_path)),
                ('checksum', models.CharField(max_length=32, unique=True)),
            ],
            options={
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='ImageAttachment',
            fields=[
                ('id', models.AutoField(auto_created=True, serialize=False, verbose_name='ID', primary_key=True)),
                ('name', models.CharField(max_length=128)),
                ('file', models.ImageField(max_length=256, upload_to=board.utils.get_upload_path)),
                ('checksum', models.CharField(max_length=32, unique=True)),
            ],
            options={
            },
            bases=(models.Model,),
        ),
    ]


text:
(function () {
  'use strict';

  angular.module('components.provider')
    .factory('CredentialsService', Service);

  /** @ngInject */
  function Service(ApiService) {
    var service = {
      validateCredentials: validateCredentials
    };

    var API_ROUTE = ApiService.routes.providers + '/credentials';

    return service;

    function validateCredentials(provider) {
      return ApiService.create(API_ROUTE, provider)
        .catch(function () {
          return {attributes: {valid: false, reason: 'There was a server error.'}};
        });
    }
  }
})();


text:
package org.apereo.cas.adaptors.x509.web.extractcert;

import org.apereo.cas.adaptors.x509.authentication.RequestHeaderX509CertificateExtractor;

import lombok.val;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.springframework.mock.web.MockHttpServletRequest;

import java.security.cert.X509Certificate;

import static org.junit.jupiter.api.Assertions.*;

/**
 * @author Hal Deadman
 * @since 5.3.0
 */
@Tag("X509")
public class X509CertificateExtractorTests {

    private static final String[] CERTIFICATE_LINES = new String[]{
        "-----BEGIN CERTIFICATE-----",
        "MIIFXTCCA0WgAwIBAgIJANFf3YTJgYifMA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV",
        "BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX",
        "aWRnaXRzIFB0eSBMdGQwHhcNMTcwNTI2MjEzNjM3WhcNMTgwNTI2MjEzNjM3WjBF",
        "MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50",
        "ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIIC",
        "CgKCAgEA2ykNBanZz4cVITNpZcWNVmErUzqgSNrK361mj9vEdB1UkHatwal9jVrR",
        "QvFgfiZ8Gl+/85t0ebJhJ+rIr1ww6JE7v2s2MThENj95K5EwZOmgvw+CBlBYsFIz",
        "8BtjlVYy+v7RaGPXfjrFkexQP9UIaiIIog2ClDZirRvb+QxS930/YW5Qo+X6EX6W",
        "/m/HvlorD25U4ni2FQ0y+EMO2e1jD88cAAMoP5f+Mf6NBK8I6yUeaSuMq7WqtHGV",
        "e4F1WOg5z9J5c/M69rB0iQr5NUQwZ1mPYf5Kr0P6+TLh8DJphbVvmHJyT3bgofeV",
        "JYl/kdjiXS5P/jwY9tfmhu04tsyzopWRUFCcj5zCiqZYaMn0wtDn08KaAh9oOlg8",
        "Z6mJ9i5EybkLm63W7z7LxuM+qnYzq4wKkKdx8hbpASwPqzJkJeXFL/LzhKdZuHiR",
        "clgPVYnm98URwhObh073dKguG/gkhcnpXcVBBVdVTJZYGBvTpQh0afXd9bcBwOzY",
        "t4MDpGiQB2fLzBOEZhQ37kUcWPmZw5bNPxhx4yE96Md0rx/Gu4ipAHuqLemb1SL5",
        "uWNesVmgY3OXaIamQIm9BCwkf8mMvoYdAT+lukTUZLtJ6s2w+Oxnl10tmb+6sTXy",
        "UB3WcBTp/o3YjAyJPnM1Wq6nVNQ4W2+NbV5purGAP09sumxeJj8CAwEAAaNQME4w",
        "HQYDVR0OBBYEFCGOYMvymUG2ZZT+lK4LvwEvx731MB8GA1UdIwQYMBaAFCGOYMvy",
        "mUG2ZZT+lK4LvwEvx731MAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQELBQADggIB",
        "AG6m4nDYCompUtRVude1qulwwAaYEMHyIIsfymI8uAE7d2o4bGjVpAUOdH/VWSOp",
        "Rzx0oK6K9cHyiBlKHw5zSZdqcRi++tDX3P9Iy5tXO//zkhMEnSpk6RF2+9JXtyhx",
        "Gma4yAET1yES+ybiFT21uZrGCC9r69rWG8JRZshc4RVWGwZsd0zrATVqfY0mZurm",
        "xLgU4UOvkTczjlrLiklwwU68M1DLcILJ5FZGTWeTJ/q1wpIn9isK2siAW/VOcbuG",
        "xdbGladnIFv+iQfuZG0yjcuMsBFsQiXi6ONM8GM+dr+61V63/1s73jYcOToEsTMM",
        "3bHeVffoSkhZvOGTRCI6QhK9wqnIKhAYqu+NbV4OphfE3gOaK+T1cASXUtSQPXoa",
        "sEoIVmbQsWRBhWvYShVqvINsH/hAT3Cf/+SslprtQUqiyt2ljdgrRFZdoyB3S7ky",
        "KWoZRvHRj2cKU65LVYwx6U1A8SGmViz4aHMSai0wwKzOVv9MGHeRaVhlMmMsbdfu",
        "wKoKJv0xYoVwEh1rB8TH8PjbL+6eFLeZXYVZnH71d5JHCghZ8W0a11ZuYkscSQWk",
        "yoTBqEpJloWksrypqp3iL4PAL5+KkB2zp66+MVAg8LcEDFJggBBJCtv4SCWV7ZOB",
        "WLu8gep+XCwSn0Wb6D3eFs4DoIiMvQ6g2rS/pk7o5eWj",
        "-----END CERTIFICATE-----"};

    private final RequestHeaderX509CertificateExtractor extractX509CertificateFromHeader
        = new RequestHeaderX509CertificateExtractor("ssl_client_cert");

    private static String certificateSingleLine(final String[] lines, final String separator) {
        val singleSpaced = new StringBuilder();
        for (val current : lines) {
            singleSpaced.append(current).append(separator);
        }
        singleSpaced.deleteCharAt(singleSpaced.length() - 1);
        return singleSpaced.toString();
    }

    private static String certificateSingleLine(final String separator) {
        return certificateSingleLine(CERTIFICATE_LINES, separator);
    }

    private static void assertCertificateParsed(final X509Certificate[] certificates) {
        assertNotNull(certificates);
        assertEquals(1, certificates.length);
        assertNotNull(certificates[0]);
    }

    @Test
    public void verifyExtractX509FromHeaderSpaceSeperator() {
        val request = new MockHttpServletRequest();
        request.addHeader(extractX509CertificateFromHeader.sslClientCertHeader(), certificateSingleLine(" "));
        assertCertificateParsed(extractX509CertificateFromHeader.extract(request));
    }

    @Test
    public void verifyExtractX509FromHeaderNoSeparator() {
        val request = new MockHttpServletRequest();
        request.addHeader(extractX509CertificateFromHeader.sslClientCertHeader(), certificateSingleLine("\t"));
        assertCertificateParsed(extractX509CertificateFromHeader.extract(request));
    }

    @Test
    public void verifyExtractX509FromHeaderNoHeader() {
        val request = new MockHttpServletRequest();
        assertNull(extractX509CertificateFromHeader.extract(request));
    }
}


text:
/**
 * Created by babbarshaer on 2015-02-05.
 */

/**
 * This is the datastore service used by Search module to store the results.
 */

// Start linking angular behind the html code.


text:
#ifndef LIBCORK_CONFIG_ARCH_H
#define LIBCORK_CONFIG_ARCH_H

/*-----------------------------------------------------------------------
 * Platform
 */

#if defined(__i386__) || defined(_M_IX86)
#define CORK_CONFIG_ARCH_X86  1
#else
#define CORK_CONFIG_ARCH_X86  0
#endif

#if defined(__x86_64__) || defined(_M_X64)
#define CORK_CONFIG_ARCH_X64  1
#else
#define CORK_CONFIG_ARCH_X64  0
#endif

#if defined(__powerpc__) || defined(__ppc__)
/* GCC-ish compiler */
#define CORK_CONFIG_ARCH_PPC  1
#elif defined(_M_PPC)
/* VS-ish compiler */
#define CORK_CONFIG_ARCH_PPC  1
#elif defined(_ARCH_PPC)
/* Something called XL C/C++? */
#define CORK_CONFIG_ARCH_PPC  1
#else
#define CORK_CONFIG_ARCH_PPC  0
#endif

#endif /* LIBCORK_CONFIG_ARCH_H */


text:
using testing::_;
using testing::AnyNumber;
using testing::NiceMock;
using testing::Ref;
using testing::Return;
using testing::SaveArg;
using testing::StrictMock;

namespace proximity_auth {
namespace {

const char kDeviceName[] = "Device name";
const char kOtherDeviceName[] = "Other device name";

const char kBluetoothAddress[] = "11:22:33:44:55:66";
const char kOtherBluetoothAddress[] = "AA:BB:CC:DD:EE:FF";

const char kPublicKey[] = "Public key";
const char kPersistentSymmetricKey[] = "PSK";

const char kSerializedMessage[] = "Yarrr, this be a serialized message. Yarr!";
const int kSerializedMessageLength = strlen(kSerializedMessage);

const char kUuid[] = "DEADBEEF-CAFE-FEED-FOOD-D15EA5EBEEF";

const int kReceiveBufferSize = 6;
const char kReceiveBufferContents[] = "bytes";

// Create a buffer for testing received data.
scoped_refptr<net::IOBuffer> CreateReceiveBuffer() {
  scoped_refptr<net::IOBuffer> buffer = new net::IOBuffer(kReceiveBufferSize);
  memcpy(buffer->data(), kReceiveBufferContents, kReceiveBufferSize);
  return buffer;
}

class MockBluetoothConnection : public BluetoothConnection {
 public:
  MockBluetoothConnection()
      : BluetoothConnection(CreateRemoteDevice(),
                            device::BluetoothUUID(kUuid)) {}

  // Calls back into the parent Connection class.
  MOCK_METHOD1(SetStatusProxy, void(Status status));
  MOCK_METHOD1(OnBytesReceived, void(const std::string& bytes));
  MOCK_METHOD2(OnDidSendMessage,
               void(const WireMessage& message, bool success));

  void SetStatus(Status status) override {
    SetStatusProxy(status);
    BluetoothConnection::SetStatus(status);
  }

  using BluetoothConnection::status;
  using BluetoothConnection::Connect;
  using BluetoothConnection::DeviceRemoved;
  using BluetoothConnection::Disconnect;

 private:
  RemoteDevice CreateRemoteDevice() {
    return RemoteDevice(kDeviceName, kPublicKey, kBluetoothAddress,
                        kPersistentSymmetricKey);
  }

  DISALLOW_COPY_AND_ASSIGN(MockBluetoothConnection);
};

class TestWireMessage : public WireMessage {
 public:
  TestWireMessage() : WireMessage("permit id", "payload") {}
  ~TestWireMessage() override {}

  std::string Serialize() const override { return kSerializedMessage; }

 private:
  DISALLOW_COPY_AND_ASSIGN(TestWireMessage);
};

}  // namespace

class ProximityAuthBluetoothConnectionTest : public testing::Test {
 public:
  ProximityAuthBluetoothConnectionTest()
      : adapter_(new device::MockBluetoothAdapter),
        device_(adapter_.get(), 0, kDeviceName, kBluetoothAddress, true, true),
        socket_(new StrictMock<device::MockBluetoothSocket>),
        uuid_(kUuid) {
    device::BluetoothAdapterFactory::SetAdapterForTesting(adapter_);

    // Suppress uninteresting Gmock call warnings.
    EXPECT_CALL(*adapter_, GetDevice(_)).Times(AnyNumber());
  }

  // Transition the connection into an in-progress state.
  void BeginConnecting(MockBluetoothConnection* connection) {
    EXPECT_EQ(Connection::DISCONNECTED, connection->status());

    ON_CALL(*adapter_, GetDevice(_)).WillByDefault(Return(&device_));
    EXPECT_CALL(*connection, SetStatusProxy(Connection::IN_PROGRESS));
    EXPECT_CALL(*adapter_, AddObserver(connection));
    EXPECT_CALL(device_, ConnectToServiceInsecurely(uuid_, _, _));
    connection->Connect();

    EXPECT_EQ(Connection::IN_PROGRESS, connection->status());
  }

  // Transition the connection into a connected state.
  // Saves the success and error callbacks passed into OnReceive(), which can be
  // accessed via receive_callback() and receive_success_callback().
  void Connect(MockBluetoothConnection* connection) {
    EXPECT_EQ(Connection::DISCONNECTED, connection->status());

    device::BluetoothDevice::ConnectToServiceCallback callback;
    ON_CALL(*adapter_, GetDevice(_)).WillByDefault(Return(&device_));
    EXPECT_CALL(*connection, SetStatusProxy(Connection::IN_PROGRESS));
    EXPECT_CALL(*adapter_, AddObserver(connection));
    EXPECT_CALL(device_, ConnectToServiceInsecurely(_, _, _))
        .WillOnce(SaveArg<1>(&callback));
    connection->Connect();
    ASSERT_FALSE(callback.is_null());

    EXPECT_CALL(*connection, SetStatusProxy(Connection::CONNECTED));
    EXPECT_CALL(*socket_, Receive(_, _, _))
        .WillOnce(DoAll(SaveArg<1>(&receive_callback_),
                        SaveArg<2>(&receive_error_callback_)));
    callback.Run(socket_);

    EXPECT_EQ(Connection::CONNECTED, connection->status());
  }

  device::BluetoothSocket::ReceiveCompletionCallback* receive_callback() {
    return &receive_callback_;
  }
  device::BluetoothSocket::ReceiveErrorCompletionCallback*
  receive_error_callback() {
    return &receive_error_callback_;
  }

 protected:
  // Mocks used for verifying interactions with the Bluetooth subsystem.
  scoped_refptr<device::MockBluetoothAdapter> adapter_;
  NiceMock<device::MockBluetoothDevice> device_;
  scoped_refptr<StrictMock<device::MockBluetoothSocket>> socket_;

  device::BluetoothUUID uuid_;

 private:
  base::MessageLoop message_loop_;

  device::BluetoothSocket::ReceiveCompletionCallback receive_callback_;
  device::BluetoothSocket::ReceiveErrorCompletionCallback
      receive_error_callback_;
};

TEST_F(ProximityAuthBluetoothConnectionTest, Connect_ConnectionWasInProgress) {
  // Create an in-progress connection.
  StrictMock<MockBluetoothConnection> connection;
  BeginConnecting(&connection);

  // A second call to Connect() should be ignored.
  EXPECT_CALL(connection, SetStatusProxy(_)).Times(0);
  connection.Connect();

  // The connection cleans up after itself upon destruction.
  EXPECT_CALL(*adapter_, RemoveObserver(&connection));
}

TEST_F(ProximityAuthBluetoothConnectionTest, Connect_ConnectionWasConnected) {
  // Create a connected connection.
  StrictMock<MockBluetoothConnection> connection;
  Connect(&connection);

  // A second call to Connect() should be ignored.
  EXPECT_CALL(connection, SetStatusProxy(_)).Times(0);
  connection.Connect();

  // The connection disconnects and unregisters as an observer upon destruction.
  EXPECT_CALL(*socket_, Disconnect(_));
  EXPECT_CALL(*adapter_, RemoveObserver(&connection));
}

TEST_F(ProximityAuthBluetoothConnectionTest, Connect_NoBluetoothAdapter) {
  // Some platforms do not support Bluetooth. This test is only meaningful on
  // those platforms.
  adapter_ = NULL;
  if (device::BluetoothAdapterFactory::IsBluetoothAdapterAvailable())
    return;

  StrictMock<MockBluetoothConnection> connection;
  EXPECT_CALL(connection, SetStatusProxy(_)).Times(0);
  connection.Connect();
}

TEST_F(ProximityAuthBluetoothConnectionTest, Connect_DeviceMissing) {
  StrictMock<MockBluetoothConnection> connection;

  ON_CALL(*adapter_, GetDevice(_))
      .WillByDefault(Return(static_cast<device::BluetoothDevice*>(NULL)));
  EXPECT_CALL(connection, SetStatusProxy(Connection::IN_PROGRESS));
  EXPECT_CALL(connection, SetStatusProxy(Connection::DISCONNECTED));
  connection.Connect();
}

TEST_F(ProximityAuthBluetoothConnectionTest,
       Connect_DeviceRemovedWhileConnecting) {
  // Create an in-progress connection.
  StrictMock<MockBluetoothConnection> connection;
  BeginConnecting(&connection);

  // Remove the device while the connection is in-progress. This should cause
  // the connection to disconnect.
  EXPECT_CALL(connection, SetStatusProxy(Connection::DISCONNECTED));
  EXPECT_CALL(*adapter_, RemoveObserver(&connection));
  connection.DeviceRemoved(adapter_.get(), &device_);
}

TEST_F(ProximityAuthBluetoothConnectionTest,
       Connect_OtherDeviceRemovedWhileConnecting) {
  // Create an in-progress connection.
  StrictMock<MockBluetoothConnection> connection;
  BeginConnecting(&connection);

  // Remove a device other than the one that is being connected to. This should
  // not have any effect on the connection.
  NiceMock<device::MockBluetoothDevice> other_device(
      adapter_.get(), 0, kOtherDeviceName, kOtherBluetoothAddress, true, true);
  EXPECT_CALL(connection, SetStatusProxy(_)).Times(0);
  connection.DeviceRemoved(adapter_.get(), &other_device);

  // The connection removes itself as an observer when it is destroyed.
  EXPECT_CALL(*adapter_, RemoveObserver(&connection));
}

TEST_F(ProximityAuthBluetoothConnectionTest, Connect_ConnectionFails) {
  StrictMock<MockBluetoothConnection> connection;

  device::BluetoothDevice::ConnectToServiceErrorCallback error_callback;
  ON_CALL(*adapter_, GetDevice(_)).WillByDefault(Return(&device_));
  EXPECT_CALL(connection, SetStatusProxy(Connection::IN_PROGRESS));
  EXPECT_CALL(*adapter_, AddObserver(&connection));
  EXPECT_CALL(device_, ConnectToServiceInsecurely(uuid_, _, _))
      .WillOnce(SaveArg<2>(&error_callback));
  connection.Connect();
  ASSERT_FALSE(error_callback.is_null());

  EXPECT_CALL(connection, SetStatusProxy(Connection::DISCONNECTED));
  EXPECT_CALL(*adapter_, RemoveObserver(&connection));
  error_callback.Run("super descriptive error message");
}

TEST_F(ProximityAuthBluetoothConnectionTest, Connect_ConnectionSucceeds) {
  StrictMock<MockBluetoothConnection> connection;
  Connect(&connection);

  // The connection disconnects and unregisters as an observer upon destruction.
  EXPECT_CALL(*socket_, Disconnect(_));
  EXPECT_CALL(*adapter_, RemoveObserver(&connection));
}

TEST_F(ProximityAuthBluetoothConnectionTest,
       Connect_ConnectionSucceeds_ThenDeviceRemoved) {
  StrictMock<MockBluetoothConnection> connection;
  Connect(&connection);

  EXPECT_CALL(connection, SetStatusProxy(Connection::DISCONNECTED));
  EXPECT_CALL(*socket_, Disconnect(_));
  EXPECT_CALL(*adapter_, RemoveObserver(&connection));
  connection.DeviceRemoved(adapter_.get(), &device_);
}

TEST_F(ProximityAuthBluetoothConnectionTest,
       Connect_ConnectionSucceeds_ReceiveData) {
  StrictMock<MockBluetoothConnection> connection;
  Connect(&connection);
  ASSERT_TRUE(receive_callback() && !receive_callback()->is_null());

  // Receive some data. Once complete, the connection should re-register to be
  // ready receive more data.
  scoped_refptr<net::IOBuffer> buffer = CreateReceiveBuffer();
  EXPECT_CALL(
      connection,
      OnBytesReceived(std::string(kReceiveBufferContents, kReceiveBufferSize)));
  EXPECT_CALL(*socket_, Receive(_, _, _));
  receive_callback()->Run(kReceiveBufferSize, buffer);
  base::RunLoop run_loop;
  run_loop.RunUntilIdle();

  // The connection disconnects and unregisters as an observer upon destruction.
  EXPECT_CALL(*socket_, Disconnect(_));
  EXPECT_CALL(*adapter_, RemoveObserver(&connection));
}

TEST_F(ProximityAuthBluetoothConnectionTest,
       Connect_ConnectionSucceeds_ReceiveDataAfterReceiveError) {
  StrictMock<MockBluetoothConnection> connection;
  Connect(&connection);
  ASSERT_TRUE(receive_error_callback() && !receive_error_callback()->is_null());

  // Simulate an error while receiving data. The connection should re-register
  // to be ready receive more data despite the error.
  device::BluetoothSocket::ReceiveCompletionCallback receive_callback;
  EXPECT_CALL(*socket_, Receive(_, _, _))
      .WillOnce(SaveArg<1>(&receive_callback));
  receive_error_callback()->Run(device::BluetoothSocket::kSystemError,
                                "The system is down. They're taking over!");
  base::RunLoop run_loop;
  run_loop.RunUntilIdle();
  ASSERT_FALSE(receive_callback.is_null());

  // Receive some data.
  scoped_refptr<net::IOBuffer> buffer = CreateReceiveBuffer();
  EXPECT_CALL(
      connection,
      OnBytesReceived(std::string(kReceiveBufferContents, kReceiveBufferSize)));
  EXPECT_CALL(*socket_, Receive(_, _, _));
  receive_callback.Run(kReceiveBufferSize, buffer);
  base::RunLoop run_loop2;
  run_loop2.RunUntilIdle();

  // The connection disconnects and unregisters as an observer upon destruction.
  EXPECT_CALL(*socket_, Disconnect(_));
  EXPECT_CALL(*adapter_, RemoveObserver(&connection));
}

TEST_F(ProximityAuthBluetoothConnectionTest,
       Disconnect_ConnectionWasAlreadyDisconnected) {
  StrictMock<MockBluetoothConnection> connection;
  EXPECT_CALL(connection, SetStatusProxy(_)).Times(0);
  connection.Disconnect();
}

TEST_F(ProximityAuthBluetoothConnectionTest,
       Disconnect_ConnectionWasInProgress) {
  // Create an in-progress connection.
  StrictMock<MockBluetoothConnection> connection;
  BeginConnecting(&connection);

  EXPECT_CALL(connection, SetStatusProxy(Connection::DISCONNECTED));
  EXPECT_CALL(*adapter_, RemoveObserver(&connection));
  connection.Disconnect();
}

TEST_F(ProximityAuthBluetoothConnectionTest,
       Disconnect_ConnectionWasConnected) {
  // Create a connected connection.
  StrictMock<MockBluetoothConnection> connection;
  Connect(&connection);

  EXPECT_CALL(connection, SetStatusProxy(Connection::DISCONNECTED));
  EXPECT_CALL(*socket_, Disconnect(_));
  EXPECT_CALL(*adapter_, RemoveObserver(&connection));
  connection.Disconnect();
}

TEST_F(ProximityAuthBluetoothConnectionTest,
       Connect_ThenDisconnectWhileInProgress_ThenBackingConnectionSucceeds) {
  StrictMock<MockBluetoothConnection> connection;
  device::BluetoothDevice::ConnectToServiceCallback callback;
  ON_CALL(*adapter_, GetDevice(_)).WillByDefault(Return(&device_));
  EXPECT_CALL(connection, SetStatusProxy(Connection::IN_PROGRESS));
  EXPECT_CALL(*adapter_, AddObserver(&connection));
  EXPECT_CALL(device_, ConnectToServiceInsecurely(uuid_, _, _))
      .WillOnce(SaveArg<1>(&callback));
  connection.Connect();
  ASSERT_FALSE(callback.is_null());

  EXPECT_CALL(connection, SetStatusProxy(Connection::DISCONNECTED));
  EXPECT_CALL(*adapter_, RemoveObserver(&connection));
  connection.Disconnect();

  EXPECT_CALL(connection, SetStatusProxy(_)).Times(0);
  EXPECT_CALL(*socket_, Receive(_, _, _)).Times(0);
  callback.Run(socket_);
}

TEST_F(ProximityAuthBluetoothConnectionTest,
       SendMessage_SendsExpectedDataOverTheWire) {
  // Create a connected connection.
  StrictMock<MockBluetoothConnection> connection;
  Connect(&connection);

  scoped_refptr<net::IOBuffer> buffer;
  scoped_ptr<TestWireMessage> wire_message(new TestWireMessage);
  EXPECT_CALL(*socket_, Send(_, kSerializedMessageLength, _, _))
      .WillOnce(SaveArg<0>(&buffer));
  connection.SendMessage(wire_message.Pass());
  ASSERT_TRUE(buffer.get());
  EXPECT_EQ(kSerializedMessage,
            std::string(buffer->data(), kSerializedMessageLength));

  // The connection disconnects and unregisters as an observer upon destruction.
  EXPECT_CALL(*socket_, Disconnect(_));
  EXPECT_CALL(*adapter_, RemoveObserver(&connection));
}

TEST_F(ProximityAuthBluetoothConnectionTest, SendMessage_Success) {
  // Create a connected connection.
  StrictMock<MockBluetoothConnection> connection;
  Connect(&connection);

  scoped_ptr<TestWireMessage> wire_message(new TestWireMessage);
  // Ownership will be transfered below, so grab a reference here.
  TestWireMessage* expected_wire_message = wire_message.get();

  device::BluetoothSocket::SendCompletionCallback callback;
  EXPECT_CALL(*socket_, Send(_, _, _, _)).WillOnce(SaveArg<2>(&callback));
  connection.SendMessage(wire_message.Pass());
  ASSERT_FALSE(callback.is_null());

  EXPECT_CALL(connection, OnDidSendMessage(Ref(*expected_wire_message), true));
  callback.Run(kSerializedMessageLength);

  // The connection disconnects and unregisters as an observer upon destruction.
  EXPECT_CALL(*socket_, Disconnect(_));
  EXPECT_CALL(*adapter_, RemoveObserver(&connection));
}

TEST_F(ProximityAuthBluetoothConnectionTest, SendMessage_Failure) {
  // Create a connected connection.
  StrictMock<MockBluetoothConnection> connection;
  Connect(&connection);

  scoped_ptr<TestWireMessage> wire_message(new TestWireMessage);
  // Ownership will be transfered below, so grab a reference here.
  TestWireMessage* expected_wire_message = wire_message.get();

  device::BluetoothSocket::ErrorCompletionCallback error_callback;
  EXPECT_CALL(*socket_, Send(_, _, _, _)).WillOnce(SaveArg<3>(&error_callback));
  connection.SendMessage(wire_message.Pass());

  ASSERT_FALSE(error_callback.is_null());
  EXPECT_CALL(connection, OnDidSendMessage(Ref(*expected_wire_message), false));
  EXPECT_CALL(connection, SetStatusProxy(Connection::DISCONNECTED));
  EXPECT_CALL(*socket_, Disconnect(_));
  EXPECT_CALL(*adapter_, RemoveObserver(&connection));
  error_callback.Run("The most helpful of error messages");
}

}  // namespace proximity_auth


text:
import { expect } from 'chai';
import * as path from 'path';
import { ipcMain, BrowserWindow, WebContents, WebPreferences, webContents } from 'electron/main';
import { emittedOnce } from './events-helpers';
import { closeWindow } from './window-helpers';

describe('ipcRenderer module', () => {
  const fixtures = path.join(__dirname, 'fixtures');

  let w: BrowserWindow;
  before(async () => {
    w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
    await w.loadURL('about:blank');
  });
  after(async () => {
    await closeWindow(w);
    w = null as unknown as BrowserWindow;
  });

  describe('send()', () => {
    it('should work when sending an object containing id property', async () => {
      const obj = {
        id: 1,
        name: 'ly'
      };
      w.webContents.executeJavaScript(`{
        const { ipcRenderer } = require('electron')
        ipcRenderer.send('message', ${JSON.stringify(obj)})
      }`);
      const [, received] = await emittedOnce(ipcMain, 'message');
      expect(received).to.deep.equal(obj);
    });

    it('can send instances of Date as Dates', async () => {
      const isoDate = new Date().toISOString();
      w.webContents.executeJavaScript(`{
        const { ipcRenderer } = require('electron')
        ipcRenderer.send('message', new Date(${JSON.stringify(isoDate)}))
      }`);
      const [, received] = await emittedOnce(ipcMain, 'message');
      expect(received.toISOString()).to.equal(isoDate);
    });

    it('can send instances of Buffer', async () => {
      const data = 'hello';
      w.webContents.executeJavaScript(`{
        const { ipcRenderer } = require('electron')
        ipcRenderer.send('message', Buffer.from(${JSON.stringify(data)}))
      }`);
      const [, received] = await emittedOnce(ipcMain, 'message');
      expect(received).to.be.an.instanceOf(Uint8Array);
      expect(Buffer.from(data).equals(received)).to.be.true();
    });

    it('throws when sending objects with DOM class prototypes', async () => {
      await expect(w.webContents.executeJavaScript(`{
        const { ipcRenderer } = require('electron')
        ipcRenderer.send('message', document.location)
      }`)).to.eventually.be.rejected();
    });

    it('does not crash when sending external objects', async () => {
      await expect(w.webContents.executeJavaScript(`{
        const { ipcRenderer } = require('electron')
        const http = require('http')

        const request = http.request({ port: 5000, hostname: '127.0.0.1', method: 'GET', path: '/' })
        const stream = request.agent.sockets['127.0.0.1:5000:'][0]._handle._externalStream

        ipcRenderer.send('message', stream)
      }`)).to.eventually.be.rejected();
    });

    it('can send objects that both reference the same object', async () => {
      w.webContents.executeJavaScript(`{
        const { ipcRenderer } = require('electron')

        const child = { hello: 'world' }
        const foo = { name: 'foo', child: child }
        const bar = { name: 'bar', child: child }
        const array = [foo, bar]

        ipcRenderer.send('message', array, foo, bar, child)
      }`);

      const child = { hello: 'world' };
      const foo = { name: 'foo', child: child };
      const bar = { name: 'bar', child: child };
      const array = [foo, bar];

      const [, arrayValue, fooValue, barValue, childValue] = await emittedOnce(ipcMain, 'message');
      expect(arrayValue).to.deep.equal(array);
      expect(fooValue).to.deep.equal(foo);
      expect(barValue).to.deep.equal(bar);
      expect(childValue).to.deep.equal(child);
    });

    it('can handle cyclic references', async () => {
      w.webContents.executeJavaScript(`{
        const { ipcRenderer } = require('electron')
        const array = [5]
        array.push(array)

        const child = { hello: 'world' }
        child.child = child
        ipcRenderer.send('message', array, child)
      }`);

      const [, arrayValue, childValue] = await emittedOnce(ipcMain, 'message');
      expect(arrayValue[0]).to.equal(5);
      expect(arrayValue[1]).to.equal(arrayValue);

      expect(childValue.hello).to.equal('world');
      expect(childValue.child).to.equal(childValue);
    });
  });

  describe('sendSync()', () => {
    it('can be replied to by setting event.returnValue', async () => {
      ipcMain.once('echo', (event, msg) => {
        event.returnValue = msg;
      });
      const msg = await w.webContents.executeJavaScript(`new Promise(resolve => {
        const { ipcRenderer } = require('electron')
        resolve(ipcRenderer.sendSync('echo', 'test'))
      })`);
      expect(msg).to.equal('test');
    });
  });

  describe('sendTo()', () => {
    const generateSpecs = (description: string, webPreferences: WebPreferences) => {
      describe(description, () => {
        let contents: WebContents;
        const payload = 'Hello World!';

        before(async () => {
          contents = (webContents as any).create({
            preload: path.join(fixtures, 'module', 'preload-ipc-ping-pong.js'),
            ...webPreferences
          });

          await contents.loadURL('about:blank');
        });

        after(() => {
          (contents as any).destroy();
          contents = null as unknown as WebContents;
        });

        it('sends message to WebContents', async () => {
          const data = await w.webContents.executeJavaScript(`new Promise(resolve => {
            const { ipcRenderer } = require('electron')
            ipcRenderer.sendTo(${contents.id}, 'ping', ${JSON.stringify(payload)})
            ipcRenderer.once('pong', (event, data) => resolve(data))
          })`);
          expect(data).to.equal(payload);
        });

        it('sends message on channel with non-ASCII characters to WebContents', async () => {
          const data = await w.webContents.executeJavaScript(`new Promise(resolve => {
            const { ipcRenderer } = require('electron')
            ipcRenderer.sendTo(${contents.id}, 'ping-æøåü', ${JSON.stringify(payload)})
            ipcRenderer.once('pong-æøåü', (event, data) => resolve(data))
          })`);
          expect(data).to.equal(payload);
        });
      });
    };

    generateSpecs('without sandbox', {});
    generateSpecs('with sandbox', { sandbox: true });
    generateSpecs('with contextIsolation', { contextIsolation: true });
    generateSpecs('with contextIsolation + sandbox', { contextIsolation: true, sandbox: true });
  });

  describe('ipcRenderer.on', () => {
    it('is not used for internals', async () => {
      const result = await w.webContents.executeJavaScript(`
        require('electron').ipcRenderer.eventNames()
      `);
      expect(result).to.deep.equal([]);
    });
  });

  describe('after context is released', () => {
    it('throws an exception', async () => {
      const error = await w.webContents.executeJavaScript(`(${() => {
        const child = window.open('', 'child', 'show=no,nodeIntegration=yes')! as any;
        const childIpc = child.require('electron').ipcRenderer;
        child.close();
        return new Promise(resolve => {
          setInterval(() => {
            try {
              childIpc.send('hello');
            } catch (e) {
              resolve(e);
            }
          }, 16);
        });
      }})()`);
      expect(error).to.have.property('message', 'IPC method called after context was released');
    });
  });
});


text:
function results_simu = glmc_simu_multiscale(tseries_all,hier,opt,flag_init)
% Simulate multiscale changes in connectivity between two populations
%
% SYNTAX:
% RESULTS = GLMC_SIMU_MULTISCALE(TSERIES,HIER,OPT)
%
% _________________________________________________________________________
% INPUTS
%
% TSERIES_ALL
%   (cell of strings) each entry is a variable TSERIES of size T x N.
%
% HIER
%   (string) a .mat file with a hierarchy on the N regions of the brain.
%
% OPT
%   (structure) with the following fields.
%
%   TYPE_DATA
%      (string, default 'real') the type of simulation. Available options:
%      'real': use real datasets for the null hypothesis.
%      'homogeneous': use an homogeneous correlation matrix under the null.
%         in this case OPT.{THETA,STD_THETA,T,N} below have to be specified.
%
%   ALPHA2
%      (scalar, default 0.2) the variance of the signal added to
%      simulate an effect.
%
%   THETA2
%      (scalar, default 0.1) the variance of the signal added to create
%      a background 'homogeneous' correlation.
%
%   LIST_SCALES
%      (vector of integers) the list of scales used for testing.
%
%   SCALE_REF
%      (integer) the scale that is used as a reference for the simulation.
%      if left empty, or equal 0, the simu is done under the null of no effect
%      at any scale.
%
%   CLUSTER_REF
%      (integer) the cluster that is used to simulate the effect at the scale
%      of reference.
%
%   PERC_RAND
%      (scalar, default 0) a percentage PERC_RAND of the cluster of reference is
%      randomly assigned to other clusters.
%
%   TYPE_FDR
%      (string, default 'BH') how the FDR is controled.
%      See the TYPE argument of NIAK_GLM_FDR.
%
%   LIST_FDR
%      (vector, default [0.05]) the levels of acceptable false-discovery rate
%      for the t-maps.
%
%   NB_SUBJECT
%      (integer) the number of subjects to use.
%
%   NB_SAMPS
%      (integer, default 0) the number of samples for the permutation-based
%      omnibus test. If the number of samples is 0, the test is not
%      generated.
%
%   FLAG_VERBOSE
%      (boolean, default 1) if the flag is 1, then the function
%      prints some infos during the processing.
%
% _________________________________________________________________________
% OUTPUTS:
%
% RESULTS
%   (structure) with the following fields:
%   TEST_Q,P_NB_DISC,MASK_TRUTH,MEAN_DIFF,STD_IIR
%
% OPT
%   Same as input OPT, but updated.
%
% _________________________________________________________________________
% SEE ALSO:
%
% _________________________________________________________________________
% COMMENTS
%
% Copyright (c) Pierre Bellec,
% Centre de recherche de l'institut de gériatrie de Montréal, 2013.
% Maintainer : pierre.bellec@criugm.qc.ca
% See licensing information in the code.
% Keywords : GLM-connectome, simulation

% 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 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.

%% Options
if (nargin < 4)||flag_init
    list_fields   = { 'perc_rand' , 'type_data' , 'theta2' , 'nb_samps' , 'list_fdr' , 'type_fdr' , 'nb_subject' , 'alpha2' , 'list_scales' , 'scale_ref' , 'cluster_ref' , 'flag_verbose' };
    list_defaults = { 0           , 'real'      , 0.1      , 0          , 0.05       , 'BH'  , NaN          , 0.2      , NaN           , NaN         , NaN           , true           };
    opt = psom_struct_defaults(opt,list_fields,list_defaults);
end

if opt.scale_ref == 0
    opt.scale_ref = [];
end

%% Read partitions
part = niak_threshold_hierarchy(hier,struct('thresh',opt.list_scales));
if ~isempty(opt.scale_ref)
    part_ref = niak_threshold_hierarchy(hier,struct('thresh',opt.scale_ref));
    ind_ref = opt.cluster_ref;
    clust_ref = part_ref == ind_ref;
    clust_ref_raw = clust_ref;
    if opt.perc_rand>0
        clust_ref_r = zeros(size(clust_ref));
        ind_c = find(clust_ref);
        %ind_c = ind_c(randperm(length(ind_c)));        % Use a deterministic discrepancy
        ind_nc = find(~clust_ref);
        %ind_nc = ind_nc(randperm(length(ind_nc)));     % Use a deterministic discrepancy
        nb_r = floor(length(ind_c)*opt.perc_rand);
        clust_ref_r(ind_c(1:(end-nb_r))) = 1;
        clust_ref_r(ind_nc(1:nb_r)) = 1;
        clust_ref = clust_ref_r>0;
    end
    clust_ref_raw = clust_ref & clust_ref_raw;
else
    warning('No scale of reference was specified, simulations are generated under the global null');
    clust_ref = [];
    ind_ref = 0;
    part_ref = zeros(size(part,1));
end

%% Generate a mask of truth
for ss = 1:length(opt.list_scales)
    mask_truth{ss} = false(opt.list_scales(ss),1);
    if ~isempty(opt.scale_ref)
        for cc = 1:opt.list_scales(ss)
            mask_truth{ss}(cc) = any(clust_ref_raw(part(:,ss)==cc));
        end
    end
end

%% Keep a random subset of subjects
ind_s = randperm(length(tseries_all));
ind_s = ind_s(1:opt.nb_subject);
tseries_all = tseries_all(ind_s);

%% Define a random group difference
ind1 = randperm(length(tseries_all));
ind1 = ind1(1:floor(length(tseries_all)/2));

%% Read time series and generate multiscale connectomes
if opt.flag_verbose
    fprintf('Generating (multiscale) connectomes ...\n')
end
conn = cell(length(opt.list_scales),1);
for tt = 1:length(tseries_all)
    niak_progress(tt,length(tseries_all));
    tseries = tseries_all{tt};

    switch opt.type_data
        case 'real'
            %% run a circular block bootstrap on the time series inside
            %% each network at the scale of reference
            %% to kill inter-network correlations at scales lower than the ref.
            %% The objective is to be able to tell with confidence which connections
            %% are impacted by the addition of a signal in the simulations that follow
            if ~isempty(opt.scale_ref)
                for cc = 1:opt.scale_ref
                    tseries(:,part_ref==cc) = niak_bootstrap_tseries(tseries(:,part_ref==cc));
                end
            end
        case 'homogeneous'
            [t,n] = size(tseries);
            tseries = randn([t n]);
            w = opt.theta;
            tseries = sqrt(1-w)*tseries + sqrt(w)*repmat(randn([t 1]),[1 n]);
        otherwise
             error('%s is an unkown type of simulations',opt.type_data);
    end
    tseries = niak_normalize_tseries(tseries);

    if any(ind1==tt)&&~isempty(opt.scale_ref)
        % simulate an effect !
        tseries_raw = tseries;
        tseries(:,clust_ref) = sqrt(1-opt.alpha2)*tseries(:,clust_ref) + sqrt(opt.alpha2)*repmat(randn([size(tseries,1) 1]),[1 sum(clust_ref)]);
    end

    %% Measure the empirical effect size
    for ss = 1:length(opt.list_scales)
        iir = niak_build_intra_inter_r(tseries,part(:,ss),true,true);
        if (tt ==1)
            conn{ss} = zeros(length(tseries_all),length(iir));
            mean_diff{ss} = zeros(sum(mask_truth{ss}),sum(mask_truth{ss}));
            sum_iir{ss} = zeros(sum(mask_truth{ss}),sum(mask_truth{ss}));
            sum_iir2{ss} = zeros(sum(mask_truth{ss}),sum(mask_truth{ss}));
        end
        conn{ss}(tt,:) = iir';
        if any(ind1==tt)&&~isempty(opt.scale_ref)
            iir_raw = niak_build_intra_inter_r(tseries_raw,part(:,ss),true,true);
            tmp = niak_lvec2mat(iir) - niak_lvec2mat(iir_raw);
            mean_diff{ss} = mean_diff{ss} + tmp(mask_truth{ss},mask_truth{ss});
            tmp_iir = niak_lvec2mat(iir_raw);
            sum_iir{ss} = sum_iir{ss} + tmp_iir(mask_truth{ss},mask_truth{ss});
            sum_iir2{ss} = sum_iir2{ss} + tmp_iir(mask_truth{ss},mask_truth{ss}).^2;
        else
            tmp_iir = niak_lvec2mat(iir);
            sum_iir{ss} = sum_iir{ss} + tmp_iir(mask_truth{ss},mask_truth{ss});
            sum_iir2{ss} = sum_iir2{ss} + tmp_iir(mask_truth{ss},mask_truth{ss}).^2;
        end
    end
end
if ~isempty(opt.scale_ref)
    for ss = 1:length(opt.list_scales)
        mean_diff{ss} = mean_diff{ss}/length(ind1);
    end
end
for ss = 1:length(opt.list_scales)
    std_iir{ss} = sqrt(length(tseries_all)/(length(tseries_all)-1))*sqrt(sum_iir2{ss}/length(tseries_all) - (sum_iir{ss}/length(tseries_all)).^2);
end

%% Generate stats
if opt.flag_verbose
    fprintf('Generate stats ...\n    scale')
end
mask1 = false(length(tseries_all),1);
mask1(ind1) = true;
opt_glm.test  = 'ttest' ;
opt_glm.flag_beta = true ;
opt_glm.flag_residuals = true ;
perc_discovery = zeros(length(opt.list_scales),length(opt.list_fdr));
test_q = cell(length(opt.list_scales),length(opt.list_fdr));
vol_disc = 0;
for ss = 1:length(opt.list_scales)
    if opt.flag_verbose
        fprintf(' - %i',opt.list_scales(ss))
    end
    glm(ss).x = [ones(length(tseries_all),1) double(mask1)];
    glm(ss).c = [0 ; 1];
    glm(ss).y = conn{ss};
    results = niak_glm( glm(ss) , opt_glm );
    for ff = 1:length(opt.list_fdr)
        q = opt.list_fdr(ff);
        [fdr,test_q{ss,ff}] = niak_glm_fdr(results.pce,opt.type_fdr,q,'correlation');
        perc_discovery(ss,ff) = sum(test_q{ss,ff}(:)/length(test_q{ss,ff}(:)));
    end
end
perc_disc = mean(perc_discovery,1);
if opt.flag_verbose
    fprintf('\n')
end

%% Generate samples under the null
if opt.nb_samps>0
    if opt.flag_verbose
        fprintf('Estimate the significance of the number of findings ...\n')
    end
    p_nb_disc = zeros(length(opt.list_fdr),1);
    perc_disc_null = zeros([opt.nb_samps length(opt.list_fdr)]);
    for num_s = 1:opt.nb_samps
        if opt.flag_verbose
            niak_progress(num_s,opt.nb_samps);
        end
        for ff = 1:length(opt.list_fdr)
            glm_null = niak_permutation_glm(glm);
            for num_e = 1:length(glm_null)
                res_null = niak_glm(glm_null(num_e),opt_glm);
                [fdr_null,test_null] = niak_glm_fdr(res_null.pce,opt.type_fdr,opt.list_fdr(ff),'correlation');
                perc_disc_null(num_s,ff) = perc_disc_null(num_s,ff) + (sum(double(test_null(:)))/length(test_null(:)));
            end
            perc_disc_null(num_s,ff) = perc_disc_null(num_s,ff)/length(glm_null);
            p_nb_disc(ff) = p_nb_disc(ff) + double(perc_disc_null(num_s,ff)>=perc_disc(ff));
        end
    end
    p_nb_disc = p_nb_disc / opt.nb_samps;
else
    p_nb_disc = NaN;
    nb_disc_null = NaN;
end

%% Save the results
results_simu.test_q = test_q;
results_simu.p_nb_disc = p_nb_disc;
results_simu.mask_truth = mask_truth;
results_simu.mean_diff = mean_diff;
results_simu.std_iir = std_iir;


text:
package com.digirati.elucidate.web.converter.oa.bulkupdate;

import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;

import com.digirati.elucidate.model.batch.OABatchOperation;
import com.digirati.elucidate.web.converter.AbstractMessageConverter;

public abstract class AbstractOABatchOperationMessageConverter extends AbstractMessageConverter<OABatchOperation> {

    protected AbstractOABatchOperationMessageConverter(MediaType... supportedMediaTypes) {
        super(supportedMediaTypes);
    }

    @Override
    protected boolean supports(Class<?> clazz) {
        return OABatchOperation.class.equals(clazz);
    }

    @Override
    protected void decorateHeaders(OABatchOperation oaBatchOperation, HttpOutputMessage outputMessage) {}
}


text:
<?php
/**
 * The following variables are available in this template:
 * - $this: the BootstrapCode object
 */
?>
<?php echo "<?php\n"; ?>
/* @var $this <?php echo $this->getControllerClass(); ?> */
/* @var $model <?php echo $this->getModelClass(); ?> */
/* @var $form TbActiveForm */
<?php echo "?>\n"; ?>

    <?php echo "<?php \$form=\$this->beginWidget('bootstrap.widgets.TbActiveForm', array(
	'id'=>'" . $this->class2id($this->modelClass) . "-form',
	// Please note: When you enable ajax validation, make sure the corresponding
	// controller action is handling ajax validation correctly.
	// There is a call to performAjaxValidation() commented in generated controller code.
	// See class documentation of CActiveForm for details on this.
	'enableAjaxValidation'=>false,
)); ?>\n"; ?>

Fields with * are required.

    <?php echo "<?php echo \$form->errorSummary(\$model); ?>\n"; ?>

    <?php
    foreach ($this->tableSchema->columns as $column) {
        if ($column->autoIncrement) {
            continue;
        }
        ?>
        <?php echo "<?php echo " . $this->generateActiveControlGroup($this->modelClass, $column) . "; ?>\n"; ?>

    <?php
    }
    ?>

        <?php echo "<?php echo TbHtml::submitButton(\$model->isNewRecord ? 'Create' : 'Save',array(
		    'color'=>TbHtml::BUTTON_COLOR_PRIMARY,
		)); ?>\n"; ?>

    <?php echo "<?php \$this->endWidget(); ?>\n"; ?>


text:
package org.hoteia.qalingo.core.web.mvc.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hoteia.qalingo.core.ModelConstants;
import org.hoteia.qalingo.core.domain.Customer;
import org.hoteia.qalingo.core.web.mvc.factory.FrontofficeViewBeanFactory;
import org.hoteia.qalingo.core.web.resolver.RequestData;
import org.hoteia.qalingo.core.web.util.RequestUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class ModelDataHandlerInterceptor implements HandlerInterceptor {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    protected FrontofficeViewBeanFactory frontofficeViewBeanFactory;

    @Autowired
    protected RequestUtil requestUtil;

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler, Exception exception) throws Exception {
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response,
                           Object handler, ModelAndView modelAndView) throws Exception {

        try {
            final RequestData requestData = requestUtil.getRequestData(request);

            modelAndView.getModelMap().put(ModelConstants.COMMON_VIEW_BEAN, frontofficeViewBeanFactory.buildViewBeanCommon(requestData));

            final Customer customer = requestData.getCustomer();
            if(customer != null){
                modelAndView.getModelMap().put(ModelConstants.CUSTOMER_VIEW_BEAN, frontofficeViewBeanFactory.buildViewBeanCustomer(requestData, customer));
            }

            modelAndView.getModelMap().put(ModelConstants.LEGAl_TERMS_VIEW_BEAN, frontofficeViewBeanFactory.buildViewBeanLegalTerms(requestData));

            modelAndView.getModelMap().put(ModelConstants.HEADER_CART, frontofficeViewBeanFactory.buildViewBeanHeaderCart(requestData));

        } catch (Exception e) {
            logger.error("inject common datas failed", e);
        }

    }

}


text:
//
// The MIT License (MIT)
//
// Copyright (c) 2013 Backelite
//
// 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 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.

#import <Foundation/Foundation.h>

@class BKTTask;
@class BKTTaskContent;
@protocol BKTTaskStep;
typedef NSOperation <BKTTaskStep> BKTStepOperation;
typedef void (^BKTTaskCompletion)(BKTTask *task, id output);
typedef void (^BKTTaskFailure)(BKTTask *task, NSError *error);

/**
 * Asynchronous task group.
 *
 * Meant particularly to handle url request when used with \ref BKTURLRequestOperation
 *
 */
@interface BKTTask : NSObject <NSCopying>

@property (strong, nonatomic) BKTStepOperation *initialStep;
@property (strong, nonatomic, readonly) BKTTaskContent *content;

/**
 *  Application defined value that can be used to identify a task.
 */
@property (strong, nonatomic) id taskId;

/**
 *  Is set to YES when the task starts, then to NO when it stops, whether it is cancelled, done, or has failed. KVO compliant. Thread safe.
 */
@property (readonly) BOOL isExecuting;

/**
 *  Is set to NO when the task stops, whether it is cancelled, done, or has failed. KVO compliant. Thread safe.
 */
@property (readonly) BOOL isFinished;

/**
 *  Is set to YES when the method -cancel is called. KVO compliant. Thread safe.
 */
@property (readonly) BOOL isCancelled;

/**
 *  Designated initializer.
 *
 *  @return An initialized task.
 */
- (id) init;

/**
 *  Adds a new step to receiver after the last one.
 *
 *  @param aStep The step to add.
 */
- (void) addStep:(BKTStepOperation *)aStep;

/**
 *  Adds a new step to receiver after another one.
 *
 *  @param aStep        The step to add.
 *  @param previousStep Reference to the step after which the new step will be added.
 *  @discussion Call with previousStep set to nil to add it as the first step.
 */
- (void) insertStep:(BKTStepOperation *)aStep afterStep:(BKTStepOperation *)previousStep;

/**
 *  Adds a step before another one. Raises an exception if nextStep is already running.
 *
 *  @param aStep    The step to add.
 *  @param nextStep Reference to the step before which the new step will be added.
 */
- (void) insertStep:(BKTStepOperation *)aStep beforeStep:(BKTStepOperation *)nextStep;

/**
 *  Adds a block to be called on completion.
 *
 *  @param target An object intended to be used to remove the related completion block when necessary. It is unretained but beware that the same object could be retained by the completion block.
 *  @param completionBlock A block called when the task is finished.
 *  @see \ref removeTargetCompletions:
 */
- (void) addTarget:(id)target completion:(BKTTaskCompletion)completionBlock;

/**
 *  Removes all completion blocks related to a target. If all completion blocks are removed, the task is automatically canceled.
 *
 *  @param target The object on which completion blocks have been added.
 *  @see \ref addTarget:completion:
 */
- (void) removeTargetCompletions:(id)target;

/**
 *  Adds a block to be called on failure.
 *
 *  @param target       An object intended to be used to remove the related failure block when necessary. It is unretained but beware that the same object could be retained by the failure block.
 *  @param failureBlock A block called when the task fails to complete.
 *  @see \ref removeTargetFailures:
 */
- (void) addTarget:(id)target failure:(BKTTaskFailure)failureBlock;

/**
 *  Removes the failure handlers registered for target.
 *
 *  @param target The object on which failure blocks have been added.
 *  @see \ref addTarget:failure:
 */
- (void) removeTargetFailures:(id)target;

/**
 *  Begins the execution of the task.
 */
- (void) start;

/**
 * Remove all targets and tries to cancel the task. In most case you should rather remove the target that is no longer interested in the result.
 * @see \ref removeTargetCompletions:
 */
- (void) cancel;

@end

@protocol BKTTaskStep <NSObject, NSCopying>

@required

/**
 *  The setter must be used exclusively by the owning task
 */
@property (unsafe_unretained, nonatomic) BKTTask *task;

/**
 *  The setter must be used exclusively by the owning task
 */
@property (unsafe_unretained, nonatomic) BKTStepOperation *previousStep;

/**
 *  The setter must be used exclusively by the owning task
 */
@property (unsafe_unretained, nonatomic) BKTStepOperation *nextStep;

/**
 *  The content to be processed by the step
 */
@property (strong, nonatomic) BKTTaskContent *content;

/**
 *  Getter for the step error object. When error is different from nil, the task will fail and call the failure block.
 *
 *  @return The step error object.
 */
- (NSError *) error;

@optional
/**
 *   Getter for the operation queue executing the step. This method does not return the main queue as steps are executed in background
 *
 *  @return The operation queue executing the step.
 */
- (NSOperationQueue *) stepOperationQueue;

@end


text:
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;

namespace Platformer.Collisions
{
    public class World
    {
        public World(Vector2 gravity)
        {
            Gravity = gravity;
        }

        public Vector2 Gravity { get; set; }

        private readonly List<Body> _dynamicBodies = new List<Body>();
        private readonly List<Body> _staticBodies = new List<Body>();

        public void AddBody(Body body)
        {
            if (body.BodyType == BodyType.Dynamic)
                _dynamicBodies.Add(body);
            else
                _staticBodies.Add(body);
        }

        public void RemoveBody(Body body)
        {
            if (body.BodyType == BodyType.Dynamic)
                _dynamicBodies.Remove(body);
            else
                _staticBodies.Remove(body);
        }

        public void Update(float deltaTime)
        {
            // apply gravity (and other forces?)
            foreach (var body in _dynamicBodies)
                body.Velocity += Gravity;

            foreach (var dynamicBody in _dynamicBodies)
            {
                dynamicBody.Position.X += dynamicBody.Velocity.X * deltaTime;
                ResolveCollisions(dynamicBody);

                dynamicBody.Position.Y += dynamicBody.Velocity.Y * deltaTime;
                ResolveCollisions(dynamicBody);
            }
        }

        private void ResolveCollisions(Body dynamicBody)
        {
            foreach (var staticBody in _staticBodies)
            {
                var vector = staticBody.Position - dynamicBody.Position;

                if (CollisionTester.AabbAabb(dynamicBody.BoundingBox, staticBody.BoundingBox, vector, out var manifold))
                {
                    dynamicBody.Position -= manifold.Normal * manifold.Penetration;
                    dynamicBody.Velocity = dynamicBody.Velocity * new Vector2(Math.Abs(manifold.Normal.Y), Math.Abs(manifold.Normal.X));
                }
            }

            foreach (var otherDynamicBody in _dynamicBodies)
            {
                if (dynamicBody != otherDynamicBody) //TODO: Equality should be implemented better than this
                {
                    var vector = otherDynamicBody.Position - dynamicBody.Position;

                    if (CollisionTester.AabbAabb(dynamicBody.BoundingBox, otherDynamicBody.BoundingBox, vector, out var manifold))
                    {
                        //Invert how the manifold is applied from how this is done with static bodyies.
                        //This will create the effect that the dynamic body in motion is pushing the other dynamic body.
                        otherDynamicBody.Position += manifold.Normal * manifold.Penetration;
                        otherDynamicBody.Velocity = otherDynamicBody.Velocity * new Vector2(System.Math.Abs(manifold.Normal.Y), System.Math.Abs(manifold.Normal.X));
                    }
                }
            }
        }
    }
}


text:
package org.apache.maven.plugin;

/**
 * Compiles application sources
 *
 * @author <a href="mailto:jason@maven.org">Jason van Zyl </a>
 * @version $Id$
 * @since 2.0
 * @deprecated package change since 3.0
 */
@Deprecated
public class CompilerMojo
    extends org.apache.maven.plugin.compiler.CompilerMojo
{
    // no op only here for backward comp
}


text:
package net.wayfarerx.dreamsleeve.data

import collection.immutable.{SortedMap, SortedSet}

import cats.Eval

/**
 * Represents a data document.
 *
 * @param title   The title of the document.
 * @param content The content of the document.
 */
case class Document(title: String, content: Fragment) extends Data {

  /* Test for equality with this document. */
  override protected[data] def calculateEquals(that: Any): Eval[Boolean] = that match {
    case Document(thatTitle, thatContent) if thatTitle == title => content.calculateEquals(thatContent)
    case _ => Eval.False
  }

  /* Calculate the hash for this document. */
  override protected def calculateHash(generator: Hash.Generator): Eval[Hash] =
    for (c <- content.evalHash(generator)) yield generator.hash(Document.Header, title, c)

  /* Calculate the string for this document. */
  override protected[data] def calculateToString(): Eval[String] =
    for (c <- content.calculateToString()) yield s"Document($title,$c)"

}

/**
 * Declarations associated with documents.
 */
object Document
  extends binary_data.Documents {

  /** The header for documents. */
  val Header: Byte = 0xE1.toByte

}

/**
 * The base type of all document fragments.
 */
sealed abstract class Fragment extends Data

/**
 * Extractor for fragment implementations.
 */
object Fragment
  extends binary_data.Fragments {

  /**
   * Extracts any fragment implementation.
   *
   * @param fragment The fragment to extract.
   * @return Eval.now(true) for every fragment.
   */
  def unapply(fragment: Fragment): Boolean =
    true

}

/**
 * The base type of all fragments that represent a single value.
 */
sealed abstract class Value extends Fragment with Comparable[Value]

/**
 * Implementations of the value types.
 */
object Value
  extends binary_data.Values {

  /**
   * Extracts any value implementation.
   *
   * @param value The value to extract.
   * @return Eval.now(true) for every value.
   */
  def unapply(value: Value): scala.Boolean =
    true

  /**
   * Represents true or false values.
   *
   * @param value The underlying value.
   */
  case class Boolean(value: scala.Boolean = false) extends Value {

    /* Test for equality with this boolean value. */
    override protected[data] def calculateEquals(that: Any): Eval[scala.Boolean] = that match {
      case Boolean(v) if v == value => Eval.True
      case _ => Eval.False
    }

    /* Calculate the hash for this boolean value. */
    override protected def calculateHash(generator: Hash.Generator): Eval[Hash] =
      Eval.now(generator.hash(Boolean.Header, value))

    /* Calculate the string for this boolean value. */
    override protected[data] def calculateToString(): Eval[java.lang.String] =
      Eval.now(s"Boolean($value)")

    /* Compare this value with another value. */
    override def compareTo(that: Value): Int = that match {
      case Boolean(b) => if (b == value) 0 else if (b) -1 else 1
      case _ => -1
    }

  }

  /**
   * Declarations associated with booleans.
   */
  object Boolean
    extends binary_data.Booleans {

    /** The header for booleans. */
    val Header: Byte = 0xC3.toByte

  }

  /**
   * Represents numerical values.
   *
   * @param value The underlying value.
   */
  case class Number(value: Double = 0.0) extends Value {

    /* Test for equality with this number value. */
    override protected[data] def calculateEquals(that: Any): Eval[scala.Boolean] = that match {
      case Number(v) if v == value => Eval.True
      case _ => Eval.False
    }

    /* Calculate the hash for this number value. */
    override protected def calculateHash(generator: Hash.Generator): Eval[Hash] =
      Eval.now(generator.hash(Number.Header, value))

    /* Calculate the string for this number value. */
    override protected[data] def calculateToString(): Eval[java.lang.String] = {
      val floor = value.floor
      if (floor == value) Eval.now(s"Number(${value.toLong})")
      else Eval.now(s"Number($value)")
    }

    /* Compare this value with another value. */
    override def compareTo(that: Value): Int = that match {
      case Boolean(_) => 1
      case Number(n) => if (n == value) 0 else if (n > value) -1 else 1
      case _ => -1
    }

  }

  /**
   * Declarations associated with numbers.
   */
  object Number
    extends binary_data.Numbers {

    /** The header for numbers. */
    val Header: Byte = 0xB4.toByte

  }

  /**
   * Represents string values.
   *
   * @param value The underlying value.
   */
  case class String(value: java.lang.String = "") extends Value {

    /* Test for equality with this string value. */
    override protected[data] def calculateEquals(that: Any): Eval[scala.Boolean] = that match {
      case String(v) if v == value => Eval.True
      case _ => Eval.False
    }

    /* Calculate the hash for this string value. */
    override protected def calculateHash(generator: Hash.Generator): Eval[Hash] =
      Eval.now(generator.hash(String.Header, value))

    /* Calculate the string for this string value. */
    override protected[data] def calculateToString(): Eval[java.lang.String] =
      Eval.now(s"String($value)")

    /* Compare this value with another value. */
    override def compareTo(that: Value): Int = that match {
      case String(s) => value.compareTo(s)
      case _ => 1
    }

  }

  /**
   * Declarations associated with strings.
   */
  object String
    extends binary_data.Strings {

    /** The header for strings. */
    val Header: Byte = 0xA5.toByte

  }

}

/**
 * Represents tables of fragments indexed by a value.
 *
 * @param entries The entries in the underlying table.
 */
case class Table(entries: SortedMap[Value, Fragment]) extends Fragment {

  /** The set of keys in this table. */
  lazy val keys: SortedSet[Value] = entries.keySet

  /** The set of values in this table. */
  lazy val values: Iterable[Fragment] = entries.values

  /**
   * Returns a fragment in this table.
   *
   * @param key The key to return the fragment for.
   * @return A fragment in this table.
   */
  def apply(key: Value): Fragment =
    entries(key)

  /**
   * Attempts to return a fragment in this table.
   *
   * @param key The key to return the fragment for.
   * @return A fragment if one exists in this table for the specified key.
   */
  def get(key: Value): Option[Fragment] =
    entries get key

  /* Test for equality with this table. */
  override protected[data] def calculateEquals(that: Any): Eval[Boolean] = that match {
    case Table(thatEntries) if thatEntries.size == entries.size =>
      (Eval.True /: entries.flatMap(e => Seq(e._1, e._2)).zip(thatEntries.flatMap(e => Seq(e._1, e._2)))) { (r, e) =>
        val (e1, e2) = e
        r flatMap { rr => if (rr) e1.calculateEquals(e2) else Eval.False }
      }
    case _ => Eval.False
  }

  /* Calculate the hash for this table. */
  override protected def calculateHash(generator: Hash.Generator): Eval[Hash] = for {
    ee <- (Eval.now(Vector[Hash]()) /: entries) { (r, e) =>
      for {
        rr <- r
        (k, v) = e
        kk <- k.evalHash(generator)
        vv <- v.evalHash(generator)
      } yield rr :+ kk :+ vv
    }
  } yield generator.hash(Table.Header, ee)

  /* Calculate the string for this table. */
  override protected[data] def calculateToString(): Eval[String] = {
    (Eval.now("") /: entries) { (r, e) =>
      for {
        rr <- r
        (k, v) = e
        kk <- k.calculateToString()
        vv <- v.calculateToString()
      } yield if (rr.isEmpty) s"$kk=$vv" else s"$rr,$kk=$vv"
    } map (c => s"Table($c)")
  }

}

/**
 * Factory for tables.
 */
object Table
  extends binary_data.Tables {

  /** The header for tables. */
  val Header: Byte = 0xD2.toByte

  /**
   * Creates a new table.
   *
   * @param entries The items to populate the table with.
   * @return A new table populated with the specified entries.
   */
  def apply(entries: (Value, Fragment)*): Table =
    Table(SortedMap(entries: _*))

}


text:
/* @flow */

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';

import Option from '../../../Option';
import Spinner from '../../../Spinner';
import styles from './styles.css'; // eslint-disable-line no-unused-vars

class LayoutComponent extends Component {

  static propTypes: Object = {
    expanded: PropTypes.bool,
    onExpandEvent: PropTypes.func,
    doCollapse: PropTypes.func,
    onChange: PropTypes.func,
    config: PropTypes.object,
    translations: PropTypes.object,
  };

  state: Object = {
    imgSrc: '',
    dragEnter: false,
    uploadHighlighted: this.props.config.uploadEnabled && !!this.props.config.uploadCallback,
    showImageLoading: false,
    height: this.props.config.defaultSize.height,
    width: this.props.config.defaultSize.width,
  };

  componentWillReceiveProps(props: Object): void {
    if (this.props.expanded && !props.expanded) {
      this.setState({
        imgSrc: '',
        dragEnter: false,
        uploadHighlighted: this.props.config.uploadEnabled && !!this.props.config.uploadCallback,
        showImageLoading: false,
        height: this.props.config.defaultSize.height,
        width: this.props.config.defaultSize.width,
      })
    } else if (props.config.uploadCallback !== this.props.config.uploadCallback ||
      props.config.uploadEnabled !== this.props.config.uploadEnabled) {
      this.setState({
        uploadHighlighted: props.config.uploadEnabled && !!props.config.uploadCallback,
      });
    }
  }

  updateValue: Function = (event: Object): void => {
    this.setState({
      [`${event.target.name}`]: event.target.value,
    });
  };

  toggleShowImageLoading: Function = (): void => {
    const showImageLoading = !this.state.showImageLoading;
    this.setState({
      showImageLoading,
    });
  };

  showImageURLOption: Function = (): void => {
    this.setState({
      uploadHighlighted: false,
    });
  };

  showImageUploadOption: Function = (): void => {
    this.setState({
      uploadHighlighted: true,
    });
  };

  addImageFromState: Function = (): void => {
    const { imgSrc, height, width } = this.state;
    const { onChange } = this.props;
    onChange(imgSrc, height, width);
  };

  addImageFromSrcLink: Function = (imgSrc: string): void => {
    const { height, width } = this.state;
    const { onChange } = this.props;
    onChange(imgSrc, height, width);
  };

  onImageDrop: Function = (event: Object): void => {
    event.preventDefault();
    event.stopPropagation();
    this.setState({
      dragEnter: false,
    });
    this.uploadImage(event.dataTransfer.files[0]);
  };

  onDragEnter: Function = (event: Object): void => {
    this.stopPropagation(event);
    this.setState({
      dragEnter: true,
    });
  };

  selectImage: Function = (event: Object): void => {
    if (event.target.files && event.target.files.length > 0) {
      this.uploadImage(event.target.files[0]);
    }
  };

  uploadImage: Function = (file: Object): void => {
    this.toggleShowImageLoading();
    const { uploadCallback } = this.props.config;
    uploadCallback(file)
      .then(({ data }) => {
        this.setState({
          showImageLoading: false,
          dragEnter: false,
        });
        this.addImageFromSrcLink(data.link);
      }).catch(() => {
        this.setState({
          showImageLoading: false,
          dragEnter: false,
        });
      });
  };

  fileUploadClick = (event) => {
    this.fileUpload = true;
    event.stopPropagation();
  }

  stopPropagation: Function = (event: Object): void => {
    if (!this.fileUpload) {
      event.preventDefault();
      event.stopPropagation();
    } else {
      this.fileUpload = false;
    }
  };

  renderAddImageModal(): Object {
    const { imgSrc, uploadHighlighted, showImageLoading, dragEnter, height, width } = this.state;
    const { config: { popupClassName, uploadCallback, uploadEnabled, urlEnabled }, doCollapse, translations } = this.props;
    return (

          {uploadEnabled && uploadCallback &&

              {translations['components.controls.image.fileUpload']}

            }
          { urlEnabled &&

              {translations['components.controls.image.byURL']}

            }

        {
          uploadHighlighted ?

                   {translations['components.controls.image.dropFileText']}

              <input
                type="file"
                id="file"
                accept="image/*"
                onChange={this.selectImage}
                className="rdw-image-modal-upload-option-input"
              />

 :

                <input
                  className="rdw-image-modal-url-input"
                  placeholder="Enter url"
                  name="imgSrc"
                  onChange={this.updateValue}
                  onBlur={this.updateValue}
                  value={imgSrc}
                />

        }

          ↕
          <input
            onChange={this.updateValue}
            onBlur={this.updateValue}
            value={height}
            name="height"
            className="rdw-embedded-modal-size-input"
            placeholder="Height"
          />
           ↔
          <input
            onChange={this.updateValue}
            onBlur={this.updateValue}
            value={width}
            name="width"
            className="rdw-embedded-modal-size-input"
            placeholder="Width"
          />

          <button
            className="rdw-image-modal-btn"
            onClick={this.addImageFromState}
            disabled={!imgSrc || !height || !width}
          >
            {translations['generic.add']}
          </button>
          <button
            className="rdw-image-modal-btn"
            onClick={doCollapse}
          >
            {translations['generic.cancel']}
          </button>

        {showImageLoading ?

            <Spinner />

 :
          undefined}

    );
  }

  render(): Object {
    const { config: { icon, className }, expanded, onExpandEvent } = this.props;
    return (

        <Option
          className={classNames(className)}
          value="unordered-list-item"
          onClick={onExpandEvent}
        >

        </Option>
        {expanded ? this.renderAddImageModal() : undefined}

    );
  }
}

export default LayoutComponent;


text:
"use strict"

var React  = require( 'react-native');

var SplashScreen = React.createClass({
	getInitialState: function() {
		return {
			intervalId: '',
			images: [],
			urls: [
				"images/android-icon-36x36.png",
				"images/android-icon-48x48.png",
				"images/android-icon-72x72.png",
				"images/android-icon-96x96.png",
				"images/android-icon-144x144.png",
				"images/android-icon-192x192.png"
			],
			currentIndex: 0,
			currentImage: 'images/android-icon-36x36.png'
		};
	},
	componentWillUnmount:function() {
		clearInterval(this.state.intervalId);
	},
	componentWillMount: function() {
		var self = this;
		var images = [];
		var intervalId = '';

		for (var i=0; i < this.state.urls.length; i++) {
			let image = new Image();
			image.src = this.state.urls[i]
			images.push(image);
		}

		intervalId = setInterval(function(){
			var index = self.state.currentIndex + 1;

			if (index === images.length) {
				index = 0;
			}
			self.setState({
				currentImage: images[index].src,
				currentIndex: index
			});
		}, 170);

		self.setState({
			intervalId: intervalId
		})
	},
	componentDidMount: function() {
		var self = this;

		setTimeout(function(){
  			self.history.pushState(null, 'subscriptions');
		}, 6000);
	},

	render: function() {
		return (

R3S

		);
	}
});

module.exports = SplashScreen;


text:
package rewrite

import (
	"fmt"
	"strings"

	"github.com/coredns/coredns/plugin"

	"github.com/miekg/dns"

	"golang.org/x/net/context"
)

// Result is the result of a rewrite
type Result int

const (
	// RewriteIgnored is returned when rewrite is not done on request.
	RewriteIgnored Result = iota
	// RewriteDone is returned when rewrite is done on request.
	RewriteDone
	// RewriteStatus is returned when rewrite is not needed and status code should be set
	// for the request.
	RewriteStatus
)

// These are defined processing mode.
const (
	// Processing should stop after completing this rule
	Stop = "stop"
	// Processing should continue to next rule
	Continue = "continue"
)

// Rewrite is plugin to rewrite requests internally before being handled.
type Rewrite struct {
	Next     plugin.Handler
	Rules    []Rule
	noRevert bool
}

// ServeDNS implements the plugin.Handler interface.
func (rw Rewrite) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {
	wr := NewResponseReverter(w, r)
	for _, rule := range rw.Rules {
		switch result := rule.Rewrite(w, r); result {
		case RewriteDone:
			respRule := rule.GetResponseRule()
			if respRule.Active == true {
				wr.ResponseRewrite = true
				wr.ResponseRules = append(wr.ResponseRules, respRule)
			}
			if rule.Mode() == Stop {
				if rw.noRevert {
					return plugin.NextOrFailure(rw.Name(), rw.Next, ctx, w, r)
				}
				return plugin.NextOrFailure(rw.Name(), rw.Next, ctx, wr, r)
			}
		case RewriteIgnored:
			break
		case RewriteStatus:
			// only valid for complex rules.
			// if cRule, ok := rule.(*ComplexRule); ok && cRule.Status != 0 {
			// return cRule.Status, nil
			// }
		}
	}
	return plugin.NextOrFailure(rw.Name(), rw.Next, ctx, w, r)
}

// Name implements the Handler interface.
func (rw Rewrite) Name() string { return "rewrite" }

// Rule describes a rewrite rule.
type Rule interface {
	// Rewrite rewrites the current request.
	Rewrite(dns.ResponseWriter, *dns.Msg) Result
	// Mode returns the processing mode stop or continue.
	Mode() string
	// GetResponseRule returns the rule to rewrite response with, if any.
	GetResponseRule() ResponseRule
}

func newRule(args ...string) (Rule, error) {
	if len(args) == 0 {
		return nil, fmt.Errorf("no rule type specified for rewrite")
	}

	arg0 := strings.ToLower(args[0])
	var ruleType string
	var expectNumArgs, startArg int
	mode := Stop
	switch arg0 {
	case Continue:
		mode = arg0
		ruleType = strings.ToLower(args[1])
		expectNumArgs = len(args) - 1
		startArg = 2
	case Stop:
		ruleType = strings.ToLower(args[1])
		expectNumArgs = len(args) - 1
		startArg = 2
	default:
		// for backward compatibility
		ruleType = arg0
		expectNumArgs = len(args)
		startArg = 1
	}

	if ruleType != "edns0" && ruleType != "name" && expectNumArgs != 3 {
		return nil, fmt.Errorf("%s rules must have exactly two arguments", ruleType)
	}
	switch ruleType {
	case "name":
		return newNameRule(mode, args[startArg:]...)
	case "class":
		return newClassRule(mode, args[startArg:]...)
	case "type":
		return newTypeRule(mode, args[startArg:]...)
	case "edns0":
		return newEdns0Rule(mode, args[startArg:]...)
	default:
		return nil, fmt.Errorf("invalid rule type %q", args[0])
	}
}


text:
require 'test_helper'

class UserAddsItemsToOrderTest < ActionDispatch::IntegrationTest
  def setup
    MenuItem.create(name: "Marinara Sauce", price: 0.99)
    cheese_pizza_image = File.open(Rails.root.join("test", "fixtures", "cheese_pizza.jpg"))
    MenuItem.create(name: "Cheese Pizza", price: 12.99, image: cheese_pizza_image)
    pepperoni_pizza_image = File.open(Rails.root.join("test", "fixtures", "pepperoni_pizza.jpg"))
    @pepperoni_pizza = MenuItem.create(name: "Pepperoni Pizza", price: 14.99, image: pepperoni_pizza_image)
    customer = Customer.create(name: "Julia Child", phone: "1234567890")
    @order = Order.create!(customer: customer, delivery_time: "02/02/2020 5:00PM", location: "66 Orange Grove Way")
    visit order_path(@order)
  end

  test "happy path adding an item to an order" do
    click_on "Add to Order"
    select "Pepperoni Pizza", from: "Menu Item"
    fill_in "Quantity", with: "12"
    click_on "Add Item to Order"
    assert page.has_css?(".notice", text: "Pepperoni Pizza has been added to the order")
    assert_equal order_path(@order), current_path
    within("table#order_items") do
      assert page.has_content?("12")
      assert page.has_content?("Pepperoni Pizza")
      assert page.has_content?("$179.88")
    end
  end

  test "sad path adding an item to an order" do
    click_on "Add to Order"
    select "", from: "Menu Item"
    fill_in "Quantity", with: "0"
    click_on "Add Item to Order"
    assert page.has_css?(".alert", text: "Item could not be added.")
    assert_equal "0", page.field_labeled("Quantity").value
    assert page.has_css?(".error.quantity", text: "must be 1 or more")
    assert_equal "", page.field_labeled("Menu Item").value
    assert page.has_css?(".error.menu_item_id", text: "can't be blank")
    # It's important to test that we can fix the form and resubmit it.
    # Breaking the form is a surprisingly common bug!
    select "Marinara Sauce", from: "Menu Item"
    fill_in "Quantity", with: "2"
    click_on "Add Item to Order"
    assert page.has_css?(".notice", text: "Marinara Sauce has been added to the order")
    assert_equal order_path(@order), current_path
    within("table#order_items") do
      assert page.has_content?("2")
      assert page.has_content?("Marinara Sauce")
      assert page.has_content?("$1.98")
    end
  end

  test "adding a duplicate item to an order" do
    @order.order_items.create(menu_item: @pepperoni_pizza, quantity: 3)
    click_on "Add to Order"
    select "Pepperoni Pizza", from: "Menu Item"
    fill_in "Quantity", with: "12"
    click_on "Add Item to Order"
    assert page.has_css?(".notice", text: "Pepperoni Pizza has been added to the order")
    assert_equal order_path(@order), current_path
    within("table#order_items") do
      assert page.has_content?("12")
      assert page.has_content?("$179.88")
      assert page.has_content?("3")
      assert page.has_content?("$44.97")
    end
  end
end


text:
'use strict';

var auth = require('./auth');
var _ = require('lodash');
var ChatInterface = require('./chatInterface');
var LobbyInterface = require('./lobbyInterface');
var GameInterface = require('./game/gameInterface');
var canJoinRoom = require('./canJoinRoom');

module.exports = {

    /**
     * Ask new sockets to authorize
     */
    listenForConnections: function(io) {
        io.sockets.on('connection', function (socket) {
            init(socket);
        });
    }
};

var init = function(socket) {

    /**
     * Standard way to return errors to the client
     * @param message
     */
    socket.emitError = function(message) {
        socket.emit('error', message);
    };

    /**
     * Standard way to show a message to the client
     * @param message
     */
    socket.emitNotif = function(message) {
        socket.emit('notif', message);
    };

    /**
     * verify the owner of this connection
     */
    auth.authorizeSocket(socket, onAuthorized);
};

/**
 * Set up a socket's interface after it has authorized
 * @param err
 * @param socket
 * @param user
 * @returns {*}
 */
var onAuthorized = function(err, socket, user) {
    if(err) {
        return socket.emit('authFail', err);
    }

    /**
     * Store values for later
     */
    socket.set('account', _.pick(user, '_id', 'name', 'site', 'group', 'guild', 'silencedUntil'));

    /**
     * Subscribe and unsubscribe to rooms
     */
    socket.on('subscribe', function(roomName) {
        socket.get('account', function(err, account) {
            if(canJoinRoom(account, roomName)) {
                socket.join(roomName);
            }
        });
    });

    socket.on('unsubscribe', function(roomName) {
        socket.leave(roomName);
    });

    /**
     * Route an event to an account
     * @param eventName
     * @param callback
     */
    socket.onAccount = function(eventName, callback) {
        socket.on(eventName, function(data) {

            // get the account
            socket.get('account', function(err, account) {
                if(err) {
                    return socket.emitError(err);
                }
                if(!account) {
                    return socket.emitError('No account is registered to this connection.');
                }

                // check bans
                account.silenced = new Date(account.silencedUntil) > new Date();
                account.banned = new Date(account.bannedUntil) > new Date();

                if(account.banned) {
                    return socket.emitError('This account has been banned');
                }

                //everything worked
                callback(data, account);
            });
        });
    };

    /**
     * Interface with different systems
     */
    LobbyInterface.initSocket(socket);
    ChatInterface.initSocket(socket);
    GameInterface.initSocket(socket);

    /**
     * let the client know that the server is ready to roll
     */
    socket.emit('ready');
};