text:
namespace {

// Used to test AddFilterFunction().
DBusHandlerResult DummyHandler(DBusConnection* connection,
                               DBusMessage* raw_message,
                               void* user_data) {
  return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
}

}  // namespace

TEST(BusTest, GetObjectProxy) {
  dbus::Bus::Options options;
  scoped_refptr<dbus::Bus> bus = new dbus::Bus(options);

  dbus::ObjectProxy* object_proxy1 =
      bus->GetObjectProxy("org.chromium.TestService",
                          "/org/chromium/TestObject");
  ASSERT_TRUE(object_proxy1);

  // This should return the same object.
  dbus::ObjectProxy* object_proxy2 =
      bus->GetObjectProxy("org.chromium.TestService",
                          "/org/chromium/TestObject");
  ASSERT_TRUE(object_proxy2);
  EXPECT_EQ(object_proxy1, object_proxy2);

  // This should not.
  dbus::ObjectProxy* object_proxy3 =
      bus->GetObjectProxy("org.chromium.TestService",
                          "/org/chromium/DifferentTestObject");
  ASSERT_TRUE(object_proxy3);
  EXPECT_NE(object_proxy1, object_proxy3);

  bus->ShutdownAndBlock();
}

TEST(BusTest, GetExportedObject) {
  dbus::Bus::Options options;
  scoped_refptr<dbus::Bus> bus = new dbus::Bus(options);

  dbus::ExportedObject* object_proxy1 =
      bus->GetExportedObject("org.chromium.TestService",
                             "/org/chromium/TestObject");
  ASSERT_TRUE(object_proxy1);

  // This should return the same object.
  dbus::ExportedObject* object_proxy2 =
      bus->GetExportedObject("org.chromium.TestService",
                             "/org/chromium/TestObject");
  ASSERT_TRUE(object_proxy2);
  EXPECT_EQ(object_proxy1, object_proxy2);

  // This should not.
  dbus::ExportedObject* object_proxy3 =
      bus->GetExportedObject("org.chromium.TestService",
                             "/org/chromium/DifferentTestObject");
  ASSERT_TRUE(object_proxy3);
  EXPECT_NE(object_proxy1, object_proxy3);

  bus->ShutdownAndBlock();
}

TEST(BusTest, ShutdownAndBlock) {
  dbus::Bus::Options options;
  scoped_refptr<dbus::Bus> bus = new dbus::Bus(options);
  ASSERT_FALSE(bus->shutdown_completed());

  // Shut down synchronously.
  bus->ShutdownAndBlock();
  EXPECT_TRUE(bus->shutdown_completed());
}

TEST(BusTest, ShutdownAndBlockWithDBusThread) {
  // Start the D-Bus thread.
  base::Thread::Options thread_options;
  thread_options.message_loop_type = MessageLoop::TYPE_IO;
  base::Thread dbus_thread("D-Bus thread");
  dbus_thread.StartWithOptions(thread_options);

  // Create the bus.
  dbus::Bus::Options options;
  options.dbus_thread_message_loop_proxy = dbus_thread.message_loop_proxy();
  scoped_refptr<dbus::Bus> bus = new dbus::Bus(options);
  ASSERT_FALSE(bus->shutdown_completed());

  // Shut down synchronously.
  bus->ShutdownOnDBusThreadAndBlock();
  EXPECT_TRUE(bus->shutdown_completed());
  dbus_thread.Stop();
}

TEST(BusTest, AddFilterFunction) {
  dbus::Bus::Options options;
  scoped_refptr<dbus::Bus> bus = new dbus::Bus(options);
  // Should connect before calling AddFilterFunction().
  bus->Connect();

  int data1 = 100;
  int data2 = 200;
  ASSERT_TRUE(bus->AddFilterFunction(&DummyHandler, &data1));
  // Cannot add the same function with the same data.
  ASSERT_FALSE(bus->AddFilterFunction(&DummyHandler, &data1));
  // Can add the same function with different data.
  ASSERT_TRUE(bus->AddFilterFunction(&DummyHandler, &data2));

  ASSERT_TRUE(bus->RemoveFilterFunction(&DummyHandler, &data1));
  ASSERT_FALSE(bus->RemoveFilterFunction(&DummyHandler, &data1));
  ASSERT_TRUE(bus->RemoveFilterFunction(&DummyHandler, &data2));

  bus->ShutdownAndBlock();
}


text:
package org.basex.io.out;

import java.io.*;

import org.basex.io.*;

/**
 * This class uses a byte buffer to speed up output stream processing.
 *
 * @author BaseX Team 2005-15, BSD License
 * @author Christian Gruen
 * @author Tim Petrowsky
 */
public final class BufferOutput extends OutputStream {
  /** Buffer size. */
  private final int bufsize;
  /** Byte buffer. */
  private final byte[] buffer;
  /** Reference to the data output stream. */
  private final OutputStream os;
  /** Current buffer position. */
  private int pos;

  /**
   * Constructor.
   * @param file target file
   * @throws IOException I/O exception
   */
  public BufferOutput(final String file) throws IOException {
    this(new FileOutputStream(file), IO.BLOCKSIZE);
  }

  /**
   * Constructor with a default buffer size.
   * @param os the stream to write to
   */
  public BufferOutput(final OutputStream os) {
    this(os, IO.BLOCKSIZE);
  }

  /**
   * Constructor with a specific buffer size.
   * @param os the stream to write to
   * @param bufs buffer size
   */
  public BufferOutput(final OutputStream os, final int bufs) {
    this.os = os;
    buffer = new byte[bufs];
    bufsize = bufs;
  }

  @Override
  public void write(final int b) throws IOException {
    if(pos == bufsize) flush();
    buffer[pos++] = (byte) b;
  }

  @Override
  public void flush() throws IOException {
    os.write(buffer, 0, pos);
    pos = 0;
  }

  @Override
  public void close() throws IOException {
    flush();
    os.close();
  }
}

redpajama_set_name: RedPajamaGithub


text:
package hqt.designpatterns.patterns.decorator;

public abstract class CondimentDecorator extends Beverage {
	public abstract String getDescription();
}


text:
<?php namespace Backend\Models;

use File;
use Lang;
use Model;
use Cache;
use Less_Parser;
use Exception;

/**
 * Brand settings that affect all users
 *
 * @package october\backend
 * @author Alexey Bobkov, Samuel Georges
 */
class BrandSetting extends Model
{
    use \System\Traits\ViewMaker;
    use \October\Rain\Database\Traits\Validation;

    public $implement = ['System.Behaviors.SettingsModel'];

    public $settingsCode = 'backend_brand_settings';

    public $settingsFields = 'fields.yaml';

    public $attachOne = [
        'logo' => ['System\Models\File']
    ];

    const CACHE_KEY = 'backend::brand.custom_css';

    const PRIMARY_COLOR   = '#34495e'; // Wet Asphalt
    const SECONDARY_COLOR = '#e67e22'; // Pumpkin
    const ACCENT_COLOR    = '#3498db'; // Peter River

    const INLINE_MENU   = 'inline';
    const TILE_MENU     = 'tile';
    const COLLAPSE_MENU = 'collapse';

    /**
     * Validation rules
     */
    public $rules = [
        'app_name'     => 'required',
        'app_tagline'  => 'required',
    ];

    public function initSettingsData()
    {
        $this->app_name = Lang::get('system::lang.app.name');
        $this->app_tagline = Lang::get('system::lang.app.tagline');

        $this->primary_color = self::PRIMARY_COLOR;
        $this->secondary_color = self::SECONDARY_COLOR;
        $this->accent_color = self::ACCENT_COLOR;

        $this->menu_mode = self::INLINE_MENU;
    }

    public function afterSave()
    {
        Cache::forget(self::CACHE_KEY);
    }

    public static function getLogo()
    {
        $settings = self::instance();
        if (!$settings->logo) {
            return null;
        }

        return $settings->logo->getPath();
    }

    public static function renderCss()
    {
        if (Cache::has(self::CACHE_KEY)) {
            return Cache::get(self::CACHE_KEY);
        }

        try {
            $customCss = self::compileCss();
            Cache::forever(self::CACHE_KEY, $customCss);
        }
        catch (Exception $ex) {
            $customCss = '/* ' . $ex->getMessage() . ' */';
        }

        return $customCss;
    }

    public static function compileCss()
    {
        $parser = new Less_Parser(['compress' => true]);

        $primaryColor = self::get('primary_color', self::PRIMARY_COLOR);
        $secondaryColor = self::get('secondary_color', self::PRIMARY_COLOR);
        $accentColor = self::get('accent_color', self::ACCENT_COLOR);

        $vars = [
            'logo-image'      => "'".self::getLogo()."'",
            'brand-primary'   => $primaryColor,
            'brand-secondary' => $secondaryColor,
            'brand-accent'    => $accentColor,
        ];

        $parser->ModifyVars($vars);

        $parser->parse(
            File::get(base_path().'/modules/backend/models/brandsetting/custom.less') .
            self::get('custom_css')
        );

        $css = $parser->getCss();

        return $css;
    }
}


text:
'use strict';

var should = require('should');

describe('Products Integration Tests:', function() {
    it('should be up and running', function () {

    });
});


text:
package psidev.psi.mi.jami.enricher;

import psidev.psi.mi.jami.model.InteractionEvidence;

/**
 * An enricher for interaction evidences.
 * As well as extending the interaction enricher, this also includes an experiment enricher.
 * Experiment is only found in InteractionEvidence .
 *
 * @author Gabriel Aldam (galdam@ebi.ac.uk)
 * @since 24/07/13

 */
public interface InteractionEvidenceEnricher
        extends InteractionEnricher<InteractionEvidence> {

    /**
     * The experimentEnricher which is currently being used for the enriching or updating of experiments.
     *
     * @return The experiment enricher. Can be null.
     */
    public ExperimentEnricher getExperimentEnricher();

    /**
     *
setExperimentEnricher.

     *
     * @param enricher a {@link psidev.psi.mi.jami.enricher.ExperimentEnricher} object.
     */
    public void setExperimentEnricher(ExperimentEnricher enricher);

}


text:
layout: page
title: Island Industries Executive Retreat
date: 2016-05-24
author: Alice Lynn
tags: weekly links, java
status: published
summary: Cras dignissim finibus varius. Vestibulum cursus lobortis bibendum.
banner: images/banner/people.jpg
booking:
  startDate: 10/31/2016
  endDate: 11/01/2016
  ctyhocn: MFEPRHX
  groupCode: IIER
published: true
---
Duis efficitur, nulla ac commodo commodo, odio enim efficitur diam, vitae dignissim metus urna eu metus. Vivamus feugiat orci quis mauris lobortis bibendum. Aliquam at porta ligula. Vivamus ut leo nec nisi luctus aliquet. Mauris vehicula urna rhoncus vulputate volutpat. Cras pulvinar risus et aliquet semper. Sed odio nibh, dignissim et ullamcorper dignissim, laoreet eleifend sapien. Suspendisse potenti. Quisque non lacus vehicula, tristique ante vel, faucibus ex.
Nulla facilisi. Ut ac felis bibendum quam ornare tempus. Morbi nisi est, iaculis finibus tempus sed, blandit in leo. Nam sollicitudin pharetra eros, in eleifend nulla finibus posuere. Sed accumsan erat quis nulla pharetra malesuada. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Curabitur eget luctus metus. Cras quis scelerisque purus.

* Sed lacinia lorem quis velit ultricies malesuada
* Praesent vel eros at nisl dapibus scelerisque.

Etiam iaculis maximus elit, at auctor tellus pretium nec. Vivamus ultrices ut neque sit amet sollicitudin. Nulla efficitur elementum dapibus. Aenean tincidunt tincidunt mauris. Praesent convallis dolor eros, ut rhoncus mi elementum eget. Aliquam egestas urna ac tincidunt luctus. Praesent id ante vitae urna iaculis mattis in at nunc. Etiam eros purus, finibus pharetra tempor id, tristique vel mi. Aenean quam dui, interdum sit amet tristique non, tristique sit amet risus. Nunc convallis eget risus vitae congue. Vestibulum pulvinar, leo vel tincidunt aliquam, velit erat rhoncus mi, vel molestie elit libero sed augue.


text:
package org.yndongyong.fastandroid.component.slider.Transformers;

import android.view.View;

import com.nineoldandroids.view.ViewHelper;

public class CubeInTransformer extends BaseTransformer {

	@Override
	protected void onTransform(View view, float position) {
		// Rotate the fragment on the left or right edge
        ViewHelper.setPivotX(view,position > 0 ? 0 : view.getWidth());
        ViewHelper.setPivotY(view,0);
        ViewHelper.setRotation(view,-90f * position);
	}

	@Override
	public boolean isPagingEnabled() {
		return true;
	}

}


text:
<?xml version='1.0' encoding='utf-8'?>

<!--L
   Copyright Ekagra Software Technologies Ltd.
   Copyright SAIC, SAIC-Frederick

   Distributed under the OSI-approved BSD 3-Clause License.
   See http://ncip.github.com/common-security-module/LICENSE.txt for details.
L-->

<!DOCTYPE hibernate-mapping
   PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
   "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="test.gov.nih.nci.security.instancelevel.domainobjects">
  <class name="TestUser">
    <id name="id" type="int">
      <generator class="increment"/>
    </id>

    <property name="username" type="string" length="32"/>
    <property name="activated" type="boolean"/>
    <filter name="activatedFilter" condition=":activatedParam = activated"/>
  </class>
  <filter-def name="activatedFilter2">
    <filter-param name="activatedParam" type="boolean"/>
  </filter-def>
</hibernate-mapping>


text:
package io.seata.rm.datasource.undo.parser;

import java.io.IOException;
import java.math.BigDecimal;
import java.sql.JDBCType;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import javax.sql.rowset.serial.SerialBlob;
import javax.sql.rowset.serial.SerialClob;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.seata.common.loader.EnhancedServiceLoader;
import io.seata.rm.datasource.DataCompareUtils;
import io.seata.rm.datasource.sql.struct.Field;
import io.seata.rm.datasource.undo.BaseUndoLogParserTest;
import io.seata.rm.datasource.undo.UndoLogParser;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

/**
 * @author Geng Zhang
 */
public class JacksonUndoLogParserTest extends BaseUndoLogParserTest {

    JacksonUndoLogParser parser = (JacksonUndoLogParser) EnhancedServiceLoader.load(UndoLogParser.class, JacksonUndoLogParser.NAME);

    @Test
    public void encode() throws NoSuchFieldException, IllegalAccessException, IOException, SQLException {
        //get the jackson mapper
        java.lang.reflect.Field reflectField = parser.getClass().getDeclaredField("mapper");
        reflectField.setAccessible(true);
        ObjectMapper mapper = (ObjectMapper)reflectField.get(parser);

        //bigint type
        Field field = new Field("bigint_type", JDBCType.BIGINT.getVendorTypeNumber(), 9223372036854775807L);
        byte[] bytes = mapper.writeValueAsBytes(field);
        Field sameField = mapper.readValue(bytes, Field.class);
        Assertions.assertTrue(DataCompareUtils.isFieldEquals(field, sameField).getResult());

        //big decimal type
        field = new Field("decimal_type", JDBCType.DECIMAL.getVendorTypeNumber(), new BigDecimal("55555555555555555555.55555555555555555555"));
        bytes = mapper.writeValueAsBytes(field);
        sameField = mapper.readValue(bytes, Field.class);
        Assertions.assertTrue(DataCompareUtils.isFieldEquals(field, sameField).getResult());

        //double type
        field = new Field("double_type", JDBCType.DOUBLE.getVendorTypeNumber(), 999999.999999999);
        bytes = mapper.writeValueAsBytes(field);
        sameField = mapper.readValue(bytes, Field.class);
        Assertions.assertTrue(DataCompareUtils.isFieldEquals(field, sameField).getResult());

        //timestamp type: accurate to millisecond
        field = new Field("timestamp_type", JDBCType.TIMESTAMP.getVendorTypeNumber(), Timestamp.valueOf("2021-05-18 17:23:22.111"));
        bytes = mapper.writeValueAsBytes(field);
        sameField = mapper.readValue(bytes, Field.class);
        Assertions.assertTrue(DataCompareUtils.isFieldEquals(field, sameField).getResult());
        //timestamp type: accurate to microseconds
        field = new Field("timestamp_type", JDBCType.TIMESTAMP.getVendorTypeNumber(), Timestamp.valueOf("2019-08-10 10:49:26.926554"));
        bytes = mapper.writeValueAsBytes(field);
        sameField = mapper.readValue(bytes, Field.class);
        Assertions.assertTrue(DataCompareUtils.isFieldEquals(field, sameField).getResult());

        //blob type
        field = new Field("blob_type", JDBCType.BLOB.getVendorTypeNumber(), new SerialBlob("hello".getBytes()));
        bytes = mapper.writeValueAsBytes(field);
        sameField = mapper.readValue(bytes, Field.class);
        Assertions.assertTrue(DataCompareUtils.isFieldEquals(field, sameField).getResult());

        //clob type
        field = new Field("clob_type", JDBCType.CLOB.getVendorTypeNumber(), new SerialClob("hello".toCharArray()));
        bytes = mapper.writeValueAsBytes(field);
        sameField = mapper.readValue(bytes, Field.class);
        Assertions.assertTrue(DataCompareUtils.isFieldEquals(field, sameField).getResult());

        //LocalDateTime type: accurate to millisecond
        LocalDateTime dateTime = LocalDateTime.of(2021, 5, 18, 17, 23, 22, 111000000);
        field = new Field("localdatetime_type", JDBCType.DATE.getVendorTypeNumber(), dateTime);
        bytes = mapper.writeValueAsBytes(field);
        sameField = mapper.readValue(bytes, Field.class);
        Assertions.assertTrue(DataCompareUtils.isFieldEquals(field, sameField).getResult());
        //LocalDateTime type: accurate to microseconds
        dateTime = LocalDateTime.of(2021, 5, 18, 17, 23, 22, 222333000);
        field = new Field("localdatetime_type2", JDBCType.DATE.getVendorTypeNumber(), dateTime);
        bytes = mapper.writeValueAsBytes(field);
        sameField = mapper.readValue(bytes, Field.class);
        Assertions.assertTrue(DataCompareUtils.isFieldEquals(field, sameField).getResult());
    }

    @Override
    public UndoLogParser getParser() {
        return parser;
    }
}


text:
package ru.iitdgroup.lingutil.match;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.function.IntToDoubleFunction;

import com.google.common.collect.Multimap;

/**
 * @author Salauyou
 */
public class MatchCombiner {

    /**
     * Finds best, in terms of score sum, combined match where each word occurs
     * at most once and doesn't overlap with any other
     * @param wordMatches  - matches of words
     * @param distanceCoef - multiplication coefficient applied to score of
     *                       resulting combined submatch, accepting
     *                       distance (in chars) between last two words
     */
    static public Seq findBestCombinedMatch(Multimap<Integer, ScoredMatch> wordMatches,
                                            IntToDoubleFunction distanceCoef) {
        List<Seq> words = new ArrayList<>();
        wordMatches.entries().forEach(e -> words.add(Seq.of(e.getKey(), e.getValue())));
        Collections.sort(words, Comparator.comparing(Seq::effectiveStart));
        Seq best = null;
        List<Seq> seqs = new ArrayList<>();
        for (Seq w : words) {
            int k = seqs.size();
            for (int i = 0; i < k; i++) {
                Seq s  = seqs.get(i);
                Seq ns = s.append(w, distanceCoef.applyAsDouble(w.start - s.end));   // continued sequence
                if (ns != null) {
                    seqs.add(ns);
                    if (best == null || best.score < ns.score)
                        best = ns;
                }
            }
            if (!w.singleWord)
                throw new IllegalArgumentException();
            seqs.add(w);
            if (best == null || best.score < w.score)
                best = w;
        }
        return best;
    }

    static public final class Seq {
        private final Seq pred;
        private final int wordFlags;
        private final int wordNumber;
        private final double coef;

        public final int start, end;
        public final double score;
        public final boolean singleWord;

        private Seq(int wordNumber, int start, int end, double score) {
            if (wordNumber > 31 || wordNumber < 0)
                throw new IllegalArgumentException();
            pred = null;
            this.start = start;
            this.end = end;
            wordFlags = 1 << wordNumber;
            this.score = score;
            this.wordNumber = wordNumber;
            this.singleWord = true;
            this.coef = 1.0;
        }

        private Seq(Seq current, Seq appended, double scoreCoef) {
            if (!appended.singleWord)
                throw new IllegalStateException();
            this.pred = current;
            this.start = appended.start;
            this.end = appended.end;
            this.wordFlags = current.wordFlags | (1 << appended.wordNumber);
            this.score = (current.score + appended.score * current.coef) * scoreCoef;
            this.coef = current.coef * scoreCoef;
            this.wordNumber = appended.wordNumber;
            this.singleWord = false;
        }

        public static Seq of(int wordNumber, int start, int end, double score) {
            return new Seq(wordNumber, start, end, score);
        }

        public static Seq of(int wordNumber, ScoredMatch m) {
            return new Seq(wordNumber, m.start, m.end, m.score);
        }

        public boolean canAppend(Seq s) {
            return s.singleWord && this.end <= s.start
                   && (this.wordFlags | 1 << s.wordNumber) != this.wordFlags;
        }

        public Seq append(Seq s, double scoreCoef) {
            return canAppend(s) ? new Seq(this, s, scoreCoef) : null;
        }

        public int effectiveStart() {
            Seq s = this;
            while (s.pred != null && (s = s.pred) != null);
            return s.start;
        }

        /**
         * Number of subs in this seq
         */
        public int size() {
            int i = 1;
            Seq s = this;
            while ((s = s.pred) != null && i++ > 0);
            return i;
        }

        @Override
        public String toString() {
            Seq s = this;
            String ss = "";
            while (s != null) {
                ss = String.format("%s(%s…%s), ", s.wordNumber, s.start, s.end) + ss;
                s = s.pred;
            }
            return String.format("Seq: %s score=%.2f", ss.substring(0, ss.length() - 2), this.score);
        }
    }

}


text:
using System;
using Alachisoft.NCache.Common.Monitoring;
using Alachisoft.NCache.Caching;
using System.Collections.Generic;

namespace Alachisoft.NCache.SocketServer.Command
{
    class ContainsCommand : CommandBase
    {
        private struct CommandInfo
        {
            public string RequestId;
            public string Key;
        }

        //PROTOBUF
        public override void ExecuteCommand(ClientManager clientManager, Alachisoft.NCache.Common.Protobuf.Command command)
        {
            CommandInfo cmdInfo;

            //TODO
            byte[] data = null;

            try
            {
                cmdInfo = ParseCommand(command, clientManager);
                if (ServerMonitor.MonitorActivity) ServerMonitor.LogClientActivity("ContCmd.Exec", "cmd parsed");

            }
            catch (Exception exc)
            {
                if (!base.immatureId.Equals("-2"))
                    //PROTOBUF:RESPONSE
                    _serializedResponsePackets.Add(Alachisoft.NCache.Common.Util.ResponseHelper.SerializeExceptionResponse(exc, command.requestID));
                return;
            }

            NCache nCache = clientManager.CmdExecuter as NCache;

            try
            {
                bool exists = nCache.Cache.Contains(cmdInfo.Key, new OperationContext(OperationContextFieldName.OperationType, OperationContextOperationType.CacheOperation));
                Alachisoft.NCache.Common.Protobuf.Response response = new Alachisoft.NCache.Common.Protobuf.Response();
                Alachisoft.NCache.Common.Protobuf.ContainResponse containsResponse = new Alachisoft.NCache.Common.Protobuf.ContainResponse();
				response.requestId = Convert.ToInt64(cmdInfo.RequestId);
                containsResponse.exists = exists;
                response.responseType = Alachisoft.NCache.Common.Protobuf.Response.Type.CONTAINS;
                response.contain = containsResponse;

                _serializedResponsePackets.Add(Alachisoft.NCache.Common.Util.ResponseHelper.SerializeResponse(response));
            }
            catch (Exception exc)
            {
                _serializedResponsePackets.Add(Alachisoft.NCache.Common.Util.ResponseHelper.SerializeExceptionResponse(exc, command.requestID));
            }
            if (ServerMonitor.MonitorActivity) ServerMonitor.LogClientActivity("ContCmd.Exec", "cmd executed on cache");

        }

        //PROTOBUF
        private CommandInfo ParseCommand(Alachisoft.NCache.Common.Protobuf.Command command, ClientManager clientManager)
        {
            CommandInfo cmdInfo = new CommandInfo();

            Alachisoft.NCache.Common.Protobuf.ContainsCommand containsCommand = command.containsCommand;

            cmdInfo.Key = containsCommand.key;
            cmdInfo.RequestId = containsCommand.requestId.ToString();

            return cmdInfo;
        }
    }
}


text:
- Low throughput in multiprocessing
- Asyncrhonous or event driven programs
    - has one thread
    - no race conditions

Synchronous
- Blocking IO ops

### Event Loops

Enter twisted

- deferred() - manages callback object aka promise object

## references

- uvloop  (released by magicloops)
- twisted examples - github.com/jdavisp3/twisted


text:
# 15. 内置工具:TypeEventSystem

QFramework 除了提供了一套架构之外,QFramework 还提供三个可以脱离架构使用的工具 TypeEventSystem、EasyEvent、BindableProperty、IOCContainer。

这些工具并不是有意提供,而是 QFramework 的架构在设计之初是通过这三个工具组合使用而成的。

在这一篇,我们来学习 TypeEventSystem 的使用。

## 基本使用

```csharp
using UnityEngine;

namespace QFramework.Example
{
    public class TypeEventSystemBasicExample : MonoBehaviour
    {
        public struct TestEventA
        {
            public int Age;
        }

        private void Start()
        {
            TypeEventSystem.Global.Register<TestEventA>(e =>
            {
                Debug.Log(e.Age);
            }).UnRegisterWhenGameObjectDestroyed(gameObject);
        }

        private void Update()
        {
            // 鼠标左键点击
            if (Input.GetMouseButtonDown(0))
            {
                TypeEventSystem.Global.Send(new TestEventA()
                {
                    Age = 18
                });
            }

            // 鼠标右键点击
            if (Input.GetMouseButtonDown(1))
            {
                TypeEventSystem.Global.Send<TestEventA>();
            }
        }
    }
}

// 输出结果
// 点击鼠标左键,则输出:
// 18
// 点击鼠标右键,则输出:
// 0
```

这就是 TypeEventSystem 的最基本用法。

## 事件继承支持
除了基本用法,TypeEventSystem 的事件还支持继承关系。

示例代码如下:
```csharp
using UnityEngine;

namespace QFramework.Example
{
    public class TypeEventSystemInheritEventExample : MonoBehaviour
    {
        public interface IEventA
        {

        }

        public struct EventB : IEventA
        {

        }

        private void Start()
        {
            TypeEventSystem.Global.Register<IEventA>(e =>
            {
                Debug.Log(e.GetType().Name);
            }).UnRegisterWhenGameObjectDestroyed(gameObject);
        }

        private void Update()
        {
            if (Input.GetMouseButtonDown(0))
            {
                TypeEventSystem.Global.Send<IEventA>(new EventB());

                // 无效
                TypeEventSystem.Global.Send<EventB>();
            }
        }
    }
}

// 输出结果:
// 当按下鼠标左键时,输出:
// EventB
```

代码不难。

## TypeEventSystem 手动注销

如果想控制 TypeEventSystem 的注销,而不是自动注销也很简单,代码如下:

```csharp
using UnityEngine;

namespace QFramework.Example
{
    public class TypeEventSystemUnRegisterExample : MonoBehaviour
    {

        public struct EventA
        {

        }

        private void Start()
        {
            TypeEventSystem.Global.Register<EventA>(OnEventA);
        }

        void OnEventA(EventA e)
        {

        }

        private void OnDestroy()
        {
            TypeEventSystem.Global.UnRegister<EventA>(OnEventA);
        }
    }
}
```

代码也很简单。

## 接口事件

TypeEventSystem 还支持接口事件模式,示例代码如下:

```csharp
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace QFramework.Example
{
    public struct InterfaceEventA
    {

    }

    public struct InterfaceEventB
    {

    }

    public class InterfaceEventModeExample : MonoBehaviour
        , IOnEvent<InterfaceEventA>
        , IOnEvent<InterfaceEventB>
    {
        public void OnEvent(InterfaceEventA e)
        {
            Debug.Log(e.GetType().Name);
        }

        public void OnEvent(InterfaceEventB e)
        {
            Debug.Log(e.GetType().Name);
        }

        private void Start()
        {
            this.RegisterEvent<InterfaceEventA>()
                .UnRegisterWhenGameObjectDestroyed(gameObject);

            this.RegisterEvent<InterfaceEventB>();
        }

        private void OnDestroy()
        {
            this.UnRegisterEvent<InterfaceEventB>();
        }

        private void Update()
        {
            if (Input.GetMouseButtonDown(0))
            {
                TypeEventSystem.Global.Send<InterfaceEventA>();
                TypeEventSystem.Global.Send<InterfaceEventB>();
            }
        }
    }
}

// 输出结果
// 当按下鼠标左键时,输出:
// InterfaceEventA
// InterfaceEventB
```

代码很简单。

同样接口事件也支持事件之间的继承。

接口事件拥有更好的约束,只要完成实现接口,就可以通过 IDE 的代码生成少写很多代码,其灵感受 CorgiEngine、TopDownEngine 启发。

## 非 MonoBehavior 脚本如何自动销毁

```csharp
public class NoneMonoScript : IUnRegisterList
{
    public List<IUnRegister> UnregisterList { get; } = new List<IUnRegister>();

    void Start()
    {
        TypeEventSystem.Global.Register<EasyEventExample.EventA>(a =>
        {

        }).AddToUnregisterList(this);
    }

    void OnDestroy()
    {
        this.UnRegisterAll();
    }
}
```

## 小结
如果想手动注销,必须要创建一个用于接收事件的方法。

而用自动注销则直接用委托即可。

这两个各有优劣,按需使用。

另外,事件的定义最好使用 struct,因为 struct 的 gc 更少,可以获得更好的性能。

接口事件拥有更好的约束,也可以通过 IDE 的代码生成来提高开发效率。

总之 TypeEventSystem 是一个非常强大的事件工具。

## 更多内容

*   转载请注明地址:[liangxiegame.com](https://liangxiegame.com) (首发) 微信公众号:凉鞋的笔记
*   QFramework 主页:[qframework.cn](https://qframework.cn)
*   QFramework 交流群: 623597263
*   QFramework Github 地址: [https://github.com/liangxiegame/qframework](https://github.com/liangxiegame/qframework)
*   QFramework Gitee 地址:[https://gitee.com/liangxiegame/QFramework](https://gitee.com/liangxiegame/QFramework)
*   GamePix 独立游戏学院 & Unity 进阶小班地址:[https://www.gamepixedu.com/](https://www.gamepixedu.com/)


text:
#pragma once
#include <string>
#include <cache.hpp>
#include <kernel_headers/where.hpp>
#include <program.hpp>
#include <traits.hpp>
#include <common/dispatch.hpp>
#include <Param.hpp>
#include <debug_opencl.hpp>
#include <type_util.hpp>
#include "names.hpp"
#include "config.hpp"
#include "scan_first.hpp"
#include <memory.hpp>

using cl::Buffer;
using cl::Program;
using cl::Kernel;
using cl::KernelFunctor;
using cl::EnqueueArgs;
using cl::NDRange;
using std::string;

namespace opencl
{
namespace kernel
{
template<typename T>
static void get_out_idx(Buffer *out_data,
                        Param &otmp, Param &rtmp,
                        Param &in, uint threads_x,
                        uint groups_x, uint groups_y)
{
    std::string refName = std::string("get_out_idx_kernel_") + std::string(dtype_traits<T>::getName());

    int device = getActiveDeviceId();
    kc_entry_t entry = kernelCache(device, refName);

    if (entry.prog==0 && entry.ker==0) {
        ToNumStr<T> toNumStr;
        std::ostringstream options;
        options << " -D T=" << dtype_traits<T>::getName()
                << " -D zero=" << toNumStr(scalar<T>(0))
                << " -D CPLX=" << af::iscplx<T>();
        if (std::is_same<T, double>::value || std::is_same<T, cdouble>::value)
            options << " -D USE_DOUBLE";

        const char* ker_strs[] = {where_cl};
        const int   ker_lens[] = {where_cl_len};
        Program prog;
        buildProgram(prog, 1, ker_strs, ker_lens, options.str());
        entry.prog = new Program(prog);
        entry.ker  = new Kernel(*entry.prog, "get_out_idx_kernel");

        addKernelToCache(device, refName, entry);
    }

    NDRange local(threads_x, THREADS_PER_GROUP / threads_x);
    NDRange global(local[0] * groups_x * in.info.dims[2], local[1] * groups_y * in.info.dims[3]);

    uint lim = divup(otmp.info.dims[0], (threads_x * groups_x));

    auto whereOp = KernelFunctor< Buffer, Buffer, KParam, Buffer, KParam,
                                  Buffer, KParam, uint, uint, uint>(*entry.ker);

    whereOp(EnqueueArgs(getQueue(), global, local),
            *out_data, *otmp.data, otmp.info,
            *rtmp.data, rtmp.info, *in.data, in.info,
            groups_x, groups_y, lim);

    CL_DEBUG_FINISH(getQueue());
}

template<typename T>
static void where(Param &out, Param &in)
{
    uint threads_x = nextpow2(std::max(32u, (uint)in.info.dims[0]));
    threads_x = std::min(threads_x, THREADS_PER_GROUP);
    uint threads_y = THREADS_PER_GROUP / threads_x;

    uint groups_x = divup(in.info.dims[0], threads_x * REPEAT);
    uint groups_y = divup(in.info.dims[1], threads_y);

    Param rtmp;
    Param otmp;

    rtmp.info.dims[0] = groups_x;
    otmp.info.dims[0] = in.info.dims[0];

    rtmp.info.strides[0] = 1;
    otmp.info.strides[0] = 1;

    rtmp.info.offset = 0;
    otmp.info.offset = 0;

    for (int k = 1; k < 4; k++) {
        rtmp.info.dims[k] = in.info.dims[k];
        rtmp.info.strides[k] = rtmp.info.strides[k - 1] * rtmp.info.dims[k - 1];

        otmp.info.dims[k] = in.info.dims[k];
        otmp.info.strides[k] = otmp.info.strides[k - 1] * otmp.info.dims[k - 1];
    }

    int rtmp_elements = rtmp.info.strides[3] * rtmp.info.dims[3];
    rtmp.data = bufferAlloc(rtmp_elements * sizeof(uint));

    int otmp_elements = otmp.info.strides[3] * otmp.info.dims[3];
    otmp.data = bufferAlloc(otmp_elements * sizeof(uint));

    scan_first_launcher<T, uint, af_notzero_t>(otmp, rtmp, in, false, groups_x, groups_y, threads_x);

    // Linearize the dimensions and perform scan
    Param ltmp = rtmp;
    ltmp.info.offset = 0;
    ltmp.info.dims[0] = rtmp_elements;
    for (int k = 1; k < 4; k++) {
        ltmp.info.dims[k] = 1;
        ltmp.info.strides[k] = rtmp_elements;
    }

    scan_first<uint, uint, af_add_t>(ltmp, ltmp);

    // Get output size and allocate output
    uint total;
    getQueue().enqueueReadBuffer(*rtmp.data, CL_TRUE,
                                  sizeof(uint) * (rtmp_elements - 1),
                                  sizeof(uint),
                                  &total);

    out.data = bufferAlloc(total * sizeof(uint));

    out.info.dims[0] = total;
    out.info.strides[0] = 1;
    for (int k = 1; k < 4; k++) {
        out.info.dims[k] = 1;
        out.info.strides[k] = total;
    }

    if (total > 0)
        get_out_idx<T>(out.data, otmp, rtmp, in, threads_x, groups_x, groups_y);

    bufferFree(rtmp.data);
    bufferFree(otmp.data);
}
}
}


text:
window.onload = function () {
    // This is a dirty hack so that we don't expand the code boxes if
    // we think the user is on a phone when the window has finished
    // loading. There should be a way to do this "responsively".
    if (!window.matchMedia('(max-device-width: 600px)').matches) {
        var codes = document.querySelectorAll(".code");
        for (var i = 0; i < codes.length; i++) {
            var style = window.getComputedStyle(codes[i].parentElement, null);
            codes[i].style.height = style.getPropertyValue("height");
        }
    }
    var allTOCs = document.querySelectorAll(".toc");
    for (var i = 0; i < allTOCs.length; i++) {
        adjustIndent(allTOCs[i]);
        var parent = allTOCs[i].parentNode;
        var fullHeight = window.innerHeight - (parent.offsetTop + parent.offsetHeight);
        allTOCs[i].style.height =  fullHeight + "px";
    }
    var names = document.querySelectorAll(".toc-name");
    for (var i = 0; i < names.length; i++) {
        names.item(i).addEventListener("click", function(ev) {
            triggerTOC(ev.target.id);
        });
    }
    var titles = document.querySelectorAll(".node-title");
    for (var i = 0; i < titles.length; i++) {
        titles.item(i).addEventListener("click", function(ev) {
            triggerNode(ev.target.parentNode);
        });
    }
    document.addEventListener("click", function(ev) {
        if (closestClass(ev.target, "tocs") === undefined) {
            for (var i = 0; i < allTOCs.length; i++) {
                deactivateTOC(allTOCs[i]);
            }
        }
    });
};

function closestClass(elem, className) {
    // Get closest match
    for (; elem && elem !== document; elem = elem.parentNode) {
        if (elem.classList.contains(className)) {
            return elem;
        }
    }
}

function adjustIndent(tocNode) {
    var indentMultiplier = 5;
    var nodes = tocNode.querySelectorAll(".node");
    for (var i = 0; i < nodes.length; i++) {
        // First, we get the indent.
        var level = Number(nodes[i].getAttribute("level"));
        // Then we apply the indent to the node-title at one less than
        // the indent level.
        if (level !== 0) {
            var title = nodes[i].querySelector(".node-title");
            title.style.textIndent = (indentMultiplier * (level - 1)) + "px";
        }
        // Finally, we apply the indent to all of the node-path
        // elements.
        var paths = nodes[i].querySelectorAll(".node-path");
        for (var j = 0; j < paths.length; j++) {
            paths[j].style.textIndent = (indentMultiplier * level) + "px";
        }
    }
}

function triggerTOC(id) {
    var allTOCs = document.querySelectorAll(".toc");
    var tocID = id + "-toc";
    var activated;
    for (var i = 0; i < allTOCs.length; i++) {
        var root = allTOCs[i];
        if (root.id == tocID && !root.classList.contains("active")) {
            root.classList.add("active");
            activated = root;
            root.parentNode.querySelector(".toc-name").classList.add("active");
            root.querySelector(".node-body").classList.add("active");
            root.querySelector(".carrot").classList.add("fa-rotate-90");
        } else {
            deactivateTOC(root)
        }
    }
    if (activated) {
        root.parentNode.classList.add("active");
    }
}

function deactivateTOC(root) {
    if (root.classList.contains("active")) {
        root.classList.remove("active");
        root.parentNode.classList.remove("active");
        root.parentNode.querySelector(".toc-name").classList.remove("active");
        deactivateAll(root.querySelector(".node"));
    }
}

function deactivateAll(node) {
    var nodes = node.querySelectorAll(".node-body");
    for (var i = 0; i < nodes.length; i++) {
        nodes[i].classList.remove("active");
    }
    var carrots = node.querySelectorAll(".carrot");
    for (var i = 0; i < carrots.length; i++) {
        carrots[i].classList.remove("fa-rotate-90");
    }
}

function triggerNode(node) {
    var body = node.querySelector(".node-body");
    if (!body.classList.contains("active")) {
        body.classList.add("active");
        body.parentNode.querySelector(".carrot").classList.add("fa-rotate-90");
    } else {
        deactivateAll(body.parentNode);
    }
}


text:
package org.olat.core.commons.persistence;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;

import org.hibernate.FlushMode;
import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.type.Type;
import org.olat.core.logging.DBRuntimeException;
import org.olat.core.logging.Tracing;
import org.olat.testutils.codepoints.server.Codepoint;
/**
 * A <b>DBQueryImpl</b> is a wrapper around a Hibernate Query object.
 *
 * @author Andreas Ch. Kapp
 *
 */
public class DBQueryImpl implements DBQuery {

	private Query query = null;

	public final static Map<String, SimpleProbe> listTableStatsMap_ = new HashMap<String, SimpleProbe>();

	public final static Set<String> registeredTables_ = new HashSet<String>();

	static {
		registeredTables_.add("org.olat.basesecurity.SecurityGroupMembershipImpl");
		registeredTables_.add("org.olat.group.area.BGAreaImpl");
		registeredTables_.add("org.olat.group.BusinessGroupImpl");
		registeredTables_.add("org.olat.resource.OLATResourceImpl");
		registeredTables_.add("org.olat.commons.lifecycle.LifeCycleEntry");
	}

	/**
	 * Default construcotr.
	 * @param q
	 */
	public DBQueryImpl(Query q) {
		query = q;
	}

	/**
	 * @see org.olat.core.commons.persistence.DBQuery#setLong(java.lang.String, long)
	 */
	public DBQuery setLong(String string, long value) {
		query.setLong(string, value);
		return this;
	}

	/**
	 * @see org.olat.core.commons.persistence.DBQuery#setString(java.lang.String, java.lang.String)
	 */
	public DBQuery setString(String string, String value) {
		query.setString(string, value);
		return this;
	}

	/**
	 * @see org.olat.core.commons.persistence.DBQuery#setTime(java.lang.String, java.util.Date)
	 */
	public DBQuery setTime(String name, Date date){
		query.setTime(name, date);
		return this;
	}

	/**
	 * @see org.olat.core.commons.persistence.DBQuery#executeUpdate(FlushMode)
	 */
	public int executeUpdate(FlushMode nullOrFlushMode) {
		if (nullOrFlushMode!=null) {
			query.setFlushMode(nullOrFlushMode);
		}
		return query.executeUpdate();
	}

	/**
	 * @see org.olat.core.commons.persistence.DBQuery#list()
	 */
	public List list() {
		Codepoint.codepoint(getClass(), "list-entry");
		final long startTime = System.currentTimeMillis();
		try{
			boolean doLog = Tracing.isDebugEnabled(DBQueryImpl.class);
			long start = 0;
			if (doLog) start = System.currentTimeMillis();
			List li = query.list();
			if (doLog) {
				long time = (System.currentTimeMillis() - start);
				Tracing.logDebug("list dbquery (time "+time+") query "+getQueryString(), DBQueryImpl.class);
			}
			String queryString = query.getQueryString().trim();
			String queryStringToLowerCase = queryString.toLowerCase();
			if (queryStringToLowerCase.startsWith("from ")) {
				queryString = queryString.substring(5).trim();
				queryStringToLowerCase = queryString.toLowerCase();
			} else if (queryStringToLowerCase.startsWith("select ") && (queryStringToLowerCase.contains(" from "))) {
				queryString = queryString.substring(queryStringToLowerCase.indexOf(" from ")+6).trim();
				queryStringToLowerCase = queryString.toLowerCase();
			} else {
				queryString = null;
			}
			if (queryString!=null) {
				final long endTime = System.currentTimeMillis();
				final long diff = endTime - startTime;
				int wherePos = queryStringToLowerCase.indexOf(" where ");
				if (wherePos!=-1) {
					queryString = queryString.substring(0, wherePos);
				}
				queryString = queryString.trim();
				StringTokenizer st = new StringTokenizer(queryString, ",");
				while(st.hasMoreTokens()) {
					String aTable = st.nextToken();
					aTable = aTable.trim();
					int spacePos = aTable.toLowerCase().indexOf(" ");
					if (spacePos!=-1) {
						aTable = aTable.substring(0, spacePos);
					}
					aTable = aTable.trim();
					SimpleProbe probe = listTableStatsMap_.get(aTable);
					if (probe==null) {
						probe = new SimpleProbe();
						listTableStatsMap_.put(aTable, probe);
					}
					probe.addMeasurement(diff);
					if (!registeredTables_.contains(aTable)) {
						aTable = "THEREST";
						probe = listTableStatsMap_.get(aTable);
						if (probe==null) {
							probe = new SimpleProbe();
							listTableStatsMap_.put(aTable, probe);
						}
						probe.addMeasurement(diff);
					}
					//System.out.println(" A TABLE: "+aTable+" stats: "+probe);
				}
			}
			return li;
		}
		catch (HibernateException he) {
			String msg ="Error in list()" ;
			throw new DBRuntimeException(msg, he);
		} finally {
			Codepoint.codepoint(getClass(), "list-exit", query);
		}
	}

	/**
	 * @see org.olat.core.commons.persistence.DBQuery#getNamedParameters()
	 */
	public String[] getNamedParameters() {
		try {
			return query.getNamedParameters();
		}
		catch (HibernateException e) {
			throw new DBRuntimeException("GetNamedParameters failed. ", e);
		}
	}

	/**
	 * @see org.olat.core.commons.persistence.DBQuery#getQueryString()
	 */
	public String getQueryString() {
		return query.getQueryString();
	}

	/**
	 * @see org.olat.core.commons.persistence.DBQuery#getReturnTypes()
	 */
	public Type[] getReturnTypes() {

		try {
			return query.getReturnTypes();
		}
		catch (HibernateException e) {
			throw new DBRuntimeException("GetReturnTypes failed. ", e);
		}
	}

	/**
	 * @return iterator
	 */
	public Iterator iterate() {
		try {
			return query.iterate();
		}
		catch (HibernateException e) {
			throw new DBRuntimeException("Iterate failed. ", e);
		}
	}

	/*public ScrollableResults scroll() {
		try {
			return query.scroll();
		}
		catch (HibernateException e) {
			throw new DBRuntimeException("Scroll failed. ", e);
		}
	}*/

	/**
	 * @see org.olat.core.commons.persistence.DBQuery#setBigDecimal(int, java.math.BigDecimal)
	 */
	public DBQuery setBigDecimal(int position, BigDecimal number) {
		query.setBigDecimal(position, number);
		return this;
	}

	/**
	 * @see org.olat.core.commons.persistence.DBQuery#setBigDecimal(java.lang.String, java.math.BigDecimal)
	 */
	public DBQuery setBigDecimal(String name, BigDecimal number) {
		query.setBigDecimal(name, number);
		return this;
	}

	/**
	 * @see org.olat.core.commons.persistence.DBQuery#setBinary(int, byte[])
	 */
	public DBQuery setBinary(int position, byte[] val) {
		query.setBinary(position, val);
		return this;
	}

	/**
	 * @see org.olat.core.commons.persistence.DBQuery#setBinary(java.lang.String, byte[])
	 */
	public DBQuery setBinary(String name, byte[] val) {
		query.setBinary(name, val);
		return this;	}

	/**
	 * @see org.olat.core.commons.persistence.DBQuery#setBoolean(int, boolean)
	 */
	public DBQuery setBoolean(int position, boolean val) {
		query.setBoolean(position, val);
		return this;
	}

	/**
	 * @see org.olat.core.commons.persistence.DBQuery#setBoolean(java.lang.String, boolean)
	 */
	public DBQuery setBoolean(String name, boolean val) {
		query.setBoolean(name, val);
		return this;
	}

	/**
	 * @see org.olat.core.commons.persistence.DBQuery#setByte(int, byte)
	 */
	public DBQuery setByte(int position, byte val) {
		query.setByte(position, val);
		return this;
	}

	/**
	 * @see org.olat.core.commons.persistence.DBQuery#setByte(java.lang.String, byte)
	 */
	public DBQuery setByte(String name, byte val) {
		query.setByte(name, val);
		return this;
	}

	/**
	 * @see org.olat.core.commons.persistence.DBQuery#setCacheable(boolean)
	 */
	public DBQuery setCacheable(boolean cacheable) {
		query.setCacheable(cacheable);
		return this;
	}

	/**
	 * @see org.olat.core.commons.persistence.DBQuery#setCacheRegion(java.lang.String)
	 */
	public DBQuery setCacheRegion(String cacheRegion) {
		query.setCacheRegion(cacheRegion);
		return this;
	}

	/**
	 * @see org.olat.core.commons.persistence.DBQuery#setCalendar(int, java.util.Calendar)
	 */
	public DBQuery setCalendar(int position, Calendar calendar) {
		query.setCalendar(position, calendar);
		return this;
	}

	/**
	 * @see org.olat.core.commons.persistence.DBQuery#setCalendar(java.lang.String, java.util.Calendar)
	 */
	public DBQuery setCalendar(String name, Calendar calendar) {
		query.setCalendar(name, calendar);
		return this;
	}

	/**
	 * @see org.olat.core.commons.persistence.DBQuery#setCalendarDate(int, java.util.Calendar)
	 */
	public DBQuery setCalendarDate(int position, Calendar calendar) {
		query.setCalendarDate(position, calendar);
		return this;

	}

	/**
	 * @see org.olat.core.commons.persistence.DBQuery#setCalendarDate(java.lang.String, java.util.Calendar)
	 */
	public DBQuery setCalendarDate(String name, Calendar calendar) {
		query.setCalendarDate(name, calendar);
		return this;
	}

	/**
	 * @see org.olat.core.commons.persistence.DBQuery#setCharacter(int, char)
	 */
	public DBQuery setCharacter(int position, char val) {
		query.setCharacter(position, val);
		return this;
	}

	/**
	 * @see org.olat.core.commons.persistence.DBQuery#setCharacter(java.lang.String, char)
	 */
	public DBQuery setCharacter(String name, char val) {
		query.setCharacter(name, val);
		return this;

	}

	/**
	 * @see org.olat.core.commons.persistence.DBQuery#setDate(int, java.util.Date)
	 */
	public DBQuery setDate(int position, Date date) {
		query.setDate(position, date);
		return this;

	}

	/**
	 * @see org.olat.core.commons.persistence.DBQuery#setDate(java.lang.String, java.util.Date)
	 */
	public DBQuery setDate(String name, Date date) {
		query.setDate(name, date);
		return this;	}

	/**
	 * @see org.olat.core.commons.persistence.DBQuery#setDouble(int, double)
	 */
	public DBQuery setDouble(int position, double val) {
		query.setDouble(position, val);
		return this;
	}

	/**
	 * @see org.olat.core.commons.persistence.DBQuery#setDouble(java.lang.String, double)
	 */
	public DBQuery setDouble(String name, double val) {
		query.setDouble(name, val);
		return this;
	}

	/**
	 * @see org.olat.core.commons.persistence.DBQuery#setEntity(int, java.lang.Object)
	 */
	public DBQuery setEntity(int position, Object val) {
		query.setEntity(position, val);
		return this;
	}

	/**
	 * @see org.olat.core.commons.persistence.DBQuery#setEntity(java.lang.String, java.lang.Object)
	 */
	public DBQuery setEntity(String name, Object val) {
		query.setEntity(name, val);
		return this;
	}

	/**
	 * @see org.olat.core.commons.persistence.DBQuery#setFirstResult(int)
	 */
	public DBQuery setFirstResult(int firstResult) {
		query.setFirstResult(firstResult);
		return this;
	}

	/**
	 * @see org.olat.core.commons.persistence.DBQuery#setFloat(int, float)
	 */
	public DBQuery setFloat(int position, float val) {
		query.setFloat(position, val);
		return this;
	}

	/**
	 * @see org.olat.core.commons.persistence.DBQuery#setFloat(java.lang.String, float)
	 */
	public DBQuery setFloat(String name, float val) {
		query.setFloat(name, val);
		return this;
	}

	/**
	 * @see org.olat.core.commons.persistence.DBQuery#setInteger(int, int)
	 */
	public DBQuery setInteger(int position, int val) {
		query.setInteger(position, val);
		return this;
	}

	/**
	 * @see org.olat.core.commons.persistence.DBQuery#setInteger(java.lang.String, int)
	 */
	public DBQuery setInteger(String name, int val) {
		query.setInteger(name, val);
		return this;
	}

	/**
	 * @see org.olat.core.commons.persistence.DBQuery#setLocale(int, java.util.Locale)
	 */
	public DBQuery setLocale(int position, Locale locale) {
		query.setLocale(position, locale);
		return this;
	}

	/**
	 * @see org.olat.core.commons.persistence.DBQuery#setLocale(java.lang.String, java.util.Locale)
	 */
	public DBQuery setLocale(String name, Locale locale) {
		query.setLocale(name, locale);
		return this;
	}

	/**
	 * @see org.olat.core.commons.persistence.DBQuery#setLockMode(java.lang.String, org.hibernate.LockMode)
	 */
	public void setLockMode(String alias, LockMode lockMode) {
		query.setLockMode(alias, lockMode);

	}

	/**
	 * @see org.olat.core.commons.persistence.DBQuery#setLong(int, long)
	 */
	public DBQuery setLong(int position, long val) {
		query.setLong(position, val);
		return this;
	}

	/**
	 * @see org.olat.core.commons.persistence.DBQuery#setMaxResults(int)
	 */
	public DBQuery setMaxResults(int maxResults) {
		query.setMaxResults(maxResults);
		return this;
	}

	/**
	 * @see org.olat.core.commons.persistence.DBQuery#setParameter(int, java.lang.Object, org.hibernate.type.Type)
	 */
	public DBQuery setParameter(int position, Object val, Type type) {
		query.setParameter(position, val, type);
		return this;
	}

	/**
	 * @see org.olat.core.commons.persistence.DBQuery#setParameter(int, java.lang.Object)
	 */
	public DBQuery setParameter(int position, Object val) {
		try {
			query.setParameter(position, val);
		}
		catch (HibernateException e) {
			throw new DBRuntimeException("DBQuery error. ", e);
		}
		return this;
	}

	/**
	 * @see org.olat.core.commons.persistence.DBQuery#setParameter(java.lang.String, java.lang.Object, org.hibernate.type.Type)
	 */
	public DBQuery setParameter(String name, Object val, Type type) {
		query.setParameter(name, val, type);
		return this;
	}

	/**
	 * @see org.olat.core.commons.persistence.DBQuery#setParameter(java.lang.String, java.lang.Object)
	 */
	public DBQuery setParameter(String name, Object val) {
		try {
			query.setParameter(name, val);
		}
		catch (HibernateException e) {
			throw new DBRuntimeException("DBQuery error. ", e);
		}
		return this;
	}

	/**
	 * @see org.olat.core.commons.persistence.DBQuery#setParameterList(java.lang.String, java.util.Collection, org.hibernate.type.Type)
	 */
	public DBQuery setParameterList(String name, Collection vals, Type type) {
		try {
			query.setParameterList(name, vals, type);
		}
		catch (HibernateException e) {
			throw new DBRuntimeException("DBQuery error. ", e);
		}
		return this;
	}

	/**
	 * @see org.olat.core.commons.persistence.DBQuery#setParameterList(java.lang.String, java.util.Collection)
	 */
	public DBQuery setParameterList(String name, Collection vals) {
		try {
			query.setParameterList(name, vals);
		}
		catch (HibernateException e) {
			throw new DBRuntimeException("DBQuery error. ", e);
		}
		return this;
	}

	/**
	 * @see org.olat.core.commons.persistence.DBQuery#setParameterList(java.lang.String, java.lang.Object[], org.hibernate.type.Type)
	 */
	public DBQuery setParameterList(String name, Object[] vals, Type type) {
		try {
			query.setParameterList(name, vals, type);
		}
		catch (HibernateException e) {
			throw new DBRuntimeException("DBQuery error. ", e);
		}
		return this;
	}

	/**
	 * @see org.olat.core.commons.persistence.DBQuery#setParameterList(java.lang.String, java.lang.Object[])
	 */
	public DBQuery setParameterList(String name, Object[] vals) {
		try {
			query.setParameterList(name, vals);
		}
		catch (HibernateException e) {
			throw new DBRuntimeException("DBQuery error. ", e);
		}
		return this;
	}

	/**
	 * @see org.olat.core.commons.persistence.DBQuery#setProperties(java.lang.Object)
	 */
	public DBQuery setProperties(Object bean) {
		try {
			query.setProperties(bean);
		}
		catch (HibernateException e) {
			throw new DBRuntimeException("DBQuery error. ", e);
		}
		return this;
	}

	public DBQuery setProperties(Map map) {
		try {
			query.setProperties(map);
		}
		catch (HibernateException e) {
			throw new DBRuntimeException("DBQuery error. ", e);
		}
		return this;
	}

	/**
	 * @see org.olat.core.commons.persistence.DBQuery#setSerializable(int, java.io.Serializable)
	 */
	public DBQuery setSerializable(int position, Serializable val) {
		query.setSerializable(position, val);
		return this;
	}

	/**
	 * @see org.olat.core.commons.persistence.DBQuery#setSerializable(java.lang.String, java.io.Serializable)
	 */
	public DBQuery setSerializable(String name, Serializable val) {
		query.setSerializable(name, val);
		return this;
	}

	/**
	 * @see org.olat.core.commons.persistence.DBQuery#setShort(int, short)
	 */
	public DBQuery setShort(int position, short val) {
		query.setShort(position, val);
		return this;
	}

	/**
	 * @see org.olat.core.commons.persistence.DBQuery#setShort(java.lang.String, short)
	 */
	public DBQuery setShort(String name, short val) {
		query.setShort(name, val);
		return this;
	}

	/**
	 * @see org.olat.core.commons.persistence.DBQuery#setString(int, java.lang.String)
	 */
	public DBQuery setString(int position, String val) {
		query.setString(position, val);
		return this;
	}

	/**
	 * @see org.olat.core.commons.persistence.DBQuery#setText(int, java.lang.String)
	 */
	public DBQuery setText(int position, String val) {
		query.setText(position, val);
		return this;
	}

	/**
	 * @see org.olat.core.commons.persistence.DBQuery#setText(java.lang.String, java.lang.String)
	 */
	public DBQuery setText(String name, String val) {
		query.setText(name, val);
		return this;
	}

	/**
	 * @see org.olat.core.commons.persistence.DBQuery#setTime(int, java.util.Date)
	 */
	public DBQuery setTime(int position, Date date) {
		query.setTime(position, date);
		return this;
	}

	/**
	 * @see org.olat.core.commons.persistence.DBQuery#setTimeout(int)
	 */
	public DBQuery setTimeout(int timeout) {
		query.setTimeout(timeout);
		return this;
	}

	/**
	 * @see org.olat.core.commons.persistence.DBQuery#setTimestamp(int, java.util.Date)
	 */
	public DBQuery setTimestamp(int position, Date date) {
		query.setTimestamp(position, date);
		return this;
	}

	/**
	 * @see org.olat.core.commons.persistence.DBQuery#setTimestamp(java.lang.String, java.util.Date)
	 */
	public DBQuery setTimestamp(String name, Date date) {
		query.setTimestamp(name, date);
		return this;
	}

	/**
	 * @see org.olat.core.commons.persistence.DBQuery#uniqueResult()
	 */
	public Object uniqueResult() {
		try {
			return query.uniqueResult();
		}
		catch (HibernateException e) {
			throw new DBRuntimeException("DBQuery error. ", e);
		}
	}

}


text:
if [ -n "$DEBUG" ]; then
  echo "$0: Setting bash option -x for debug"
  PS4='+($(basename ${BASH_SOURCE}):${LINENO}): ${FUNCNAME[0]:+${FUNCNAME[0]}(): }'
  set -x
fi

# Exit on error
set -e; set -o pipefail

PFX=${PFX:-==>}
HOME=${HOME:?}
DOTFILES_DIR=${DOTFILES_DIR:?}
HOMEBREW_URL=${HOMEBREW_URL:?}
PACKAGES=(
  ack
  awscli
  cmake
  git
  git-extras
  mongodb-community@4.0
  httpie
  heroku
  iperf
  jq
  neovim
  openssl
  redis
  tree
  watch
  wget
  doctl
)

function installHomebrew() {
  echo "$PFX Installing homebrew..."

  if [ ! -x /usr/local/bin/brew ]; then
    echo "$PFX Homebrew url: $HOMEBREW_URL"
    ruby -e "$(curl -fsSL $HOMEBREW_URL)"
  else
    echo "$PFX Homebrew already installed, skipping..."
  fi
}

function addHomebrewTaps() {
  echo "$PFX Adding homebrew taps..."

  brew tap mongodb/brew
  brew tap heroku/brew
}

function installHomebrewPackages() {
  echo "$PFX Installing homebrew packages..."

  for PACKAGE in "${PACKAGES[@]}"; do
    echo "$PFX Installing package: $PACKAGE"
    brew install $PACKAGE
    configurePackage $PACKAGE
    echo "$PFX Install complete: $(date +"%Y-%m-%d-%H%M%S")"
  done
}

function configurePackage() {
  local PACKAGE=$1

  local CONFIGURATIONS_DIR=$DOTFILES_DIR/bin/install/osx/configurations/cli
  local CONFIGURATION_SCRIPT_NAME=$(echo $PACKAGE | cut -d@ -f1).sh
  local CONFIGURATION_SCRIPT=$CONFIGURATIONS_DIR/$CONFIGURATION_SCRIPT_NAME

  if [ -e $CONFIGURATION_SCRIPT ]; then
    $CONFIGURATION_SCRIPT
  else
    echo "$PFX No configuration script..."
  fi
}

#
# Main
#

installHomebrew
addHomebrewTaps
installHomebrewPackages

exit 0


text:
<resources>
    <string name="app_name">AT90AppListLoader</string>

    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>

    <string name="menu_configure_locale">Change language</string>
</resources>


text:
<?php

declare(strict_types=1);

namespace Knp\DoctrineBehaviors\Tests\Fixtures\Entity\Translatable;

use Doctrine\ORM\Mapping\Column;
use Doctrine\ORM\Mapping\DiscriminatorColumn;
use Doctrine\ORM\Mapping\Entity;
use Doctrine\ORM\Mapping\GeneratedValue;
use Doctrine\ORM\Mapping\Id;
use Doctrine\ORM\Mapping\InheritanceType;
use Knp\DoctrineBehaviors\Contract\Entity\TranslationInterface;
use Knp\DoctrineBehaviors\Exception\ShouldNotHappenException;
use Knp\DoctrineBehaviors\Model\Translatable\TranslationTrait;

#[Entity]
#[InheritanceType(value: 'JOINED')]
#[DiscriminatorColumn(name:'handle', type:'string')]
class TranslatableEntityWithJoinTableInheritanceTranslation implements TranslationInterface
{
    use TranslationTrait;

    #[Id]
    #[Column(type: 'integer')]
    #[GeneratedValue(strategy: 'AUTO')]
    private int $id;

    #[Column(type: 'string')]
    private ?string $title = null;

    public function getId(): int
    {
        return $this->id;
    }

    /**
     * @throws ShouldNotHappenException
     */
    public function getTitle(): string
    {
        if ($this->title === null) {
            throw new ShouldNotHappenException();
        }

        return $this->title;
    }

    public function setTitle(string $title): void
    {
        $this->title = $title;
    }
}


text:
if (window.testRunner)
    testRunner.dumpAsText();

var testStyles = document.createElement('style');
testStyles.innerText = ".test-pass { color: green; } .test-fail { color: red; }";
document.querySelector('head').appendChild(testStyles);

var g_testIndex = 0;
var g_log = ["You should see a series of PASS lines."];

// Make async actually be sync for the sake of simpler testing.
function async(func, args)
{
    func.apply(null, args);
}

function mockResults()
{
    return {
        tests: {},
        "skipped": 0,
        "num_regressions": 0,
        "version": 0,
        "num_passes": 0,
        "fixable": 0,
        "num_flaky": 0,
        "layout_tests_dir": "/WEBKITROOT",
        "chromium_revision": 12345,
        "pixel_tests_enabled": true
    };
}

function isFailureExpected(expected, actual)
{
    var isExpected = true;
    if (actual != 'SKIP') {
        var expectedArray = expected.split(' ');
        var actualArray = actual.split(' ');
        for (var i = 0; i < actualArray.length; i++) {
            var actualValue = actualArray[i];
            if (expectedArray.indexOf(actualValue) == -1 &&
                (expectedArray.indexOf('FAIL') == -1 ||
                 (actualValue != 'TEXT' && actualValue != 'IMAGE+TEXT' && actualValue != 'AUDIO')))
                isExpected = false;
        }
    }
    return isExpected;
}

function mockExpectation(expected, actual)
{
    return {
        expected: expected,
        time_ms: 1,
        actual: actual,
        has_stderr: false,
        is_unexpected: !isFailureExpected(expected, actual)
    };
}

function currentTestName() {
    var testName = 'TEST ' + g_testIndex;
    if (g_testName)
        testName += ' (' + g_testName + ')';
    return testName;
}

function logPass(msg)
{
    g_log.push('' + msg + ': ' + currentTestName())
}

function logFail(msg)
{
    g_log.push('' + msg + ': ' + currentTestName())
}

function assertTrue(bool)
{
    if (bool)
        logPass('PASS');
    else
        logFail('FAIL');
}

function runTest(results, assertions, opt_testName, opt_localStorageValue)
{
    document.body.innerHTML = '';
    g_testIndex++;
    g_state = undefined;
    g_testName = opt_testName || '';
    localStorage.setItem(OptionWriter._key, opt_localStorageValue || '');

    try {
        ADD_RESULTS(results);
        originalGeneratePage();
    } catch (e) {
        logFail("FAIL: uncaught exception " + e.toString());
    }

    try {
        assertions();
    } catch (e) {
        logFail("FAIL: uncaught exception executing assertions " + e.toString());
    }
}

function runDefaultSingleRowTest(test, expected, actual, isExpected, textResults, imageResults, opt_testName)
{
    results = mockResults();
    results.tests[test] = mockExpectation(expected, actual);
    runSingleRowTest(results, isExpected, textResults, imageResults, opt_testName);
}

function runSingleRowTest(results, isExpected, textResults, imageResults, opt_testName)
{
    for (var key in results.tests)
        var test = key;
    var expected = results.tests[test].expected;
    var actual = results.tests[test].actual;
    runTest(results, function() {
        if (isExpected)
            assertTrue(document.querySelector('tbody').className == 'expected');
        else
            assertTrue(document.querySelector('tbody').className.indexOf('expected') == -1);

        assertTrue(document.querySelector('tbody td:nth-child(1)').textContent == '+' + test + ' \u2691');
        assertTrue(document.querySelector('tbody td:nth-child(2)').textContent == textResults);
        assertTrue(document.querySelector('tbody td:nth-child(3)').textContent == imageResults);
        assertTrue(document.querySelector('tbody td:nth-child(4)').textContent == actual);
        assertTrue(document.querySelector('tbody td:nth-child(5)').textContent == expected);
    }, opt_testName || 'single row test');

}

function runTests()
{
    var results = mockResults();
    var subtree = results.tests['foo'] = {}
    subtree['bar.html'] = mockExpectation('PASS', 'TEXT');
    runTest(results, function() {
        assertTrue(document.getElementById('image-results-header').textContent == '');
        assertTrue(document.getElementById('text-results-header').textContent != '');
    }, 'text results header');

    results = mockResults();
    var subtree = results.tests['foo'] = {}
    subtree['bar.html'] = mockExpectation('TEXT', 'MISSING');
    subtree['bar.html'].is_missing_text = true;
    subtree['bar.html'].is_missing_audio = true;
    subtree['bar.html'].is_missing_image = true;
    runTest(results, function() {
        assertTrue(!document.getElementById('results-table'));
        assertTrue(document.querySelector('#missing-table .test-link').textContent == 'foo/bar.html');
        assertTrue(document.getElementsByClassName('result-link')[0].textContent == 'audio result');
        assertTrue(document.getElementsByClassName('result-link')[1].textContent == 'result');
        assertTrue(document.getElementsByClassName('result-link')[2].textContent == 'png result');
    }, 'actual result links');

    results = mockResults();
    var subtree = results.tests['foo'] = {}
    subtree['bar.html'] = mockExpectation('PASS', 'TEXT');
    subtree['bar.html'].has_stderr = true;
    runTest(results, function() {
        assertTrue(document.getElementById('results-table'));
        assertTrue(document.querySelector('#stderr-table .result-link').textContent == 'stderr');
    }, 'stderr link');

    results = mockResults();
    var subtree = results.tests['foo'] = {}
    subtree['bar.html'] = mockExpectation('TEXT', 'PASS');
    subtree['bar1.html'] = mockExpectation('CRASH', 'PASS');
    subtree['bar2.html'] = mockExpectation('IMAGE', 'PASS');
    subtree['crash.html'] = mockExpectation('IMAGE', 'CRASH');
    subtree['timeout.html'] = mockExpectation('IMAGE', 'TIMEOUT');
    runTest(results, function() {
        assertTrue(!document.getElementById('results-table'));

        var testLinks = document.querySelectorAll('#passes-table .test-link');
        assertTrue(testLinks[0].textContent == 'foo/bar.html');
        assertTrue(testLinks[1].textContent == 'foo/bar1.html');
        assertTrue(testLinks[2].textContent == 'foo/bar2.html');

        assertTrue(!document.querySelector('#passes-table .expand-button'));

        var expectationTypes = document.querySelectorAll('#passes-table td:last-of-type');
        assertTrue(expectationTypes[0].textContent == 'TEXT');
        assertTrue(expectationTypes[1].textContent == 'CRASH');
        assertTrue(expectationTypes[2].textContent == 'IMAGE');

        assertTrue(document.getElementById('crash-tests-table'));
        assertTrue(document.getElementById('crash-tests-table').textContent.indexOf('crash log') != -1);
        assertTrue(document.getElementById('timeout-tests-table'));
        assertTrue(document.getElementById('timeout-tests-table').textContent.indexOf('expected actual diff') != -1);
    }, 'crash and timeout tests tables');

    function isExpanded(expandLink)
    {
        var enDash = '\u2013';
        return expandLink.textContent == enDash;
    }

    function isCollapsed(expandLink)
    {
        return expandLink.textContent == '+';
    }

    results = mockResults();
    var subtree = results.tests['foo'] = {}
    subtree['bar.html'] = mockExpectation('TEXT', 'PASS');
    subtree['bar-missing.html'] = mockExpectation('TEXT', 'MISSING');
    subtree['bar-missing.html'].is_missing_text = true;
    subtree['bar-stderr.html'] = mockExpectation('PASS', 'TEXT');
    subtree['bar-stderr.html'].has_stderr = true;
    subtree['bar-unexpected-pass.html'] = mockExpectation('TEXT', 'PASS');
    runTest(results, function() {
        assertTrue(document.querySelectorAll('tbody tr').length == 5);
        expandAllExpectations();
        assertTrue(document.querySelectorAll('tbody tr').length == 8);
        var expandLinks = document.querySelectorAll('.expand-button-text');
        for (var i = 0; i < expandLinks.length; i++)
            assertTrue(isExpanded(expandLinks[i]));

        collapseAllExpectations();
        // Collapsed expectations stay in the dom, but are display:none.
        assertTrue(document.querySelectorAll('tbody tr').length == 8);
        var expandLinks = document.querySelectorAll('.expand-button-text');
        for (var i = 0; i < expandLinks.length; i++)
            assertTrue(isCollapsed(expandLinks[i]));

        expandExpectations(expandLinks[1]);
        assertTrue(isCollapsed(expandLinks[0]));
        assertTrue(isExpanded(expandLinks[1]));

        collapseExpectations(expandLinks[1]);
        assertTrue(expandLinks[1].textContent == '+');
    }, 'collapsing expectation rows');

    results = mockResults();
    var subtree = results.tests['foo'] = {}
    subtree['bar.html'] = mockExpectation('PASS', 'TEXT');
    subtree['bar-expected-fail.html'] = mockExpectation('TEXT', 'TEXT');
    runTest(results, function() {
        assertTrue(document.querySelectorAll('.expected').length == 1);
        assertTrue(document.querySelector('.expected .test-link').textContent == 'foo/bar-expected-fail.html');

        assertTrue(window.getComputedStyle(document.querySelectorAll('tbody')[0], null)['display'] == 'none');

        expandAllExpectations();
        assertTrue(visibleExpandLinks().length == 1);
        assertTrue(document.querySelectorAll('.results-row').length == 1);
        assertTrue(window.getComputedStyle(document.querySelectorAll('tbody')[0], null)['display'] == 'none');

        document.getElementById('show-expected-failures').checked = true;
        document.getElementById('show-expected-failures').onchange();

        assertTrue(visibleExpandLinks().length == 2);
        assertTrue(document.querySelectorAll('.results-row').length == 1);
        assertTrue(window.getComputedStyle(document.querySelectorAll('tbody')[0], null)['display'] != 'none');

        expandAllExpectations();
        assertTrue(document.querySelectorAll('.results-row').length == 2);
        assertTrue(window.getComputedStyle(document.querySelectorAll('tbody')[0], null)['display'] != 'none');
    }, 'expanding expectation rows');

    results = mockResults();
    results.tests['only-expected-fail.html'] = mockExpectation('TEXT', 'TEXT');
    runTest(results, function() {
        assertTrue(window.getComputedStyle(document.getElementById('results-table').parentNode, null)['display'] == 'none');
    }, 'only one expected fail result');

    runDefaultSingleRowTest('bar-skip.html', 'TEXT', 'SKIP', true, '', '');
    runDefaultSingleRowTest('bar-flaky-fail.html', 'PASS FAIL', 'TEXT', true, 'expected actual diff pretty diff ', '');
    runDefaultSingleRowTest('bar-flaky-fail-unexpected.html', 'PASS TEXT', 'IMAGE', false, '', 'images diff ');
    runDefaultSingleRowTest('bar-audio.html', 'TEXT', 'AUDIO', false, 'expected audio actual audio ', '');
    runDefaultSingleRowTest('bar-image.html', 'TEXT', 'IMAGE', false, '', 'images diff ');
    runDefaultSingleRowTest('bar-image-plus-text.html', 'TEXT', 'IMAGE+TEXT', false, 'expected actual diff pretty diff ', 'images diff ');

    // Test the mapping for FAIL onto only ['IMAGE+TEXT', 'AUDIO', 'TEXT', 'IMAGE'].
    runDefaultSingleRowTest('bar-image.html', 'FAIL', 'IMAGE+TEXT', true, 'expected actual diff pretty diff ', 'images diff ');
    runDefaultSingleRowTest('bar-image.html', 'FAIL', 'AUDIO', true, 'expected audio actual audio ', '');
    runDefaultSingleRowTest('bar-image.html', 'FAIL', 'TEXT', true, 'expected actual diff pretty diff ', '');
    runDefaultSingleRowTest('bar-image.html', 'FAIL', 'IMAGE', false, '', 'images diff ');

    results = mockResults();
    results.tests['bar-reftest.html'] = mockExpectation('PASS', 'IMAGE');
    results.tests['bar-reftest.html'].reftest_type = ['=='];
    runSingleRowTest(results, false, '', 'ref html images diff ', 'match reftest single row test');

    results = mockResults();
    results.tests['bar-reftest-mismatch.html'] = mockExpectation('PASS', 'IMAGE');
    results.tests['bar-reftest-mismatch.html'].reftest_type = ['!='];
    runSingleRowTest(results, false, '', 'ref mismatch html actual ', 'mismatch reftest single row test');

    results = mockResults();
    results.tests['bar-reftest.html'] = mockExpectation('IMAGE', 'PASS');
    results.tests['bar-reftest.html'].reftest_type = ['=='];
    results.pixel_tests_enabled = false;
    runTest(results, function() {
        assertTrue(document.querySelector('tbody td:nth-child(1)').textContent == 'bar-reftest.html \u2691');
    }, 'match reftest');

    results = mockResults();
    results.tests['bar-reftest-mismatch.html'] = mockExpectation('IMAGE', 'PASS');
    results.tests['bar-reftest-mismatch.html'].reftest_type = ['!='];
    results.pixel_tests_enabled = false;
    runTest(results, function() {
        assertTrue(document.querySelector('tbody td:nth-child(1)').textContent == 'bar-reftest-mismatch.html \u2691');
    }, 'mismatch reftest');

    results = mockResults();
    var subtree = results.tests['foo'] = {}
    subtree['bar-flaky-pass.html'] = mockExpectation('PASS TEXT', 'PASS');
    runTest(results, function() {
        assertTrue(!document.getElementById('results-table'));
        assertTrue(document.getElementById('passes-table'));
        assertTrue(document.body.textContent.indexOf('foo/bar-flaky-pass.html') != -1);
    }, 'expected flaky and passed');

    results = mockResults();
    var subtree = results.tests['foo'] = {}
    subtree['bar-flaky-fail.html'] = mockExpectation('PASS TEXT', 'IMAGE PASS');
    runTest(results, function() {
        assertTrue(!document.getElementById('results-table'));
        assertTrue(document.getElementById('flaky-tests-table'));
        assertTrue(document.body.textContent.indexOf('bar-flaky-fail.html') != -1);
    }, 'expected flaky and image mismatch');

    results = mockResults();
    var subtree = results.tests['foo'] = {}
    subtree['bar-flaky-expected.html'] = mockExpectation('PASS FAIL', 'PASS TEXT');
    runTest(results, function() {
        assertTrue(!document.getElementById('results-table'));
        assertTrue(document.getElementById('flaky-tests-table'));
        assertTrue(document.body.textContent.indexOf('bar-flaky-expected.html') != -1);
        assertTrue(document.querySelector('tbody').className == 'expected');
    }, 'expected flaky and text mismatch');

    results = mockResults();
    var subtree = results.tests['foo'] = {}
    subtree['bar-really-long-path-that-should-probably-wrap-because-otherwise-the-table-will-be-too-wide.html'] = mockExpectation('PASS', 'TEXT');
    runTest(results, function() {
        document.body.style.width = '800px';
        var links = document.querySelectorAll('tbody a');
        assertTrue(links[0].getClientRects().length == 2);
        assertTrue(links[1].getClientRects().length == 1);
        document.body.style.width = '';
    }, 'long test name');

    results = mockResults();
    var subtree = results.tests['foo'] = {}
    subtree['bar.html'] = mockExpectation('TEXT', 'TEXT');
    runTest(results, function() {
        assertTrue(document.querySelector('tbody td:nth-child(2)').textContent.indexOf('pretty diff') != -1);
    }, 'pretty diff link');

    results = mockResults();
    var subtree = results.tests['foo'] = {}
    subtree['bar.html'] = mockExpectation('TEXT', 'PASS');
    subtree['bar-1.html'] = mockExpectation('TEXT', 'CRASH');
    subtree['bar-5.html'] = mockExpectation('TEXT', 'IMAGE+TEXT');
    subtree['bar-3.html'] = mockExpectation('PASS', 'TEXT');
    subtree['bar-2.html'] = mockExpectation('PASS', 'IMAGE');
    runTest(results, function() {
        // FIXME: This just ensures we don't get a JS error.
        // Verify that the sort is correct and that inline expanded expectations
        // move along with the test they're attached to.
        TableSorter.sortColumn(0);
        TableSorter.sortColumn(0);
        TableSorter.sortColumn(1);
        TableSorter.sortColumn(1);
        TableSorter.sortColumn(2);
        TableSorter.sortColumn(2);
        TableSorter.sortColumn(3);
        TableSorter.sortColumn(3);
        TableSorter.sortColumn(4);
        TableSorter.sortColumn(4);
        TableSorter.sortColumn(0);
        logPass('PASS');
    }, 'TableSorter.sortColumn does not raise a JS error');

    results = mockResults();
    var subtree = results.tests['foo'] = {}
    subtree['bar-5.html'] = mockExpectation('TEXT', 'IMAGE+TEXT');
    runTest(results, function() {
        expandAllExpectations();
        var png = document.querySelector('[src*="bar-5-expected.png"]');
        var x = png.offsetLeft + 1;
        var y = png.offsetTop + 1;
        var mockEvent = {
            target: png,
            clientX: x,
            clientY: y
        }
        PixelZoomer.showOnDelay = false;
        PixelZoomer.handleMouseMove(mockEvent);
        assertTrue(!!document.querySelector('.pixel-zoom-container'));
        assertTrue(document.querySelectorAll('.zoom-image-container').length == 3);
    }, 'zoom image on hover');

    results = mockResults();
    var subtree = results.tests['fullscreen'] = {}
    subtree['full-screen-api.html'] = mockExpectation('TEXT', 'IMAGE+TEXT');
    runTest(results, function() {
        // Use a regexp to match windows and unix-style paths.
        var expectedRegExp = new RegExp('^file.*' + results.layout_tests_dir + '/fullscreen/full-screen-api.html$');
        assertTrue(expectedRegExp.exec(document.querySelector('tbody td:first-child a').href));
    }, 'local test link');

    var oldShouldUseTracLinks = shouldUseTracLinks;
    shouldUseTracLinks = function() { return true; };

    results = mockResults();
    var subtree = results.tests['fullscreen'] = {}
    subtree['full-screen-api.html'] = mockExpectation('TEXT', 'IMAGE+TEXT');
    runTest(results, function() {
        var expectedHref = 'https://crrev.com/' + results.chromium_revision + '/third_party/WebKit/LayoutTests/fullscreen/full-screen-api.html';
        assertTrue(document.querySelector('tbody td:first-child a').href == expectedHref);
    }, 'chromium revision link');

    results = mockResults();
    var subtree = results.tests['fullscreen'] = {}
    subtree['full-screen-api.html'] = mockExpectation('TEXT', 'IMAGE+TEXT');
    results.chromium_revision = '';
    runTest(results, function() {
        var expectedHref = 'https://chromium.googlesource.com/chromium/src/+/master/third_party/WebKit/LayoutTests/fullscreen/full-screen-api.html';
        assertTrue(document.querySelector('tbody td:first-child a').href == expectedHref);
    }, 'googlesource test link');

    shouldUseTracLinks = oldShouldUseTracLinks;

    results = mockResults();
    results.tests['bar.html'] = mockExpectation('PASS', 'IMAGE');
    runTest(results, function() {
        assertTrue(document.querySelector('tbody td:nth-child(3)').textContent == 'images diff ');

        document.getElementById('toggle-images').checked = false;
        // FIXME: We shouldn't need to call updateTogglingImages. Setting checked above should call it.
        updateTogglingImages();
        // FIXME: We get extra spaces in the DOM every time we enable/disable image toggling.
        assertTrue(document.querySelector('tbody td:nth-child(3)').textContent == 'expected actual  diff ');

        document.getElementById('toggle-images').checked = true;
        updateTogglingImages();
        assertTrue(document.querySelector('tbody td:nth-child(3)').textContent == ' images   diff ');
    }, 'toggle images option');

    results = mockResults();
    results.tests['reading-options-from-localstorage.html'] = mockExpectation('IMAGE+TEXT', 'IMAGE+TEXT');
    runTest(results, function() {
        assertTrue(window.getComputedStyle(document.querySelector('tbody'), null)['display'] != 'none');
        assertTrue(document.querySelector('tbody td:nth-child(3)').textContent == 'expected actual  diff ');
    }, 'reading options from localstorage', '{"toggle-images":false,"show-expected-failures":true}');

    function enclosingNodeWithTagNameHasClassName(node, tagName, className) {
        while (node && (!node.tagName || node.localName != tagName))
            node = node.parentNode;
        if (!node)
            return false;
        return node.className == className;
    }

    results = mockResults();
    var subtree = results.tests['foo'] = {}
    subtree['expected-to-pass-but-crashed.html'] = mockExpectation('PASS', 'CRASH');
    subtree['expected-to-pass-or-crash-and-crashed.html'] = mockExpectation('PASS CRASH', 'CRASH');
    subtree['expected-to-pass-but-timeouted.html'] = mockExpectation('PASS', 'CRASH');
    subtree['expected-to-pass-or-timeout-and-timeouted.html'] = mockExpectation('PASS TIMEOUT', 'TIMEOUT');
    subtree['expected-fail-but-passed.html'] = mockExpectation('FAIL', 'PASS');
    subtree['expected-pass-or-fail-and-passed.html'] = mockExpectation('PASS FAIL', 'PASS');
    runTest(results, function() {
        assertTrue(!document.getElementById('results-table'));

        var testLinks = document.querySelectorAll('.test-link');
        assertTrue(testLinks[0].innerText == 'foo/expected-to-pass-but-crashed.html');
        assertTrue(!enclosingNodeWithTagNameHasClassName(testLinks[0], 'tbody', 'expected'));
        assertTrue(testLinks[1].innerText == 'foo/expected-to-pass-or-crash-and-crashed.html');
        assertTrue(enclosingNodeWithTagNameHasClassName(testLinks[1], 'tbody', 'expected'));
        assertTrue(!enclosingNodeWithTagNameHasClassName(testLinks[0], 'table', 'expected'));

        assertTrue(testLinks[2].innerText == 'foo/expected-to-pass-but-timeouted.html');
        assertTrue(!enclosingNodeWithTagNameHasClassName(testLinks[2], 'tbody', 'expected'));
        assertTrue(testLinks[3].innerText == 'foo/expected-to-pass-or-timeout-and-timeouted.html');
        assertTrue(enclosingNodeWithTagNameHasClassName(testLinks[3], 'tbody', 'expected'));
        assertTrue(!enclosingNodeWithTagNameHasClassName(testLinks[2], 'table', 'expected'));

        assertTrue(testLinks[4].innerText == 'foo/expected-fail-but-passed.html');
        assertTrue(!enclosingNodeWithTagNameHasClassName(testLinks[4], 'tbody', 'expected'));
        assertTrue(testLinks[5].innerText == 'foo/expected-pass-or-fail-and-passed.html');
        assertTrue(enclosingNodeWithTagNameHasClassName(testLinks[5], 'tbody', 'expected'));
        assertTrue(!enclosingNodeWithTagNameHasClassName(testLinks[4], 'table', 'expected'));
    }, 'class names 1');

    results = mockResults();
    var subtree = results.tests['foo'] = {}
    subtree['expected-to-pass-or-crash-and-crashed.html'] = mockExpectation('PASS CRASH', 'CRASH');
    subtree['expected-to-pass-or-timeout-and-timeouted.html'] = mockExpectation('PASS TIMEOUT', 'TIMEOUT');
    subtree['expected-pass-or-fail-and-passed.html'] = mockExpectation('PASS FAIL', 'PASS');
    runTest(results, function() {
        assertTrue(!document.getElementById('results-table'));

        var testLinks = document.querySelectorAll('.test-link');
        assertTrue(testLinks[0].innerText == 'foo/expected-to-pass-or-crash-and-crashed.html');
        assertTrue(enclosingNodeWithTagNameHasClassName(testLinks[0], 'tbody', 'expected'));
        assertTrue(enclosingNodeWithTagNameHasClassName(testLinks[0], 'div', 'expected'));

        assertTrue(testLinks[1].innerText == 'foo/expected-to-pass-or-timeout-and-timeouted.html');
        assertTrue(enclosingNodeWithTagNameHasClassName(testLinks[1], 'tbody', 'expected'));
        assertTrue(enclosingNodeWithTagNameHasClassName(testLinks[1], 'div', 'expected'));

        assertTrue(testLinks[2].innerText == 'foo/expected-pass-or-fail-and-passed.html');
        assertTrue(enclosingNodeWithTagNameHasClassName(testLinks[2], 'tbody', 'expected'));
        assertTrue(enclosingNodeWithTagNameHasClassName(testLinks[2], 'div', 'expected'));
    }, 'class names 2');

    results = mockResults();
    var subtree = results.tests['foo'] = {}
    subtree['bar.html'] = mockExpectation('TEXT', 'PASS');
    subtree['crash.html'] = mockExpectation('IMAGE', 'CRASH');
    subtree['flaky-fail.html'] = mockExpectation('PASS TEXT', 'IMAGE PASS');
    runTest(results, function() {
        assertTrue(!document.getElementById('results-table'));

        var resultText = document.body.textContent;
        assertTrue(resultText.indexOf('crash.html') != -1);
        assertTrue(resultText.indexOf('flaky-fail.html') != -1);
        assertTrue(resultText.indexOf('crash.html') < resultText.indexOf('flaky-fail.html'));
    }, 'crash and flaky fail test order');

    results = mockResults();
    var subtree = results.tests['foo'] = {}
    subtree['expected-missing.html'] = mockExpectation('MISSING', 'MISSING');
    subtree['expected-missing.html'].is_missing_text = true;
    subtree['expected-missing.html'].is_missing_image = true;
    subtree['unexpected-missing.html'] = mockExpectation('PASS', 'MISSING');
    subtree['unexpected-missing.html'].is_missing_text = true;
    runTest(results, function() {
        assertTrue(!document.getElementById('results-table'));
        assertTrue(visibleExpandLinks().length == 1);
        assertTrue(document.querySelector('#missing-table tbody.expected .test-link').textContent == 'foo/expected-missing.html');
        assertTrue(document.querySelector('#missing-table tbody.expected').getElementsByClassName('result-link')[0].textContent == 'result');
        assertTrue(document.querySelector('#missing-table tbody.expected').getElementsByClassName('result-link')[1].textContent == 'png result');
        assertTrue(document.querySelector('#missing-table tbody:not(.expected) .test-link').textContent == 'foo/unexpected-missing.html');
        assertTrue(document.querySelector('#missing-table tbody:not(.expected) .result-link').textContent == 'result');

        document.getElementById('show-expected-failures').checked = true;
        document.getElementById('show-expected-failures').onchange();
        expandAllExpectations();
        assertTrue(visibleExpandLinks().length == 2);
    }, 'missing results table');

    results = mockResults();
    var subtree = results.tests['foo'] = {}
    subtree['bar.html'] = mockExpectation('TEXT', 'FAIL');
    subtree['bar1.html'] = mockExpectation('TEXT', 'FAIL');
    subtree['bar2.html'] = mockExpectation('TEXT', 'FAIL');

    runTest(results, function() {
        if (window.eventSender) {
            eventSender.keyDown('k'); // previous
            var testRows = document.querySelectorAll('#results-table tbody');
            assertTrue(!testRows[0].classList.contains('current'));
            assertTrue(!testRows[1].classList.contains('current'));
            assertTrue(testRows[2].classList.contains('current'));
        }
    }, 'keyboard shortcuts: prev');

    runTest(results, function() {
        if (window.eventSender) {
            eventSender.keyDown('j'); // next
            var testRows = document.querySelectorAll('#results-table tbody');
            assertTrue(testRows[0].classList.contains('current'));
            assertTrue(!testRows[1].classList.contains('current'));
            assertTrue(!testRows[2].classList.contains('current'));
        }
    }, 'keyboard shortcuts: next');

    results = mockResults();
    var subtree = results.tests['foo'] = {}
    subtree['bar.html'] = mockExpectation('TEXT', 'FAIL');
    subtree['bar1.html'] = mockExpectation('TEXT', 'FAIL');
    subtree['bar2.html'] = mockExpectation('TEXT', 'FAIL');
    subtree['bar3.html'] = mockExpectation('TEXT', 'PASS');
    subtree['bar4.html'] = mockExpectation('IMAGE', 'PASS');

    runTest(results, function() {
        assertTrue(document.getElementById('results-table'));
        assertTrue(visibleExpandLinks().length == 3);

        if (window.eventSender) {
            eventSender.keyDown('i', ["metaKey"]);
            eventSender.keyDown('i', ["shiftKey"]);
            eventSender.keyDown('i', ["ctrlKey"]);
            var testRows = document.querySelectorAll('tbody');
            assertTrue(!testRows[0].classList.contains('current'));
            assertTrue(!testRows[1].classList.contains('current'));
            assertTrue(!testRows[2].classList.contains('current'));

            eventSender.keyDown('i'); // first
            assertTrue(testRows[0].classList.contains('current'));
            assertTrue(!testRows[1].classList.contains('current'));
            assertTrue(!testRows[2].classList.contains('current'));

            eventSender.keyDown('j', ["metaKey"]);
            eventSender.keyDown('j', ["shiftKey"]);
            eventSender.keyDown('j', ["ctrlKey"]);
            assertTrue(testRows[0].classList.contains('current'));
            assertTrue(!testRows[1].classList.contains('current'));
            assertTrue(!testRows[2].classList.contains('current'));

            eventSender.keyDown('j'); // next
            assertTrue(!testRows[0].classList.contains('current'));
            assertTrue(testRows[1].classList.contains('current'));
            assertTrue(!testRows[2].classList.contains('current'));

            eventSender.keyDown('k', ["metaKey"]);
            eventSender.keyDown('k', ["shiftKey"]);
            eventSender.keyDown('k', ["ctrlKey"]);
            assertTrue(!testRows[0].classList.contains('current'));
            assertTrue(testRows[1].classList.contains('current'));
            assertTrue(!testRows[2].classList.contains('current'));

            eventSender.keyDown('k'); // previous
            assertTrue(testRows[0].classList.contains('current'));
            assertTrue(!testRows[1].classList.contains('current'));
            assertTrue(!testRows[2].classList.contains('current'));

            eventSender.keyDown('l', ["metaKey"]);
            eventSender.keyDown('l', ["shiftKey"]);
            eventSender.keyDown('l', ["ctrlKey"]);
            assertTrue(testRows[0].classList.contains('current'));
            assertTrue(!testRows[1].classList.contains('current'));
            assertTrue(!testRows[2].classList.contains('current'));

            eventSender.keyDown('l'); // last
            assertTrue(!testRows[0].classList.contains('current'));
            assertTrue(!testRows[1].classList.contains('current'));
            assertTrue(testRows[4].classList.contains('current'));

            var flaggedTestsTextbox = document.getElementById('flagged-tests');

            eventSender.keyDown('f'); // flag
            assertTrue(flaggedTestsTextbox.innerText == 'foo/bar4.html');
            eventSender.keyDown('f'); // unflag

            eventSender.keyDown('i'); // first

            eventSender.keyDown('e', ["metaKey"]);
            eventSender.keyDown('e', ["shiftKey"]);
            eventSender.keyDown('e', ["ctrlKey"]);
            var expandLinks = document.querySelectorAll('.expand-button-text');
            assertTrue(!isExpanded(expandLinks[0]));

            eventSender.keyDown('e'); // expand
            assertTrue(isExpanded(expandLinks[0]));

            eventSender.keyDown('c', ["metaKey"]);
            eventSender.keyDown('c', ["shiftKey"]);
            eventSender.keyDown('c', ["ctrlKey"]);
            assertTrue(isExpanded(expandLinks[0]));

            eventSender.keyDown('c'); // collapse
            assertTrue(isCollapsed(expandLinks[0]));

            eventSender.keyDown('f', ["metaKey"]);
            eventSender.keyDown('f', ["shiftKey"]);
            eventSender.keyDown('f', ["ctrlKey"]);
            assertTrue(flaggedTestsTextbox.innerText == '');

            eventSender.keyDown('f'); // flag
            assertTrue(flaggedTestsTextbox.innerText == 'foo/bar.html');

            eventSender.keyDown('j'); // next
            eventSender.keyDown('f'); // flag
            assertTrue(flaggedTestsTextbox.innerText == 'foo/bar.html\nfoo/bar1.html');

            document.getElementById('use-newlines').checked = false;
            TestNavigator.updateFlaggedTestTextBox();
            assertTrue(flaggedTestsTextbox.innerText == 'foo/bar.html foo/bar1.html');

            eventSender.keyDown('f'); // unflag
            assertTrue(flaggedTestsTextbox.innerText == 'foo/bar.html');

            eventSender.keyDown('k'); // previous
            eventSender.keyDown('f'); // flag
            assertTrue(flaggedTestsTextbox.innerText == '');
        }
    }, 'keyboard shortcuts');

    results = mockResults();
    var subtree = results.tests['foo'] = {}
    subtree['bar.html'] = mockExpectation('TEXT', 'PASS');
    subtree['bar-1.html'] = mockExpectation('TEXT', 'CRASH');
    subtree['bar-2.html'] = mockExpectation('PASS', 'IMAGE');
    subtree['bar-3.html'] = mockExpectation('PASS', 'TEXT');
    subtree['bar-4.html'] = mockExpectation('TEXT', 'TEXT');
    subtree['bar-5.html'] = mockExpectation('TEXT', 'IMAGE+TEXT');
    subtree['bar-stderr-expected.html'] = mockExpectation('IMAGE', 'IMAGE');
    subtree['bar-stderr-expected.html'].has_stderr = true;
    subtree['bar-expected-timeout.html'] = mockExpectation('TIMEOUT', 'TIMEOUT');
    subtree['bar-expected-crash.html'] = mockExpectation('CRASH', 'CRASH');
    subtree['bar-missing.html'] = mockExpectation('TEXT', 'MISSING');
    subtree['bar-missing.html'].is_missing_text = true;
    runTest(results, function() {
        var titles = document.getElementsByTagName('h1');
        assertTrue(titles[0].textContent == 'Tests that crashed (1): [flag all] [unflag all]');
        assertTrue(titles[1].textContent == 'Tests that failed text/pixel/audio diff (3): [flag all] [unflag all]');
        assertTrue(titles[2].textContent == 'Tests that had no expected results (probably new) (1): [flag all] [unflag all]');
        assertTrue(titles[3].textContent == 'Tests that timed out (0): [flag all] [unflag all]');
        assertTrue(titles[4].textContent == 'Tests that had stderr output (1): [flag all] [unflag all]');
        assertTrue(titles[5].textContent == 'Tests expected to fail but passed (1): [flag all] [unflag all]');

        document.getElementById('show-expected-failures').checked = true;
        document.getElementById('show-expected-failures').onchange();

        assertTrue(titles[0].textContent == 'Tests that crashed (2): [flag all] [unflag all]');
        assertTrue(titles[1].textContent == 'Tests that failed text/pixel/audio diff (5): [flag all] [unflag all]');
        assertTrue(titles[2].textContent == 'Tests that had no expected results (probably new) (1): [flag all] [unflag all]');
        assertTrue(titles[3].textContent == 'Tests that timed out (1): [flag all] [unflag all]');
        assertTrue(titles[4].textContent == 'Tests that had stderr output (1): [flag all] [unflag all]');
        assertTrue(titles[5].textContent == 'Tests expected to fail but passed (1): [flag all] [unflag all]');
    }, 'table titles 1');

    results = mockResults();
    var subtree = results.tests['foo'] = {}
    subtree['bar.html'] = mockExpectation('', 'PASS TEXT');
    subtree['bar-1.html'] = mockExpectation('', 'TEXT IMAGE');
    subtree['bar-2.html'] = mockExpectation('IMAGE TEXT', 'TEXT IMAGE');
    subtree['bar-3.html'] = mockExpectation('PASS TEXT', 'TEXT PASS');
    runTest(results, function() {
        var titles = document.getElementsByTagName('h1');
        assertTrue(titles[0].textContent == 'Tests that failed text/pixel/audio diff (1): [flag all] [unflag all]');
        assertTrue(titles[1].textContent == 'Flaky tests (failed the first run and passed on retry) (1): [flag all] [unflag all]');

        assertTrue(document.querySelectorAll('#results-table tbody').length == 2);
        assertTrue(document.querySelectorAll('#flaky-tests-table tbody').length == 2);
    }, 'table titles 2');

    results = mockResults();
    var subtree = results.tests['foo'] = {}
    subtree['bar.html'] = mockExpectation('TEXT', 'IMAGE');
    subtree['bar1.html'] = mockExpectation('TEXT', 'TEXT');
    subtree['bar2.html'] = mockExpectation('TEXT', 'TEXT');
    runTest(results, function() {
        flagAll(document.querySelector('.flag-all'));
        var flaggedTestsTextbox = document.getElementById('flagged-tests');
        assertTrue(flaggedTestsTextbox.innerText == 'foo/bar.html');

        document.getElementById('show-expected-failures').checked = true;
        document.getElementById('show-expected-failures').onchange();

        flagAll(document.querySelector('.flag-all'));
        assertTrue(flaggedTestsTextbox.innerText == 'foo/bar.html\nfoo/bar1.html\nfoo/bar2.html');

        unflag(document.querySelector('.flag'));
        assertTrue(flaggedTestsTextbox.innerText == 'foo/bar1.html\nfoo/bar2.html');
    }, 'flagging tests');

    results = mockResults();
    var subtree = results.tests['foo'] = {}
    subtree['bar.html'] = mockExpectation('TEXT', 'IMAGE');
    subtree['bar1.html'] = mockExpectation('TEXT', 'IMAGE');
    runTest(results, function() {
        flagAll(document.querySelector('.flag-all'));
        var flaggedTestsTextbox = document.getElementById('flagged-tests');
        assertTrue(flaggedTestsTextbox.innerText == 'foo/bar.html\nfoo/bar1.html');
    }, 'flagged tests with newlines', '{"use-newlines":true}');

    results = mockResults();
    var subtree = results.tests['foo'] = {}
    subtree['bar.html'] = mockExpectation('TEXT', 'IMAGE');
    subtree['bar1.html'] = mockExpectation('TEXT', 'IMAGE');
    runTest(results, function() {
        flagAll(document.querySelector('.flag-all'));
        var flaggedTestsTextbox = document.getElementById('flagged-tests');
        assertTrue(flaggedTestsTextbox.innerText == 'foo/bar.html foo/bar1.html');
    }, 'flagged tests with spaces', '{"use-newlines":false}');

    results = mockResults();
    results.tests['foo/bar-image.html'] = mockExpectation('PASS', 'TEXT IMAGE+TEXT');
    results.pixel_tests_enabled = false;
    runTest(results, function() {
        assertTrue(document.querySelector('tbody td:nth-child(3) a').getAttribute('href') == 'retries/foo/bar-image-diffs.html');
    }, 'image diff links with IMAGE+TEXT result');

    results = mockResults();
    results.tests['foo/bar-image.html'] = mockExpectation('PASS', 'TEXT IMAGE');
    results.pixel_tests_enabled = false;
    runTest(results, function() {
        assertTrue(!document.getElementById('results-table'));
        assertTrue(document.querySelector('#flaky-tests-table td:nth-child(3) a').getAttribute('href') == 'retries/foo/bar-image-diffs.html');
    }, 'image diff links flaky TEXT IMAGE result');

    results = mockResults();
    results.tests['foo'] = mockExpectation('PASS', 'TEXT');
    results.tests['foo'].has_repaint_overlay = true;
    runTest(results, function() {
        assertTrue(document.querySelector('tbody td:nth-child(2)').textContent.indexOf('overlay') != -1);
    }, 'repaint overlay')

    document.body.innerHTML = '
' + g_log.join('\n') + '
';
}

var originalGeneratePage = generatePage;
generatePage = runTests;