text:
package com.intellij.util.xml;

import java.util.Arrays;

import com.intellij.codeInspection.InspectionManager;
import com.intellij.ide.highlighter.XmlFileType;
import com.intellij.lang.annotation.HighlightSeverity;
import com.intellij.psi.PsiFileFactory;
import com.intellij.psi.xml.XmlFile;
import com.intellij.psi.xml.XmlTag;
import com.intellij.util.xml.highlighting.DomElementAnnotationsManager;
import com.intellij.util.xml.highlighting.DomElementProblemDescriptorImpl;
import com.intellij.util.xml.highlighting.DomElementsProblemsHolder;
import com.intellij.util.xml.highlighting.DomElementsProblemsHolderImpl;
import com.intellij.util.xml.highlighting.MockDomInspection;

/**
 * @author peter
 */
public abstract class DomAnnotationsTest extends DomTestCase{

  @Override
  protected <T extends DomElement> T createElement(final String xml, final Class<T> aClass) {
    final String name = "a.xml";
    final XmlFile file = (XmlFile)PsiFileFactory.getInstance(getProject()).createFileFromText(name, XmlFileType.INSTANCE, xml, 0,
                                                                                true);
    final XmlTag tag = file.getDocument().getRootTag();
    final String rootTagName = tag != null ? tag.getName() : "root";
    final T element = getDomManager().getFileElement(file, aClass, rootTagName).getRootElement();
    assertNotNull(element);
    assertSame(tag, element.getXmlTag());
    return element;
  }

  public void testResolveProblemsAreReportedOnlyOnce() throws Throwable {
    final MyElement myElement = createElement("<my-class>abc</my-class>", MyElement.class);

    new MockDomInspection(MyElement.class).checkFile(DomUtil.getFile(myElement), InspectionManager.getInstance(getProject()), true);
    final DomElementsProblemsHolder holder = DomElementAnnotationsManager.getInstance(getProject()).getProblemHolder(myElement);

    final DomElement element = myElement.getMyClass();
    assertEquals(0, holder.getProblems(myElement).size());
    assertEquals(0, holder.getProblems(myElement).size());
    assertEquals(1, holder.getProblems(element).size());
    assertEquals(1, holder.getProblems(element).size());
    assertEquals(1, holder.getProblems(myElement, true, true).size());
    assertEquals(1, holder.getProblems(myElement, true, true).size());
  }

  public void testMinSeverity() throws Throwable {
    final MyElement element = createElement("", MyElement.class);
    final DomElementsProblemsHolderImpl holder = new DomElementsProblemsHolderImpl(DomUtil.getFileElement(element));
    final DomElementProblemDescriptorImpl error = new DomElementProblemDescriptorImpl(element, "abc", HighlightSeverity.ERROR);
    final DomElementProblemDescriptorImpl warning = new DomElementProblemDescriptorImpl(element, "abc", HighlightSeverity.WARNING);
    holder.addProblem(error, MockDomInspection.class);
    holder.addProblem(warning, MockDomInspection.class);
    assertEquals(Arrays.asList(error), holder.getProblems(element, true, true, HighlightSeverity.ERROR));
    assertEquals(Arrays.asList(error, warning), holder.getProblems(element, true, true, HighlightSeverity.WARNING));
  }

  public interface MyElement extends DomElement{
    GenericDomValue<String> getMyClass();
  }

}


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!--

-->
<templates><template autoinsert="true" context="java" deleted="false" description="init method for junit 4" enabled="true" name="b4">${before:import('org.junit.Before')}${initMocks:importStatic('org.mockito.MockitoAnnotations.*')}
@${:newType(org.junit.Before)}
public void initBeforeTest() throws Exception {
	initMocks(this);
	${cursor}
}</template><template autoinsert="true" context="java" deleted="false" description="Junit 4 for testing exception" enabled="true" name="te">${:import('org.junit.Test')}
@${annotation:newType(org.junit.Test)}(expected=${expectionname}.class)
public void should_throw_${testname}_when() throws Exception {
	${cursor}
}</template><template autoinsert="true" context="java-members" deleted="false" description="test method (JUnit 4)" enabled="true" name="tt">${staticImport:importStatic('org.junit.Assert.*')}${staticImport1:importStatic('org.mockito.Mockito.*')}${staticImport2:importStatic('org.mockito.MockitoAnnotations.Mock')}
@${:newType(org.junit.Test)}
public void should_${testname}() throws Exception {
	${cursor}
}</template></templates>

redpajama_set_name: RedPajamaGithub


text:
using NodaTime;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using jaytwo.Common.Extensions;

namespace jaytwo.TimeZones.Test.TimeZones
{
    [TestFixture]
    public static class DurationExtensionsTests
    {
        private static Duration GetDuration(TimeSpan value)
        {
            return Duration.FromTimeSpan(value);
        }

        private static Duration? GetDuration(TimeSpan? value)
        {
            if (value.HasValue)
            {
                return Duration.FromTimeSpan(value.Value);
            }
            else
            {
                return null;
            }
        }

        #region GetTotalDays
        private static IEnumerable<TestCaseData> GetTotalDays_TestCases()
        {
            yield return new TestCaseData(TimeSpan.FromHours(12)).Returns(0.5d);
            yield return new TestCaseData(TimeSpan.FromHours(24)).Returns(1d);
            yield return new TestCaseData(TimeSpan.FromHours(36)).Returns(1.5d);
            yield return new TestCaseData(TimeSpan.FromHours(48)).Returns(2d);
        }

        [Test]
        [TestCaseSource("GetTotalDays_TestCases")]
        public static double NodaTimeHelpers_GetTotalDays(TimeSpan timespan)
        {
            return NodaTimeHelpers.GetTotalDays(GetDuration(timespan));
        }

        [Test]
        [TestCaseSource("GetTotalDays_TestCases")]
        [TestCase(null, Result = null)]
        public static double? NodaTimeHelpers_GetTotalDays_Nullable(TimeSpan? timespan)
        {
            return NodaTimeHelpers.GetTotalDays(GetDuration(timespan));
        }

        [Test]
        [TestCaseSource("GetTotalDays_TestCases")]
        public static double DurationExtensions_GetTotalDays(TimeSpan timespan)
        {
            return GetDuration(timespan).GetTotalDays();
        }

        [Test]
        [TestCaseSource("GetTotalDays_TestCases")]
        [TestCase(null, Result = null)]
        public static double? DurationExtensions_GetTotalDays_Nullable(TimeSpan? timespan)
        {
            return GetDuration(timespan).GetTotalDays();
        }
        #endregion

        #region GetTotalHours
        private static IEnumerable<TestCaseData> GetTotalHours_TestCases()
        {
            yield return new TestCaseData(TimeSpan.FromMinutes(30)).Returns(0.5d);
            yield return new TestCaseData(TimeSpan.FromMinutes(60)).Returns(1d);
            yield return new TestCaseData(TimeSpan.FromMinutes(90)).Returns(1.5d);
            yield return new TestCaseData(TimeSpan.FromMinutes(120)).Returns(2d);
        }

        [Test]
        [TestCaseSource("GetTotalHours_TestCases")]
        public static double NodaTimeHelpers_GetTotalHours(TimeSpan timespan)
        {
            return NodaTimeHelpers.GetTotalHours(GetDuration(timespan));
        }

        [Test]
        [TestCaseSource("GetTotalHours_TestCases")]
        [TestCase(null, Result = null)]
        public static double? NodaTimeHelpers_GetTotalHours_Nullable(TimeSpan? timespan)
        {
            return NodaTimeHelpers.GetTotalHours(GetDuration(timespan));
        }

        [Test]
        [TestCaseSource("GetTotalHours_TestCases")]
        public static double DurationExtensions_GetTotalHours(TimeSpan timespan)
        {
            return GetDuration(timespan).GetTotalHours();
        }

        [Test]
        [TestCaseSource("GetTotalHours_TestCases")]
        [TestCase(null, Result = null)]
        public static double? DurationExtensions_GetTotalHours_Nullable(TimeSpan? timespan)
        {
            return GetDuration(timespan).GetTotalHours();
        }
        #endregion

        #region GetTotalMinutes
        private static IEnumerable<TestCaseData> GetTotalMinutes_TestCases()
        {
            yield return new TestCaseData(TimeSpan.FromSeconds(30)).Returns(0.5d);
            yield return new TestCaseData(TimeSpan.FromSeconds(60)).Returns(1d);
            yield return new TestCaseData(TimeSpan.FromSeconds(90)).Returns(1.5d);
            yield return new TestCaseData(TimeSpan.FromSeconds(120)).Returns(2d);
        }

        [Test]
        [TestCaseSource("GetTotalMinutes_TestCases")]
        public static double NodaTimeHelpers_GetTotalMinutes(TimeSpan timespan)
        {
            return NodaTimeHelpers.GetTotalMinutes(GetDuration(timespan));
        }

        [Test]
        [TestCaseSource("GetTotalMinutes_TestCases")]
        [TestCase(null, Result = null)]
        public static double? NodaTimeHelpers_GetTotalMinutes_Nullable(TimeSpan? timespan)
        {
            return NodaTimeHelpers.GetTotalMinutes(GetDuration(timespan));
        }

        [Test]
        [TestCaseSource("GetTotalMinutes_TestCases")]
        public static double DurationExtensions_GetTotalMinutes(TimeSpan timespan)
        {
            return GetDuration(timespan).GetTotalMinutes();
        }

        [Test]
        [TestCaseSource("GetTotalMinutes_TestCases")]
        [TestCase(null, Result = null)]
        public static double? DurationExtensions_GetTotalMinutes_Nullable(TimeSpan? timespan)
        {
            return GetDuration(timespan).GetTotalMinutes();
        }
        #endregion

        #region GetTotalSeconds
        private static IEnumerable<TestCaseData> GetTotalSeconds_TestCases()
        {
            yield return new TestCaseData(TimeSpan.FromMilliseconds(500)).Returns(0.5d);
            yield return new TestCaseData(TimeSpan.FromMilliseconds(1000)).Returns(1d);
            yield return new TestCaseData(TimeSpan.FromMilliseconds(1500)).Returns(1.5d);
            yield return new TestCaseData(TimeSpan.FromMilliseconds(2000)).Returns(2d);
        }

        [Test]
        [TestCaseSource("GetTotalSeconds_TestCases")]
        public static double NodaTimeHelpers_GetTotalSeconds(TimeSpan timespan)
        {
            return NodaTimeHelpers.GetTotalSeconds(GetDuration(timespan));
        }

        [Test]
        [TestCaseSource("GetTotalSeconds_TestCases")]
        [TestCase(null, Result = null)]
        public static double? NodaTimeHelpers_GetTotalSeconds_Nullable(TimeSpan? timespan)
        {
            return NodaTimeHelpers.GetTotalSeconds(GetDuration(timespan));
        }

        [Test]
        [TestCaseSource("GetTotalSeconds_TestCases")]
        public static double DurationExtensions_GetTotalSeconds(TimeSpan timespan)
        {
            return GetDuration(timespan).GetTotalSeconds();
        }

        [Test]
        [TestCaseSource("GetTotalSeconds_TestCases")]
        [TestCase(null, Result = null)]
        public static double? DurationExtensions_GetTotalSeconds_Nullable(TimeSpan? timespan)
        {
            return GetDuration(timespan).GetTotalSeconds();
        }
        #endregion

        #region GetTotalMilliseconds
        private static IEnumerable<TestCaseData> GetTotalMilliseconds_TestCases()
        {
            yield return new TestCaseData(TimeSpan.FromMilliseconds(500)).Returns(500d);
            yield return new TestCaseData(TimeSpan.FromMilliseconds(1000)).Returns(1000d);
            yield return new TestCaseData(TimeSpan.FromMilliseconds(1500)).Returns(1500d);
            yield return new TestCaseData(TimeSpan.FromMilliseconds(2000)).Returns(2000d);
        }

        [Test]
        [TestCaseSource("GetTotalMilliseconds_TestCases")]
        public static double NodaTimeHelpers_GetTotalMilliseconds(TimeSpan timespan)
        {
            return NodaTimeHelpers.GetTotalMilliseconds(GetDuration(timespan));
        }

        [Test]
        [TestCaseSource("GetTotalMilliseconds_TestCases")]
        [TestCase(null, Result = null)]
        public static double? NodaTimeHelpers_GetTotalMilliseconds_Nullable(TimeSpan? timespan)
        {
            return NodaTimeHelpers.GetTotalMilliseconds(GetDuration(timespan));
        }

        [Test]
        [TestCaseSource("GetTotalMilliseconds_TestCases")]
        public static double DurationExtensions_GetTotalMilliseconds(TimeSpan timespan)
        {
            return GetDuration(timespan).GetTotalMilliseconds();
        }

        [Test]
        [TestCaseSource("GetTotalMilliseconds_TestCases")]
        [TestCase(null, Result = null)]
        public static double? DurationExtensions_GetTotalMilliseconds_Nullable(TimeSpan? timespan)
        {
            return GetDuration(timespan).GetTotalMilliseconds();
        }
        #endregion
    }
}


text:
package runtime

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"reflect"

	"google.golang.org/protobuf/encoding/protojson"
	"google.golang.org/protobuf/proto"
)

// JSONPb is a Marshaler which marshals/unmarshals into/from JSON
// with the "google.golang.org/protobuf/encoding/protojson" marshaler.
// It supports the full functionality of protobuf unlike JSONBuiltin.
//
// The NewDecoder method returns a DecoderWrapper, so the underlying
// *json.Decoder methods can be used.
type JSONPb struct {
	protojson.MarshalOptions
	protojson.UnmarshalOptions
}

// ContentType always returns "application/json".
func (*JSONPb) ContentType(_ interface{}) string {
	return "application/json"
}

// Marshal marshals "v" into JSON.
func (j *JSONPb) Marshal(v interface{}) ([]byte, error) {
	if _, ok := v.(proto.Message); !ok {
		return j.marshalNonProtoField(v)
	}

	var buf bytes.Buffer
	if err := j.marshalTo(&buf, v); err != nil {
		return nil, err
	}
	return buf.Bytes(), nil
}

func (j *JSONPb) marshalTo(w io.Writer, v interface{}) error {
	p, ok := v.(proto.Message)
	if !ok {
		buf, err := j.marshalNonProtoField(v)
		if err != nil {
			return err
		}
		_, err = w.Write(buf)
		return err
	}
	b, err := j.MarshalOptions.Marshal(p)
	if err != nil {
		return err
	}

	_, err = w.Write(b)
	return err
}

var (
	// protoMessageType is stored to prevent constant lookup of the same type at runtime.
	protoMessageType = reflect.TypeOf((*proto.Message)(nil)).Elem()
)

// marshalNonProto marshals a non-message field of a protobuf message.
// This function does not correctly marshal arbitrary data structures into JSON,
// it is only capable of marshaling non-message field values of protobuf,
// i.e. primitive types, enums; pointers to primitives or enums; maps from
// integer/string types to primitives/enums/pointers to messages.
func (j *JSONPb) marshalNonProtoField(v interface{}) ([]byte, error) {
	if v == nil {
		return []byte("null"), nil
	}
	rv := reflect.ValueOf(v)
	for rv.Kind() == reflect.Ptr {
		if rv.IsNil() {
			return []byte("null"), nil
		}
		rv = rv.Elem()
	}

	if rv.Kind() == reflect.Slice {
		if rv.IsNil() {
			if j.EmitUnpopulated {
				return []byte("[]"), nil
			}
			return []byte("null"), nil
		}

		if rv.Type().Elem().Implements(protoMessageType) {
			var buf bytes.Buffer
			err := buf.WriteByte('[')
			if err != nil {
				return nil, err
			}
			for i := 0; i < rv.Len(); i++ {
				if i != 0 {
					err = buf.WriteByte(',')
					if err != nil {
						return nil, err
					}
				}
				if err = j.marshalTo(&buf, rv.Index(i).Interface().(proto.Message)); err != nil {
					return nil, err
				}
			}
			err = buf.WriteByte(']')
			if err != nil {
				return nil, err
			}

			return buf.Bytes(), nil
		}
	}

	if rv.Kind() == reflect.Map {
		m := make(map[string]*json.RawMessage)
		for _, k := range rv.MapKeys() {
			buf, err := j.Marshal(rv.MapIndex(k).Interface())
			if err != nil {
				return nil, err
			}
			m[fmt.Sprintf("%v", k.Interface())] = (*json.RawMessage)(&buf)
		}
		if j.Indent != "" {
			return json.MarshalIndent(m, "", j.Indent)
		}
		return json.Marshal(m)
	}
	if enum, ok := rv.Interface().(protoEnum); ok && !j.UseEnumNumbers {
		return json.Marshal(enum.String())
	}
	return json.Marshal(rv.Interface())
}

// Unmarshal unmarshals JSON "data" into "v"
func (j *JSONPb) Unmarshal(data []byte, v interface{}) error {
	return unmarshalJSONPb(data, j.UnmarshalOptions, v)
}

// NewDecoder returns a Decoder which reads JSON stream from "r".
func (j *JSONPb) NewDecoder(r io.Reader) Decoder {
	d := json.NewDecoder(r)
	return DecoderWrapper{
		Decoder:          d,
		UnmarshalOptions: j.UnmarshalOptions,
	}
}

// DecoderWrapper is a wrapper around a *json.Decoder that adds
// support for protos to the Decode method.
type DecoderWrapper struct {
	*json.Decoder
	protojson.UnmarshalOptions
}

// Decode wraps the embedded decoder's Decode method to support
// protos using a jsonpb.Unmarshaler.
func (d DecoderWrapper) Decode(v interface{}) error {
	return decodeJSONPb(d.Decoder, d.UnmarshalOptions, v)
}

// NewEncoder returns an Encoder which writes JSON stream into "w".
func (j *JSONPb) NewEncoder(w io.Writer) Encoder {
	return EncoderFunc(func(v interface{}) error {
		if err := j.marshalTo(w, v); err != nil {
			return err
		}
		// mimic json.Encoder by adding a newline (makes output
		// easier to read when it contains multiple encoded items)
		_, err := w.Write(j.Delimiter())
		return err
	})
}

func unmarshalJSONPb(data []byte, unmarshaler protojson.UnmarshalOptions, v interface{}) error {
	d := json.NewDecoder(bytes.NewReader(data))
	return decodeJSONPb(d, unmarshaler, v)
}

func decodeJSONPb(d *json.Decoder, unmarshaler protojson.UnmarshalOptions, v interface{}) error {
	p, ok := v.(proto.Message)
	if !ok {
		return decodeNonProtoField(d, unmarshaler, v)
	}

	// Decode into bytes for marshalling
	var b json.RawMessage
	err := d.Decode(&b)
	if err != nil {
		return err
	}

	return unmarshaler.Unmarshal([]byte(b), p)
}

func decodeNonProtoField(d *json.Decoder, unmarshaler protojson.UnmarshalOptions, v interface{}) error {
	rv := reflect.ValueOf(v)
	if rv.Kind() != reflect.Ptr {
		return fmt.Errorf("%T is not a pointer", v)
	}
	for rv.Kind() == reflect.Ptr {
		if rv.IsNil() {
			rv.Set(reflect.New(rv.Type().Elem()))
		}
		if rv.Type().ConvertibleTo(typeProtoMessage) {
			// Decode into bytes for marshalling
			var b json.RawMessage
			err := d.Decode(&b)
			if err != nil {
				return err
			}

			return unmarshaler.Unmarshal([]byte(b), rv.Interface().(proto.Message))
		}
		rv = rv.Elem()
	}
	if rv.Kind() == reflect.Map {
		if rv.IsNil() {
			rv.Set(reflect.MakeMap(rv.Type()))
		}
		conv, ok := convFromType[rv.Type().Key().Kind()]
		if !ok {
			return fmt.Errorf("unsupported type of map field key: %v", rv.Type().Key())
		}

		m := make(map[string]*json.RawMessage)
		if err := d.Decode(&m); err != nil {
			return err
		}
		for k, v := range m {
			result := conv.Call([]reflect.Value{reflect.ValueOf(k)})
			if err := result[1].Interface(); err != nil {
				return err.(error)
			}
			bk := result[0]
			bv := reflect.New(rv.Type().Elem())
			if err := unmarshalJSONPb([]byte(*v), unmarshaler, bv.Interface()); err != nil {
				return err
			}
			rv.SetMapIndex(bk, bv.Elem())
		}
		return nil
	}
	if rv.Kind() == reflect.Slice {
		var sl []json.RawMessage
		if err := d.Decode(&sl); err != nil {
			return err
		}
		if sl != nil {
			rv.Set(reflect.MakeSlice(rv.Type(), 0, 0))
		}
		for _, item := range sl {
			bv := reflect.New(rv.Type().Elem())
			if err := unmarshalJSONPb([]byte(item), unmarshaler, bv.Interface()); err != nil {
				return err
			}
			rv.Set(reflect.Append(rv, bv.Elem()))
		}
		return nil
	}
	if _, ok := rv.Interface().(protoEnum); ok {
		var repr interface{}
		if err := d.Decode(&repr); err != nil {
			return err
		}
		switch v := repr.(type) {
		case string:
			// TODO(yugui) Should use proto.StructProperties?
			return fmt.Errorf("unmarshaling of symbolic enum %q not supported: %T", repr, rv.Interface())
		case float64:
			rv.Set(reflect.ValueOf(int32(v)).Convert(rv.Type()))
			return nil
		default:
			return fmt.Errorf("cannot assign %#v into Go type %T", repr, rv.Interface())
		}
	}
	return d.Decode(v)
}

type protoEnum interface {
	fmt.Stringer
	EnumDescriptor() ([]byte, []int)
}

var typeProtoMessage = reflect.TypeOf((*proto.Message)(nil)).Elem()

// Delimiter for newline encoded JSON streams.
func (j *JSONPb) Delimiter() []byte {
	return []byte("\n")
}

var (
	convFromType = map[reflect.Kind]reflect.Value{
		reflect.String:  reflect.ValueOf(String),
		reflect.Bool:    reflect.ValueOf(Bool),
		reflect.Float64: reflect.ValueOf(Float64),
		reflect.Float32: reflect.ValueOf(Float32),
		reflect.Int64:   reflect.ValueOf(Int64),
		reflect.Int32:   reflect.ValueOf(Int32),
		reflect.Uint64:  reflect.ValueOf(Uint64),
		reflect.Uint32:  reflect.ValueOf(Uint32),
		reflect.Slice:   reflect.ValueOf(Bytes),
	}
)


text:
namespace Halide {
namespace Internal {

using std::pair;

class StoreCollector : public IRMutator2 {
public:
    const std::string store_name;
    const int store_stride, max_stores;
    std::vector<Stmt> &let_stmts;
    std::vector<Stmt> &stores;

    StoreCollector(const std::string &name, int stride, int ms,
                   std::vector<Stmt> &lets,
                   std::vector<Stmt> &ss) :
        store_name(name), store_stride(stride), max_stores(ms),
        let_stmts(lets), stores(ss), collecting(true) {}
private:

    using IRMutator2::visit;

    // Don't enter any inner constructs for which it's not safe to pull out stores.
    Stmt visit(const For *op) override {collecting = false; return op;}
    Stmt visit(const IfThenElse *op) override {collecting = false; return op;}
    Stmt visit(const ProducerConsumer *op) override {collecting = false; return op;}
    Stmt visit(const Allocate *op) override {collecting = false; return op;}
    Stmt visit(const Realize *op) override {collecting = false; return op;}

    bool collecting;
    // These are lets that we've encountered since the last collected
    // store. If we collect another store, these "potential" lets
    // become lets used by the collected stores.
    std::vector<Stmt> potential_lets;

    Expr visit(const Load *op) override {
        if (!collecting) {
            return op;
        }

        // If we hit a load from the buffer we're trying to collect
        // stores for, stop collecting to avoid reordering loads and
        // stores from the same buffer.
        if (op->name == store_name) {
            collecting = false;
            return op;
        } else {
            return IRMutator2::visit(op);
        }
    }

    Stmt visit(const Store *op) override {
        if (!collecting) {
            return op;
        }

        // By default, do nothing.
        Stmt stmt = op;

        if (stores.size() >= (size_t)max_stores) {
            // Already have enough stores.
            collecting = false;
            return stmt;
        }

        // Make sure this Store doesn't do anything that causes us to
        // stop collecting.
        stmt = IRMutator2::visit(op);
        if (!collecting) {
            return stmt;
        }

        if (op->name != store_name) {
            // Not a store to the buffer we're looking for.
            return stmt;
        }

        const Ramp *r = op->index.as<Ramp>();
        if (!r || !is_const(r->stride, store_stride)) {
            // Store doesn't store to the ramp we're looking
            // for. Can't interleave it. Since we don't want to
            // reorder stores, stop collecting.
            collecting = false;
            return stmt;
        }

        // This store is good, collect it and replace with a no-op.
        stores.push_back(op);
        stmt = Evaluate::make(0);

        // Because we collected this store, we need to save the
        // potential lets since the last collected store.
        let_stmts.insert(let_stmts.end(), potential_lets.begin(), potential_lets.end());
        potential_lets.clear();
        return stmt;
    }

    Expr visit(const Call *op) override {
        if (!op->is_pure()) {
            // Avoid reordering calls to impure functions
            collecting = false;
            return op;
        } else {
            return IRMutator2::visit(op);
        }
    }

    Stmt visit(const LetStmt *op) override {
        if (!collecting) {
            return op;
        }
        Stmt stmt = IRMutator2::visit(op);

        // If we're still collecting, we need to save the let as a potential let.
        if (collecting) {
            potential_lets.push_back(op);
        }
        return stmt;
    }

    Stmt visit(const Block *op) override {
        if (!collecting) {
            return op;
        }

        Stmt first = mutate(op->first);
        Stmt rest = op->rest;
        // We might have decided to stop collecting during mutation of first.
        if (collecting) {
            rest = mutate(rest);
        }
        return Block::make(first, rest);
    }
};

Stmt collect_strided_stores(Stmt stmt, const std::string& name, int stride, int max_stores,
                            std::vector<Stmt> lets, std::vector<Stmt> &stores) {

    StoreCollector collect(name, stride, max_stores, lets, stores);
    return collect.mutate(stmt);
}

class Deinterleaver : public IRMutator2 {
public:
    int starting_lane;
    int new_lanes;
    int lane_stride;

    // lets for which we have even and odd lane specializations
    const Scope<> &external_lets;

    Deinterleaver(const Scope<> &lets) : external_lets(lets) {}

private:
    Scope<Expr> internal;

    using IRMutator2::visit;

    Expr visit(const Broadcast *op) override {
        if (new_lanes == 1) {
            return op->value;
        }
        return Broadcast::make(op->value, new_lanes);
    }

    Expr visit(const Load *op) override {
        if (op->type.is_scalar()) {
            return op;
        } else {
            Type t = op->type.with_lanes(new_lanes);
            return Load::make(t, op->name, mutate(op->index), op->image, op->param, mutate(op->predicate));
        }
    }

    Expr visit(const Ramp *op) override {
        Expr expr = op->base + starting_lane * op->stride;
        internal_assert(expr.type() == op->base.type());
        if (new_lanes > 1) {
            expr = Ramp::make(expr, op->stride * lane_stride, new_lanes);
        }
        return expr;
    }

    Expr visit(const Variable *op) override {
        if (op->type.is_scalar()) {
            return op;
        } else {

            Type t = op->type.with_lanes(new_lanes);
            if (internal.contains(op->name)) {
                return internal.get(op->name);
            } else if (external_lets.contains(op->name) &&
                       starting_lane == 0 &&
                       lane_stride == 2) {
                return Variable::make(t, op->name + ".even_lanes", op->image, op->param, op->reduction_domain);
            } else if (external_lets.contains(op->name) &&
                       starting_lane == 1 &&
                       lane_stride == 2) {
                return Variable::make(t, op->name + ".odd_lanes", op->image, op->param, op->reduction_domain);
            } else if (external_lets.contains(op->name) &&
                       starting_lane == 0 &&
                       lane_stride == 3) {
                return Variable::make(t, op->name + ".lanes_0_of_3", op->image, op->param, op->reduction_domain);
            } else if (external_lets.contains(op->name) &&
                       starting_lane == 1 &&
                       lane_stride == 3) {
                return Variable::make(t, op->name + ".lanes_1_of_3", op->image, op->param, op->reduction_domain);
            } else if (external_lets.contains(op->name) &&
                       starting_lane == 2 &&
                       lane_stride == 3) {
                return Variable::make(t, op->name + ".lanes_2_of_3", op->image, op->param, op->reduction_domain);
            } else {
                // Uh-oh, we don't know how to deinterleave this vector expression
                // Make llvm do it
                std::vector<int> indices;
                for (int i = 0; i < new_lanes; i++) {
                    indices.push_back(starting_lane + lane_stride * i);
                }
                return Shuffle::make({op}, indices);
            }
        }
    }

    Expr visit(const Cast *op) override {
        if (op->type.is_scalar()) {
            return op;
        } else {
            Type t = op->type.with_lanes(new_lanes);
            return Cast::make(t, mutate(op->value));
        }
    }

    Expr visit(const Call *op) override {
        Type t = op->type.with_lanes(new_lanes);

        // Don't mutate scalars
        if (op->type.is_scalar()) {
            return op;
        } else if (op->is_intrinsic(Call::glsl_texture_load)) {
            // glsl_texture_load returns a <uint x 4> result. Deinterleave by
            // wrapping the call in a shuffle_vector
            std::vector<int> indices;
            for (int i = 0; i < new_lanes; i++) {
                indices.push_back(i*lane_stride + starting_lane);
            }
            return Shuffle::make({op}, indices);
        } else {

            // Vector calls are always parallel across the lanes, so we
            // can just deinterleave the args.

            // Beware of other intrinsics for which this is not true!
            // Currently there's only interleave_vectors and
            // shuffle_vector.

            std::vector<Expr> args(op->args.size());
            for (size_t i = 0; i < args.size(); i++) {
                args[i] = mutate(op->args[i]);
            }

            return Call::make(t, op->name, args, op->call_type,
                              op->func, op->value_index, op->image, op->param);
        }
    }

    Expr visit(const Let *op) override {
        if (op->type.is_vector()) {
            Expr new_value = mutate(op->value);
            std::string new_name = unique_name('t');
            Type new_type = new_value.type();
            Expr new_var = Variable::make(new_type, new_name);
            Expr body;
            {
                ScopedBinding<Expr> p(internal, op->name, new_var);
                body = mutate(op->body);
            }

            // Define the new name.
            Expr expr = Let::make(new_name, new_value, body);

            // Someone might still use the old name.
            return Let::make(op->name, op->value, expr);
        } else {
            return IRMutator2::visit(op);
        }
    }

    Expr visit(const Shuffle *op) override {
        if (op->is_interleave()) {
            internal_assert(starting_lane >= 0 && starting_lane < lane_stride);
            if ((int)op->vectors.size() == lane_stride) {
                return op->vectors[starting_lane];
            } else if ((int)op->vectors.size() % lane_stride == 0) {
                // Pick up every lane-stride vector.
                std::vector<Expr> new_vectors(op->vectors.size() / lane_stride);
                for (size_t i = 0; i < new_vectors.size(); i++) {
                    new_vectors[i] = op->vectors[i*lane_stride + starting_lane];
                }
                return Shuffle::make_interleave(new_vectors);
            } else {
                // Interleave some vectors then deinterleave by some other factor...
                // Brute force!
                std::vector<int> indices;
                for (int i = 0; i < new_lanes; i++) {
                    indices.push_back(i*lane_stride + starting_lane);
                }
                return Shuffle::make({op}, indices);
            }
        } else {
            // Extract every nth numeric arg to the shuffle.
            std::vector<int> indices;
            for (int i = 0; i < new_lanes; i++) {
                int idx = i * lane_stride + starting_lane;
                indices.push_back(op->indices[idx]);
            }
            return Shuffle::make({op}, indices);
        }
    }
};

Expr extract_odd_lanes(Expr e, const Scope<> &lets) {
    internal_assert(e.type().lanes() % 2 == 0);
    Deinterleaver d(lets);
    d.starting_lane = 1;
    d.lane_stride = 2;
    d.new_lanes = e.type().lanes()/2;
    e = d.mutate(e);
    return simplify(e);
}

Expr extract_even_lanes(Expr e, const Scope<> &lets) {
    internal_assert(e.type().lanes() % 2 == 0);
    Deinterleaver d(lets);
    d.starting_lane = 0;
    d.lane_stride = 2;
    d.new_lanes = (e.type().lanes()+1)/2;
    e = d.mutate(e);
    return simplify(e);
}

Expr extract_even_lanes(Expr e) {
    internal_assert(e.type().lanes() % 2 == 0);
    Scope<> lets;
    return extract_even_lanes(e, lets);
}

Expr extract_odd_lanes(Expr e) {
    internal_assert(e.type().lanes() % 2 == 0);
    Scope<> lets;
    return extract_odd_lanes(e, lets);
}

Expr extract_mod3_lanes(Expr e, int lane, const Scope<> &lets) {
    internal_assert(e.type().lanes() % 3 == 0);
    Deinterleaver d(lets);
    d.starting_lane = lane;
    d.lane_stride = 3;
    d.new_lanes = (e.type().lanes()+2)/3;
    e = d.mutate(e);
    return simplify(e);
}

Expr extract_lane(Expr e, int lane) {
    Scope<> lets;
    Deinterleaver d(lets);
    d.starting_lane = lane;
    d.lane_stride = e.type().lanes();
    d.new_lanes = 1;
    e = d.mutate(e);
    return simplify(e);
}

class Interleaver : public IRMutator2 {
    Scope<ModulusRemainder> alignment_info;

    Scope<> vector_lets;

    using IRMutator2::visit;

    bool should_deinterleave;
    int num_lanes;

    Expr deinterleave_expr(Expr e) {
        if (e.type().lanes() <= num_lanes) {
            // Just scalarize
            return e;
        } else if (num_lanes == 2) {
            Expr a = extract_even_lanes(e, vector_lets);
            Expr b = extract_odd_lanes(e, vector_lets);
            return Shuffle::make_interleave({a, b});
        } else if (num_lanes == 3) {
            Expr a = extract_mod3_lanes(e, 0, vector_lets);
            Expr b = extract_mod3_lanes(e, 1, vector_lets);
            Expr c = extract_mod3_lanes(e, 2, vector_lets);
            return Shuffle::make_interleave({a, b, c});
        } else if (num_lanes == 4) {
            Expr a = extract_even_lanes(e, vector_lets);
            Expr b = extract_odd_lanes(e, vector_lets);
            Expr aa = extract_even_lanes(a, vector_lets);
            Expr ab = extract_odd_lanes(a, vector_lets);
            Expr ba = extract_even_lanes(b, vector_lets);
            Expr bb = extract_odd_lanes(b, vector_lets);
            return Shuffle::make_interleave({aa, ba, ab, bb});
        } else {
            // Give up and don't do anything clever for >4
            return e;
        }
    }

    template<typename T, typename Body>
    Body visit_let(const T *op) {
        Expr value = mutate(op->value);
        if (value.type() == Int(32)) {
            alignment_info.push(op->name, modulus_remainder(value, alignment_info));
        }

        if (value.type().is_vector()) {
            vector_lets.push(op->name);
        }
        Body body = mutate(op->body);
        if (value.type().is_vector()) {
            vector_lets.pop(op->name);
        }
        if (value.type() == Int(32)) {
            alignment_info.pop(op->name);
        }

        Body result;
        if (value.same_as(op->value) && body.same_as(op->body)) {
            result = op;
        } else {
            result = T::make(op->name, value, body);
        }

        // For vector lets, we may additionally need a let defining the even and odd lanes only
        if (value.type().is_vector()) {
            if (value.type().lanes() % 2 == 0) {
                result = T::make(op->name + ".even_lanes", extract_even_lanes(value, vector_lets), result);
                result = T::make(op->name + ".odd_lanes", extract_odd_lanes(value, vector_lets), result);
            }
            if (value.type().lanes() % 3 == 0) {
                result = T::make(op->name + ".lanes_0_of_3", extract_mod3_lanes(value, 0, vector_lets), result);
                result = T::make(op->name + ".lanes_1_of_3", extract_mod3_lanes(value, 1, vector_lets), result);
                result = T::make(op->name + ".lanes_2_of_3", extract_mod3_lanes(value, 2, vector_lets), result);
            }
        }

        return result;
    }

    Expr visit(const Let *op) override {
        return visit_let<Let, Expr>(op);
    }

    Stmt visit(const LetStmt *op) override {
        return visit_let<LetStmt, Stmt>(op);
    }

    Expr visit(const Mod *op) override {
        const Ramp *r = op->a.as<Ramp>();
        for (int i = 2; i <= 4; ++i) {
            if (r &&
                is_const(op->b, i) &&
                (r->type.lanes() % i) == 0) {
                should_deinterleave = true;
                num_lanes = i;
                break;
            }
        }
        return IRMutator2::visit(op);
    }

    Expr visit(const Div *op) override {
        const Ramp *r = op->a.as<Ramp>();
        for (int i = 2; i <= 4; ++i) {
            if (r &&
                is_const(op->b, i) &&
                (r->type.lanes() % i) == 0) {
                should_deinterleave = true;
                num_lanes = i;
                break;
            }
        }
        return IRMutator2::visit(op);
    }

    Expr visit(const Call *op) override {
        if (!op->is_pure()) {
            // deinterleaving potentially changes the order of execution.
            should_deinterleave = false;
        }
        return IRMutator2::visit(op);
    }

    Expr visit(const Load *op) override {
        bool old_should_deinterleave = should_deinterleave;
        int old_num_lanes = num_lanes;

        should_deinterleave = false;
        Expr idx = mutate(op->index);
        bool should_deinterleave_idx = should_deinterleave;

        should_deinterleave = false;
        Expr predicate = mutate(op->predicate);
        bool should_deinterleave_predicate = should_deinterleave;

        Expr expr;
        if (should_deinterleave_idx && (should_deinterleave_predicate || is_one(predicate))) {
            // If we want to deinterleave both the index and predicate
            // (or the predicate is one), then deinterleave the
            // resulting load.
            expr = Load::make(op->type, op->name, idx, op->image, op->param, predicate);
            expr = deinterleave_expr(expr);
        } else if (should_deinterleave_idx) {
            // If we only want to deinterleave the index and not the
            // predicate, deinterleave the index prior to the load.
            idx = deinterleave_expr(idx);
            expr = Load::make(op->type, op->name, idx, op->image, op->param, predicate);
        } else if (should_deinterleave_predicate) {
            // Similarly, deinterleave the predicate prior to the load
            // if we don't want to deinterleave the index.
            predicate = deinterleave_expr(predicate);
            expr = Load::make(op->type, op->name, idx, op->image, op->param, predicate);
        } else if (!idx.same_as(op->index) || !predicate.same_as(op->index)) {
            expr = Load::make(op->type, op->name, idx, op->image, op->param, predicate);
        } else {
            expr = op;
        }

        should_deinterleave = old_should_deinterleave;
        num_lanes = old_num_lanes;
        return expr;
    }

    Stmt visit(const Store *op) override {
        bool old_should_deinterleave = should_deinterleave;
        int old_num_lanes = num_lanes;

        should_deinterleave = false;
        Expr idx = mutate(op->index);
        if (should_deinterleave) {
            idx = deinterleave_expr(idx);
        }

        should_deinterleave = false;
        Expr value = mutate(op->value);
        if (should_deinterleave) {
            value = deinterleave_expr(value);
        }

        should_deinterleave = false;
        Expr predicate = mutate(op->predicate);
        if (should_deinterleave) {
            predicate = deinterleave_expr(predicate);
        }

        Stmt stmt = Store::make(op->name, value, idx, op->param, predicate);

        should_deinterleave = old_should_deinterleave;
        num_lanes = old_num_lanes;

        return stmt;
    }

    Stmt visit(const Block *op) override {
        const LetStmt *let = op->first.as<LetStmt>();
        const Store *store = op->first.as<Store>();

        {
            // This isn't really a true block, so there can't be multiple
            // stores to collapse.
            if (!op->rest.defined()) goto fail;

            // Gather all the let stmts surrounding the first.
            std::vector<Stmt> let_stmts;
            while (let) {
                let_stmts.push_back(let);
                store = let->body.as<Store>();
                let = let->body.as<LetStmt>();
            }

            // There was no inner store.
            if (!store) goto fail;

            const Ramp *r0 = store->index.as<Ramp>();

            // It's not a store of a ramp index.
            if (!r0) goto fail;

            const int64_t *stride_ptr = as_const_int(r0->stride);

            // The stride isn't a constant or is <= 0
            if (!stride_ptr || *stride_ptr < 1) goto fail;

            const int64_t stride = *stride_ptr;
            const int lanes = r0->lanes;
            const int64_t expected_stores = stride == 1 ? lanes : stride;

            // Collect the rest of the stores.
            std::vector<Stmt> stores;
            stores.push_back(store);
            Stmt rest = collect_strided_stores(op->rest, store->name,
                                               stride, expected_stores,
                                               let_stmts, stores);

            // Check the store collector didn't collect too many
            // stores (that would be a bug).
            internal_assert(stores.size() <= (size_t)expected_stores);

            // Not enough stores collected.
            if (stores.size() != (size_t)expected_stores) goto fail;

            Type t = store->value.type();
            Expr base;
            std::vector<Expr> args(stores.size());
            std::vector<Expr> predicates(stores.size());

            int min_offset = 0;
            std::vector<int> offsets(stores.size());

            std::string load_name;
            Buffer<> load_image;
            Parameter load_param;
            for (size_t i = 0; i < stores.size(); ++i) {
                const Ramp *ri = stores[i].as<Store>()->index.as<Ramp>();
                internal_assert(ri);

                // Mismatched store vector laness.
                if (ri->lanes != lanes) goto fail;

                Expr diff = simplify(ri->base - r0->base);
                const int64_t *offs = as_const_int(diff);

                // Difference between bases is not constant.
                if (!offs) goto fail;

                offsets[i] = *offs;
                if (*offs < min_offset) {
                    min_offset = *offs;
                }

                if (stride == 1) {
                    // Difference between bases is not a multiple of the lanes.
                    if (*offs % lanes != 0) goto fail;

                    // This case only triggers if we have an immediate load of the correct stride on the RHS.
                    // TODO: Could we consider mutating the RHS so that we can handle more complex Expr's than just loads?
                    const Load *load = stores[i].as<Store>()->value.as<Load>();
                    if (!load) goto fail;
                    // TODO(psuriana): Predicated load is not currently handled.
                    if (!is_one(load->predicate)) goto fail;

                    const Ramp *ramp = load->index.as<Ramp>();
                    if (!ramp) goto fail;

                    // Load stride or lanes is not equal to the store lanes.
                    if (!is_const(ramp->stride, lanes) || ramp->lanes != lanes) goto fail;

                    if (i == 0) {
                        load_name  = load->name;
                        load_image = load->image;
                        load_param = load->param;
                    } else {
                        if (load->name != load_name) goto fail;
                    }
                }
            }

            // Gather the args for interleaving.
            for (size_t i = 0; i < stores.size(); ++i) {
                int j = offsets[i] - min_offset;
                if (stride == 1) {
                    j /= stores.size();
                }

                if (j == 0) {
                    base = stores[i].as<Store>()->index.as<Ramp>()->base;
                }

                // The offset is not between zero and the stride.
                if (j < 0 || (size_t)j >= stores.size()) goto fail;

                // We already have a store for this offset.
                if (args[j].defined()) goto fail;

                if (stride == 1) {
                    // Convert multiple dense vector stores of strided vector loads
                    // into one dense vector store of interleaving dense vector loads.
                    args[j] = Load::make(t, load_name, stores[i].as<Store>()->index,
                                         load_image, load_param, const_true(t.lanes()));
                } else {
                    args[j] = stores[i].as<Store>()->value;
                }
                predicates[j] = stores[i].as<Store>()->predicate;
            }

            // One of the stores should have had the minimum offset.
            internal_assert(base.defined());

            // Generate a single interleaving store.
            t = t.with_lanes(lanes*stores.size());
            Expr index = Ramp::make(base, make_one(base.type()), t.lanes());
            Expr value = Shuffle::make_interleave(args);
            Expr predicate = Shuffle::make_interleave(predicates);
            Stmt new_store = Store::make(store->name, value, index, store->param, predicate);

            // Continue recursively into the stuff that
            // collect_strided_stores didn't collect.
            Stmt stmt = Block::make(new_store, mutate(rest));

            // Rewrap the let statements we pulled off.
            while (!let_stmts.empty()) {
                const LetStmt *let = let_stmts.back().as<LetStmt>();
                stmt = LetStmt::make(let->name, let->value, stmt);
                let_stmts.pop_back();
            }

            // Success!
            return stmt;
        }

      fail:
        // We didn't pass one of the tests. But maybe there are more
        // opportunities within. Continue recursively.
        return Block::make(mutate(op->first), mutate(op->rest));
    }
  public:
    Interleaver() : should_deinterleave(false) {}
};

Stmt rewrite_interleavings(Stmt s) {
    return Interleaver().mutate(s);
}

namespace {
void check(Expr a, Expr even, Expr odd) {
    a = simplify(a);
    Expr correct_even = extract_even_lanes(a);
    Expr correct_odd = extract_odd_lanes(a);
    if (!equal(correct_even, even)) {
        internal_error << correct_even << " != " << even << "\n";
    }
    if (!equal(correct_odd, odd)) {
        internal_error << correct_odd << " != " << odd << "\n";
    }
}
}

void deinterleave_vector_test() {
    std::pair<Expr, Expr> result;
    Expr x = Variable::make(Int(32), "x");
    Expr ramp = Ramp::make(x + 4, 3, 8);
    Expr ramp_a = Ramp::make(x + 4, 6, 4);
    Expr ramp_b = Ramp::make(x + 7, 6, 4);
    Expr broadcast = Broadcast::make(x + 4, 16);
    Expr broadcast_a = Broadcast::make(x + 4, 8);
    Expr broadcast_b = broadcast_a;

    check(ramp, ramp_a, ramp_b);
    check(broadcast, broadcast_a, broadcast_b);

    check(Load::make(ramp.type(), "buf", ramp, Buffer<>(), Parameter(), const_true(ramp.type().lanes())),
          Load::make(ramp_a.type(), "buf", ramp_a, Buffer<>(), Parameter(), const_true(ramp_a.type().lanes())),
          Load::make(ramp_b.type(), "buf", ramp_b, Buffer<>(), Parameter(), const_true(ramp_b.type().lanes())));

    std::cout << "deinterleave_vector test passed" << std::endl;
}

}
}


text:
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Linq;

namespace Correspondence.Linq
{
    public static class TaskExtensions
    {
        public static Task<B> AndThen<A,B>(
            this Task<A> asyncFirst,
            Func<A, B> second)
        {
            return asyncFirst.ContinueWith(ta => second(ta.Result));
        }

        public static async Task<B> AndThen<A,B>(
            this Task<A> asyncFirst,
            Func<A, Task<B>> asyncSecond)
        {
            return await await asyncFirst.ContinueWith(ta => asyncSecond(ta.Result));
        }

        public static async Task<IEnumerable<A>> Where<A>(
            this Task<IEnumerable<A>> asyncSource,
            Func<A, bool> predicate)
        {
            return (await asyncSource).Where(predicate);
        }

        public static async Task<IEnumerable<A>> Where<A>(
            this Task<IEnumerable<A>> asyncSource,
            Func<A, Task<bool>> asyncPredicate)
        {
            return await (await asyncSource).Where(asyncPredicate);
        }

        public static async Task<IEnumerable<A>> Where<A>(
            this IEnumerable<A> source,
            Func<A, Task<bool>> asyncPredicate)
        {
            var filtered = await source.Select(async a =>
            {
                bool condition = await asyncPredicate(a);
                return new { a, condition };
            });

            return filtered
                .Where(p => p.condition)
                .Select(p => p.a);
        }

        public static async Task<IEnumerable<B>> Select<A, B>(
            this Task<IEnumerable<A>> asyncSource,
            Func<A, B> selector)
        {
            return (await asyncSource).Select(selector);
        }

        public static async Task<IEnumerable<B>> Select<A, B>(
            this Task<IEnumerable<A>> asyncSource,
            Func<A, Task<B>> asyncSelector)
        {
            return await (await asyncSource).Select(asyncSelector);
        }

        public static async Task<IEnumerable<B>> Select<A, B>(
            this IEnumerable<A> source,
            Func<A, Task<B>> asyncSelector)
        {
            return await Task.WhenAll(Enumerable.Select(source, asyncSelector));
        }

        public static async Task<IEnumerable<A>> OrderBy<A, B>(
            this Task<IEnumerable<A>> asyncSource,
            Func<A, Task<B>> asyncKeySelector)
        {
            return await (await asyncSource).OrderBy(asyncKeySelector);
        }

        public static async Task<IEnumerable<A>> OrderBy<A, B>(
            this Task<IEnumerable<A>> asyncSource,
            Func<A, B> keySelector)
        {
            return (await asyncSource).OrderBy(keySelector);
        }

        public static async Task<IEnumerable<A>> OrderBy<A,B>(
            this IEnumerable<A> source,
            Func<A, Task<B>> asyncKeySelector)
        {
            var indexed = await source.Select(async a =>
            {
                var b = await asyncKeySelector(a);
                return new { a, b };
            });
            return indexed
                .OrderBy(p => p.b)
                .Select(p => p.a);
        }

        public static async Task<A> FirstOrDefault<A>(
            this Task<IEnumerable<A>> asyncSource)
        {
            return (await asyncSource).FirstOrDefault();
        }

        public static async Task<A> FirstOrDefault<A>(
            this Task<IEnumerable<A>> asyncSource,
            Func<A, bool> predicate)
        {
            return (await asyncSource).FirstOrDefault(predicate);
        }

        public static async Task<A> LastOrDefault<A>(
            this Task<IEnumerable<A>> asyncSource)
        {
            return (await asyncSource).LastOrDefault();
        }

        public static async Task<A> LastOrDefault<A>(
            this Task<IEnumerable<A>> asyncSource,
            Func<A, bool> predicate)
        {
            return (await asyncSource).LastOrDefault(predicate);
        }
    }
}


text:
export * from './form';
export * from './http';
export * from './interfaces';
export * from './user';


text:
<?php

require_once 'phuby/environment.php';

Phuby\Environment::initialize(__DIR__);


text:
from setuptools import setup, find_packages

setup(name='django-softdelete',
      version='0.4.1',
      description='Soft delete support for Django ORM, with undelete.',
      author='Steve Coursen',
      author_email='smcoursen@gmail.com',
      maintainer='Steve Coursen',
      maintainer_email='smcoursen@gmail.com',
      license="BSD",
      url="https://github.com/scoursen/django-softdelete",
      packages=find_packages(),
      install_requires=['setuptools',],
      include_package_data=True,
      setup_requires=['setuptools_hg',],
      classifiers=[
        'Framework :: Django',
        'License :: OSI Approved :: BSD License',
        'Environment :: Web Environment',
        ]
)


text:
//removespaces in objects and make cammel case
// remove under scores and add spaces to name feild

//using units4.js file

var unitsNew = {};

$.each(units2, function(index, value) {

	// index = camelCase(index);

	unitsNew[index] = {};

	$.each(value, function(i, v) {

		removedbrackets = RemoveBrackets(i)
		iInCammelCase = camelCase(removedbrackets);
		theName = createName(i);

		unitsNew[index][iInCammelCase] = {};

		unitsNew[index][iInCammelCase].scale = v.factor;
		unitsNew[index][iInCammelCase].symbol = "";
		unitsNew[index][iInCammelCase].name = theName;

	});
});

function camelCase(input) {
	return input.toLowerCase().replace(/(_| |-|\/)(.)/g, function(match, group1, group2) {
		console.log(input + " " + match + " " + group1 + " " + group2);
		return group2.toUpperCase();
	});
}

function RemoveBrackets(input){
	return input.replace(/[()]|\./g,'', "");

}

function createName(input) {
	/*return input.replace(/([^ \t]+)/g, function(match, group1){
		return group1.;

	});*/
	input = input.replace(/(_| |-|\/)(.)/g, function(match, group1, group2) {
		return match.toUpperCase().replace('_', ' ');
	});
	return input;
}

// using units.js file

var selectO = {};

$.each(units, function(index, value) {
	selectO[index] = [2];
	var j = 0;
	$.each(value, function(i, v) {
		if (j < 2) {
			selectO[index][j] = i;
		}
		j++;
	});
});


text:
import {schema} from 'normalizr'

// Types
import {ResourceType, Telegraf} from 'src/types'

// Schemas
import {labelSchema} from './labels'

// Defines the schema for the "telegrafs" resource
export const telegrafSchema = new schema.Entity(
  ResourceType.Telegrafs,
  {
    labels: [labelSchema],
  },
  {
    // add buckets to metadata if not present
    processStrategy: (t: Telegraf): Telegraf => {
      if (!t.metadata) {
        return {
          ...t,
          metadata: {
            buckets: [],
          },
        }
      }

      if (!t.metadata.buckets) {
        return {
          ...t,
          metadata: {
            ...t.metadata,
            buckets: [],
          },
        }
      }

      return t
    },
  }
)

export const arrayOfTelegrafs = [telegrafSchema]


text:
package com.spectralogic.dsbrowser.gui.components.interruptedjobwindow;

import com.spectralogic.ds3client.Ds3Client;
import com.spectralogic.dsbrowser.gui.DeepStorageBrowserPresenter;
import com.spectralogic.dsbrowser.gui.components.ds3panel.Ds3Common;
import com.spectralogic.dsbrowser.gui.services.jobinterruption.FilesAndFolderMap;

import java.util.Map;

public class EndpointInfo {

    private final String endpoint;
    private final Ds3Client client;
    private final Map<String, FilesAndFolderMap> jobIdAndFilesFoldersMap;
    private final DeepStorageBrowserPresenter deepStorageBrowserPresenter;
    private final Ds3Common ds3Common;

    public EndpointInfo() {
        this(null, null, null, null, null);
    }

    public EndpointInfo(final String endpoint, final Ds3Client client, final Map<String, FilesAndFolderMap> jobIdAndFilesFoldersMap, final DeepStorageBrowserPresenter deepStorageBrowserPresenter, final Ds3Common ds3Common) {
        this.endpoint = endpoint;
        this.client = client;
        this.jobIdAndFilesFoldersMap = jobIdAndFilesFoldersMap;
        this.deepStorageBrowserPresenter = deepStorageBrowserPresenter;
        this.ds3Common = ds3Common;
    }

    public Ds3Common getDs3Common() {
        return ds3Common;
    }

    public DeepStorageBrowserPresenter getDeepStorageBrowserPresenter() {
        return deepStorageBrowserPresenter;
    }

    public String getEndpoint() {
        return endpoint;
    }

    public Ds3Client getClient() {
        return client;
    }

    public Map<String, FilesAndFolderMap> getJobIdAndFilesFoldersMap() {
        return jobIdAndFilesFoldersMap;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>

<!--
   Licensed to the Apache Software Foundation (ASF) under one or more
   contributor license agreements.  See the NOTICE file distributed with
   this work for additional information regarding copyright ownership.
   The ASF licenses this file to You 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.
  -->

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>falcon-main</artifactId>
        <groupId>org.apache.falcon</groupId>
        <version>0.7-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>falcon-unit</artifactId>

    <dependencies>

        <dependency>
            <groupId>org.apache.falcon</groupId>
            <artifactId>falcon-common</artifactId>
        </dependency>

        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-client</artifactId>
        </dependency>

        <dependency>
            <groupId>org.apache.oozie</groupId>
            <artifactId>oozie-core</artifactId>
        </dependency>

        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
        </dependency>

        <dependency>
            <groupId>org.apache.falcon</groupId>
            <artifactId>falcon-client</artifactId>
        </dependency>

        <dependency>
            <groupId>org.apache.falcon</groupId>
            <artifactId>falcon-hadoop-dependencies</artifactId>
        </dependency>

        <dependency>
            <groupId>org.apache.falcon</groupId>
            <artifactId>falcon-oozie-el-extension</artifactId>
        </dependency>

        <dependency>
            <groupId>org.apache.falcon</groupId>
            <artifactId>falcon-oozie-adaptor</artifactId>
        </dependency>

        <dependency>
            <groupId>org.apache.falcon</groupId>
            <artifactId>falcon-prism</artifactId>
            <classifier>classes</classifier>
            <version>${project.version}</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>2.4</version>
                <configuration>
                    <excludes>
                        <exclude>**/log4j.xml</exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Branchmodel extends CI_Model {

	public function show_branch()
	{
		$this->db->select('branch_id, branch_name, branch_address, contact_info');
		$this->db->from('branches');
		$this->db->where('branches.active',1);
		return $this->db->get()->result_array();
	}

	public function branch_detail($value)
	{
		$this->db->select('branch_name, branch_address, contact_info');
		$this->db->from('branches');
		$this->db->where('branches.branch_id', $value);
		return $this->db->get()->result_array();
	}

	public function add($data)
	{
		$this->db->insert('branches',$data);
	}

	public function edit($branch_id,$data)
	{
		$this->db->where('branch_id', $branch_id);
		$this->db->update('branches', $data);
	}

}


text:
{% extends "submit-form.html" %}
{% block title %}Sporkk - URL Shortener{% endblock %}

{% block css_head %}
{{ super() }}

{% endblock %}

{% block form %}

	<form id="paste" name="paste" method="POST">
		<legend>Pastebin</legend>
		{% if error is defined and error != None %}

Error: {{ error }}

		{% endif %}

				Poster Name
				Syntax Highlighting

				<input type="text" name="poster_name" tabindex="1" placeholder="Anonymous" id="poster_name">
				<select name="syntax" tabindex="2" id="syntax">
					{% for dbname, item in syntax_options.iteritems() %}
						<option value="{{ dbname }}">{{ item.dispname }}</option>
					{% endfor %}
				</select>

		<textarea type="text" name="paste_content" tabindex="3" placeholder="Paste content..." cols="100" rows="14" wrap="true" class="expand" id="paste_content" required></textarea>

		<button type="submit" name="action" value="paste" tabindex="4" class="btn">Submit</button>
	</form>

{% endblock %}

{% block js_body %}
{{ super() }}

{% endblock %}


text:
//
// Copyright (C) OpenSim Ltd.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program; if not, see <http://www.gnu.org/licenses/>.
//

#ifndef __INET_QUEUEFILTER_H
#define __INET_QUEUEFILTER_H

#include "inet/common/MatchableObject.h"
#include "inet/common/queue/PacketQueue.h"

namespace inet {

namespace visualizer {

/**
 * This class provides a generic filter for queues. The filter is expressed
 * as a pattern using the cMatchExpression format.
 */
class INET_API QueueFilter
{
  protected:
    cMatchExpression matchExpression;

  public:
    void setPattern(const char *pattern);

    bool matches(const PacketQueue *queue) const;
};

} // namespace visualizer

} // namespace inet

#endif // ifndef __INET_QUEUEFILTER_H


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Uses of Class configuration.ModuleConfiguration</title>
<meta name="date" content="2014-10-29">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
configuration.ModuleConfiguration

Packages that use ModuleConfiguration

Package
Description

configuration

Configuration classes including module configurations and project directory structure configurations.

modules

Sources relevant to the information extraction modules especially
 abstract module classes for the different types of modules (file-dependent,
 environment, daemon), and the module implementations.

modules.configuration

storage

Storage backend to save and load extraction results.

Uses of ModuleConfiguration in configuration

Methods in configuration that return ModuleConfiguration

Modifier and Type
Method and Description

ModuleConfiguration
ModuleConfiguration.addSupportedSystem(OperatingSystem.OsName os)

The default is "system independent".

Uses of ModuleConfiguration in modules

Subclasses of ModuleConfiguration in modules

Modifier and Type
Class and Description

class
GeneralExecutableModuleConfig

Fields in modules declared as ModuleConfiguration

Modifier and Type
Field and Description

ModuleConfiguration
AbstractModule.config

Methods in modules that return ModuleConfiguration

Modifier and Type
Method and Description

ModuleConfiguration
AbstractModule.getConfig()

Methods in modules with parameters of type ModuleConfiguration

Modifier and Type
Method and Description

void
GeneralNativeCommandModuleEnv.setConfig(ModuleConfiguration config)

void
AbstractModule.setConfig(ModuleConfiguration config)

Uses of ModuleConfiguration in modules.configuration

Subclasses of ModuleConfiguration in modules.configuration

Modifier and Type
Class and Description

class
ChecksumFileModuleConfig

class
DirectoryMonitorModuleConfig

class
LogGrepConfig

class
LSOFConfig

class
ProcessExtractionModulesConfiguration

class
RegexConfig

class
XmlQueryConfig

Uses of ModuleConfiguration in storage

Methods in storage that return ModuleConfiguration

Modifier and Type
Method and Description

static ModuleConfiguration
ConfigSaver.loadModuleConfiguration(java.io.File source)

Loads a ModuleConfiguration from File

static ModuleConfiguration
ConfigSaver.loadModuleConfiguration(java.io.InputStream source)

Load a ModuleConfiguration from JSON file.

static ModuleConfiguration
ConfigSaver.loadModuleConfiguration(java.lang.String source)

Load a ModuleConfiguration from JSON file.

Methods in storage with parameters of type ModuleConfiguration

Modifier and Type
Method and Description

static java.lang.String
ConfigSaver.hash(ModuleConfiguration config)

Calculates a MD5 hash String for a ModuleConfiguration.

static void
ConfigSaver.saveModuleConfiguration(java.io.File destination,
                       ModuleConfiguration conf)

Saves a ModuleConfiguration to file.

static java.lang.String
ConfigSaver.saveModuleConfiguration(ModuleConfiguration config)

static void
ConfigSaver.saveModuleConfiguration(java.io.OutputStream destiantion,
                       ModuleConfiguration config)

Saves a ModuleConfiguration to an OutputStream

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
/* global requirejs */
const tests = [
    ...['text', 'json'],
    // Keep only the test spec files under the test directory.
    // Karma prepends these with /base/, so make sure that's included.
    ...Object.keys(window.__karma__.files).filter((file) => {
        'use strict';
        return /^\/base\/test\/.*[sS]pec\.js$/.test(file);
    }),
];

// hack to make jed (the i18n library that Jupyter uses) happy.
document.nbjs_translations = {
    domain: 'nbjs',
    locale_data: {
        nbjs: {
            '': {
                domain: 'nbjs',
            },
        },
    },
};

// hack to spoof createReactClass, needed by a Jupyter component we aren't testing.
window.createReactClass = () => {
    'use strict';
    /* no op */
};

requirejs.config({
    baseUrl: '/narrative/static/',

    paths: {
        moment: 'components/moment/moment',
        codemirror: 'components/codemirror',
        bootstraptour: 'components/bootstrap-tour/build/js/bootstrap-tour.min',
        bootstrap: 'ext_components/bootstrap/dist/js/bootstrap.min',
        testUtil: '../../test/unit/testUtil',
        narrativeMocks: '../../test/unit/mocks',
        unitTestUtils: '../../test/unit/utils',
        bluebird: 'ext_components/bluebird/js/browser/bluebird.min',
        jed: 'components/jed/jed',
        custom: 'kbase/custom',
        // Note that this is only provided in the testing amd module configuration;
        // Mock Service Worker (MSW) is not active in the actual Narrative web app.
        msw: 'ext_modules/msw/index',
    },
    map: {
        '*': {
            'jquery-ui': 'jqueryui',
        },
    },

    deps: tests,

    shim: {
        jquery: {
            deps: [],
            exports: 'jquery',
        },
        bootstraptour: {
            deps: ['bootstrap'],
            exports: 'Tour',
        },
        bootstrap: {
            deps: ['jquery'],
            exports: 'Bootstrap',
        },
    },

    callback: function () {
        'use strict';
        require(['testUtil'], (TestUtil) => {
            TestUtil.make().then(() => {
                window.__karma__.start();
            });
        }, (error) => {
            console.error('Failed to open TestUtil file.');
            console.error(error);
            throw error;
        });
    },
});


text:
All notable changes to this project will be documented in this file. Dates are displayed in UTC.

Generated by [`auto-changelog`](https://github.com/CookPete/auto-changelog).

#### [1.4.0](https://github.com/nicoespeon/gitgraph.js/compare/@gitgraph/js@1.3.5...@gitgraph/js@1.4.0)

> 6 March 2021

- docs: add Marty as a contributor [`#408`](https://github.com/nicoespeon/gitgraph.js/pull/408)
- docs: add longgt as a contributor [`#406`](https://github.com/nicoespeon/gitgraph.js/pull/406)
- docs: add aensley as a contributor [`#404`](https://github.com/nicoespeon/gitgraph.js/pull/404)
- docs: add soumyart as a contributor [`#403`](https://github.com/nicoespeon/gitgraph.js/pull/403)
- docs: add acransac as a contributor [`#402`](https://github.com/nicoespeon/gitgraph.js/pull/402)
- (@gitgraph/js) Add option to make graph responsive [`#401`](https://github.com/nicoespeon/gitgraph.js/pull/401)
- Branch Deletion [`#399`](https://github.com/nicoespeon/gitgraph.js/pull/399)
- Migrate linting to eslint [`#395`](https://github.com/nicoespeon/gitgraph.js/pull/395)
- [React] Fix strict mode label placement [`#392`](https://github.com/nicoespeon/gitgraph.js/pull/392)
- Fix linting glob [`#394`](https://github.com/nicoespeon/gitgraph.js/pull/394)
- docs: add crutchcorn as a contributor [`#393`](https://github.com/nicoespeon/gitgraph.js/pull/393)
- [React] Individual file breakout [`#391`](https://github.com/nicoespeon/gitgraph.js/pull/391)
- Fix body of last commit not visible [`#386`](https://github.com/nicoespeon/gitgraph.js/pull/386)
- Fix infrastractural problems [`#385`](https://github.com/nicoespeon/gitgraph.js/pull/385)
- docs: add andreasonny83 as a contributor [`#384`](https://github.com/nicoespeon/gitgraph.js/pull/384)
- Fix failing TravisCI [`#383`](https://github.com/nicoespeon/gitgraph.js/pull/383)
- feat: update address about Usage Demo & Documentation [`#382`](https://github.com/nicoespeon/gitgraph.js/pull/382)
- docs: add Nebula83 as a contributor [`#368`](https://github.com/nicoespeon/gitgraph.js/pull/368)
- fix: replace 'transparent' with 'none' [`#366`](https://github.com/nicoespeon/gitgraph.js/pull/366)
- Bump websocket-extensions from 0.1.3 to 0.1.4 [`#362`](https://github.com/nicoespeon/gitgraph.js/pull/362)
- Fixing the parent branch name in readme [`#355`](https://github.com/nicoespeon/gitgraph.js/pull/355)
- Bump https-proxy-agent from 2.2.1 to 2.2.4 [`#353`](https://github.com/nicoespeon/gitgraph.js/pull/353)
- Use hash instead of hashAbbrev as key [`#321`](https://github.com/nicoespeon/gitgraph.js/issues/321)
- Make JS graph responsive with an option [`#303`](https://github.com/nicoespeon/gitgraph.js/issues/303)
- Fix body of last commit not visible [`#374`](https://github.com/nicoespeon/gitgraph.js/issues/374)
- Backfill with contributors since GitGraph v2 [`#296`](https://github.com/nicoespeon/gitgraph.js/issues/296)

#### [1.3.5](https://github.com/nicoespeon/gitgraph.js/compare/@gitgraph/js@1.3.4...@gitgraph/js@1.3.5)

> 4 April 2020

- Fix undefined current when importing parent branches [`#352`](https://github.com/nicoespeon/gitgraph.js/pull/352)

#### [1.3.4](https://github.com/nicoespeon/gitgraph.js/compare/@gitgraph/js@1.3.3...@gitgraph/js@1.3.4)

> 22 March 2020

- Fix the issue that HEAD is not updated when calling checkout [`#349`](https://github.com/nicoespeon/gitgraph.js/pull/349)
- Bump acorn from 5.7.2 to 5.7.4 [`#348`](https://github.com/nicoespeon/gitgraph.js/pull/348)
- Reference the new lerna site [`#343`](https://github.com/nicoespeon/gitgraph.js/pull/343)
- Bump handlebars from 4.1.2 to 4.5.3 [`#342`](https://github.com/nicoespeon/gitgraph.js/pull/342)
- Change Tag SVG radius value [`#340`](https://github.com/nicoespeon/gitgraph.js/pull/340)
- Gitter chat badge added to README [`#338`](https://github.com/nicoespeon/gitgraph.js/pull/338)

#### [1.3.3](https://github.com/nicoespeon/gitgraph.js/compare/@gitgraph/js@1.3.2...@gitgraph/js@1.3.3)

> 19 November 2019

- Fixing graph when the same branch is merged multiple times in a row [`#335`](https://github.com/nicoespeon/gitgraph.js/pull/335)
- Fix ineffective merge when fastForward is set to false [`#330`](https://github.com/nicoespeon/gitgraph.js/pull/330)
- Bump mixin-deep from 1.3.1 to 1.3.2 [`#323`](https://github.com/nicoespeon/gitgraph.js/pull/323)

#### [1.3.2](https://github.com/nicoespeon/gitgraph.js/compare/@gitgraph/js@1.3.1...@gitgraph/js@1.3.2)

> 29 July 2019

- Fix commit display without message [`#315`](https://github.com/nicoespeon/gitgraph.js/pull/315)
- Bump fstream from 1.0.11 to 1.0.12 [`#311`](https://github.com/nicoespeon/gitgraph.js/pull/311)
- Bump handlebars from 4.0.12 to 4.1.2 [`#310`](https://github.com/nicoespeon/gitgraph.js/pull/310)
- Bump js-yaml from 3.12.2 to 3.13.1 [`#312`](https://github.com/nicoespeon/gitgraph.js/pull/312)
- Bump lodash.template from 4.4.0 to 4.5.0 [`#313`](https://github.com/nicoespeon/gitgraph.js/pull/313)
- Bump lodash-es from 4.17.11 to 4.17.15 [`#314`](https://github.com/nicoespeon/gitgraph.js/pull/314)
- Bump merge from 1.2.0 to 1.2.1 [`#309`](https://github.com/nicoespeon/gitgraph.js/pull/309)
- Bump cached-path-relative from 1.0.1 to 1.0.2 [`#308`](https://github.com/nicoespeon/gitgraph.js/pull/308)
- Bump lodash from 4.17.11 to 4.17.13 [`#307`](https://github.com/nicoespeon/gitgraph.js/pull/307)
- Pass graph as a prop to react component [`#306`](https://github.com/nicoespeon/gitgraph.js/pull/306)

#### [1.3.1](https://github.com/nicoespeon/gitgraph.js/compare/@gitgraph/js@1.3.0...@gitgraph/js@1.3.1)

> 21 July 2019

- Fix compact mode with import [`#305`](https://github.com/nicoespeon/gitgraph.js/pull/305)

#### [1.3.0](https://github.com/nicoespeon/gitgraph.js/compare/@gitgraph/js@1.2.0...@gitgraph/js@1.3.0)

> 7 June 2019

- Add options to render branch label on every commit [`#299`](https://github.com/nicoespeon/gitgraph.js/pull/299)
- Upgrade to TypeScript v3.5 [`#298`](https://github.com/nicoespeon/gitgraph.js/pull/298)
- Add links to online bundles + playground [`#283`](https://github.com/nicoespeon/gitgraph.js/issues/283)

#### [1.2.0](https://github.com/nicoespeon/gitgraph.js/compare/@gitgraph/js@1.1.0...@gitgraph/js@1.2.0)

> 23 May 2019

- Fixes #162 [`#295`](https://github.com/nicoespeon/gitgraph.js/pull/295)

#### [1.1.0](https://github.com/nicoespeon/gitgraph.js/compare/@gitgraph/js@1.0.0...@gitgraph/js@1.1.0)

> 7 May 2019

- Generate browser bundle for @gitgraph/js [`#287`](https://github.com/nicoespeon/gitgraph.js/pull/287)
- Implement custom render for tags [`#289`](https://github.com/nicoespeon/gitgraph.js/pull/289)
- Customize how we render branches labels [`#286`](https://github.com/nicoespeon/gitgraph.js/pull/286)
- Stream lerna outputs [`#281`](https://github.com/nicoespeon/gitgraph.js/issues/281)

#### [1.0.0](https://github.com/nicoespeon/gitgraph.js/compare/@gitgraph/js@1.0.0-4...@gitgraph/js@1.0.0)

> 16 April 2019

- Introduce changelogs to packages. [`#280`](https://github.com/nicoespeon/gitgraph.js/pull/280)
- Allow branching from another branch [`#279`](https://github.com/nicoespeon/gitgraph.js/pull/279)
- Website revamp [`#272`](https://github.com/nicoespeon/gitgraph.js/pull/272)
- Add stories for large graph [`#269`](https://github.com/nicoespeon/gitgraph.js/pull/269)

#### [1.0.0-4](https://github.com/nicoespeon/gitgraph.js/compare/@gitgraph/js@1.0.0-3...@gitgraph/js@1.0.0-4)

> 12 April 2019

- Add multiple merges from same commit stories [`#265`](https://github.com/nicoespeon/gitgraph.js/pull/265)
- Improve perfs & fix tag bug in horizontal mode [`#268`](https://github.com/nicoespeon/gitgraph.js/pull/268)
- Cleanup after #253 [`#264`](https://github.com/nicoespeon/gitgraph.js/pull/264)
- Factor expensive computations out of commit iterations [`#253`](https://github.com/nicoespeon/gitgraph.js/pull/253)

#### [1.0.0-3](https://github.com/nicoespeon/gitgraph.js/compare/@gitgraph/js@1.0.0-2...@gitgraph/js@1.0.0-3)

> 7 April 2019

- Drop yup from @gitgraph/core [`#257`](https://github.com/nicoespeon/gitgraph.js/pull/257)

#### [1.0.0-2](https://github.com/nicoespeon/gitgraph.js/compare/@gitgraph/js@1.0.0-1...@gitgraph/js@1.0.0-2)

> 7 April 2019

- Drop lodash from @gitgraph/core [`#256`](https://github.com/nicoespeon/gitgraph.js/pull/256)

#### [1.0.0-1](https://github.com/nicoespeon/gitgraph.js/compare/@gitgraph/js@1.0.0-0...@gitgraph/js@1.0.0-1)

> 5 April 2019

- Set up Chromatic for all rendering packages [`#255`](https://github.com/nicoespeon/gitgraph.js/pull/255)

#### [1.0.0-0](https://github.com/nicoespeon/gitgraph.js/compare/@gitgraph/js@0.1.1...@gitgraph/js@1.0.0-0)

> 5 April 2019

- Move all stories from gitgraph-js to stories [`c5ebee1`](https://github.com/nicoespeon/gitgraph.js/commit/c5ebee1c43238f054541ea309688ea3ff262721e)
- Drop stories from gitgraph-react [`565fcc9`](https://github.com/nicoespeon/gitgraph.js/commit/565fcc9734599e327ae3a6fbb40ac175648065d4)
- Create stories package to regroup all stories [`94b36d1`](https://github.com/nicoespeon/gitgraph.js/commit/94b36d12f48c38795cb9a6e17e8472b743a1d705)

#### [0.1.1](https://github.com/nicoespeon/gitgraph.js/compare/@gitgraph/js@0.1.0...@gitgraph/js@0.1.1)

> 4 April 2019

- Fix/vertical reverse merge [`#254`](https://github.com/nicoespeon/gitgraph.js/pull/254)
- Passing optional commitOptions object to commit [`#252`](https://github.com/nicoespeon/gitgraph.js/pull/252)

#### 0.1.0

> 31 March 2019

- Create @gitgraph/js [`#242`](https://github.com/nicoespeon/gitgraph.js/pull/242)
- Add BranchesOrderFunction option to set user-defined branches order [`#247`](https://github.com/nicoespeon/gitgraph.js/pull/247)
- Extract the concept of "BranchesOrder" (formerly "GraphColumns"). [`#246`](https://github.com/nicoespeon/gitgraph.js/pull/246)
- Setup Chromatic QA (automated visual testing) [`#241`](https://github.com/nicoespeon/gitgraph.js/pull/241)
- Customize Tag style [`#239`](https://github.com/nicoespeon/gitgraph.js/pull/239)
- Render tags [`#236`](https://github.com/nicoespeon/gitgraph.js/pull/236)
- Upgrade to Storybook 5 [`#235`](https://github.com/nicoespeon/gitgraph.js/pull/235)
- Fix and improve the `translateCommitMessagesWithBranchLabel` strategy [`#234`](https://github.com/nicoespeon/gitgraph.js/pull/234)
- Fix commit message body visibility [`#233`](https://github.com/nicoespeon/gitgraph.js/pull/233)
- Fix live update labels position [`#232`](https://github.com/nicoespeon/gitgraph.js/pull/232)
- React/branches labels [`#231`](https://github.com/nicoespeon/gitgraph.js/pull/231)
- Fix/blackarrow arrow orientation [`#230`](https://github.com/nicoespeon/gitgraph.js/pull/230)
- GitGraph.js v2-alpha [`#188`](https://github.com/nicoespeon/gitgraph.js/pull/188)
- fix arrow color problem [`#216`](https://github.com/nicoespeon/gitgraph.js/pull/216)
- Add commit object to the mouseEventOptions object [`#214`](https://github.com/nicoespeon/gitgraph.js/pull/214)
- Accept options.details HTMLElement in commit method [`#211`](https://github.com/nicoespeon/gitgraph.js/pull/211)
- Update Readme to integrate Hall of Fame [`#209`](https://github.com/nicoespeon/gitgraph.js/pull/209)
- Add the ability to put some text in the commit bubble. (commitDotText) [`#196`](https://github.com/nicoespeon/gitgraph.js/pull/196)
- fix wrong arrow angle on branching [`#171`](https://github.com/nicoespeon/gitgraph.js/pull/171)
- Fix for strange branch lines for merge commit with details. [`#168`](https://github.com/nicoespeon/gitgraph.js/pull/168)
- Adding incompatible version to showcase using support branches [`#163`](https://github.com/nicoespeon/gitgraph.js/pull/163)
- Firefox 53 fix [`#165`](https://github.com/nicoespeon/gitgraph.js/pull/165)
- Close #140. Vertical arrow with multiple branch commit. [`#154`](https://github.com/nicoespeon/gitgraph.js/pull/154)
- Fix incorrect font height in labels and tags when graph canvas is contained in a floating div. [`#155`](https://github.com/nicoespeon/gitgraph.js/pull/155)
- fix issue 140 wrong arrow angle [`#150`](https://github.com/nicoespeon/gitgraph.js/pull/150)
- Add typescript definition [`#152`](https://github.com/nicoespeon/gitgraph.js/pull/152)
- Support branch label rotation in 'horizontal mode'. [`#134`](https://github.com/nicoespeon/gitgraph.js/pull/134)
- Added fix for JSHint via Grunt (null path warning). [`#133`](https://github.com/nicoespeon/gitgraph.js/pull/133)
- Fix typo in README.md [`#135`](https://github.com/nicoespeon/gitgraph.js/pull/135)
- Issue: Click object is not passed to the consumer end click handler. [`#130`](https://github.com/nicoespeon/gitgraph.js/pull/130)
- Issue: Canvas event handlers cannot be disposed from the consumer end. [`#131`](https://github.com/nicoespeon/gitgraph.js/pull/131)
- Improve readability of markdown files as plaintext [`#125`](https://github.com/nicoespeon/gitgraph.js/pull/125)
- Update link to Jasmine [`#122`](https://github.com/nicoespeon/gitgraph.js/pull/122)
- Fix offsetX and offsetY for older FF [`#116`](https://github.com/nicoespeon/gitgraph.js/pull/116)
- Add the possibility to avoid the black border for tag rendering. [`#114`](https://github.com/nicoespeon/gitgraph.js/pull/114)
- Close #109. [`#112`](https://github.com/nicoespeon/gitgraph.js/pull/112)
- Branch from current commit or a specific commit. [`#88`](https://github.com/nicoespeon/gitgraph.js/pull/88)
- Restore line dash after applying it to branch [`#106`](https://github.com/nicoespeon/gitgraph.js/pull/106)
- [Bug Fix] Align tags properly [`#104`](https://github.com/nicoespeon/gitgraph.js/pull/104)
- Support for commit:mouseout event [`#100`](https://github.com/nicoespeon/gitgraph.js/pull/100)
- Closes #46 [`#99`](https://github.com/nicoespeon/gitgraph.js/pull/99)
- Fix #87 [`#96`](https://github.com/nicoespeon/gitgraph.js/pull/96)
- Fix #89 [`#95`](https://github.com/nicoespeon/gitgraph.js/pull/95)
- [BUGFIX] [`#93`](https://github.com/nicoespeon/gitgraph.js/pull/93)
- Adds `detailId` to commitWithDetailsConfig example [`#92`](https://github.com/nicoespeon/gitgraph.js/pull/92)
- Added the ability to assign 'onClick' events to commits. [`#76`](https://github.com/nicoespeon/gitgraph.js/pull/76)
- Fixes #66 #60 #59 [`#71`](https://github.com/nicoespeon/gitgraph.js/pull/71)
- Fix the column calculation algorithm [`#72`](https://github.com/nicoespeon/gitgraph.js/pull/72)
- Add branch name at beginning of commit messages [`#69`](https://github.com/nicoespeon/gitgraph.js/pull/69)
- Exposed classes under the GitGraph namespace. [`#57`](https://github.com/nicoespeon/gitgraph.js/pull/57)
- Replace link to releases, use latest [`#56`](https://github.com/nicoespeon/gitgraph.js/pull/56)
- Add more branch display options [`#54`](https://github.com/nicoespeon/gitgraph.js/pull/54)
- Add more message display options [`#53`](https://github.com/nicoespeon/gitgraph.js/pull/53)
- Yep, that's right! [`#52`](https://github.com/nicoespeon/gitgraph.js/pull/52)
- Seems to be a good option for those who wish to go further. Thanks :+1: [`#51`](https://github.com/nicoespeon/gitgraph.js/pull/51)
- Close #39 - now triggers an event with a bunch of data (author, date, message, sha1) [`#47`](https://github.com/nicoespeon/gitgraph.js/pull/47)
- Good enough to close issue #28. [`#43`](https://github.com/nicoespeon/gitgraph.js/pull/43)
- Support for high-resolution displays from @claui [`#41`](https://github.com/nicoespeon/gitgraph.js/pull/41)
- Add lineDash option to branch and commits [`#139`](https://github.com/nicoespeon/gitgraph.js/issues/139)
- Fix details left positionning [`#145`](https://github.com/nicoespeon/gitgraph.js/issues/145)
- Make tooltip container configurable [`#147`](https://github.com/nicoespeon/gitgraph.js/issues/147)
- Display details in vertical-reverse mode too [`#81`](https://github.com/nicoespeon/gitgraph.js/issues/81)
- Add .tag() method to Branch and Graph [`#75`](https://github.com/nicoespeon/gitgraph.js/issues/75)
- Fix rendering when parent branch has no commit [`#121`](https://github.com/nicoespeon/gitgraph.js/issues/121)
- Merge fix-hover-event-firefox into develop [`#107`](https://github.com/nicoespeon/gitgraph.js/issues/107)
- Add an option to disable tooltips in compact mode [`#102`](https://github.com/nicoespeon/gitgraph.js/issues/102)
- Refactor commitOffsetLeft and fix details position [`#85`](https://github.com/nicoespeon/gitgraph.js/issues/85)
- Adds `detailId` to commitWithDetailsConfig example [`#84`](https://github.com/nicoespeon/gitgraph.js/issues/84)
- Correct typo in code [`#90`](https://github.com/nicoespeon/gitgraph.js/issues/90)
- Refactor detail to detailId - Close #30 [`#30`](https://github.com/nicoespeon/gitgraph.js/issues/30)
- Create branch from another one - Close #29 [`#29`](https://github.com/nicoespeon/gitgraph.js/issues/29)
- Add the CONTRIBUTING.md [`#1`](https://github.com/nicoespeon/gitgraph.js/issues/1)
- Update "How to start" in the README with Bower information [`#3`](https://github.com/nicoespeon/gitgraph.js/issues/3)
- Add gitgraph logo into README - close #11 [`#11`](https://github.com/nicoespeon/gitgraph.js/issues/11)
- Fix firefox MouseEvent - close #27 [`#27`](https://github.com/nicoespeon/gitgraph.js/issues/27)
- Fix jsdoc with IIFE - close #26 [`#26`](https://github.com/nicoespeon/gitgraph.js/issues/26)
- Dynamically loading external CSS file - close #20 [`#20`](https://github.com/nicoespeon/gitgraph.js/issues/20)
- Fix fork - close #25 [`#25`](https://github.com/nicoespeon/gitgraph.js/issues/25)
- Auto render - close #22 [`#22`](https://github.com/nicoespeon/gitgraph.js/issues/22)
- Fix simple merge in compact mode close #21 [`#21`](https://github.com/nicoespeon/gitgraph.js/issues/21)
- Multi-merge finish ! Close #17 [`#17`](https://github.com/nicoespeon/gitgraph.js/issues/17)
- Merge branch 'feature/travis-ci' into develop [`#16`](https://github.com/nicoespeon/gitgraph.js/issues/16)
- Remove possibility to merge without commit [`#12`](https://github.com/nicoespeon/gitgraph.js/issues/12)
- Merge branch 'feature/readme-basics' into develop [`#6`](https://github.com/nicoespeon/gitgraph.js/issues/6)
- Merge branch 'feature/grunt-workflow' into develop [`#2`](https://github.com/nicoespeon/gitgraph.js/issues/2)
- Add .editorconfig file for contribution [`#7`](https://github.com/nicoespeon/gitgraph.js/issues/7)


text:
@if "%_echo%"=="" echo off

setlocal

call %~d0%~p0..\..\..\config.bat

"%PEVERIFY%" magic.dll
@if ERRORLEVEL 1 goto Error

"%PEVERIFY%" provider.dll
@if ERRORLEVEL 1 goto Error

"%PEVERIFY%" test.exe
@if ERRORLEVEL 1 goto Error

test.exe
@if ERRORLEVEL 1 goto Error

endlocal
exit /b 0


text:
<?php

namespace Drupal\redirect_404\Controller;

use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Url;
use Drupal\redirect_404\RedirectNotFoundStorageInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;

/**
 * Controller to ignore a path from the 'Fix 404 pages' page.
 */
class Fix404IgnoreController extends ControllerBase {

  /**
   * The config factory.
   *
   * @var \Drupal\Core\Config\ConfigFactoryInterface
   */
  protected $configuration;

  /**
   * The redirect storage.
   *
   * @var \Drupal\redirect_404\RedirectNotFoundStorageInterface
   */
  protected $redirectStorage;

  /**
   * Constructs a Fix404Ignore object.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The config factory.
   * @param \Drupal\redirect_404\RedirectNotFoundStorageInterface $redirect_storage
   *   A redirect storage.
   */
  public function __construct(ConfigFactoryInterface $config_factory, RedirectNotFoundStorageInterface $redirect_storage) {
    $this->configuration = $config_factory;
    $this->redirectStorage = $redirect_storage;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('config.factory'),
      $container->get('redirect.not_found_storage')
    );
  }

  /**
   * Adds path into the ignored list.
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The HttpRequest object representing the current request.
   *
   * @return \Symfony\Component\HttpFoundation\RedirectResponse
   */
  public function ignorePath(Request $request) {
    $ignored_paths = $this->config('redirect_404.settings')->get('pages');
    $path = $request->query->get('path');
    $langcode = $request->query->get('langcode');

    if (empty($ignored_paths) || !strpos($path, $ignored_paths)) {
      $this->redirectStorage->resolveLogRequest($path, $langcode);

      drupal_set_message($this->t('Resolved the path %path in the database. Please check the ignored list and save the settings.', [
        '%path' => $path,
      ]));
    }

    $options = [
      'query' => [
        'ignore' => $path,
        'destination' => Url::fromRoute('redirect_404.fix_404')->getInternalPath(),
      ],
    ];

    return $this->redirect('redirect.settings', [], $options);
  }

}


text:
import cloneDeep from 'clonedeep';
import {diff} from 'objectdiff';
import {Package} from '../Package';

let firstDocs, startDocs, endDocs, lastDocs;
const options = {
  start: null,
  end: null
};

export const docDiffLoggerPackage = new Package('docDiffLogger')

.factory('docDiffLoggerOptions', function() {
  return options;
})

.eventHandler('processorStart', function() {
  return function capturePreviousDocs(event, processor, docs) {
    firstDocs = firstDocs || cloneDeep(docs);

    if ( options.start === processor.name ) {
      startDocs = cloneDeep(docs);
    }
  };
})

.eventHandler('processorEnd', function(log) {
  return function(_event, processor, docs) {
    lastDocs = docs;

    if ( options.end === processor.name ) {
      endDocs = cloneDeep(docs);
      logDiff(log);
    }
  };
})

.eventHandler('generationEnd', function(log) {
  return function() {
    if ( options.start && !startDocs ) {
      throw new Error('docDiffLogger: missing start processor');
    }
    if ( options.end && !endDocs ) {
      throw new Error('docDiffLogger: missing end processor');
    }
    if ( !options.end ) {
      logDiff(log);
    }
  };
});

function logDiff(log) {
  const changes = diff(startDocs || firstDocs, endDocs || lastDocs);
  log.info(options);
  log.info(changes);
}


text:
"""Client Interface for Pygame.

Pygame used to parse keyboard and mouse commands as well as display
images in a window

"""

from PygameClientInterface import PygameClientInterface

class JoystickClientInterface(PygameClientInterface):

    """
    __init__ function -> setup XMLRPC as well as pygame
    """

    def __init__(self, server_uri, update_image=True, joystick_id=0,
                 has_control=True):
        import pygame
        pygame.joystick.init()
        self.__joystick = pygame.joystick.Joystick(joystick_id)
        self.__joystick.init()

        self.__velocity_factor = 1.

        self.__has_control = has_control

        # Use base class to setup XMLRPC server
        PygameClientInterface.__init__(self, server_uri, update_image)

    def hasControl(self):
        """Return True if user wants to send control commands.

        Tab key and shift-tab toggle this.

        """
        # Check if control flag should be toggled.
        import pygame
        if pygame.key.get_pressed()[pygame.K_TAB]:
            self.__has_control = not (
                pygame.key.get_mods() & pygame.KMOD_LSHIFT)

            if self.__has_control:
                print('Take control')
            else:
                print('Release control')

        return self.__has_control

    def drive(self):
        pitch = -self.__joystick.get_axis(1) * self.__velocity_factor
        yaw = -self.__joystick.get_axis(2) * self.__velocity_factor

        self._proxy.setVel(0, pitch, 0)
        self._proxy.setRot(yaw)

    def processClients(self):
        exclusive_control = self.hasControl()

        if exclusive_control:
            self.drive()
            self.setWaypoint()

        return PygameClientInterface.processClients(
            self, exclusive_control=exclusive_control)

    def setWaypoint(self):
        """Process waypoint setting functions."""
        import pygame

        if pygame.key.get_pressed()[pygame.K_y]:
            self._proxy.setWayPoint()


text:
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <group android:id="@+id/menu_group_1">
        <item
            android:id="@+id/menu_feed"
            android:title="My Feed" />
        <item
            android:id="@+id/menu_direct"
            android:title="Instagram Direct" />
        <item
            android:id="@+id/menu_news"
            android:title="News" />
        <item
            android:id="@+id/menu_popular"
            android:title="Popular" />
        <item
            android:id="@+id/menu_photos_nearby"
            android:title="Photos Nearby" />
        <item
            android:id="@+id/menu_photo_you_liked"
            android:title="Photos You've Liked" />
    </group>
    <group android:id="@+id/menu_group_2">
        <item
            android:id="@+id/menu_settings"
            android:title="Settings" />
        <item
            android:id="@+id/menu_about"
            android:title="About" />
    </group>
</menu>


text:
/**
*	This barrel file provides the export for the lazy loaded DashboardComponent.
*/
export * from './tour.list.component';
export * from './tour.edit.component';
export * from './tour.add.component';
export * from './tour.component';
export * from './tour.routing';


text:
package bootstrap.liftweb

import net.liftweb._
import common._
import http._
import ru.nightuser.databasecourse.HttpApi;

class Boot extends Loggable {
  def boot {
    LiftRules.early.append(_.setCharacterEncoding("UTF-8"))
    LiftRules.htmlProperties.default.set((r: Req) =>
      new Html5Properties(r.userAgent))

    HttpApi.init()
  }
}


text:
/* vim: set sw=2 ts=2 et: */

Components.utils.import("resource://app/modules/CustomizableUI.jsm");

var kiosek = {
  init: function () {
    if (gBrowser) {
      gBrowser.tabContainer.addEventListener("TabClose", kiosek.tabRemoved, false);
    }
  },
  tabRemoved: function (event) {
    /* Get number of tabs. */
    var num = gBrowser.browsers.length;

    /* If there are two tabs, the second tab has no title and the closed tab
     * does have a title (ie is not the same tab) then close the browser. */
    if ((num == 2) && (!gBrowser.getBrowserAtIndex(1).contentTitle) && event.target.linkedBrowser.contentTitle) {
      goQuitApplication();
    }

    if ((num == 2) && (!gBrowser.getBrowserAtIndex(0).contentTitle)) {
      goQuitApplication();
    }
  }
};

window.addEventListener("load", function load(event) {
  window.removeEventListener("load", load, false);

  /* Start in full screen. */
  window.fullScreen = true;

  /* Initialize the service above. */
  kiosek.init();
}, false);

/* override browser.js */
function BrowserLoadURL(aTriggeringEvent, aPostData) {
  var url = gURLBar.value;
  if (url.match(/^file:/) || url.match(/^\//) || url.match(/^resource:/) || url.match(/^about:/)) {
    alert("Access to this protocol has been disabled!");
    return;
  }

  if (aTriggeringEvent instanceof MouseEvent) {
    /* Do nothing for right clicks. */
    if (aTriggeringEvent.button == 2) {
      return;
    }

    /* We have a mouse event (from the go button), so use the standard UI link behaviors. */
    openUILink(url, aTriggeringEvent, false, false, true, aPostData);
    return;
  }

  if (aTriggeringEvent && aTriggeringEvent.altKey) {
    handleURLBarRevert();
    content.focus();
    gBrowser.loadOneTab(url, null, null, aPostData, false, true);
    aTriggeringEvent.preventDefault();
    aTriggeringEvent.stopPropagation();
  }
  else {
    loadURI(url, null, aPostData, true);
  }

  focusElement(content);
}

(function () {
  function onPageLoad(event) {
    var doc = event.target;
    var win = doc.defaultView;

    // ignore frame loads
    if (win != win.top) {
      return;
    }

    var uri = doc.documentURIObject;

    /* If we get a neterror, try again in 10 seconds. */
    if (uri.spec.match("about:neterror")) {
      window.setTimeout(function (win) {
        win.location.reload();
      }, 10000, win);
    }
  }

  function startup() {
    var navigatorToolbox = document.getElementById("navigator-toolbox");
    navigatorToolbox.iconsize = "small";
    navigatorToolbox.setAttribute("iconsize", "small");

    var showPrintButton = false;

    try {
      showPrintButton = Services.prefs.getBoolPref("extensions.kiosek.showprintbutton");
    } catch(e) {}

    if (showPrintButton) {
      CustomizableUI.addWidgetToArea("print-button", "nav-bar");
    } else {
      CustomizableUI.removeWidgetFromArea("print-button");
    }

    window.removeEventListener("load", startup, false);
    document.getElementById("appcontent").addEventListener("DOMContentLoaded", onPageLoad, false);
  }

  function shutdown() {
    window.removeEventListener("unload", shutdown, false);
    document.getElementById("appcontent").removeEventListener("DOMContentLoaded", onPageLoad, false);
  }

  window.addEventListener("load", startup, false);
  window.addEventListener("unload", shutdown, false);
})();

/* Disable shift click from opening window. */
var ffWhereToOpenLink = whereToOpenLink;

whereToOpenLink = function (e, ignoreButton, ignoreAlt) {
  var where = ffWhereToOpenLink(e, ignoreButton, ignoreAlt);
  if (where == "window") {
    where = "tab";
  }
  return where;
}