text:
author: jericson
comments: true
date: 2014-12-15 00:00:16+00:00
layout: post
redirect_from: /2014/12/winter-bash-2014
hero:
slug: winter-bash-2014
title: Winter Bash 2014
wordpress_id: 14896
tags:
- company
- announcement
- community
- stackexchange
---

> There is no better antidote, at least for the worst hours and eclipses of the soul, than to conjure up...serious frivolity.
> - [Friedrich Nietzsche](https://books.google.com/books?id=Nl-vaAdJD3MC&pg=PA61&lpg=PA61#v=onepage&q&f=false)

[![Winter Bash 2014](https://i.stack.imgur.com/urxgC.png)](http://winterbash2014.stackexchange.com)

## What's Winter Bash again?

No, it's not a new flavor of [Unix shell](http://en.wikipedia.org/wiki/Bash_(Unix_shell)). Rather, Winter Bash is an [ancient tradition](http://stackexchange.com/promos/2/hat-dash) of Stack Exchange. (2011 is ancient according to Internet time.) Here's how it works:

  1. Starting right now, when you complete one of [30-odd challenges](http://winterbash2014.stackexchange.com/) while logged on a [participating site](http://winterbash2014.stackexchange.com/leaderboard), you will be awarded the associated hat. To notify you, an icon will light up on the top bar. In addition, admire your hat collection on the [Winter Bash 2014 site](http://winterbash2014.stackexchange.com/). Finally, your profile includes the number of unique snowflakes **hats** (![You have a hat to wear!](https://i.stack.imgur.com/VmGTG.png)) you've earned all around the network.

  2. Once you acquire an item, click your avatar to pick a hat that you earned--not just on the current site, but anywhere. When you are satisfied the hat's position, click "Wear hat" and it will be visible everywhere your avatar is displayed. Optionally, you may have a different look on each site. Once you are wearing a hat, you'll also see an option to go unadorned. (But really, why would you want that?)

[![I'm a pirate!](https://i.stack.imgur.com/8FDy0.png)](http://meta.stackexchange.com/users/1438/jon-ericson)

  3. On January 4, 2015 at 23:59:59 UTC, all hats will be returned to the Stack Exchange vault. The best way to preserve holiday memories is to [take plenty of pictures](http://www.take-a-screenshot.org/) before they are gone.

## Again with the hats? What happened to "We hate fun"?

In the face of the darkening days of winter, we put aside our [steely, businesslike frowns](http://blog.stackoverflow.com/2010/01/stack-overflow-where-we-hate-fun/) to wear [virtual cosmetic items](https://wiki.teamfortress.com/wiki/Cosmetic_items). It's our solemn duty to cut out the nonsense leaving pure, unadulterated knowledge as permanent artifacts helpful to future visitors. And that task is no laughing matter.

Yet, to quote [G. K. Chesterton](http://www.ccel.org/ccel/chesterton/heretics.xvi.html):

About what other subjects can one make jokes except serious subjects?

The truth is, we don't really hate fun. Contributing to a volunteer effort should be an enjoyable experience. Heck, [fake internet points](http://blog.stackoverflow.com/2013/09/five-years-ago-stack-overflow-launched-then-a-miracle-occurred/) are integral to how these sites operate. Winter Bash reminds us that there's more to life than nose-to-the-grindstone work and quality content. We don't stop having fun when the event ends. We go back to having fun with a larger purpose.

## Is everything going to be the same as last year?

Management gave us a clear mandate when it came to building new features into Winter Bash:

We were not allowed to spend weeks on snow animation.

Thankfully, we could reuse last year's start-of-the-art snowfall algorithm for the [official Winter Bash 2014 homepage](http://winterbash2014.stackexchange.com/). There you can discover a nearly* complete list of hats and how you can earn them. The activities this year are mostly fresh and (hopefully) all fun. If you could go ahead and answer 5 questions on Saturday, that'd be great. Mmmkay?

Once again, we are delighted with the work of freelance illustrator, [Elias Stein](http://www.eliasstein.com/). It's difficult to express how satisfying it feels to think up a concept (Tam o' Shanter!) and have it manifest a few days later:

[![Tam o' Shanter](https://i.stack.imgur.com/hdKRn.png)](http://en.wikipedia.org/wiki/Tam_o%27_Shanter_%28cap%29)

In the past, some people have had trouble getting hats to fit properly. [Last year](http://blog.stackoverflow.com/2013/12/winter-bash-2013-is-here/), we added the ability to reposition hats, but that did little to satisfy folks with especially large or disembodied heads. So, this year [hats can be resized and twisted to fit your head](http://meta.stackexchange.com/questions/212056/all-i-want-is-a-well-fitted-hat). (Thanks, [balpha](http://balpha.de/about/)!)

[![Shog The Hunter](https://i.stack.imgur.com/9lMdh.png)](http://meta.stackexchange.com/users/811/shog9)

If you have any questions about the event, try the [Frequently Asked Questions.](http://winterbash2014.stackexchange.com/faq) If your question isn't covered there, please ask it on [Meta Stack Exchange](http://meta.stackexchange.com/questions/tagged/winterbash-2014), our Q&A; site about our network of Q&A; sites.

Before signing off, I apologize to our [Southern Hemisphere friends](http://meta.pt.stackoverflow.com/questions/2288/o-que-voc%C3%AAs-t%C3%AAm-na-cabe%C3%A7a) for the name. I wanted to go with something season-neutral like HAT ATTACK or December Fling, but tradition ruled the day. Just remember: while you are sipping refreshing drinks and enjoying the sunshine, it's [cold](https://www.youtube.com/watch?v=tuCO7Kq744U),  wet, and dark up here.

**Act now and get [an exclusive hat only available today](http://winterbash2014.stackexchange.com/saint-lucia)!**

* * *

\* [![status-bydesign](https://i.stack.imgur.com/BRAuT.png)](http://meta.stackexchange.com/questions/212799/how-do-i-get-the-winterbash-2013-secret-hats)


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('collector', '0004_auto_20150604_1916'),
    ]

    operations = [
        migrations.AlterField(
            model_name='page',
            name='source_hash',
            field=models.IntegerField(default=0, db_index=True),
        ),
        migrations.AlterField(
            model_name='stylesheet',
            name='source_hash',
            field=models.IntegerField(default=0, db_index=True),
        ),
    ]

redpajama_set_name: RedPajamaGithub


text:
import os
import subprocess
from uranium import task_requires

def main(build):
    build.packages.install(".", develop=True)

@task_requires("main")
def test(build):
    build.packages.install("pytest-cov")
    pytest = os.path.join(build.root, "bin", "py.test")
    subprocess.call([
        pytest, "--cov", "swagger_schema",
        "swagger_schema",
        "--cov-report", "term-missing"
    ] + build.options.args)

def publish(build):
    """ publish the uranium package """
    build.packages.install("wheel")
    build.executables.run([
        "python", "setup.py",
        "sdist", "bdist_wheel", "--universal", "upload", "--release"
    ])


text:
all: dist/innosetup/vagrant-spk-setup.exe

WINE := wine
WINEARGS := WINEDEBUG=-all WINEPREFIX=$$PWD/state/wineprefix

clean:
	rm -f dist/innosetup/vagrant-spk-setup.exe

distclean:
	rm -rf state build vendor dist ../build ../dist vagrant-spk.spec

wine: /usr/bin/wine
	sudo apt-get install wine:i386

vendor:
	mkdir -p vendor

state:
	mkdir -p state

vendor/python.msi: | vendor state/wineprefix
	wget https://www.python.org/ftp/python/2.7.10/python-2.7.10.msi -O vendor/python.msi
	touch vendor/python.msi

vendor/python.msi.installed: | vendor/python.msi
	cp vendor/python.msi vendor/python-tmp.msi
	$(WINEARGS) $(WINE) msiexec /i vendor/python-tmp.msi /qn
	touch vendor/python.msi.installed

state/wineprefix/drive_c/Python27/Scripts/pyinstaller.exe: | vendor/python.msi.installed vendor/pywin32.exe.installed
	$(WINEARGS) $(WINE) 'c:/python27/python.exe' -m pip install pyinstaller==3.1.1

vendor/pywin32.exe: | vendor
	wget http://iweb.dl.sourceforge.net/project/pywin32/pywin32/Build%20219/pywin32-219.win32-py2.7.exe -O vendor/pywin32.exe

vendor/pywin32.exe.installed: | vendor/pywin32.exe
	unzip vendor/pywin32.exe || true
	mv PLATLIB/* SCRIPTS/* state/wineprefix/drive_c/Python27/Lib/site-packages/
	rmdir PLATLIB SCRIPTS
	$(WINEARGS) $(WINE) 'c:/python27/python.exe' state/wineprefix/drive_c/Python27/Lib/site-packages/pywin32_postinstall.py -install
	touch vendor/pywin32.exe.installed

dist/vagrant-spk.exe: ../vagrant-spk | state/wineprefix/drive_c/Python27/Scripts/pyinstaller.exe
	$(WINEARGS) $(WINE) c:/python27/Scripts/pyinstaller -F ../vagrant-spk

vendor/innosetup.exe: | vendor
	wget 'http://www.jrsoftware.org/download.php/is.exe?site=1' -O vendor/innosetup.exe

vendor/innosetup.exe.installed: | state/wineprefix vendor/innosetup.exe
	$(WINEARGS) $(WINE) vendor/innosetup.exe /VERYSILENT
	touch vendor/innosetup.exe.installed

dist/innosetup/vagrant-spk-setup.exe: dist/vagrant-spk.exe | vendor/innosetup.exe.installed vendor/msysgit.7z vendor/msysgit/bin
	# Some WINE installs are seemingly 64-bit but install InnoSetup to Program Files, not
	# Program Files (x86). We work around this with a symlink.
	if [ ! -d 'state/wineprefix/drive_c/Program Files (x86)' ] ; then ln -s 'Program Files' 'state/wineprefix/drive_c/Program Files (x86)' ; fi
	$(WINEARGS) $(WINE) 'c:/program files (x86)/inno setup 5/iscc.exe' windows-installer.iss

vendor/msysgit.7z:
	wget https://github.com/msysgit/msysgit/releases/download/Git-1.9.5-preview20150319/PortableGit-1.9.5-preview20150319.7z -O vendor/msysgit.7z

vendor/msysgit/bin:
	mkdir -p vendor/msysgit
	(cd vendor/msysgit ; 7z e -aoa ../msysgit.7z)

state/regdata: | state
	printf '[HKEY_CURRENT_USER\\Software\\Wine\\WineDbg]\n"ShowCrashDialog"=dword:00000000\n' > state/regdata

state/wineprefix: state/regdata
	mkdir -p state/wineprefix
	$(WINEARGS) $(WINE) wineboot
	$(WINEARGS) $(WINE) regedit state/regdata
	touch state/wineprefix


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

package org.curioswitch.common.testing.assertj.proto;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.curioswitch.common.testing.assertj.proto.ProtoAssert.assertThat;

import com.google.common.collect.ImmutableMap;
import com.google.protobuf.ByteString;
import com.google.protobuf.Descriptors.FieldDescriptor;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.Message;
import com.google.protobuf.UnknownFieldSet;
import com.google.protobuf.UnknownFieldSet.Field;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

/** Unit tests for {@link FieldScope}, and their interaction with {@link ProtoAssert}. */
@RunWith(Parameterized.class)
public class FieldScopesTest extends ProtoAssertTestBase {

  @Parameters(name = "{0}")
  public static Collection<Object[]> parameters() {
    return ProtoAssertTestBase.parameters();
  }

  // Set up for the ignoringTopLevelField tests.
  // ignoringFieldMessage and ignoringFieldDiffMessage are simple messages with two fields set. They
  // are the same for the "good" field, and different for the "bad" field. The *FieldNumber and
  // *FieldDescriptor members point to these fields.

  private final Message ignoringFieldMessage;
  private final Message ignoringFieldDiffMessage;
  private final int goodFieldNumber;
  private final int badFieldNumber;
  private final FieldDescriptor goodFieldDescriptor;
  private final FieldDescriptor badFieldDescriptor;

  public FieldScopesTest(TestType testType) {
    super(testType);

    ignoringFieldMessage = parse("o_int: 3 r_string: \"foo\"");
    ignoringFieldDiffMessage = parse("o_int: 3 r_string: \"bar\"");
    goodFieldNumber = getFieldNumber("o_int");
    badFieldNumber = getFieldNumber("r_string");
    goodFieldDescriptor = getFieldDescriptor("o_int");
    badFieldDescriptor = getFieldDescriptor("r_string");
  }

  @Test
  public void testUnequalMessages() {
    Message message = parse("o_int: 3 r_string: \"foo\"");
    Message diffMessage = parse("o_int: 5 r_string: \"bar\"");

    assertThat(diffMessage).isNotEqualTo(message);
  }

  @Test
  public void testFieldScopes_all() {
    Message message = parse("o_int: 3 r_string: \"foo\"");
    Message diffMessage = parse("o_int: 5 r_string: \"bar\"");

    assertThat(diffMessage).withPartialScope(FieldScopes.all()).isNotEqualTo(message);
    assertThat(diffMessage).ignoringFieldScope(FieldScopes.all()).isEqualTo(message);

    assertThatThrownBy(
            () ->
                assertThat(diffMessage).ignoringFieldScope(FieldScopes.all()).isNotEqualTo(message))
        .isInstanceOf(AssertionError.class)
        .satisfies(isNotEqualToFailureMessage())
        .hasMessageContaining("ignored: o_int")
        .hasMessageContaining("ignored: r_string");
  }

  @Test
  public void testFieldScopes_none() {
    Message message = parse("o_int: 3 r_string: \"foo\"");
    Message diffMessage = parse("o_int: 5 r_string: \"bar\"");

    assertThat(diffMessage).ignoringFieldScope(FieldScopes.none()).isNotEqualTo(message);
    assertThat(diffMessage).withPartialScope(FieldScopes.none()).isEqualTo(message);

    assertThatThrownBy(
            () ->
                assertThat(diffMessage).withPartialScope(FieldScopes.none()).isNotEqualTo(message))
        .isInstanceOf(AssertionError.class)
        .satisfies(isNotEqualToFailureMessage())
        .hasMessageContaining("ignored: o_int")
        .hasMessageContaining("ignored: r_string");
  }

  @Test
  public void testIgnoringTopLevelField_ignoringField() {
    assertThat(ignoringFieldDiffMessage)
        .ignoringFields(goodFieldNumber)
        .isNotEqualTo(ignoringFieldMessage);
    assertThat(ignoringFieldDiffMessage)
        .ignoringFields(badFieldNumber)
        .isEqualTo(ignoringFieldMessage);

    assertThatThrownBy(
            () ->
                assertThat(ignoringFieldDiffMessage)
                    .ignoringFields(goodFieldNumber)
                    .isEqualTo(ignoringFieldMessage))
        .isInstanceOf(AssertionError.class)
        .satisfies(isEqualToFailureMessage())
        .hasMessageContaining("modified: r_string[0]: \"foo\" -> \"bar\"");

    assertThatThrownBy(
            () ->
                assertThat(ignoringFieldDiffMessage)
                    .ignoringFields(badFieldNumber)
                    .isNotEqualTo(ignoringFieldMessage))
        .isInstanceOf(AssertionError.class)
        .satisfies(isNotEqualToFailureMessage())
        .hasMessageContaining("ignored: r_string");
  }

  @Test
  public void testIgnoringTopLevelField_fieldScopes_ignoringFields() {
    assertThat(ignoringFieldDiffMessage)
        .withPartialScope(FieldScopes.ignoringFields(goodFieldNumber))
        .isNotEqualTo(ignoringFieldMessage);
    assertThat(ignoringFieldDiffMessage)
        .ignoringFieldScope(FieldScopes.ignoringFields(goodFieldNumber))
        .isEqualTo(ignoringFieldMessage);
    assertThat(ignoringFieldDiffMessage)
        .withPartialScope(FieldScopes.ignoringFields(badFieldNumber))
        .isEqualTo(ignoringFieldMessage);
    assertThat(ignoringFieldDiffMessage)
        .ignoringFieldScope(FieldScopes.ignoringFields(badFieldNumber))
        .isNotEqualTo(ignoringFieldMessage);
  }

  @Test
  public void testIgnoringTopLevelField_fieldScopes_allowingFields() {
    assertThat(ignoringFieldDiffMessage)
        .withPartialScope(FieldScopes.allowingFields(goodFieldNumber))
        .isEqualTo(ignoringFieldMessage);
    assertThat(ignoringFieldDiffMessage)
        .ignoringFieldScope(FieldScopes.allowingFields(goodFieldNumber))
        .isNotEqualTo(ignoringFieldMessage);
    assertThat(ignoringFieldDiffMessage)
        .withPartialScope(FieldScopes.allowingFields(badFieldNumber))
        .isNotEqualTo(ignoringFieldMessage);
    assertThat(ignoringFieldDiffMessage)
        .ignoringFieldScope(FieldScopes.allowingFields(badFieldNumber))
        .isEqualTo(ignoringFieldMessage);
  }

  @Test
  public void testIgnoringTopLevelField_fieldScopes_allowingFieldDescriptors() {
    assertThat(ignoringFieldDiffMessage)
        .withPartialScope(FieldScopes.allowingFieldDescriptors(goodFieldDescriptor))
        .isEqualTo(ignoringFieldMessage);
    assertThat(ignoringFieldDiffMessage)
        .ignoringFieldScope(FieldScopes.allowingFieldDescriptors(goodFieldDescriptor))
        .isNotEqualTo(ignoringFieldMessage);
    assertThat(ignoringFieldDiffMessage)
        .withPartialScope(FieldScopes.allowingFieldDescriptors(badFieldDescriptor))
        .isNotEqualTo(ignoringFieldMessage);
    assertThat(ignoringFieldDiffMessage)
        .ignoringFieldScope(FieldScopes.allowingFieldDescriptors(badFieldDescriptor))
        .isEqualTo(ignoringFieldMessage);
  }

  @Test
  public void testIgnoringTopLevelField_fieldScopes_ignoringFieldDescriptors() {
    assertThat(ignoringFieldDiffMessage)
        .withPartialScope(FieldScopes.ignoringFieldDescriptors(goodFieldDescriptor))
        .isNotEqualTo(ignoringFieldMessage);
    assertThat(ignoringFieldDiffMessage)
        .ignoringFieldScope(FieldScopes.ignoringFieldDescriptors(goodFieldDescriptor))
        .isEqualTo(ignoringFieldMessage);
    assertThat(ignoringFieldDiffMessage)
        .withPartialScope(FieldScopes.ignoringFieldDescriptors(badFieldDescriptor))
        .isEqualTo(ignoringFieldMessage);
    assertThat(ignoringFieldDiffMessage)
        .ignoringFieldScope(FieldScopes.ignoringFieldDescriptors(badFieldDescriptor))
        .isNotEqualTo(ignoringFieldMessage);
  }

  @Test
  public void testEmptySubMessage() {
    Message message = parse("o_int: 1 o_sub_test_message: { }");
    Message eqMessage = parse("o_int: 2 o_sub_test_message: { }");
    Message diffMessage = parse("o_int: 3");

    // Different logic gets exercised when we add an 'ignore' clause.
    // Let's ensure o_sub_test_message is compared properly in all cases.
    int fieldNumber = getFieldNumber("o_int");

    assertThat(eqMessage).isNotEqualTo(message);
    assertThat(eqMessage).ignoringFieldAbsence().isNotEqualTo(message);
    assertThat(eqMessage).ignoringFields(fieldNumber).isEqualTo(message);
    assertThat(eqMessage).ignoringFields(fieldNumber).ignoringFieldAbsence().isEqualTo(message);

    assertThat(diffMessage).isNotEqualTo(message);
    assertThat(diffMessage).ignoringFieldAbsence().isNotEqualTo(message);
    assertThat(diffMessage).ignoringFields(fieldNumber).isNotEqualTo(message);
    assertThat(diffMessage).ignoringFields(fieldNumber).ignoringFieldAbsence().isEqualTo(message);
  }

  @Test
  public void testIgnoreSubMessageField() {
    Message message = parse("o_int: 1 o_sub_test_message: { o_int: 2 }");
    Message diffMessage = parse("o_int: 2 o_sub_test_message: { o_int: 2 }");
    Message eqMessage1 = parse("o_int: 1");
    Message eqMessage2 = parse("o_int: 1 o_sub_test_message: {}");
    Message eqMessage3 = parse("o_int: 1 o_sub_test_message: { o_int: 3 r_string: \"x\" }");
    int fieldNumber = getFieldNumber("o_sub_test_message");

    assertThat(diffMessage).ignoringFields(fieldNumber).isNotEqualTo(message);
    assertThat(eqMessage1).ignoringFields(fieldNumber).isEqualTo(message);
    assertThat(eqMessage2).ignoringFields(fieldNumber).isEqualTo(message);
    assertThat(eqMessage3).ignoringFields(fieldNumber).isEqualTo(message);

    assertThatThrownBy(() -> assertThat(diffMessage).ignoringFields(fieldNumber).isEqualTo(message))
        .isInstanceOf(AssertionError.class)
        .satisfies(isEqualToFailureMessage())
        .hasMessageContaining("modified: o_int: 1 -> 2");

    assertThatThrownBy(
            () -> assertThat(eqMessage3).ignoringFields(fieldNumber).isNotEqualTo(message))
        .isInstanceOf(AssertionError.class)
        .satisfies(isNotEqualToFailureMessage())
        .hasMessageContaining("ignored: o_sub_test_message");
  }

  @Test
  public void testIgnoreFieldOfSubMessage() {
    // Ignore o_int of sub message fields.
    Message message = parse("o_int: 1 o_sub_test_message: { o_int: 2 r_string: \"foo\" }");
    Message diffMessage1 = parse("o_int: 2 o_sub_test_message: { o_int: 2 r_string: \"foo\" }");
    Message diffMessage2 = parse("o_int: 1 o_sub_test_message: { o_int: 2 r_string: \"bar\" }");
    Message eqMessage = parse("o_int: 1 o_sub_test_message: { o_int: 3 r_string: \"foo\" }");

    FieldDescriptor fieldDescriptor =
        getFieldDescriptor("o_sub_test_message").getMessageType().findFieldByName("o_int");
    FieldScope partialScope = FieldScopes.ignoringFieldDescriptors(fieldDescriptor);

    assertThat(diffMessage1).withPartialScope(partialScope).isNotEqualTo(message);
    assertThat(diffMessage2).withPartialScope(partialScope).isNotEqualTo(message);
    assertThat(eqMessage).withPartialScope(partialScope).isEqualTo(message);

    assertThatThrownBy(
            () -> assertThat(diffMessage1).withPartialScope(partialScope).isEqualTo(message))
        .isInstanceOf(AssertionError.class)
        .satisfies(isEqualToFailureMessage())
        .hasMessageContaining("modified: o_int: 1 -> 2");

    assertThatThrownBy(
            () -> assertThat(diffMessage2).withPartialScope(partialScope).isEqualTo(message))
        .isInstanceOf(AssertionError.class)
        .satisfies(isEqualToFailureMessage())
        .hasMessageContaining("modified: o_sub_test_message.r_string[0]: \"foo\" -> \"bar\"");
  }

  @Test
  public void testIgnoringAllButOneFieldOfSubMessage() {
    // Consider all of TestMessage, but none of o_sub_test_message, except
    // o_sub_test_message.o_int.
    Message message =
        parse(
            "o_int: 3 o_sub_test_message: { o_int: 4 r_string: \"foo\" } "
                + "r_sub_test_message: { o_int: 5 r_string: \"bar\" }");

    // All of these differ in a critical field.
    Message diffMessage1 =
        parse(
            "o_int: 999999 o_sub_test_message: { o_int: 4 r_string: \"foo\" } "
                + "r_sub_test_message: { o_int: 5 r_string: \"bar\" }");
    Message diffMessage2 =
        parse(
            "o_int: 3 o_sub_test_message: { o_int: 999999 r_string: \"foo\" } "
                + "r_sub_test_message: { o_int: 5 r_string: \"bar\" }");
    Message diffMessage3 =
        parse(
            "o_int: 3 o_sub_test_message: { o_int: 4 r_string: \"foo\" } "
                + "r_sub_test_message: { o_int: 999999 r_string: \"bar\" }");
    Message diffMessage4 =
        parse(
            "o_int: 3 o_sub_test_message: { o_int: 4 r_string: \"foo\" } "
                + "r_sub_test_message: { o_int: 5 r_string: \"999999\" }");

    // This one only differs in o_sub_test_message.r_string, which is ignored.
    Message eqMessage =
        parse(
            "o_int: 3 o_sub_test_message: { o_int: 4 r_string: \"999999\" } "
                + "r_sub_test_message: { o_int: 5 r_string: \"bar\" }");

    FieldScope fieldScope =
        FieldScopes.ignoringFields(getFieldNumber("o_sub_test_message"))
            .allowingFieldDescriptors(
                getFieldDescriptor("o_sub_test_message").getMessageType().findFieldByName("o_int"));

    assertThat(diffMessage1).withPartialScope(fieldScope).isNotEqualTo(message);
    assertThat(diffMessage2).withPartialScope(fieldScope).isNotEqualTo(message);
    assertThat(diffMessage3).withPartialScope(fieldScope).isNotEqualTo(message);
    assertThat(diffMessage4).withPartialScope(fieldScope).isNotEqualTo(message);
    assertThat(eqMessage).withPartialScope(fieldScope).isEqualTo(message);

    assertThatThrownBy(
            () -> assertThat(diffMessage4).withPartialScope(fieldScope).isEqualTo(message))
        .isInstanceOf(AssertionError.class)
        .satisfies(isEqualToFailureMessage())
        .hasMessageContaining("modified: r_sub_test_message[0].r_string[0]: \"bar\" -> \"999999\"");

    assertThatThrownBy(
            () -> assertThat(eqMessage).withPartialScope(fieldScope).isNotEqualTo(message))
        .isInstanceOf(AssertionError.class)
        .satisfies(isNotEqualToFailureMessage())
        .hasMessageContaining("ignored: o_sub_test_message.r_string");
  }

  @Test
  public void testFromSetFields() {
    Message scopeMessage =
        parse(
            "o_int: 1 r_string: \"x\" o_test_message: { o_int: 1 } "
                + "r_test_message: { r_string: \"x\" } r_test_message: { o_int: 1 } "
                + "o_sub_test_message: { o_test_message: { o_int: 1 } }");

    // 1 = compared, [2, 3] = ignored, 4 = compared and fails
    Message message =
        parse(
            "o_int: 1 r_string: \"1\" o_test_message: {o_int: 1 r_string: \"2\" } "
                + "r_test_message: { o_int: 1 r_string: \"1\" } "
                + "r_test_message: { o_int: 1 r_string: \"1\" } "
                + "o_sub_test_message: { o_int: 2 o_test_message: { o_int: 1 r_string: \"2\" } }");
    Message diffMessage =
        parse(
            "o_int: 4 r_string: \"4\" o_test_message: {o_int: 4 r_string: \"3\" } "
                + "r_test_message: { o_int: 4 r_string: \"4\" } "
                + "r_test_message: { o_int: 4 r_string: \"4\" }"
                + "o_sub_test_message: { r_string: \"3\" o_int: 3 "
                + "o_test_message: { o_int: 4 r_string: \"3\" } }");
    Message eqMessage =
        parse(
            "o_int: 1 r_string: \"1\" o_test_message: {o_int: 1 r_string: \"3\" } "
                + "r_test_message: { o_int: 1 r_string: \"1\" } "
                + "r_test_message: { o_int: 1 r_string: \"1\" }"
                + "o_sub_test_message: { o_int: 3 o_test_message: { o_int: 1 r_string: \"3\" } }");

    assertThat(diffMessage).isNotEqualTo(message);
    assertThat(eqMessage).isNotEqualTo(message);

    assertThat(diffMessage)
        .withPartialScope(FieldScopes.fromSetFields(scopeMessage))
        .isNotEqualTo(message);
    assertThat(eqMessage)
        .withPartialScope(FieldScopes.fromSetFields(scopeMessage))
        .isEqualTo(message);

    assertThatThrownBy(() -> assertThat(diffMessage).isEqualTo(message))
        .isInstanceOf(AssertionError.class)
        .satisfies(isEqualToFailureMessage())
        .hasMessageContaining("1 -> 4")
        .hasMessageContaining("\"1\" -> \"4\"")
        .hasMessageContaining("2 -> 3")
        .hasMessageContaining("\"2\" -> \"3\"");

    assertThatThrownBy(
            () ->
                assertThat(diffMessage)
                    .withPartialScope(FieldScopes.fromSetFields(scopeMessage))
                    .isEqualTo(message))
        .isInstanceOf(AssertionError.class)
        .satisfies(isEqualToFailureMessage())
        .hasMessageContaining("1 -> 4")
        .hasMessageContaining("\"1\" -> \"4\"")
        .satisfies(
            e ->
                assertThat(e.getMessage())
                    .doesNotContain("2 -> 3")
                    .doesNotContain("\"2\" -> \"3\""));

    assertThatThrownBy(
            () ->
                assertThat(eqMessage)
                    .withPartialScope(FieldScopes.fromSetFields(scopeMessage))
                    .isNotEqualTo(message))
        .isInstanceOf(AssertionError.class)
        .satisfies(isNotEqualToFailureMessage())
        .hasMessageContaining("ignored: o_test_message.r_string")
        .hasMessageContaining("ignored: o_sub_test_message.o_int")
        .hasMessageContaining("ignored: o_sub_test_message.o_test_message.r_string");
  }

  @Ignore // Ignored upstream.
  public void testFromSetFields_unknownFields() throws InvalidProtocolBufferException {
    if (isProto3()) {
      // No unknown fields in Proto 3.
      return;
    }

    // Make sure that merging of repeated fields, separation by tag number, and separation by
    // unknown field type all work.
    Message scopeMessage =
        fromUnknownFields(
            UnknownFieldSet.newBuilder()
                .addField(20, Field.newBuilder().addFixed32(1).addFixed64(1).build())
                .addField(
                    21,
                    Field.newBuilder()
                        .addVarint(1)
                        .addLengthDelimited(ByteString.copyFrom("1", StandardCharsets.UTF_8))
                        .addGroup(
                            UnknownFieldSet.newBuilder()
                                .addField(1, Field.newBuilder().addFixed32(1).build())
                                .build())
                        .addGroup(
                            UnknownFieldSet.newBuilder()
                                .addField(2, Field.newBuilder().addFixed64(1).build())
                                .build())
                        .build())
                .build());

    // 1 = compared, [2, 3] = ignored, 4 = compared and fails
    Message message =
        fromUnknownFields(
            UnknownFieldSet.newBuilder()
                .addField(19, Field.newBuilder().addFixed32(2).addFixed64(2).build())
                .addField(
                    20,
                    Field.newBuilder()
                        .addFixed32(1)
                        .addFixed64(1)
                        .addVarint(2)
                        .addLengthDelimited(ByteString.copyFrom("2", StandardCharsets.UTF_8))
                        .addGroup(
                            UnknownFieldSet.newBuilder()
                                .addField(1, Field.newBuilder().addFixed32(2).build())
                                .build())
                        .build())
                .addField(
                    21,
                    Field.newBuilder()
                        .addFixed32(2)
                        .addFixed64(2)
                        .addVarint(1)
                        .addLengthDelimited(ByteString.copyFrom("1", StandardCharsets.UTF_8))
                        .addGroup(
                            UnknownFieldSet.newBuilder()
                                .addField(1, Field.newBuilder().addFixed32(1).addFixed64(2).build())
                                .addField(2, Field.newBuilder().addFixed32(2).addFixed64(1).build())
                                .addField(3, Field.newBuilder().addFixed32(2).build())
                                .build())
                        .build())
                .build());
    Message diffMessage =
        fromUnknownFields(
            UnknownFieldSet.newBuilder()
                .addField(19, Field.newBuilder().addFixed32(3).addFixed64(3).build())
                .addField(
                    20,
                    Field.newBuilder()
                        .addFixed32(4)
                        .addFixed64(4)
                        .addVarint(3)
                        .addLengthDelimited(ByteString.copyFrom("3", StandardCharsets.UTF_8))
                        .addGroup(
                            UnknownFieldSet.newBuilder()
                                .addField(1, Field.newBuilder().addFixed32(3).build())
                                .build())
                        .build())
                .addField(
                    21,
                    Field.newBuilder()
                        .addFixed32(3)
                        .addFixed64(3)
                        .addVarint(4)
                        .addLengthDelimited(ByteString.copyFrom("4", StandardCharsets.UTF_8))
                        .addGroup(
                            UnknownFieldSet.newBuilder()
                                .addField(1, Field.newBuilder().addFixed32(4).addFixed64(3).build())
                                .addField(2, Field.newBuilder().addFixed32(3).addFixed64(4).build())
                                .addField(3, Field.newBuilder().addFixed32(3).build())
                                .build())
                        .build())
                .build());
    Message eqMessage =
        fromUnknownFields(
            UnknownFieldSet.newBuilder()
                .addField(19, Field.newBuilder().addFixed32(3).addFixed64(3).build())
                .addField(
                    20,
                    Field.newBuilder()
                        .addFixed32(1)
                        .addFixed64(1)
                        .addVarint(3)
                        .addLengthDelimited(ByteString.copyFrom("3", StandardCharsets.UTF_8))
                        .addGroup(
                            UnknownFieldSet.newBuilder()
                                .addField(1, Field.newBuilder().addFixed32(3).build())
                                .build())
                        .build())
                .addField(
                    21,
                    Field.newBuilder()
                        .addFixed32(3)
                        .addFixed64(3)
                        .addVarint(1)
                        .addLengthDelimited(ByteString.copyFrom("1", StandardCharsets.UTF_8))
                        .addGroup(
                            UnknownFieldSet.newBuilder()
                                .addField(1, Field.newBuilder().addFixed32(1).addFixed64(3).build())
                                .addField(2, Field.newBuilder().addFixed32(3).addFixed64(1).build())
                                .addField(3, Field.newBuilder().addFixed32(3).build())
                                .build())
                        .build())
                .build());

    assertThat(diffMessage).isNotEqualTo(message);
    assertThat(eqMessage).isNotEqualTo(message);

    assertThat(diffMessage)
        .withPartialScope(FieldScopes.fromSetFields(scopeMessage))
        .isNotEqualTo(message);
    assertThat(eqMessage)
        .withPartialScope(FieldScopes.fromSetFields(scopeMessage))
        .isEqualTo(message);

    assertThatThrownBy(() -> assertThat(diffMessage).isEqualTo(message))
        .isInstanceOf(AssertionError.class)
        .satisfies(isEqualToFailureMessage())
        .hasMessageContaining("1 -> 4")
        .hasMessageContaining("\"1\" -> \"4\"")
        .hasMessageContaining("2 -> 3")
        .hasMessageContaining("\"2\" -> \"3\"");

    assertThatThrownBy(
            () ->
                assertThat(diffMessage)
                    .withPartialScope(FieldScopes.fromSetFields(scopeMessage))
                    .isEqualTo(message))
        .isInstanceOf(AssertionError.class)
        .satisfies(isEqualToFailureMessage())
        .hasMessageContaining("1 -> 4")
        .hasMessageContaining("\"1\" -> \"4\"")
        .satisfies(
            t ->
                assertThat(t.getMessage())
                    .doesNotContain("2 -> 3")
                    .doesNotContain("\"2\" -> \"3\""));

    assertThatThrownBy(
            () ->
                assertThat(eqMessage)
                    .withPartialScope(FieldScopes.fromSetFields(scopeMessage))
                    .isNotEqualTo(message))
        .isInstanceOf(AssertionError.class)
        .satisfies(isNotEqualToFailureMessage())
        .hasMessageContaining("1 -> 4")
        .hasMessageContaining("\"1\" -> \"4\"")
        .satisfies(
            t ->
                assertThat(t.getMessage())
                    .doesNotContain("2 -> 3")
                    .doesNotContain("\"2\" -> \"3\""));
  }

  @Test
  public void testFieldNumbersAreRecursive() {
    // o_int is compared, r_string is not.
    Message message =
        parse("o_int: 1 r_string: \"foo\" r_test_message: { o_int: 2 r_string: \"bar\" }");
    Message diffMessage =
        parse("o_int: 2 r_string: \"bar\" r_test_message: { o_int: 1 r_string: \"foo\" }");
    Message eqMessage =
        parse("o_int: 1 r_string: \"bar\" r_test_message: { o_int: 2 r_string: \"foo\" }");
    int fieldNumber = getFieldNumber("o_int");
    FieldDescriptor fieldDescriptor = getFieldDescriptor("o_int");

    assertThat(diffMessage)
        .withPartialScope(FieldScopes.allowingFields(fieldNumber))
        .isNotEqualTo(message);
    assertThat(eqMessage)
        .withPartialScope(FieldScopes.allowingFields(fieldNumber))
        .isEqualTo(message);
    assertThat(diffMessage)
        .withPartialScope(FieldScopes.allowingFieldDescriptors(fieldDescriptor))
        .isNotEqualTo(message);
    assertThat(eqMessage)
        .withPartialScope(FieldScopes.allowingFieldDescriptors(fieldDescriptor))
        .isEqualTo(message);

    assertThatThrownBy(
            () ->
                assertThat(diffMessage)
                    .withPartialScope(FieldScopes.allowingFields(fieldNumber))
                    .isEqualTo(message))
        .isInstanceOf(AssertionError.class)
        .satisfies(isEqualToFailureMessage())
        .hasMessageContaining("modified: o_int: 1 -> 2")
        .hasMessageContaining("modified: r_test_message[0].o_int: 2 -> 1");

    assertThatThrownBy(
            () ->
                assertThat(eqMessage)
                    .withPartialScope(FieldScopes.allowingFields(fieldNumber))
                    .isNotEqualTo(message))
        .isInstanceOf(AssertionError.class)
        .satisfies(isNotEqualToFailureMessage())
        .hasMessageContaining("ignored: r_test_message[0].r_string");
  }

  @Test
  public void testMultipleFieldNumbers() {
    Message message = parse("o_int: 1 r_string: \"x\" o_enum: TWO");
    Message diffMessage = parse("o_int: 2 r_string: \"y\" o_enum: TWO");
    Message eqMessage =
        parse("o_int: 1 r_string: \"x\" o_enum: ONE o_sub_test_message: { r_string: \"bar\" }");

    FieldScope fieldScope =
        FieldScopes.allowingFields(getFieldNumber("o_int"), getFieldNumber("r_string"));

    assertThat(diffMessage).withPartialScope(fieldScope).isNotEqualTo(message);
    assertThat(eqMessage).withPartialScope(fieldScope).isEqualTo(message);

    assertThatThrownBy(
            () -> assertThat(diffMessage).withPartialScope(fieldScope).isEqualTo(message))
        .isInstanceOf(AssertionError.class)
        .satisfies(isEqualToFailureMessage())
        .hasMessageContaining("modified: o_int: 1 -> 2")
        .hasMessageContaining("modified: r_string[0]: \"x\" -> \"y\"");

    assertThatThrownBy(
            () -> assertThat(eqMessage).withPartialScope(fieldScope).isNotEqualTo(message))
        .isInstanceOf(AssertionError.class)
        .satisfies(isNotEqualToFailureMessage())
        .hasMessageContaining("ignored: o_enum")
        .hasMessageContaining("ignored: o_sub_test_message");
  }

  @Test
  public void testInvalidFieldNumber() {
    Message message1 = parse("o_int: 44");
    Message message2 = parse("o_int: 33");

    assertThatThrownBy(() -> assertThat(message1).ignoringFields(999).isEqualTo(message2))
        .hasStackTraceContaining(
            "Message type " + fullMessageName() + " has no field with number 999.");
  }

  @Test
  public void testIgnoreFieldsAtDifferentLevels() {
    // Ignore all 'o_int' fields, in different ways.
    Message message =
        parse(
            "o_int: 1 r_string: \"foo\" o_sub_test_message: { o_int: 2 "
                + "o_sub_sub_test_message: { o_int: 3 r_string: \"bar\" } }");

    // Even though o_int is ignored, message presence is not.  So these all fail.
    Message diffMessage1 = parse("r_string: \"baz\"");
    Message diffMessage2 = parse("r_string: \"foo\"");
    Message diffMessage3 = parse("r_string: \"foo\" o_sub_test_message: {}");
    Message diffMessage4 =
        parse("r_string: \"foo\" o_sub_test_message: { o_sub_sub_test_message: {} }");

    // All of these messages are equivalent, because all o_int are ignored.
    Message eqMessage1 =
        parse(
            "o_int: 111 r_string: \"foo\" o_sub_test_message: { o_int: 222 "
                + "o_sub_sub_test_message: { o_int: 333 r_string: \"bar\" } }");
    Message eqMessage2 =
        parse(
            "o_int: 1 r_string: \"foo\" o_sub_test_message: { o_int: 2 "
                + "o_sub_sub_test_message: { o_int: 3 r_string: \"bar\" } }");
    Message eqMessage3 =
        parse(
            "r_string: \"foo\" o_sub_test_message: { "
                + "o_sub_sub_test_message: { r_string: \"bar\" } }");
    Message eqMessage4 =
        parse(
            "o_int: 333 r_string: \"foo\" o_sub_test_message: { o_int: 111 "
                + "o_sub_sub_test_message: { o_int: 222 r_string: \"bar\" } }");

    FieldDescriptor top = getFieldDescriptor("o_int");
    FieldDescriptor middle =
        getFieldDescriptor("o_sub_test_message").getMessageType().findFieldByName("o_int");
    FieldDescriptor bottom =
        getFieldDescriptor("o_sub_test_message")
            .getMessageType()
            .findFieldByName("o_sub_sub_test_message")
            .getMessageType()
            .findFieldByName("o_int");

    ImmutableMap<String, FieldScope> fieldScopes =
        ImmutableMap.of(
            "BASIC",
            FieldScopes.ignoringFieldDescriptors(top, middle, bottom),
            "CHAINED",
            FieldScopes.ignoringFieldDescriptors(top)
                .ignoringFieldDescriptors(middle)
                .ignoringFieldDescriptors(bottom),
            "REPEATED",
            FieldScopes.ignoringFieldDescriptors(top, middle)
                .ignoringFieldDescriptors(middle, bottom));

    for (String scopeName : fieldScopes.keySet()) {
      String msg = "FieldScope(" + scopeName + ")";
      FieldScope scope = fieldScopes.get(scopeName);

      assertThat(diffMessage1).as(msg).withPartialScope(scope).isNotEqualTo(message);
      assertThat(diffMessage2).as(msg).withPartialScope(scope).isNotEqualTo(message);
      assertThat(diffMessage3).as(msg).withPartialScope(scope).isNotEqualTo(message);
      assertThat(diffMessage4).as(msg).withPartialScope(scope).isNotEqualTo(message);

      assertThat(eqMessage1).as(msg).withPartialScope(scope).isEqualTo(message);
      assertThat(eqMessage2).as(msg).withPartialScope(scope).isEqualTo(message);
      assertThat(eqMessage3).as(msg).withPartialScope(scope).isEqualTo(message);
      assertThat(eqMessage4).as(msg).withPartialScope(scope).isEqualTo(message);
    }
  }

  @Test
  public void testFromSetFields_iterables_errorForDifferentMessageTypes() {
    // Don't run this test twice.
    if (!testIsRunOnce()) {
      return;
    }

    assertThatThrownBy(
            () ->
                FieldScopes.fromSetFields(
                    TestMessage2.newBuilder().setOInt(2).build(),
                    TestMessage3.newBuilder().setOInt(2).build()))
        .isInstanceOf(RuntimeException.class)
        .hasMessageContaining("Cannot create scope from messages with different descriptors")
        .hasMessageContaining(TestMessage2.getDescriptor().getFullName())
        .hasMessageContaining(TestMessage3.getDescriptor().getFullName());
  }

  @Test
  public void testFromSetFields_iterables_errorIfDescriptorMismatchesSubject() {
    // Don't run this test twice.
    if (!testIsRunOnce()) {
      return;
    }

    Message message =
        TestMessage2.newBuilder().setOInt(1).addRString("foo").addRString("bar").build();
    Message eqMessage =
        TestMessage2.newBuilder().setOInt(1).addRString("foo").addRString("bar").build();

    assertThatThrownBy(
            () ->
                assertThat(message)
                    .withPartialScope(
                        FieldScopes.fromSetFields(
                            TestMessage3.newBuilder().setOInt(2).build(),
                            TestMessage3.newBuilder().addRString("foo").build()))
                    .isEqualTo(eqMessage))
        .isInstanceOf(RuntimeException.class)
        .hasMessageContaining(
            "Message given to FieldScopes.fromSetFields() "
                + "does not have the same descriptor as the message being tested")
        .hasMessageContaining(TestMessage2.getDescriptor().getFullName())
        .hasMessageContaining(TestMessage3.getDescriptor().getFullName());
  }

  @Test
  public void testIterableFieldScopeMethodVariants_protoSubject() {
    Message message = parse("o_int: 1 r_string: \"foo\"");
    Message eqExceptInt = parse("o_int: 2 r_string: \"foo\"");

    assertThat(message).ignoringFields(listOf(getFieldNumber("o_int"))).isEqualTo(eqExceptInt);
    assertThat(message)
        .reportingMismatchesOnly()
        .ignoringFields(listOf(getFieldNumber("o_int")))
        .isEqualTo(eqExceptInt);
    assertThat(message)
        .ignoringFieldScope(FieldScopes.allowingFields(listOf(getFieldNumber("o_int"))))
        .isEqualTo(eqExceptInt);
    assertThat(message)
        .withPartialScope(FieldScopes.ignoringFields(listOf(getFieldNumber("o_int"))))
        .isEqualTo(eqExceptInt);
    assertThat(message)
        .ignoringFieldDescriptors(listOf(getFieldDescriptor("o_int")))
        .isEqualTo(eqExceptInt);
    assertThat(message)
        .reportingMismatchesOnly()
        .ignoringFieldDescriptors(listOf(getFieldDescriptor("o_int")))
        .isEqualTo(eqExceptInt);
    assertThat(message)
        .ignoringFieldScope(
            FieldScopes.allowingFieldDescriptors(listOf(getFieldDescriptor("o_int"))))
        .isEqualTo(eqExceptInt);
    assertThat(message)
        .withPartialScope(FieldScopes.ignoringFieldDescriptors(listOf(getFieldDescriptor("o_int"))))
        .isEqualTo(eqExceptInt);
  }
}


text:
define(['./has'], function(has){
	var global = this,
		doc = document,
		readyStates = { 'loaded': 1, 'complete': 1 },
		fixReadyState = typeof doc.readyState != "string",
		ready = !!readyStates[doc.readyState];

	// For FF <= 3.5
	if(fixReadyState){ doc.readyState = "loading"; }

	if(!ready){
		var readyQ = [], tests = [],
			detectReady = function(evt){
				evt = evt || global.event;
				if(ready || (evt.type == "readystatechange" && !readyStates[doc.readyState])){ return; }
				ready = 1;

				// For FF <= 3.5
				if(fixReadyState){ doc.readyState = "complete"; }

				while(readyQ.length){
					(readyQ.shift())(doc);
				}
			},
			on = function(node, event){
				node.addEventListener(event, detectReady, false);
				readyQ.push(function(){ node.removeEventListener(event, detectReady, false); });
			};

		if(!has("dom-addeventlistener")){
			on = function(node, event){
				event = "on" + event;
				node.attachEvent(event, detectReady);
				readyQ.push(function(){ node.detachEvent(event, detectReady); });
			};

			var div = doc.createElement("div");
			try{
				if(div.doScroll && global.frameElement === null){
					// the doScroll test is only useful if we're in the top-most frame
					tests.push(function(){
						// Derived with permission from Diego Perini's IEContentLoaded
						// http://javascript.nwbox.com/IEContentLoaded/
						try{
							div.doScroll("left");
							return 1;
						}catch(e){}
					});
				}
			}catch(e){}
		}

		on(doc, "DOMContentLoaded");
		on(global, "load");

		if("onreadystatechange" in doc){
			on(doc, "readystatechange");
		}else if(!fixReadyState){
			// if the ready state property exists and there's
			// no readystatechange event, poll for the state
			// to change
			tests.push(function(){
				return readyStates[doc.readyState];
			});
		}

		if(tests.length){
			var poller = function(){
				if(ready){ return; }
				var i = tests.length;
				while(i--){
					if(tests[i]()){
						detectReady("poller");
						return;
					}
				}
				setTimeout(poller, 30);
			};
			poller();
		}
	}

	function domReady(callback){
		// summary:
		//		Plugin to delay require()/define() callback from firing until the DOM has finished loading.
		if(ready){
			callback(doc);
		}else{
			readyQ.push(callback);
		}
	}
	domReady.load = function(id, req, load){
		domReady(load);
	};

	return domReady;
});


text:
using NServiceBus;

class ConfiguringWorker
{
    public void Foo()
    {
        #region ConfiguringWorker

        Configure.With()
            .EnlistWithMSMQDistributor();

        #endregion
    }
}


text:
package edu.neu.coe.info6205.util;

public class Range {
    /**
     * Constructor
     *
     * @param low  the lowest number considered in range.
     * @param high the highest number considered in range.
     */
    public Range(int low, int high) {
        this.low = low;
        this.high = high;
    }

    /**
     * Method to determine if a number is in this Range.
     *
     * @param number the number to be tested.
     * @return true if the number is in this Range (inclusive).
     */
    public boolean contains(int number) {
        return (number >= low && number <= high);
    }

    public static Range valueOf(int low, int high) {
        return new Range(low, high);
    }

    private final int low;
    private final int high;
}


text:
              INSERTAR

Protocolos

              <form class="mu-reservation-form" action="<?= base_url() . 'index.php/Protocolos/insertar/'.$idAlumno?>" method="post">

                        <select name="nombre">
                            <option value="">Opciones</option>
                            <option value="absentismo">Absentismo</option>
                            <option value="acoso">Acoso</option>
                            <option value="ident">Identidad Genero</option>
                            <option value="solicitud">Solicitud Atención Especif.</option>
                        </select>

                        <input type="text" class="form-control" value="<?= set_value('fecha_ini') ?>" placeholder="Fecha de Inicio (dd/mm/aaaa)" name="fecha_ini">
                        <?= form_error('fecha_ini'); ?>

                        <input type="text" class="form-control" value="<?= set_value('fecha_fin') ?>" placeholder="Fecha de Fin (dd/mm/aaaa)" name="fecha_fin">
                        <?= form_error('fecha_fin'); ?>

                      <textarea class="form-control" rows="5" value="<?= set_value('observaciones') ?>"  placeholder="Observaciones" name="observaciones"></textarea>

                          <input type="hidden" name="idAlumno" value="<?=$idAlumno?>">
                          <button type="submit" name="aceptar" class="mu-readmore-btn">Aceptar</button>

              </form>


text:
package main

import (
	"errors"
	"reflect"
	"testing"
)

func TestParseCommandLineParams(t *testing.T) {
	tests := []struct {
		name      string
		parameter string
		params    *commandLineParams
		err       error
	}{
		{
			"no parameters",
			"",
			&commandLineParams{
				importMap: map[string]string{},
			},
			nil,
		},
		{
			"unknown parameter",
			"k=v",
			nil,
			errors.New(`unknown parameter "k"`),
		},
		{
			"empty parameter value - no equals sign",
			"import_prefix",
			nil,
			errors.New(`invalid parameter "import_prefix": expected format of parameter to be k=v`),
		},
		{
			"empty parameter value - no value",
			"import_prefix=",
			nil,
			errors.New(`invalid parameter "import_prefix": expected format of parameter to be k=v`),
		},
		{
			"import_prefix parameter",
			"import_prefix=github.com/example/repo",
			&commandLineParams{
				importMap:    map[string]string{},
				importPrefix: "github.com/example/repo",
			},
			nil,
		},
		{
			"single import parameter starting with 'M'",
			"Mrpcutil/empty.proto=github.com/example/rpcutil",
			&commandLineParams{
				importMap: map[string]string{
					"rpcutil/empty.proto": "github.com/example/rpcutil",
				},
			},
			nil,
		},
		{
			"multiple import parameters starting with 'M'",
			"Mrpcutil/empty.proto=github.com/example/rpcutil,Mrpc/haberdasher/service.proto=github.com/example/rpc/haberdasher",
			&commandLineParams{
				importMap: map[string]string{
					"rpcutil/empty.proto":           "github.com/example/rpcutil",
					"rpc/haberdasher/service.proto": "github.com/example/rpc/haberdasher",
				},
			},
			nil,
		},
		{
			"single import parameter starting with 'go_import_mapping@'",
			"go_import_mapping@rpcutil/empty.proto=github.com/example/rpcutil",
			&commandLineParams{
				importMap: map[string]string{
					"rpcutil/empty.proto": "github.com/example/rpcutil",
				},
			},
			nil,
		},
		{
			"multiple import parameters starting with 'go_import_mapping@'",
			"go_import_mapping@rpcutil/empty.proto=github.com/example/rpcutil,go_import_mapping@rpc/haberdasher/service.proto=github.com/example/rpc/haberdasher",
			&commandLineParams{
				importMap: map[string]string{
					"rpcutil/empty.proto":           "github.com/example/rpcutil",
					"rpc/haberdasher/service.proto": "github.com/example/rpc/haberdasher",
				},
			},
			nil,
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			params, err := parseCommandLineParams(tt.parameter)
			switch {
			case err != nil:
				if tt.err == nil {
					t.Fatal(err)
				}
				if err.Error() != tt.err.Error() {
					t.Errorf("got error = %v, want %v", err, tt.err)
				}
			case err == nil:
				if tt.err != nil {
					t.Errorf("got error = %v, want %v", err, tt.err)
				}
			}
			if !reflect.DeepEqual(params, tt.params) {
				t.Errorf("got params = %v, want %v", params, tt.params)
			}
		})
	}
}


text:
@echo off
..\..\dudeldu.exe -loop -shuffle -debug -auth web:web demo_playlist.dpl


text:
package org.apache.http.impl.nio.codecs;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

import org.apache.http.impl.io.HttpTransportMetricsImpl;
import org.apache.http.impl.nio.reactor.SessionInputBufferImpl;
import org.apache.http.mockup.ReadableByteChannelMockup;
import org.apache.http.nio.reactor.SessionInputBuffer;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;

/**
 * Simple tests for {@link LengthDelimitedDecoder}.
 *
 *
 * @version $Id$
 */
public class TestLengthDelimitedDecoder extends TestCase {

    // ------------------------------------------------------------ Constructor
    public TestLengthDelimitedDecoder(String testName) {
        super(testName);
    }

    // ------------------------------------------------------------------- Main
    public static void main(String args[]) {
        String[] testCaseName = { TestLengthDelimitedDecoder.class.getName() };
        junit.textui.TestRunner.main(testCaseName);
    }

    // ------------------------------------------------------- TestCase Methods

    public static Test suite() {
        return new TestSuite(TestLengthDelimitedDecoder.class);
    }

    private static String convert(final ByteBuffer src) {
        src.flip();
        StringBuffer buffer = new StringBuffer(src.remaining());
        while (src.hasRemaining()) {
            buffer.append((char)(src.get() & 0xff));
        }
        return buffer.toString();
    }

    private static String readFromFile(final File file) throws Exception {
        FileInputStream filestream = new FileInputStream(file);
        InputStreamReader reader = new InputStreamReader(filestream);
        try {
            StringBuffer buffer = new StringBuffer();
            char[] tmp = new char[2048];
            int l;
            while ((l = reader.read(tmp)) != -1) {
                buffer.append(tmp, 0, l);
            }
            return buffer.toString();
        } finally {
            reader.close();
        }
    }

    public void testBasicDecoding() throws Exception {
        ReadableByteChannel channel = new ReadableByteChannelMockup(
                new String[] {"stuff;", "more stuff"}, "US-ASCII");
        HttpParams params = new BasicHttpParams();

        SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params);
        HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl();
        LengthDelimitedDecoder decoder = new LengthDelimitedDecoder(
                channel, inbuf, metrics, 16);

        ByteBuffer dst = ByteBuffer.allocate(1024);

        int bytesRead = decoder.read(dst);
        assertEquals(6, bytesRead);
        assertEquals("stuff;", convert(dst));
        assertFalse(decoder.isCompleted());
        assertEquals(6, metrics.getBytesTransferred());

        dst.clear();
        bytesRead = decoder.read(dst);
        assertEquals(10, bytesRead);
        assertEquals("more stuff", convert(dst));
        assertTrue(decoder.isCompleted());
        assertEquals(16, metrics.getBytesTransferred());

        dst.clear();
        bytesRead = decoder.read(dst);
        assertEquals(-1, bytesRead);
        assertTrue(decoder.isCompleted());
        assertEquals(16, metrics.getBytesTransferred());
    }

    public void testCodingBeyondContentLimit() throws Exception {
        ReadableByteChannel channel = new ReadableByteChannelMockup(
                new String[] {
                        "stuff;",
                        "more stuff; and a lot more stuff"}, "US-ASCII");
        HttpParams params = new BasicHttpParams();

        SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params);
        HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl();
        LengthDelimitedDecoder decoder = new LengthDelimitedDecoder(
                channel, inbuf, metrics, 16);

        ByteBuffer dst = ByteBuffer.allocate(1024);

        int bytesRead = decoder.read(dst);
        assertEquals(6, bytesRead);
        assertEquals("stuff;", convert(dst));
        assertFalse(decoder.isCompleted());
        assertEquals(6, metrics.getBytesTransferred());

        dst.clear();
        bytesRead = decoder.read(dst);
        assertEquals(10, bytesRead);
        assertEquals("more stuff", convert(dst));
        assertTrue(decoder.isCompleted());
        assertEquals(16, metrics.getBytesTransferred());

        dst.clear();
        bytesRead = decoder.read(dst);
        assertEquals(-1, bytesRead);
        assertTrue(decoder.isCompleted());
        assertEquals(16, metrics.getBytesTransferred());
    }

    public void testBasicDecodingSmallBuffer() throws Exception {
        ReadableByteChannel channel = new ReadableByteChannelMockup(
                new String[] {"stuff;", "more stuff"}, "US-ASCII");
        HttpParams params = new BasicHttpParams();

        SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params);
        HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl();
        LengthDelimitedDecoder decoder = new LengthDelimitedDecoder(
                channel, inbuf, metrics, 16);

        ByteBuffer dst = ByteBuffer.allocate(4);

        int bytesRead = decoder.read(dst);
        assertEquals(4, bytesRead);
        assertEquals("stuf", convert(dst));
        assertFalse(decoder.isCompleted());
        assertEquals(4, metrics.getBytesTransferred());

        dst.clear();
        bytesRead = decoder.read(dst);
        assertEquals(2, bytesRead);
        assertEquals("f;", convert(dst));
        assertFalse(decoder.isCompleted());
        assertEquals(6, metrics.getBytesTransferred());

        dst.clear();
        bytesRead = decoder.read(dst);
        assertEquals(4, bytesRead);
        assertEquals("more", convert(dst));
        assertFalse(decoder.isCompleted());
        assertEquals(10, metrics.getBytesTransferred());

        dst.clear();
        bytesRead = decoder.read(dst);
        assertEquals(4, bytesRead);
        assertEquals(" stu", convert(dst));
        assertFalse(decoder.isCompleted());
        assertEquals(14, metrics.getBytesTransferred());

        dst.clear();
        bytesRead = decoder.read(dst);
        assertEquals(2, bytesRead);
        assertEquals("ff", convert(dst));
        assertTrue(decoder.isCompleted());
        assertEquals(16, metrics.getBytesTransferred());

        dst.clear();
        bytesRead = decoder.read(dst);
        assertEquals(-1, bytesRead);
        assertTrue(decoder.isCompleted());
        assertEquals(16, metrics.getBytesTransferred());
    }

    public void testDecodingFromSessionBuffer1() throws Exception {
        ReadableByteChannel channel = new ReadableByteChannelMockup(
                new String[] {"stuff;", "more stuff"}, "US-ASCII");
        HttpParams params = new BasicHttpParams();

        SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params);
        HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl();

        inbuf.fill(channel);

        assertEquals(6, inbuf.length());

        LengthDelimitedDecoder decoder = new LengthDelimitedDecoder(
                channel, inbuf, metrics, 16);

        ByteBuffer dst = ByteBuffer.allocate(1024);

        int bytesRead = decoder.read(dst);
        assertEquals(6, bytesRead);
        assertEquals("stuff;", convert(dst));
        assertFalse(decoder.isCompleted());
        assertEquals(0, metrics.getBytesTransferred());

        dst.clear();
        bytesRead = decoder.read(dst);
        assertEquals(10, bytesRead);
        assertEquals("more stuff", convert(dst));
        assertTrue(decoder.isCompleted());
        assertEquals(10, metrics.getBytesTransferred());

        dst.clear();
        bytesRead = decoder.read(dst);
        assertEquals(-1, bytesRead);
        assertTrue(decoder.isCompleted());
        assertEquals(10, metrics.getBytesTransferred());
    }

    public void testDecodingFromSessionBuffer2() throws Exception {
        ReadableByteChannel channel = new ReadableByteChannelMockup(
                new String[] {
                        "stuff;",
                        "more stuff; and a lot more stuff"}, "US-ASCII");
        HttpParams params = new BasicHttpParams();

        SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params);
        HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl();

        inbuf.fill(channel);
        inbuf.fill(channel);

        assertEquals(38, inbuf.length());

        LengthDelimitedDecoder decoder = new LengthDelimitedDecoder(
                channel, inbuf, metrics, 16);

        ByteBuffer dst = ByteBuffer.allocate(1024);

        int bytesRead = decoder.read(dst);
        assertEquals(16, bytesRead);
        assertEquals("stuff;more stuff", convert(dst));
        assertTrue(decoder.isCompleted());
        assertEquals(0, metrics.getBytesTransferred());

        dst.clear();
        bytesRead = decoder.read(dst);
        assertEquals(-1, bytesRead);
        assertTrue(decoder.isCompleted());
        assertEquals(0, metrics.getBytesTransferred());
    }

    public void testBasicDecodingFile() throws Exception {
        ReadableByteChannel channel = new ReadableByteChannelMockup(
                new String[] {"stuff; ", "more stuff; ", "a lot more stuff!!!"}, "US-ASCII");
        HttpParams params = new BasicHttpParams();

        SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params);
        HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl();
        LengthDelimitedDecoder decoder = new LengthDelimitedDecoder(
                channel, inbuf, metrics, 36);

        File fileHandle = File.createTempFile("testFile", ".txt");

        RandomAccessFile testfile = new RandomAccessFile(fileHandle, "rw");
        FileChannel fchannel = testfile.getChannel();

        long pos = 0;
        while (!decoder.isCompleted()) {
            long bytesRead = decoder.transfer(fchannel, pos, 10);
            if (bytesRead > 0) {
                pos += bytesRead;
            }
        }
        assertEquals(testfile.length(), metrics.getBytesTransferred());
        fchannel.close();

        assertEquals("stuff; more stuff; a lot more stuff!", readFromFile(fileHandle));

        fileHandle.delete();
    }

    public void testDecodingFileWithBufferedSessionData() throws Exception {
        ReadableByteChannel channel = new ReadableByteChannelMockup(
                new String[] {"stuff; ", "more stuff; ", "a lot more stuff!!!"}, "US-ASCII");
        HttpParams params = new BasicHttpParams();

        SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params);
        HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl();
        LengthDelimitedDecoder decoder = new LengthDelimitedDecoder(
                channel, inbuf, metrics, 36);

        int i = inbuf.fill(channel);
        assertEquals(7, i);

        File fileHandle = File.createTempFile("testFile", ".txt");

        RandomAccessFile testfile = new RandomAccessFile(fileHandle, "rw");
        FileChannel fchannel = testfile.getChannel();

        long pos = 0;
        while (!decoder.isCompleted()) {
            long bytesRead = decoder.transfer(fchannel, pos, 10);
            if (bytesRead > 0) {
                pos += bytesRead;
            }
        }

        assertEquals(testfile.length() - 7, metrics.getBytesTransferred());
        fchannel.close();

        assertEquals("stuff; more stuff; a lot more stuff!", readFromFile(fileHandle));

        fileHandle.delete();
    }

    public void testDecodingFileWithOffsetAndBufferedSessionData() throws Exception {
        ReadableByteChannel channel = new ReadableByteChannelMockup(
                new String[] {"stuff; ", "more stuff; ", "a lot more stuff!"}, "US-ASCII");
        HttpParams params = new BasicHttpParams();

        SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params);
        HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl();
        LengthDelimitedDecoder decoder = new LengthDelimitedDecoder(
                channel, inbuf, metrics, 36);

        int i = inbuf.fill(channel);
        assertEquals(7, i);

        File fileHandle = File.createTempFile("testFile", ".txt");

        RandomAccessFile testfile = new RandomAccessFile(fileHandle, "rw");
        byte[] beginning = "beginning; ".getBytes("US-ASCII");
        testfile.write(beginning);
        testfile.close();

        testfile = new RandomAccessFile(fileHandle, "rw");
        FileChannel fchannel = testfile.getChannel();

        long pos = beginning.length;
        while (!decoder.isCompleted()) {
            if(testfile.length() < pos)
                testfile.setLength(pos);
            long bytesRead = decoder.transfer(fchannel, pos, 10);
            if (bytesRead > 0) {
                pos += bytesRead;
            }
        }

        // count everything except the initial 7 bytes that went to the session buffer
        assertEquals(testfile.length() - 7 - beginning.length, metrics.getBytesTransferred());
        fchannel.close();

        assertEquals("beginning; stuff; more stuff; a lot more stuff!", readFromFile(fileHandle));

        fileHandle.delete();
    }

    public void testWriteBeyondFileSize() throws Exception {
        ReadableByteChannel channel = new ReadableByteChannelMockup(
                new String[] {"a"}, "US-ASCII");
        HttpParams params = new BasicHttpParams();

        SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params);
        HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl();
        LengthDelimitedDecoder decoder = new LengthDelimitedDecoder(
                channel, inbuf, metrics, 1);

        File fileHandle = File.createTempFile("testFile", ".txt");

        RandomAccessFile testfile = new RandomAccessFile(fileHandle, "rw");
        FileChannel fchannel = testfile.getChannel();
        assertEquals(0, testfile.length());

        try {
            decoder.transfer(fchannel, 5, 10);
            fail("expected IOException");
        } catch(IOException iox) {}

        fileHandle.delete();
    }

    public void testCodingBeyondContentLimitFile() throws Exception {
        ReadableByteChannel channel = new ReadableByteChannelMockup(
                new String[] {
                        "stuff;",
                        "more stuff; and a lot more stuff"}, "US-ASCII");
        HttpParams params = new BasicHttpParams();

        SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params);
        HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl();
        LengthDelimitedDecoder decoder = new LengthDelimitedDecoder(
                channel, inbuf, metrics, 16);

        File fileHandle = File.createTempFile("testFile", ".txt");
        RandomAccessFile testfile  = new RandomAccessFile(fileHandle, "rw");
        FileChannel fchannel = testfile.getChannel();

        long bytesRead = decoder.transfer(fchannel, 0, 6);
        assertEquals(6, bytesRead);
        assertFalse(decoder.isCompleted());
        assertEquals(6, metrics.getBytesTransferred());

        bytesRead = decoder.transfer(fchannel,0 , 10);
        assertEquals(10, bytesRead);
        assertTrue(decoder.isCompleted());
        assertEquals(16, metrics.getBytesTransferred());

        bytesRead = decoder.transfer(fchannel, 0, 1);
        assertEquals(-1, bytesRead);
        assertTrue(decoder.isCompleted());
        assertEquals(16, metrics.getBytesTransferred());

        fileHandle.delete();
    }

    public void testInvalidConstructor() {
        ReadableByteChannel channel = new ReadableByteChannelMockup(
                new String[] {"stuff;", "more stuff"}, "US-ASCII");
        HttpParams params = new BasicHttpParams();

        SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params);
        HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl();
        try {
            new LengthDelimitedDecoder(null, null, null, 10);
            fail("IllegalArgumentException should have been thrown");
        } catch (IllegalArgumentException ex) {
            // ignore
        }
        try {
            new LengthDelimitedDecoder(channel, null, null, 10);
            fail("IllegalArgumentException should have been thrown");
        } catch (IllegalArgumentException ex) {
            // ignore
        }
        try {
            new LengthDelimitedDecoder(channel, inbuf, null, 10);
            fail("IllegalArgumentException should have been thrown");
        } catch (IllegalArgumentException ex) {
            // ignore
        }
        try {
            new LengthDelimitedDecoder(channel, inbuf, metrics, -10);
            fail("IllegalArgumentException should have been thrown");
        } catch (IllegalArgumentException ex) {
            // ignore
        }
    }

    public void testInvalidInput() throws Exception {
        String s = "stuff";
        ReadableByteChannel channel = new ReadableByteChannelMockup(
                new String[] {s}, "US-ASCII");
        HttpParams params = new BasicHttpParams();

        SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params);
        HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl();
        LengthDelimitedDecoder decoder = new LengthDelimitedDecoder(
                channel, inbuf, metrics, 3);

        try {
            decoder.read(null);
            fail("IllegalArgumentException should have been thrown");
        } catch (IllegalArgumentException ex) {
            // expected
        }
    }

}


text:
'''
:py:mod:`fits.py` - FITS conversion
-----------------------------------

Converts the :py:mod:`everest` de-trended light curves to the
*FITS* format using
`PyFits <http://stsdas.stsci.edu/download/docs/The_PyFITS_Handbook.pdf>`_.
These *FITS* files make up the public :py:mod:`everest` catalog.

'''

from __future__ import division, print_function, absolute_import, \
     unicode_literals
from . import __version__ as EVEREST_VERSION
from .config import EVEREST_DAT, EVEREST_SRC, QUALITY_BAD, QUALITY_NAN, \
     QUALITY_OUT, QUALITY_REC, QUALITY_TRN, EVEREST_MAJOR_MINOR
try:
    import pyfits
except ImportError:
    try:
        import astropy.io.fits as pyfits
    except ImportError:
        raise Exception('Please install the `pyfits` package.')
import os
import numpy as np
from time import strftime
import logging
log = logging.getLogger(__name__)

__all__ = ['MakeFITS']

def PrimaryHDU(model):
    '''
    Construct the primary HDU file containing basic header info.

    '''

    # Get mission cards
    cards = model._mission.HDUCards(model.meta, hdu=0)
    if 'KEPMAG' not in [c[0] for c in cards]:
        cards.append(('KEPMAG', model.mag, 'Kepler magnitude'))

    # Add EVEREST info
    cards.append(('COMMENT', '************************'))
    cards.append(('COMMENT', '*     EVEREST INFO     *'))
    cards.append(('COMMENT', '************************'))
    cards.append(('MISSION', model.mission, 'Mission name'))
    cards.append(('VERSION', EVEREST_MAJOR_MINOR, 'EVEREST pipeline version'))
    cards.append(('SUBVER', EVEREST_VERSION, 'EVEREST pipeline subversion'))
    cards.append(('DATE', strftime('%Y-%m-%d'),
                  'EVEREST file creation date (YYYY-MM-DD)'))

    # Create the HDU
    header = pyfits.Header(cards=cards)
    hdu = pyfits.PrimaryHDU(header=header)

    return hdu

def LightcurveHDU(model):
    '''
    Construct the data HDU file containing the arrays and the observing info.

    '''

    # Get mission cards
    cards = model._mission.HDUCards(model.meta, hdu=1)

    # Add EVEREST info
    cards.append(('COMMENT', '************************'))
    cards.append(('COMMENT', '*     EVEREST INFO     *'))
    cards.append(('COMMENT', '************************'))
    cards.append(('MISSION', model.mission, 'Mission name'))
    cards.append(('VERSION', EVEREST_MAJOR_MINOR, 'EVEREST pipeline version'))
    cards.append(('SUBVER', EVEREST_VERSION, 'EVEREST pipeline subversion'))
    cards.append(('DATE', strftime('%Y-%m-%d'),
                  'EVEREST file creation date (YYYY-MM-DD)'))
    cards.append(('MODEL', model.name, 'Name of EVEREST model used'))
    cards.append(('APNAME', model.aperture_name, 'Name of aperture used'))
    cards.append(('BPAD', model.bpad, 'Chunk overlap in cadences'))
    for c in range(len(model.breakpoints)):
        cards.append(
            ('BRKPT%02d' % (c + 1), model.breakpoints[c],
             'Light curve breakpoint'))
    cards.append(('CBVNUM', model.cbv_num, 'Number of CBV signals to recover'))
    cards.append(('CBVNITER', model.cbv_niter,
                  'Number of CBV SysRem iterations'))
    cards.append(('CBVWIN', model.cbv_win, 'Window size for smoothing CBVs'))
    cards.append(('CBVORD', model.cbv_order, 'Order when smoothing CBVs'))
    cards.append(('CDIVS', model.cdivs, 'Cross-validation subdivisions'))
    cards.append(('CDPP', model.cdpp, 'Average de-trended CDPP'))
    cards.append(('CDPPR', model.cdppr, 'Raw CDPP'))
    cards.append(('CDPPV', model.cdppv, 'Average validation CDPP'))
    cards.append(('CDPPG', model.cdppg, 'Average GP-de-trended CDPP'))
    for i in range(99):
        try:
            cards.append(('CDPP%02d' % (i + 1),
                          model.cdpp_arr[i] if not np.isnan(
                model.cdpp_arr[i]) else 0, 'Chunk de-trended CDPP'))
            cards.append(('CDPPR%02d' % (
                i + 1), model.cdppr_arr[i] if not np.isnan(
                model.cdppr_arr[i]) else 0, 'Chunk raw CDPP'))
            cards.append(('CDPPV%02d' % (i + 1),
                          model.cdppv_arr[i] if not np.isnan(
                model.cdppv_arr[i]) else 0, 'Chunk validation CDPP'))
        except:
            break
    cards.append(
        ('CVMIN', model.cv_min, 'Cross-validation objective function'))
    cards.append(
        ('GITER', model.giter, 'Number of GP optimiziation iterations'))
    cards.append(
        ('GMAXF', model.giter, 'Max number of GP function evaluations'))
    cards.append(('GPFACTOR', model.gp_factor,
                  'GP amplitude initialization factor'))
    cards.append(('KERNEL', model.kernel, 'GP kernel name'))
    if model.kernel == 'Basic':
        cards.append(
            ('GPWHITE', model.kernel_params[0],
             'GP white noise amplitude (e-/s)'))
        cards.append(
            ('GPRED', model.kernel_params[1],
             'GP red noise amplitude (e-/s)'))
        cards.append(
            ('GPTAU', model.kernel_params[2],
             'GP red noise timescale (days)'))
    elif model.kernel == 'QuasiPeriodic':
        cards.append(
            ('GPWHITE', model.kernel_params[0],
             'GP white noise amplitude (e-/s)'))
        cards.append(
            ('GPRED', model.kernel_params[1], 'GP red noise amplitude (e-/s)'))
        cards.append(('GPGAMMA', model.kernel_params[2], 'GP scale factor'))
        cards.append(('GPPER', model.kernel_params[3], 'GP period (days)'))
    for c in range(len(model.breakpoints)):
        for o in range(model.pld_order):
            cards.append(('LAMB%02d%02d' % (c + 1, o + 1),
                          model.lam[c][o], 'Cross-validation parameter'))
            if model.name == 'iPLD':
                cards.append(('RECL%02d%02d' % (c + 1, o + 1),
                              model.reclam[c][o],
                              'Cross-validation parameter'))
    cards.append(('LEPS', model.leps, 'Cross-validation tolerance'))
    cards.append(('MAXPIX', model.max_pixels, 'Maximum size of TPF aperture'))
    for i, source in enumerate(model.nearby[:99]):
        cards.append(('NRBY%02dID' %
                      (i + 1), source['ID'], 'Nearby source ID'))
        cards.append(
            ('NRBY%02dX' % (i + 1), source['x'], 'Nearby source X position'))
        cards.append(
            ('NRBY%02dY' % (i + 1), source['y'], 'Nearby source Y position'))
        cards.append(
            ('NRBY%02dM' % (i + 1), source['mag'], 'Nearby source magnitude'))
        cards.append(('NRBY%02dX0' %
                      (i + 1), source['x0'], 'Nearby source reference X'))
        cards.append(('NRBY%02dY0' %
                      (i + 1), source['y0'], 'Nearby source reference Y'))
    for i, n in enumerate(model.neighbors):
        cards.append(
            ('NEIGH%02d' % i, model.neighbors[i],
             'Neighboring star used to de-trend'))
    cards.append(('OITER', model.oiter, 'Number of outlier search iterations'))
    cards.append(('OPTGP', model.optimize_gp, 'GP optimization performed?'))
    cards.append(
        ('OSIGMA', model.osigma, 'Outlier tolerance (standard deviations)'))
    for i, planet in enumerate(model.planets):
        cards.append(
            ('P%02dT0' % (i + 1), planet[0], 'Planet transit time (days)'))
        cards.append(
            ('P%02dPER' % (i + 1), planet[1], 'Planet transit period (days)'))
        cards.append(
            ('P%02dDUR' % (i + 1), planet[2],
             'Planet transit duration (days)'))
    cards.append(('PLDORDER', model.pld_order, 'PLD de-trending order'))
    cards.append(('SATUR', model.saturated, 'Is target saturated?'))
    cards.append(('SATTOL', model.saturation_tolerance,
                  'Fractional saturation tolerance'))

    # Add the EVEREST quality flags to the QUALITY array
    quality = np.array(model.quality)
    quality[np.array(model.badmask, dtype=int)] += 2 ** (QUALITY_BAD - 1)
    quality[np.array(model.nanmask, dtype=int)] += 2 ** (QUALITY_NAN - 1)
    quality[np.array(model.outmask, dtype=int)] += 2 ** (QUALITY_OUT - 1)
    quality[np.array(model.recmask, dtype=int)] += 2 ** (QUALITY_REC - 1)
    quality[np.array(model.transitmask, dtype=int)] += 2 ** (QUALITY_TRN - 1)

    # When de-trending, we interpolated to fill in NaN fluxes. Here
    # we insert the NaNs back in, since there's no actual physical
    # information at those cadences.
    flux = np.array(model.flux)
    flux[model.nanmask] = np.nan

    # Create the arrays list
    arrays = [pyfits.Column(name='CADN', format='D', array=model.cadn),
              pyfits.Column(name='FLUX', format='D', array=flux, unit='e-/s'),
              pyfits.Column(name='FRAW', format='D',
                            array=model.fraw, unit='e-/s'),
              pyfits.Column(name='FRAW_ERR', format='D',
                            array=model.fraw_err, unit='e-/s'),
              pyfits.Column(name='QUALITY', format='J', array=quality),
              pyfits.Column(name='TIME', format='D',
                            array=model.time, unit='BJD - 2454833')]

    # Add the CBVs
    if model.fcor is not None:
        arrays += [pyfits.Column(name='FCOR', format='D',
                                 array=model.fcor, unit='e-/s')]
        for n in range(model.XCBV.shape[1]):
            arrays += [pyfits.Column(name='CBV%02d' %
                                     (n + 1), format='D',
                                     array=model.XCBV[:, n])]

    # Did we subtract a background term?
    if hasattr(model.bkg, '__len__'):
        arrays.append(pyfits.Column(name='BKG', format='D',
                                    array=model.bkg, unit='e-/s'))

    # Create the HDU
    header = pyfits.Header(cards=cards)
    cols = pyfits.ColDefs(arrays)
    hdu = pyfits.BinTableHDU.from_columns(cols, header=header, name='ARRAYS')

    return hdu

def PixelsHDU(model):
    '''
    Construct the HDU containing the pixel-level light curve.

    '''

    # Get mission cards
    cards = model._mission.HDUCards(model.meta, hdu=2)

    # Add EVEREST info
    cards = []
    cards.append(('COMMENT', '************************'))
    cards.append(('COMMENT', '*     EVEREST INFO     *'))
    cards.append(('COMMENT', '************************'))
    cards.append(('MISSION', model.mission, 'Mission name'))
    cards.append(('VERSION', EVEREST_MAJOR_MINOR, 'EVEREST pipeline version'))
    cards.append(('SUBVER', EVEREST_VERSION, 'EVEREST pipeline subversion'))
    cards.append(('DATE', strftime('%Y-%m-%d'),
                  'EVEREST file creation date (YYYY-MM-DD)'))

    # Create the HDU
    header = pyfits.Header(cards=cards)

    # The pixel timeseries
    arrays = [pyfits.Column(name='FPIX', format='%dD' %
                            model.fpix.shape[1], array=model.fpix)]

    # The first order PLD vectors for all the neighbors (npixels, ncadences)
    X1N = model.X1N
    if X1N is not None:
        arrays.append(pyfits.Column(name='X1N', format='%dD' %
                                    X1N.shape[1], array=X1N))

    cols = pyfits.ColDefs(arrays)
    hdu = pyfits.BinTableHDU.from_columns(cols, header=header, name='PIXELS')

    return hdu

def ApertureHDU(model):
    '''
    Construct the HDU containing the aperture used to de-trend.

    '''

    # Get mission cards
    cards = model._mission.HDUCards(model.meta, hdu=3)

    # Add EVEREST info
    cards.append(('COMMENT', '************************'))
    cards.append(('COMMENT', '*     EVEREST INFO     *'))
    cards.append(('COMMENT', '************************'))
    cards.append(('MISSION', model.mission, 'Mission name'))
    cards.append(('VERSION', EVEREST_MAJOR_MINOR, 'EVEREST pipeline version'))
    cards.append(('SUBVER', EVEREST_VERSION, 'EVEREST pipeline subversion'))
    cards.append(('DATE', strftime('%Y-%m-%d'),
                  'EVEREST file creation date (YYYY-MM-DD)'))

    # Create the HDU
    header = pyfits.Header(cards=cards)
    hdu = pyfits.ImageHDU(data=model.aperture,
                          header=header, name='APERTURE MASK')

    return hdu

def ImagesHDU(model):
    '''
    Construct the HDU containing sample postage stamp images of the target.

    '''

    # Get mission cards
    cards = model._mission.HDUCards(model.meta, hdu=4)

    # Add EVEREST info
    cards.append(('COMMENT', '************************'))
    cards.append(('COMMENT', '*     EVEREST INFO     *'))
    cards.append(('COMMENT', '************************'))
    cards.append(('MISSION', model.mission, 'Mission name'))
    cards.append(('VERSION', EVEREST_MAJOR_MINOR, 'EVEREST pipeline version'))
    cards.append(('SUBVER', EVEREST_VERSION, 'EVEREST pipeline subversion'))
    cards.append(('DATE', strftime('%Y-%m-%d'),
                  'EVEREST file creation date (YYYY-MM-DD)'))

    # The images
    format = '%dD' % model.pixel_images[0].shape[1]
    arrays = [pyfits.Column(name='STAMP1', format=format,
                            array=model.pixel_images[0]),
              pyfits.Column(name='STAMP2', format=format,
                            array=model.pixel_images[1]),
              pyfits.Column(name='STAMP3', format=format,
                            array=model.pixel_images[2])]

    # Create the HDU
    header = pyfits.Header(cards=cards)
    cols = pyfits.ColDefs(arrays)
    hdu = pyfits.BinTableHDU.from_columns(
        cols, header=header, name='POSTAGE STAMPS')

    return hdu

def HiResHDU(model):
    '''
    Construct the HDU containing the hi res image of the target.

    '''

    # Get mission cards
    cards = model._mission.HDUCards(model.meta, hdu=5)

    # Add EVEREST info
    cards.append(('COMMENT', '************************'))
    cards.append(('COMMENT', '*     EVEREST INFO     *'))
    cards.append(('COMMENT', '************************'))
    cards.append(('MISSION', model.mission, 'Mission name'))
    cards.append(('VERSION', EVEREST_MAJOR_MINOR, 'EVEREST pipeline version'))
    cards.append(('SUBVER', EVEREST_VERSION, 'EVEREST pipeline subversion'))
    cards.append(('DATE', strftime('%Y-%m-%d'),
                  'EVEREST file creation date (YYYY-MM-DD)'))

    # Create the HDU
    header = pyfits.Header(cards=cards)
    if model.hires is not None:
        hdu = pyfits.ImageHDU(
            data=model.hires, header=header, name='HI RES IMAGE')
    else:
        hdu = pyfits.ImageHDU(data=np.empty(
            (0, 0), dtype=float), header=header, name='HI RES IMAGE')
    return hdu

def MakeFITS(model, fitsfile=None):
    '''
    Generate a FITS file for a given :py:mod:`everest` run.

    :param model: An :py:mod:`everest` model instance

    '''

    # Get the fits file name
    if fitsfile is None:
        outfile = os.path.join(model.dir, model._mission.FITSFile(
            model.ID, model.season, model.cadence))
    else:
        outfile = os.path.join(model.dir, fitsfile)
    if os.path.exists(outfile) and not model.clobber:
        return
    elif os.path.exists(outfile):
        os.remove(outfile)

    log.info('Generating FITS file...')

    # Create the HDUs
    primary = PrimaryHDU(model)
    lightcurve = LightcurveHDU(model)
    pixels = PixelsHDU(model)
    aperture = ApertureHDU(model)
    images = ImagesHDU(model)
    hires = HiResHDU(model)

    # Combine to get the HDUList
    hdulist = pyfits.HDUList(
        [primary, lightcurve, pixels, aperture, images, hires])

    # Output to the FITS file
    hdulist.writeto(outfile)

    return


text:
#import <Foundation/Foundation.h>

#import "../GRPCCallOptions.h"

@interface GRPCCallOptions ()

/**
 * Parameter used for internal logging.
 */
@property(readonly) id logContext;

@end

@interface GRPCMutableCallOptions ()

/**
 * Parameter used for internal logging.
 */
@property(readwrite) id logContext;

@end


text: O nosso desafio é construir soluções práticas e sofisticadas para uma empresa que é referência mundial no segmento de beleza feminina. Essa empresa é a Sobrancelhas Design, que está presente em todo o continente americano com mais de 300 unidades.


text:
<!DOCTYPE html>

	<meta http-equiv="X-UA-Compatible" content="IE=edge" />
	<meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
	<link data-name="vs/editor/editor.main" rel="stylesheet" href="https://microsoft.github.io/monaco-editor/node_modules/monaco-editor/min/vs/editor/editor.main.css">
	<link rel="stylesheet" href="/static/tutorial-tool/tutorial.css">

MakeCode Tutorial Tool

		<button id="run-button">Run in MakeCode</button>
		<select id="endpoint-select"></select>


text:
#include <cassert>
#include <chrono>
#include <iostream>
#include <memory>
#include <vector>

#include "environment.h"
#include "heuristic.h"
#include "rocksample/context.h"
#include "rocksample/operator.h"
#include "string_registry.h"
#include "support.h"
#include "uc_search.h"

namespace rocksample {

using namespace std;

bool RockSample(bool verbose, bool input_file, float discount) {
  // operator names
  const int kNorth = StringRegistry::Get()->GetInt("north");
  const int kSouth = StringRegistry::Get()->GetInt("south");
  const int kEast = StringRegistry::Get()->GetInt("east");
  const int kWest = StringRegistry::Get()->GetInt("west");
  const int kSample = StringRegistry::Get()->GetInt("sample");
  const int kCheck = StringRegistry::Get()->GetInt("check");
  const int kNoop = StringRegistry::Get()->GetInt("noop");

  // predicates
  const int kX = StringRegistry::Get()->GetInt("x");
  const int kY = StringRegistry::Get()->GetInt("y");
  const int kSampled = StringRegistry::Get()->GetInt("sampled");
  const int kBRockGood = StringRegistry::Get()->GetInt("rock_good");
  const int kTerminated = StringRegistry::Get()->GetInt("terminated");
  const int kSteps = StringRegistry::Get()->GetInt("steps");

  int num_locs;
  int num_rocks;
  vector<int> rock_locs;
  int robot_x;
  int robot_y;
  vector<float> rock_qualities;
  vector<float> rock_sampled;

  // read domain description from redirected input file
  if (input_file) {
    // environment
    if (!(cin >> num_locs)) {
      cout << "Invalid domain description file format" << endl;
      return -1;
    }

    if (!(cin >> num_rocks)) {
      cout << "Invalid domain description file format" << endl;
      return -1;
    }

    for (int rock = 0; rock < num_rocks; ++rock) {
      int rock_x;
      if (!(cin >> rock_x)) {
        cout << "Invalid domain description file format" << endl;
        return -1;
      }
      rock_locs.push_back(rock_x);

      int rock_y;
      if (!(cin >> rock_y)) {
        cout << "Invalid domain description file format" << endl;
        return -1;
      }
      rock_locs.push_back(rock_y);
    }

    for (int rock = 0; rock < num_rocks; ++rock) {
      float rock_q;
      if (!(cin >> rock_q)) {
        cout << "Invalid domain description file format" << endl;
        return -1;
      }
      rock_qualities.push_back(rock_q);
    }

    for (int rock = 0; rock < num_rocks; ++rock) {
      float rock_s;
      if (!(cin >> rock_s)) {
        cout << "Invalid domain description file format" << endl;
        return -1;
      }
      rock_sampled.push_back(rock_s);
    }

    // start position
    if (!(cin >> robot_x)) {
      cout << "Invalid domain description file format" << endl;
      return -1;
    }

    if (!(cin >> robot_y)) {
      cout << "Invalid domain description file format" << endl;
      return -1;
    }
  } else {
    // realy tiny

    /*
    // environment
    num_locs = 1;
    num_rocks = 1;
    rock_locs.push_back(0);
    rock_locs.push_back(0);

    rock_qualities.push_back(0.5f);

    rock_sampled.push_back(0.f);

    // start position
    robot_x = 0;
    robot_y = 0;
    */

    // tiny

    // environment
    num_locs = 2;
    num_rocks = 2;
    rock_locs.push_back(0);
    rock_locs.push_back(0);
    rock_locs.push_back(1);
    rock_locs.push_back(1);

    rock_qualities.push_back(0.5f);
    rock_qualities.push_back(0.5f);

    rock_sampled.push_back(0.f);
    rock_sampled.push_back(0.f);

    // start position
    robot_x = 0;
    robot_y = 1;
  }

  assert((rock_locs.size() / 2) == num_rocks);
  assert((rock_locs.size() % 2) == 0);
  assert(robot_x >= 0 && robot_x < num_locs);
  assert(robot_y >= 0 && robot_y < num_locs);

  Environment env(num_locs, num_rocks, rock_locs);
  // generate start state
  unique_ptr<State> start_state(new State({Fluent(kX, {}, robot_x, 1.f),
                                           Fluent(kY, {}, robot_y, 1.f)}));
  for (int rock = 0; rock < num_rocks; rock++) {
    start_state -> Add(Fluent(kSampled, {}, rock, rock_sampled[rock]));
    // initially, rocks have a 50% chance of being good
    start_state -> Add(Fluent(kBRockGood, {}, rock, rock_qualities[rock]));
  }
  start_state -> Add(Fluent(kSteps, {}, 0, 0.f));

  // goal state (terminated and off the right edge of the map after expected num steps)
  unique_ptr<State> goal_state(new State({Fluent(kTerminated, {}, 0, 1.f),
                                          Fluent(kX, {}, num_locs, 1.f),
                                          Fluent(kSteps, {}, 0, 1.f/(1.f - discount))}));
  const vector<const State*> goal_set = {goal_state.get()};

  bool log_cost = true;
  float move_cost_multiplier = 1.f;
  float sample_cost_multiplier = 1.f;
  float check_cost_multiplier = 1.f;
  // all action probs are 1/(1-y) and all action obs are 1
  unique_ptr<Operator> north_op(new NorthOperator(kNorth, discount, move_cost_multiplier, log_cost));
  unique_ptr<Operator> south_op(new SouthOperator(kSouth, discount, move_cost_multiplier, log_cost));
  unique_ptr<Operator> east_op(new EastOperator(kEast, discount, move_cost_multiplier, log_cost));
  unique_ptr<Operator> west_op(new WestOperator(kWest, discount, move_cost_multiplier, log_cost));
  unique_ptr<Operator> sample_op(new SampleOperator(kSample, discount, sample_cost_multiplier, log_cost));
  unique_ptr<Operator> check_op(new CheckOperator(kCheck, discount, check_cost_multiplier, log_cost));
  unique_ptr<Operator> no_op(new NoOperator(kNoop, 1.f, 1.f, log_cost));
  const vector<const ::Operator*> operators = {north_op.get(), south_op.get(), east_op.get(), west_op.get(), sample_op.get(), check_op.get(), no_op.get()};

  return Search(move(start_state), goal_set, operators, env, HZero(), verbose);
}

} // namespace rocksample


text:
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE chapter SYSTEM "chapter.dtd">

<chapter>

    <copyright>
      <year>1997</year><year>2013</year>
      <holder>Ericsson AB. All Rights Reserved.</holder>
    </copyright>
    <legalnotice>
      Licensed under the Apache License, Version 2.0 (the "License");
      you may not use this file except in compliance with the License.
      You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

      Unless required by applicable law or agreed to in writing, software
      distributed under the License is distributed on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      See the License for the specific language governing permissions and
      limitations under the License.

    </legalnotice>

    <title>Windows NT</title>
    <prepared>Kenneth Lundin</prepared>
    <responsible>Kenneth Lundin</responsible>
    <docno></docno>
    <approved></approved>
    <checked></checked>
    <date>1997-11-25</date>
    <rev>PA2</rev>
    <file>embedded_nt.xml</file>

  <marker id="windows nt"></marker>

This section describes the operating system-specific parts of OTP
    that relate to Windows NT.

A normal installation of Windows NT 4.0, with Service Pack 4 or
    later, is required for an embedded Windows NT running OTP.

    <title>Memory Use</title>

RAM memory of 96 MB is recommended to run OTP on Windows NT.
      A system with less than 64 MB of RAM is not recommended.

    <title>Disk Space Use</title>

A minimum Windows NT installation with networking needs 250 MB,
      and an extra 130 MB for the swap file.

    <title>Installing an Embedded System</title>

Normal Windows NT installation is performed. No additional
      application programs are needed, such as Internet Explorer or
      web server. Networking with TCP/IP is required.

Service Pack 4 or later must be installed.

      <title>Hardware Watchdog</title>

For Windows NT running on standard PCs with ISA and/or PCI bus,
        an extension card with a hardware watchdog can be installed.

For more information, see the <c>heart(3)</c> manual page in
        <c>kernel</c>.

    <title>Starting Erlang</title>

On an embedded system, the <c>erlsrv</c> module is to be used
      to install the Erlang process as a Windows system service.
      This service can start after Windows NT has booted.

For more information, see the <c>erlsrv</c> manual page
      in <c>erts</c>.

</chapter>