text:
// Compiled by ClojureScript 0.0-2173
goog.provide('defpi.ringbuffer');
goog.require('cljs.core');

/**
* @constructor
*/
defpi.ringbuffer.RingBuffer = (function (size,idx,content){
this.size = size;
this.idx = idx;
this.content = content;
this.cljs$lang$protocol_mask$partition1$ = 0;
this.cljs$lang$protocol_mask$partition0$ = 8388608;
})
defpi.ringbuffer.RingBuffer.cljs$lang$type = true;
defpi.ringbuffer.RingBuffer.cljs$lang$ctorStr = "defpi.ringbuffer/RingBuffer";
defpi.ringbuffer.RingBuffer.cljs$lang$ctorPrWriter = (function (this__4010__auto__,writer__4011__auto__,opt__4012__auto__){return cljs.core._write.call(null,writer__4011__auto__,"defpi.ringbuffer/RingBuffer");
});
defpi.ringbuffer.RingBuffer.prototype.cljs$core$ISeqable$_seq$arity$1 = (function (this$){var self__ = this;
var this$__$1 = this;return defpi.ringbuffer.rb_seq.call(null,this$__$1);
});
defpi.ringbuffer.__GT_RingBuffer = (function __GT_RingBuffer(size,idx,content){return (new defpi.ringbuffer.RingBuffer(size,idx,content));
});
defpi.ringbuffer.mk_ringbuffer = (function mk_ringbuffer(size){return (new defpi.ringbuffer.RingBuffer(size,0,cljs.core.PersistentArrayMap.EMPTY));
});
defpi.ringbuffer.add = (function add(rb,el){var idx = rb.idx;var size = rb.size;return (new defpi.ringbuffer.RingBuffer(size,cljs.core.mod.call(null,(idx + 1),size),cljs.core.assoc.call(null,rb.content,idx,el)));
});
defpi.ringbuffer.rb_rseq = (function() {
var rb_rseq = null;
var rb_rseq__1 = (function (rb){return defpi.ringbuffer.rb_seq.call(null,rb,rb.idx,rb.size);
});
var rb_rseq__3 = (function (rb,idx,left){return (new cljs.core.LazySeq(null,(function (){if((left > 0))
{return cljs.core.cons.call(null,cljs.core.get.call(null,rb.content,idx),defpi.ringbuffer.rb_seq.call(null,rb,cljs.core.mod.call(null,(idx + 1),rb.size),(left - 1)));
} else
{return null;
}
}),null,null));
});
rb_rseq = function(rb,idx,left){
switch(arguments.length){
case 1:
return rb_rseq__1.call(this,rb);
case 3:
return rb_rseq__3.call(this,rb,idx,left);
}
throw(new Error('Invalid arity: ' + arguments.length));
};
rb_rseq.cljs$core$IFn$_invoke$arity$1 = rb_rseq__1;
rb_rseq.cljs$core$IFn$_invoke$arity$3 = rb_rseq__3;
return rb_rseq;
})()
;
defpi.ringbuffer.rb_seq = (function() {
var rb_seq = null;
var rb_seq__1 = (function (rb){return rb_seq.call(null,rb,rb.idx,rb.size);
});
var rb_seq__3 = (function (rb,idx,left){var idx__$1 = cljs.core.mod.call(null,(idx - 1),rb.size);return (new cljs.core.LazySeq(null,(function (){if((left > 0))
{return cljs.core.cons.call(null,cljs.core.get.call(null,rb.content,idx__$1),rb_seq.call(null,rb,idx__$1,(left - 1)));
} else
{return null;
}
}),null,null));
});
rb_seq = function(rb,idx,left){
switch(arguments.length){
case 1:
return rb_seq__1.call(this,rb);
case 3:
return rb_seq__3.call(this,rb,idx,left);
}
throw(new Error('Invalid arity: ' + arguments.length));
};
rb_seq.cljs$core$IFn$_invoke$arity$1 = rb_seq__1;
rb_seq.cljs$core$IFn$_invoke$arity$3 = rb_seq__3;
return rb_seq;
})()
;

//# sourceMappingURL=ringbuffer.js.map


text:
.simple-image-chooser .image-radio-group{
	position:static;
	width:auto;
}

redpajama_set_name: RedPajamaGithub


text:
                Users
{{total}} users sorted by {{sortField}}.
                {{total}} users matching "{{searchValue}}" in {{searchField}}, sorted by {{sortField}}.

                                    <button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown" aria-expanded="false">look in {{searchField}} for </button>

name

email

                                <input class="form-control" ng-model="searchValue" placeholder="Search">

                                    <button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown" aria-expanded="false">sort by {{sortField}} </button>

login date

email

email

                                    <button ng-click="refresh()" type="button" class="btn btn-primary"> Search</button>

{{entity.name}}

                                    {{ entity.email || 'No email.' }}

                                    Last Login
                                     {{ entity.loginDate | moment: 'fromNow' }}


text:
<!DOCTYPE html>

  This tests that filesystem URLs created in a secure context are treated as
  secure origins. This test passes if the iframe renders PASS correctly, and no
  console warning appears.


text:
body {
    padding-top: 60px; /* 60px to make the container go all the way to the bottom of the topbar */
}

.tools {
    margin: 5px 0;
}

.pagination .current {
    font-weight: bold;
}

textarea {
	width: 500px;
	height: 200px;
}


text:
/*
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Formatting;

namespace RefactoringEssentials.CSharp.Diagnostics
{
    [ExportCodeFixProvider(LanguageNames.CSharp), System.Composition.Shared]
    public class MemberCanBeMadeStaticCodeFixProvider : CodeFixProvider
    {
        public override ImmutableArray<string> FixableDiagnosticIds
        {
            get
            {
                return ImmutableArray.Create(CSharpDiagnosticIDs.MemberCanBeMadeStaticAnalyzerID);
            }
        }

        public override FixAllProvider GetFixAllProvider()
        {
            return WellKnownFixAllProviders.BatchFixer;
        }

        public async override Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            var document = context.Document;
            var cancellationToken = context.CancellationToken;
            var span = context.Span;
            var diagnostics = context.Diagnostics;
            var root = await document.GetSyntaxRootAsync(cancellationToken);
            var diagnostic = diagnostics.First();
            var node = root.FindNode(context.Span);

            if (node is MethodDeclarationSyntax)
                MakeMethodStaticFix(node as MethodDeclarationSyntax, diagnostic, context, root);
            else if (node is PropertyDeclarationSyntax)
                MakePropertyStaticFix(node as PropertyDeclarationSyntax, diagnostic, context, root);
            else if (node is EventDeclarationSyntax)
                MakeEventStaticFix(node as EventDeclarationSyntax, diagnostic, context, root);

        }

        public void MakeMethodStaticFix(MethodDeclarationSyntax methodDeclaration, Diagnostic diagnostic, CodeFixContext context, SyntaxNode root)
        {
            context.RegisterCodeFix(CodeActionFactory.Create(methodDeclaration.Span, diagnostic.Severity, "Method can be made static",
                token =>
                {
                    var oldNode = methodDeclaration;
                    var newRoot = root.ReplaceNode(oldNode, methodDeclaration
                        .WithModifiers(methodDeclaration.Modifiers.Add(SyntaxFactory.Token(SyntaxKind.StaticKeyword)))
                        .WithAdditionalAnnotations(Formatter.Annotation));
                    return Task.FromResult(context.Document.WithSyntaxRoot(newRoot));
                }), diagnostic);

        }

        public void MakePropertyStaticFix(PropertyDeclarationSyntax propertyDeclaration, Diagnostic diagnostic, CodeFixContext context, SyntaxNode root)
        {
            context.RegisterCodeFix(CodeActionFactory.Create(propertyDeclaration.Span, diagnostic.Severity, "Property can be made static",
                token =>
                {
                    var oldNode = propertyDeclaration;

                var newRoot = root.ReplaceNode(oldNode, propertyDeclaration
                                               .WithModifiers(propertyDeclaration.Modifiers.Add(SyntaxFactory.Token(SyntaxKind.StaticKeyword)))
                                               .WithAdditionalAnnotations(Formatter.Annotation)
                                              );
                    return Task.FromResult(context.Document.WithSyntaxRoot(newRoot));
                }), diagnostic);
        }

        public void MakeEventStaticFix(EventDeclarationSyntax eventDeclaration, Diagnostic diagnostic, CodeFixContext context, SyntaxNode root)
        {
            context.RegisterCodeFix(CodeActionFactory.Create(eventDeclaration.Span, diagnostic.Severity, "Event can be made static",
                token =>
                {
                    var oldNode = eventDeclaration;
                var newRoot = root.ReplaceNode(oldNode, eventDeclaration.WithModifiers(eventDeclaration.Modifiers.Add(SyntaxFactory.Token(SyntaxKind.StaticKeyword))).WithAdditionalAnnotations(Formatter.Annotation));
                    return Task.FromResult(context.Document.WithSyntaxRoot(newRoot));
                }), diagnostic);
        }

    }
}
*/


text:
using AjaxControlToolkit.Reference.Core.Parsing;
using System;
using System.Collections.Generic;
using AjaxControlToolkit.ReferenceCore.Parsing;

namespace AjaxControlToolkit.Reference.Core {

    public class Documentation {

        IDictionary<string, TypeDoc> _types;

        public void Add(IEnumerable<RawDoc> rawDocs, ContentType contentType) {

            foreach(var rawDoc in rawDocs)
                ProcessInfo(rawDoc.TargetNamePrefix, rawDoc.TargetFullName).Fill(rawDoc.Elements, contentType);
        }

        DocBase ProcessInfo(string targetNamePrefix, string fullName) {
            switch(targetNamePrefix) {
                case "T": {
                        return GetTypeByName(fullName);
                    }
                case "M": {
                        var info = new MethodDoc(fullName);
                        GetTypeByName(info.Namespace).AddMethod(info);
                        return info;
                    }
                case "P": {
                        var info = new PropertyDoc(fullName);
                        GetTypeByName(info.Namespace).AddProperty(info);
                        return info;
                    }
                case "E": {
                        var info = new EventDoc(fullName);
                        GetTypeByName(info.Namespace).AddEvent(info);
                        return info;
                    }
                case "cM": {
                        var info = new MethodDoc(fullName);
                        GetTypeByName(info.Namespace).AddClientMethod(info);
                        return info;
                    }
                case "cP": {
                        var info = new ClientPropertyDoc(fullName);
                        GetTypeByName(info.Namespace).AddClientProperty(info);
                        return info;
                    }
                case "cE": {
                        var info = new ClientEventDoc(fullName);
                        GetTypeByName(info.Namespace).AddClientEvent(info);
                        return info;
                    }
            }

            throw new ArgumentException("Unknown info type", "fullName");
        }

        TypeDoc GetTypeByName(string typeName) {
            if(!_types.ContainsKey(typeName))
                _types.Add(typeName, new TypeDoc(typeName));

            return _types[typeName];
        }

        public Documentation() {
            _types = new Dictionary<string, TypeDoc>();
        }

        public IEnumerable<TypeDoc> Types {
            get { return _types.Values; }
        }
    }
}


text:
package com.hotels.styx.client.loadbalancing.strategies;

import com.google.common.collect.ImmutableList;
import com.hotels.styx.api.Environment;
import com.hotels.styx.api.HttpHandler;
import com.hotels.styx.api.Id;
import com.hotels.styx.api.configuration.Configuration;
import com.hotels.styx.api.extension.ActiveOrigins;
import com.hotels.styx.api.extension.Origin;
import com.hotels.styx.api.extension.OriginsSnapshot;
import com.hotels.styx.api.extension.RemoteHost;
import com.hotels.styx.api.extension.loadbalancing.spi.LoadBalancer;
import com.hotels.styx.api.extension.loadbalancing.spi.LoadBalancingMetric;
import com.hotels.styx.api.extension.loadbalancing.spi.LoadBalancingMetricSupplier;
import com.hotels.styx.client.connectionpool.stubs.StubConnectionFactory;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.util.Optional;

import static com.hotels.styx.api.Id.id;
import static com.hotels.styx.api.extension.Origin.newOriginBuilder;
import static com.hotels.styx.api.extension.RemoteHost.remoteHost;
import static java.util.Arrays.asList;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class RoundRobinStrategyTest {
    private static final StubConnectionFactory connectionFactory = new StubConnectionFactory();
    private static final RemoteHost HOST_1 = remoteHostFor("localhost", 1);
    private static final RemoteHost HOST_2 = remoteHostFor("localhost", 2);
    private static final RemoteHost HOST_3 = remoteHostFor("localhost", 3);
    private static final RemoteHost HOST_4 = remoteHostFor("localhost", 4);
    private static final RemoteHost HOST_5 = remoteHostFor("localhost", 5);
    private static final RemoteHost HOST_6 = remoteHostFor("localhost", 6);
    private Id APP_ID = id("app");
    private Environment environment;
    private Configuration configuration;

    private static RemoteHost remoteHostFor(String host, int port) {
        Origin origin = newOriginBuilder(host, port).build();

        LoadBalancingMetricSupplier metric = mock(LoadBalancingMetricSupplier.class);
        when(metric.loadBalancingMetric()).thenReturn(new LoadBalancingMetric(45));

        return remoteHost(origin, mock(HttpHandler.class), metric);
    }

    private LoadBalancer strategy;

    @BeforeEach
    public void setUp() {
        environment = mock(Environment.class);
        configuration = mock(Configuration.class);
        strategy = new RoundRobinStrategy.Factory().create(
                environment,
                configuration,
                () -> asList(HOST_1, HOST_2, HOST_3));
    }

    @Test
    public void cyclesThroughOrigins() {
        assertThat(strategy.choose(null), is(Optional.of(HOST_1)));
        assertThat(strategy.choose(null), is(Optional.of(HOST_2)));
        assertThat(strategy.choose(null), is(Optional.of(HOST_3)));
        assertThat(strategy.choose(null), is(Optional.of(HOST_1)));
        assertThat(strategy.choose(null), is(Optional.of(HOST_2)));
    }

    @Test
    public void returnsEmptyIfNoActiveOrigins() {
        strategy = new RoundRobinStrategy.Factory().create(environment, configuration, ImmutableList::of);
        assertThat(strategy.choose(null), is(Optional.empty()));
    }

    @Test
    public void refreshesAtOriginsChange() {
        ActiveOrigins activeOrigins = mock(ActiveOrigins.class);
        when(activeOrigins.snapshot()).thenReturn(asList(HOST_1, HOST_2, HOST_3));
        strategy = new RoundRobinStrategy.Factory().create(environment, configuration, activeOrigins);

        assertThat(strategy.choose(null), is(Optional.of(HOST_1)));
        assertThat(strategy.choose(null), is(Optional.of(HOST_2)));
        assertThat(strategy.choose(null), is(Optional.of(HOST_3)));
        assertThat(strategy.choose(null), is(Optional.of(HOST_1)));
        assertThat(strategy.choose(null), is(Optional.of(HOST_2)));

        when(activeOrigins.snapshot()).thenReturn(asList(HOST_2, HOST_4, HOST_6));
        strategy.originsChanged(new OriginsSnapshot(
                APP_ID,
                asList(HOST_2, HOST_4, HOST_6),
                asList(HOST_1, HOST_3),
                asList(HOST_5)
                ));

        assertThat(strategy.choose(null), is(Optional.of(HOST_6)));
        assertThat(strategy.choose(null), is(Optional.of(HOST_2)));
        assertThat(strategy.choose(null), is(Optional.of(HOST_4)));
        assertThat(strategy.choose(null), is(Optional.of(HOST_6)));
        assertThat(strategy.choose(null), is(Optional.of(HOST_2)));
        assertThat(strategy.choose(null), is(Optional.of(HOST_4)));
    }

}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>
  File: README

    — Documentation by YARD 0.8.7.6

</title>

  <link rel="stylesheet" href="css/style.css" type="text/css" charset="utf-8" />

  <link rel="stylesheet" href="css/common.css" type="text/css" charset="utf-8" />

    Index »
    File: README

(no frames)

      Class List

      Method List

      File List

ViPRuby

### A Ruby library for EMCs ViPR Controller (ViPR-C) REST API

How to use:

Install and usage:

gem install vipruby
require 'vipruby'

Create a ViPR object:

base_url = 'vipr.mydomain.com'
user_name = 'root'
password = 'mypw'
verify_cert = false

vipr = Vipr.new(base_url,user_name,password,verify_cert)

Methods Exist for:

vCenter

Add vCenters (to root or specific tenant)

Remove vCenters

Get vCenter Information

Hosts

Add Hosts

Add Host Initators

Remove Hosts

Get Host Information

Storage Systems

Add Storage Arrays

Tenants

Get All Tenants

Get One Tenant Information

Get Subtenants of One Tenant

Get Projects of One Tenant

Service Catalog

Get Root Service Catalog Information

Get Categories of a Catalog

Get Services of a Category of a Catalog

Order A Service

For all methods, see the Gem
Documentation for all code samples

Licensing

Licensed under the Apache License, Version 2.0 (the "License"); you may not
use this file except in compliance with the License. You may obtain a copy
of the License at www.apache.org/licenses/LICENSE-2.0

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

To Do:

Add more methods for more controller specific actions.

Add methods for blob specific actions

  Generated on Mon Jun  1 15:10:33 2015 by
  yard
  0.8.7.6 (ruby-2.1.2).


text:
package cdl

import "fmt"

// Implementation of a DOM visitor that augments the contents of the DOM by
// adding a sequential instruction ID to each instruction.

type setIDVisitor struct {
	id int32
}

func newSetIDVisitor() DOMVisitor {
	return &setIDVisitor{}
}

// Accept goes through all scenarios and sub-scenarios and calls visitor for each of them.
func (v *setIDVisitor) Accept(d *DOM) {
	for _, s := range d.Scenarios {
		if err, ok := s.accept(v).(error); ok {
			fmt.Println(err)
		}
	}
	for _, s := range d.SubScenarios {
		if err, ok := s.accept(v).(error); ok {
			fmt.Println(err)
		}
	}
}

// VisitScenario is called for each scenario.
func (v *setIDVisitor) VisitScenario(i *Instruction) interface{} {
	v.id = 0
	return i.VisitChildren(v)
}

// VisitSubScenario is called for each sub-scenario.
func (v *setIDVisitor) VisitSubScenario(i *Instruction) interface{} {
	v.id = 0
	return i.VisitChildren(v)
}

func (v *setIDVisitor) setID(i *Instruction) {
	i.ID = v.id
	v.id++
}

// VisitGroupAtLeastOnce is called for each at-least-once instruction group.
func (v *setIDVisitor) VisitGroupAtLeastOnce(i *Instruction) interface{} {
	v.setID(i)
	return i.VisitChildren(v)
}

// VisitGroupZeroOrMore is called for each GroupZeroOrMore instruction group.
func (v *setIDVisitor) VisitGroupZeroOrMore(i *Instruction) interface{} {
	v.setID(i)
	return i.VisitChildren(v)
}

// VisitGroupAnyOrder is called for each GroupAnyOrder instruction group.
func (v *setIDVisitor) VisitGroupAnyOrder(i *Instruction) interface{} {
	v.setID(i)
	return i.VisitChildren(v)
}

// VisitCall is called for each gNMI call instruction.
func (v *setIDVisitor) VisitCall(i *Instruction) interface{} {
	v.setID(i)
	return i.VisitChildren(v)
}

// VisitOpenStr is called for each open-stream instruction.
func (v *setIDVisitor) VisitOpenStr(i *Instruction) interface{} {
	v.setID(i)
	return i.VisitChildren(v)
}

// VisitCloseStr is called for each close-stream instruction.
func (v *setIDVisitor) VisitCloseStr(i *Instruction) interface{} {
	v.setID(i)
	return i.VisitChildren(v)
}

// VisitSend is called for each send instruction.
func (v *setIDVisitor) VisitSend(i *Instruction) interface{} {
	v.setID(i)
	return i.VisitChildren(v)
}

// VisitReceive is called for each receive instruction.
func (v *setIDVisitor) VisitReceive(i *Instruction) interface{} {
	v.setID(i)
	return i.VisitChildren(v)
}

// VisitVarDeclaration is called for each varDeclaration instruction.
func (v *setIDVisitor) VisitVarDeclaration(i *Instruction) interface{} {
	v.setID(i)
	return i.VisitChildren(v)
}


text:
package org.tmatesoft.sqljet.core.map;

import org.tmatesoft.sqljet.core.SqlJetException;

/**
 * @author TMate Software Ltd.
 * @author Sergey Scherbina (sergey.scherbina@gmail.com)
 *
 */
public interface ISqlJetMapCursor extends ISqlJetMapIterator {

    /**
     * @throws SqlJetException
     */
    void close() throws SqlJetException;

    /**
     * @return current key.
     * @throws SqlJetException
     */
    Object[] getKey() throws SqlJetException;

    /**
     * @return current date.
     * @throws SqlJetException
     */
    Object[] getValue() throws SqlJetException;

    /**
     * @param key
     * @return true if cursor was set to the key specified.
     *
     * @throws SqlJetException
     */
    boolean goToKey(Object[] key) throws SqlJetException;

    /**
     * @param key
     * @param value
     * @throws SqlJetException
     */
    void put(Object[] key, Object[] value) throws SqlJetException;

    /**
     * @throws SqlJetException
     */
    ISqlJetMapTableCursor getMapTable() throws SqlJetException;

    /**
     * @throws SqlJetException
     */
    ISqlJetMapIndexCursor getMapIndex() throws SqlJetException;

}


text:
This is a fork of the work-in-progress skin for ZoneMinder version >= 1.24 by [Kyle Johnson](https://github.com/kylejohnson/modern).

This skin is currently being developed by Emergent Ltd. Any suggestions of features, comments and code are welcome =)

##FEATURES

* Single page for live view and playback
* Timeline of events
* Playback across multiple cameras at once
* Individual camera and preset selection
* Valid HTML5
* No need for Java, Flash, etc - just a decent browser

##FUTURE

* Exporting of multiple events
* Improved backend (No dropping back to classic)
* Ability to change fixed FPS for playback (currently assumes 5FPS)
* Support for variable FPS playback


text:
//-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------

#include "platformX86UNIX/platformX86UNIX.h"
#include "platform/platform.h"
#include <stdarg.h>
#include <ctype.h>
#include <stdlib.h>

#ifdef HAS_VSSCANF
#  undef HAS_VSSCANF
#endif

/* this routine turns a string to all uppercase - rjp */
char *__strtoup(char *str)
{
   char *newStr = str;
   if (newStr == NULL)
      return(NULL);
   while (*newStr)
   {
      *newStr = toupper(*newStr);
      *newStr++;
   }
   return(str);
}
/* this routine turns a string to all lowercase - rjp */
char *__strtolwr(char *str)
{
   char *newStr = str;
   if (newStr == NULL)
      return(NULL);
   while (*newStr)
   {
      *newStr = tolower(*newStr);
      *newStr++;
   }
   return(str);
}

char *strtolwr(char* str)
{
   return __strtolwr(str);
}

char *stristr(char *szStringToBeSearched, const char *szSubstringToSearchFor)
{
   char *pPos = NULL;
   char *szCopy1 = NULL;
   char *szCopy2 = NULL;

   // verify parameters
   if ( szStringToBeSearched == NULL ||
        szSubstringToSearchFor == NULL )
   {
      return szStringToBeSearched;
   }

   // empty substring - return input (consistent with strstr)
   if (strlen(szSubstringToSearchFor) == 0 ) {
      return szStringToBeSearched;
   }

   szCopy1 = __strtolwr(strdup(szStringToBeSearched));
   szCopy2 = __strtolwr(strdup(szSubstringToSearchFor));

   if ( szCopy1 == NULL || szCopy2 == NULL  ) {
      // another option is to raise an exception here
      free((void*)szCopy1);
      free((void*)szCopy2);
      return NULL;
   }

   pPos = strstr(szCopy1, szCopy2);

   if ( pPos != NULL ) {
      // map to the original string
      pPos = szStringToBeSearched + (pPos - szCopy1);
   }

   free((void*)szCopy1);
   free((void*)szCopy2);

   return pPos;
} // stristr(...)

char *dStrdup_r(const char *src, const char *fileName, U32 lineNumber)
{
   char *buffer = (char *) dMalloc_r(dStrlen(src) + 1, fileName, lineNumber);
   dStrcpy(buffer, src);
   return buffer;
}

char* dStrcat(char *dst, const char *src)
{
   return strcat(dst,src);
}

char* dStrncat(char *dst, const char *src, U32 len)
{
   return strncat(dst,src,len);
}

// concatenates a list of src's onto the end of dst
// the list of src's MUST be terminated by a NULL parameter
// dStrcatl(dst, sizeof(dst), src1, src2, NULL);
char* dStrcatl(char *dst, U32 dstSize, ...)
{
   const char* src;
   char *p = dst;

   AssertFatal(dstSize > 0, "dStrcatl: destination size is set zero");
   dstSize--;  // leave room for string termination

   // find end of dst
   while (dstSize && *p++)
      dstSize--;

   va_list args;
   va_start(args, dstSize);

   // concatenate each src to end of dst
   while ( (src = va_arg(args, const char*)) != NULL )
      while( dstSize && *src )
      {
         *p++ = *src++;
         dstSize--;
      }

   va_end(args);

   // make sure the string is terminated
   *p = 0;

   return dst;
}

// copy a list of src's into dst
// the list of src's MUST be terminated by a NULL parameter
// dStrccpyl(dst, sizeof(dst), src1, src2, NULL);
char* dStrcpyl(char *dst, U32 dstSize, ...)
{
   const char* src;
   char *p = dst;

   AssertFatal(dstSize > 0, "dStrcpyl: destination size is set zero");
   dstSize--;  // leave room for string termination

   va_list args;
   va_start(args, dstSize);

   // concatenate each src to end of dst
   while ( (src = va_arg(args, const char*)) != NULL )
      while( dstSize && *src )
      {
         *p++ = *src++;
         dstSize--;
      }

   va_end(args);

   // make sure the string is terminated
   *p = 0;

   return dst;
}

S32 dStrcmp(const char *str1, const char *str2)
{
   return strcmp(str1, str2);
}

S32 dStrcmp(const UTF16 *str1, const UTF16 *str2)
{
   int ret;
   const UTF16 *a, *b;
   a = str1;
   b = str2;

   while (*a && *b && (ret = *a - *b) == 0)
   {
      a++, b++;
   }

   if (*a == 0 && *b != 0)
      return -1;

   if (*b == 0 && *a != 0)
      return 1;

   return ret;
}

S32 dStricmp(const char *str1, const char *str2)
{
   return strcasecmp(str1, str2);
}

S32 dStrncmp(const char *str1, const char *str2, U32 len)
{
   return strncmp(str1, str2, len);
}

S32 dStrnicmp(const char *str1, const char *str2, U32 len)
{
   return strncasecmp(str1, str2, len);
}

char* dStrcpy(char *dst, const char *src)
{
   return strcpy(dst,src);
}

char* dStrncpy(char *dst, const char *src, U32 len)
{
   return strncpy(dst,src,len);
}

U32 dStrlen(const char *str)
{
   return strlen(str);
}

char* dStrupr(char *str)
{
#ifdef __MWERKS__ // metrowerks strupr is broken
   _strupr(str);
   return str;
#else
   return __strtoup(str);
#endif
}

char* dStrlwr(char *str)
{
   return __strtolwr(str);
}

char* dStrchr(char *str, S32 c)
{
   return strchr(str,c);
}

const char* dStrchr(const char *str, S32 c)
{
   return strchr(str,c);
}

const char* dStrrchr(const char *str, S32 c)
{
   return strrchr(str,c);
}

char* dStrrchr(char *str, S32 c)
{
   return strrchr(str,c);
}

U32 dStrspn(const char *str, const char *set)
{
   return(strspn(str, set));
}

U32 dStrcspn(const char *str, const char *set)
{
   return strcspn(str, set);
}

char* dStrstr(char *str1, char *str2)
{
   return strstr(str1,str2);
}

char* dStrstr(const char *str1, const char *str2)
{
   return strstr((char *)str1,str2);
}

char* dStrtok(char *str, const char *sep)
{
   return strtok(str, sep);
}

S32 dAtoi(const char *str)
{
   return atoi(str);
}

F32 dAtof(const char *str)
{
   return atof(str);
}

bool dAtob(const char *str)
{
   return !dStricmp(str, "true") || dAtof(str);
}

bool dIsalnum(const char c)
{
   return isalnum(c);
}

bool dIsalpha(const char c)
{
   return(isalpha(c));
}

bool dIsspace(const char c)
{
   return(isspace(c));
}

bool dIsdigit(const char c)
{
   return(isdigit(c));
}

void dPrintf(const char *format, ...)
{
   va_list args;
   va_start(args, format);
   vprintf(format, args);
   va_end(args);
}

S32 dVprintf(const char *format, va_list arglist)
{
   S32 len = vprintf(format, arglist);
   return (len);
}

S32 dSprintf(char *buffer, U32 bufferSize, const char *format, ...)
{
   va_list args;
   va_start(args, format);

   S32 len = vsnprintf(buffer, bufferSize, format, args);

   va_end(args);

   return len;
}

S32 dVsprintf(char *buffer, U32 bufferSize, const char *format, va_list arglist)
{
   S32 len = vsnprintf(buffer, bufferSize, format, arglist);

   return len;
}

S32 dStrrev(char *str)
{
   // Get string length
   S32 l = dStrlen(str) - 1;

   for (int x = 0; x < 1; x++,l--)
   {
      // triple XOR trick
      str[x]^=str[l];

      str[l]^=str[x];
      str[x]^=str[l];
   }

   return l;
}

S32 dItoa(S32 n, char s[])
{
   S32 i, sign;

   if ((sign = n) < 0)
	n = -n;

   i = 0;
   do {
      s[i++] = n % 10 + '0';
   } while((n /= 10) > 0);

   if (sign < 0)
      s[i++] = '-';

   dStrrev(s);

   return dStrlen(s);
}

S32 dSscanf(const char *buffer, const char *format, ...)
{
   va_list args;
#if defined(HAS_VSSCANF)
   va_start(args, format);
   return __vsscanf(buffer, format, args);
#else
   va_start(args, format);

   // Boy is this lame.  We have to scan through the format string, and find out how many
   //  arguments there are.  We'll store them off as void*, and pass them to the sscanf
   //  function through specialized calls.  We're going to have to put a cap on the number of args that
   //  can be passed, 8 for the moment.  Sigh.
   static void* sVarArgs[20];
   U32 numArgs = 0;

   for (const char* search = format; *search != '\0'; search++) {
      if (search[0] == '%' && search[1] != '%')
         numArgs++;
   }
   AssertFatal(numArgs <= 20, "Error, too many arguments to lame implementation of dSscanf.  Fix implmentation");

   // Ok, we have the number of arguments...
   for (U32 i = 0; i < numArgs; i++)
      sVarArgs[i] = va_arg(args, void*);
   va_end(args);

   switch (numArgs) {
     case 0: return 0;
     case 1:  return sscanf(buffer, format, sVarArgs[0]);
     case 2:  return sscanf(buffer, format, sVarArgs[0], sVarArgs[1]);
     case 3:  return sscanf(buffer, format, sVarArgs[0], sVarArgs[1], sVarArgs[2]);
     case 4:  return sscanf(buffer, format, sVarArgs[0], sVarArgs[1], sVarArgs[2], sVarArgs[3]);
     case 5:  return sscanf(buffer, format, sVarArgs[0], sVarArgs[1], sVarArgs[2], sVarArgs[3], sVarArgs[4]);
     case 6:  return sscanf(buffer, format, sVarArgs[0], sVarArgs[1], sVarArgs[2], sVarArgs[3], sVarArgs[4], sVarArgs[5]);
     case 7:  return sscanf(buffer, format, sVarArgs[0], sVarArgs[1], sVarArgs[2], sVarArgs[3], sVarArgs[4], sVarArgs[5], sVarArgs[6]);
     case 8:  return sscanf(buffer, format, sVarArgs[0], sVarArgs[1], sVarArgs[2], sVarArgs[3], sVarArgs[4], sVarArgs[5], sVarArgs[6], sVarArgs[7]);
     case 9:  return sscanf(buffer, format, sVarArgs[0], sVarArgs[1], sVarArgs[2], sVarArgs[3], sVarArgs[4], sVarArgs[5], sVarArgs[6], sVarArgs[7], sVarArgs[8]);
     case 10: return sscanf(buffer, format, sVarArgs[0], sVarArgs[1], sVarArgs[2], sVarArgs[3], sVarArgs[4], sVarArgs[5], sVarArgs[6], sVarArgs[7], sVarArgs[8], sVarArgs[9]);
     case 11: return sscanf(buffer, format, sVarArgs[0], sVarArgs[1], sVarArgs[2], sVarArgs[3], sVarArgs[4], sVarArgs[5], sVarArgs[6], sVarArgs[7], sVarArgs[8], sVarArgs[9], sVarArgs[10]);
     case 12: return sscanf(buffer, format, sVarArgs[0], sVarArgs[1], sVarArgs[2], sVarArgs[3], sVarArgs[4], sVarArgs[5], sVarArgs[6], sVarArgs[7], sVarArgs[8], sVarArgs[9], sVarArgs[10], sVarArgs[11]);
     case 13: return sscanf(buffer, format, sVarArgs[0], sVarArgs[1], sVarArgs[2], sVarArgs[3], sVarArgs[4], sVarArgs[5], sVarArgs[6], sVarArgs[7], sVarArgs[8], sVarArgs[9], sVarArgs[10], sVarArgs[11], sVarArgs[12]);
     case 14: return sscanf(buffer, format, sVarArgs[0], sVarArgs[1], sVarArgs[2], sVarArgs[3], sVarArgs[4], sVarArgs[5], sVarArgs[6], sVarArgs[7], sVarArgs[8], sVarArgs[9], sVarArgs[10], sVarArgs[11], sVarArgs[12], sVarArgs[13]);
     case 15: return sscanf(buffer, format, sVarArgs[0], sVarArgs[1], sVarArgs[2], sVarArgs[3], sVarArgs[4], sVarArgs[5], sVarArgs[6], sVarArgs[7], sVarArgs[8], sVarArgs[9], sVarArgs[10], sVarArgs[11], sVarArgs[12], sVarArgs[13], sVarArgs[14]);
     case 16: return sscanf(buffer, format, sVarArgs[0], sVarArgs[1], sVarArgs[2], sVarArgs[3], sVarArgs[4], sVarArgs[5], sVarArgs[6], sVarArgs[7], sVarArgs[8], sVarArgs[9], sVarArgs[10], sVarArgs[11], sVarArgs[12], sVarArgs[13], sVarArgs[14], sVarArgs[15]);
     case 17: return sscanf(buffer, format, sVarArgs[0], sVarArgs[1], sVarArgs[2], sVarArgs[3], sVarArgs[4], sVarArgs[5], sVarArgs[6], sVarArgs[7], sVarArgs[8], sVarArgs[9], sVarArgs[10], sVarArgs[11], sVarArgs[12], sVarArgs[13], sVarArgs[14], sVarArgs[15], sVarArgs[16]);
     case 18: return sscanf(buffer, format, sVarArgs[0], sVarArgs[1], sVarArgs[2], sVarArgs[3], sVarArgs[4], sVarArgs[5], sVarArgs[6], sVarArgs[7], sVarArgs[8], sVarArgs[9], sVarArgs[10], sVarArgs[11], sVarArgs[12], sVarArgs[13], sVarArgs[14], sVarArgs[15], sVarArgs[16], sVarArgs[17]);
     case 19: return sscanf(buffer, format, sVarArgs[0], sVarArgs[1], sVarArgs[2], sVarArgs[3], sVarArgs[4], sVarArgs[5], sVarArgs[6], sVarArgs[7], sVarArgs[8], sVarArgs[9], sVarArgs[10], sVarArgs[11], sVarArgs[12], sVarArgs[13], sVarArgs[14], sVarArgs[15], sVarArgs[16], sVarArgs[17], sVarArgs[18]);
     case 20: return sscanf(buffer, format, sVarArgs[0], sVarArgs[1], sVarArgs[2], sVarArgs[3], sVarArgs[4], sVarArgs[5], sVarArgs[6], sVarArgs[7], sVarArgs[8], sVarArgs[9], sVarArgs[10], sVarArgs[11], sVarArgs[12], sVarArgs[13], sVarArgs[14], sVarArgs[15], sVarArgs[16], sVarArgs[17], sVarArgs[18], sVarArgs[19]);
   }
   return 0;
#endif
}

S32 dFflushStdout()
{
   return fflush(stdout);
}

S32 dFflushStderr()
{
   return fflush(stderr);
}

void dQsort(void *base, U32 nelem, U32 width, S32 (QSORT_CALLBACK *fcmp)(const void *, const void *))
{
   qsort(base, nelem, width, fcmp);
}

StringTableEntry Platform::createUUID(void)
{
   return NULL;
}


text:
using UnityEngine;
using System;

namespace AudioPoolingSystem
{
    [Serializable]
    public class AudioEntity
    {
        public SoundType soundType;
        public AudioClip audioClip;
    }
}


text:
import net.katagaitai.phpscan.MainTest;
import net.katagaitai.phpscan.ast.PhpAstParserTest;
import net.katagaitai.phpscan.compiler.CompilerTest;
import net.katagaitai.phpscan.compiler.ProjectCompilerTest;
import net.katagaitai.phpscan.interceptor.InterceptorTest;
import net.katagaitai.phpscan.interpreter.InterpreterTest;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;

@RunWith(Suite.class)
@SuiteClasses({ PhpAstParserTest.class, CompilerTest.class, ProjectCompilerTest.class, InterpreterTest.class,
		InterceptorTest.class, MainTest.class })
public class AllTests {

}


text:
import { CounterActionType } from "../constants";

export interface CounterState {
  value: number;
}

const INITIAL_STATE = {
  value: 0,
};

export default function counter(state: CounterState = INITIAL_STATE, action: { type: CounterActionType }): CounterState {
  switch (action.type) {
    case CounterActionType.INCREMENT_COUNTER:
      return { value: state.value += 1 };
    case CounterActionType.DECREMENT_COUNTER:
      return { value: state.value -= 1 };
    default:
      return state;
  }
}


text:
a              { color: #0078cc; }

.button {
                background: #004a95 url('../images/bg-button-blue.gif') top left repeat-x !important;
                border-color: #004994 !important;

                }

#sidebar #main-nav li a.nav-top-item {
                background: transparent url('../images/bg-menu-item-blue.gif') right center no-repeat;
                }

ul.content-box-tabs li a:hover {
                color:#0078cc;
                }

.pagination a.current {
                background: #004a95 url('../images/bg-button-blue.gif') top left repeat-x !important;
                border-color: #004994 !important;
                }

.action-button span:hover {
				color: #0078cc;0;
                }


text:
package com.sixrr.stockmetrics.classCalculators;

import com.intellij.psi.JavaRecursiveElementVisitor;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiComment;
import com.intellij.psi.PsiElementVisitor;
import com.sixrr.metrics.utils.ClassUtils;
import com.sixrr.stockmetrics.utils.TodoUtil;

public class TodoCommentCountClassCalculator extends ClassCalculator
{
	private int elementCount = 0;

	@Override
	protected PsiElementVisitor createVisitor()
	{
		return new Visitor();
	}

	private class Visitor extends JavaRecursiveElementVisitor
	{

		@Override
		public void visitClass(PsiClass aClass)
		{
			final int prevElementCount = elementCount;
			if(!ClassUtils.isAnonymous(aClass))
			{
				elementCount = 0;
			}
			super.visitClass(aClass);
			if(!ClassUtils.isAnonymous(aClass))
			{
				if(!aClass.isInterface())
				{
					postMetric(aClass, elementCount);
				}
				elementCount = prevElementCount;
			}
		}

		@Override
		public void visitComment(PsiComment comment)
		{
			super.visitComment(comment);
			if(TodoUtil.isTodoComment(comment))
			{

				elementCount += com.sixrr.stockmetrics.utils.LineUtil.countLines(comment);
			}
		}
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you under the Apache License, Version 2.0 (the
    "License"); you may not use this file except in compliance
    with the License.  You may obtain a copy of the License at

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

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

<simple-methods xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="http://ofbiz.apache.org/dtds/simple-methods-v2.xsd">

    <simple-method method-name="createFixedAssetMaintUpdateWorkEffort" login-required="true"
        short-description="Create FixedAssetMaint and Update Schedule information in WorkEffort">
        <set-service-fields map="parameters" service-name="createFixedAssetMaint" to-map="createFixedAssetMaintCtx"/>
        <call-service service-name="createFixedAssetMaint" in-map-name="createFixedAssetMaintCtx">
            <result-to-field result-name="maintHistSeqId" field="findAssetMaintLookup.maintHistSeqId"/>
            <result-to-result result-name="maintHistSeqId"/>
        </call-service>
        <check-errors/>
        <set from-field="parameters.fixedAssetId" field="findAssetMaintLookup.fixedAssetId"/>
        <find-by-primary-key entity-name="FixedAssetMaint" map="findAssetMaintLookup" value-field="findAssetMaint"/>
        <set from-field="findAssetMaint.scheduleWorkEffortId" field="updateWorkEffortCtx.workEffortId"/>
        <set-service-fields map="parameters" service-name="updateWorkEffort" to-map="updateWorkEffortCtx"/>
        <!-- Maintenance WorkEffort entity -->
        <call-service service-name="updateWorkEffort" in-map-name="updateWorkEffortCtx"/>
    </simple-method>

    <simple-method method-name="updateFixedAssetMaintAndWorkEffort" login-required="true"
        short-description="Update FixedAssetMaint and Schedule information in WorkEffort">
        <set-service-fields map="parameters" service-name="updateFixedAssetMaint" to-map="updateFixedAssetMaintCtx"/>
        <call-service service-name="updateFixedAssetMaint" in-map-name="updateFixedAssetMaintCtx"/>
        <check-errors/>
        <if-compare field="parameters.statusId" operator="equals" value="FAM_CANCELLED">
            <set field="updateWorkEffortCtx.currentStatusId" value="CAL_CANCELLED"/>
        </if-compare>
        <set-service-fields map="parameters" service-name="updateWorkEffort" to-map="updateWorkEffortCtx"/>
        <set from-field="parameters.scheduleWorkEffortId" field="updateWorkEffortCtx.workEffortId"/>
        <set from-field="parameters.scheduleWorkEffortId" field="workEffortId"/>
        <entity-one entity-name="WorkEffort" value-field="workEffort"/>
        <set field="updateWorkEffortCtx.actualCompletionDate" from-field="parameters.actualCompletionDate" default-value="${workEffort.actualCompletionDate}"/>
        <call-service service-name="updateWorkEffort" in-map-name="updateWorkEffortCtx"/>
    </simple-method>

    <simple-method method-name="createWorkEffortAndAssocWithParent" login-required="true"
        short-description="Create WorkEffort and Associate it with Parent (identified by workEffortFromId)">
        <set from-field="parameters.workEffortIdTo" field="parameters.workEffortId"/>
        <set-service-fields map="parameters" service-name="createWorkEffortAndAssoc" to-map="createWorkEffortAndAssocCtx"/>
        <call-service service-name="createWorkEffortAndAssoc" in-map-name="createWorkEffortAndAssocCtx"/>
        <check-errors/>
    </simple-method>

    <!-- ==============Permission Checking Service============= -->
    <simple-method method-name="assetMaintPermissionCheck" short-description="Asset Maintenance permission logic">
        <set field="primaryPermission" value="ASSETMAINT"/>
        <call-simple-method method-name="genericBasePermissionCheck" xml-resource="component://common/script/org/ofbiz/common/permission/CommonPermissionServices.xml"/>
    </simple-method>

</simple-methods>


text:
var ring = require('webrtc-ring');
var srt = require('simple-raytracer');
var fs = require('fs');
var workify = require('webworkify');
var w = workify(require('./raytracer-worker.js'));

var log = require('bows')('rbp2p');
var domready = require('domready');

window.app = {
  init: function () {
    var nodeConfig = {
      signalingURL: 'http://localhost:9000',
      logging: false
    };

    var startTime;
    var endTime;
    var scene;
    var tasks;
    var N_UNITS = 50;
    var N_BROWSERS = 10;
    var results = {};
    var resultsCount = 0;
    var node = ring.createNode(nodeConfig);

    node.e.on('ready', ready);
    node.e.on('message', messageReceived);

    function ready() {
      log('node is ready');

      // prepare the scene

      var scene_file = fs.readFileSync('./scenes/pokeball.rt', 'utf8');
      scene = srt.prepareScene.byFile(scene_file);

      tasks = srt.prepareTasks({
        split: N_UNITS,
        width: scene.global.width,
        height: scene.global.height
      });

      log('A TASK: ', tasks[0]);

      // enable interaction to start through a button

      domready(function () {
        var body = document.querySelector('body');
        body.innerHTML = '<button>DO IT</button>';
        var button = document.querySelector('body');
        button.addEventListener('click', idsLookup);
      });
    }

    function idsLookup() {
      startTime = Date.now();
      log('Started at: ', startTime);
      // 1. query for nodes available
      node.sendSucessor({
        type: 'id-gossip',
        origin: node.id(),
        idsAvailable: []
      });
    }

    function startDecentralizedRaytracing(nodeIds) {
      log('my id and idsAvailable: ', node.id(), nodeIds);
      // 2. send tasks
      var tasksPerBrowser = (N_UNITS * N_UNITS) / N_BROWSERS;

      function sendMessages(offset, remaindingIds) {
        if(offset === (N_UNITS * N_UNITS)){
          return;
        }
        var destId = remaindingIds.shift();

        for(var i=0;i<tasksPerBrowser;i++) {
          node.send(destId, {
                              type: 'task',
                              task: tasks[i+offset],
                              origin: node.id()
                            });
          log('send task to: ', destId);
        }

        sendMessages(offset + tasksPerBrowser, remaindingIds);
      }
      sendMessages(0, nodeIds);

    }

    function messageReceived(message) {
      if (message.type === 'task') {
        log('Received Task');

        // message.task
        // message.task.id

        // create a worker here
        // when worker finishes, babam!

        w.addEventListener('message', function (ev) {
          if (ev.data.id !== message.task.id) {
            // console.log('not same id', ev.data.id, message.task.id);
            return; // not the event I expected
          }

          node.send(message.origin, {
                            type: 'result',
                            result: {
                              id: message.task.id//,
                              // data: ev.data.result
                            }
                          });
        });

        w.postMessage({
          task: message.task,
          scene: scene
        }); // send the worker a message

      }
      if (message.type === 'result') {
        log('Received result');
        results[message.result.id] = message.result.data;
        resultsCount += 1;
        if(resultsCount === N_UNITS * N_UNITS){
          finalize();
        }
        // add to the result array
        // if end, finalize()
      }

      if (message.type === 'id-gossip') {
        if (message.origin === node.id()){
          startDecentralizedRaytracing(message.idsAvailable);
        } else {
          message.idsAvailable.push(node.id());
          node.sendSucessor(message);
        }
        // add my id to the id array and pass it along
        // if it was me that started, startDecentralized Raytracing
      }

    }

    function finalize() {
      endTime = Date.now();
      log('Ended at: ', endTime);
      var diff = endTime - startTime;
      log('It took: ' + diff + ' ms');
    }

    // var w = workify(require('./raytracer-worker.js'));
    // w.addEventListener('message', function (ev) {
    //     console.log(ev.data);
    // });

    // w.postMessage(4); // send the worker a message

  }
};

window.app.init();


text:
namespace FastFood.Data
{
	public static class Configuration
	{
		public static string ConnectionString = @"Server=ASUS\SQLEXPRESS;Database=FastFood;Trusted_Connection=True";
	}
}


text:
package ru.tulupov.nsuconnect.request;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Response;

import java.util.HashMap;
import java.util.Map;

import ru.tulupov.nsuconnect.model.Command;
import ru.tulupov.nsuconnect.model.RequestSession;

public class CommandRequest extends BaseRequest<Command[]> {
    public CommandRequest(RequestSession session, Response.Listener<Command[]> listener, Response.ErrorListener errorListener) {

        super(Method.POST,
                String.format("%s?=%s=%s", Config.MSG_ENDPOINT.toString(), Constants.IDENTIFIER, session.getLastId()),
                session,
                Command[].class,
                listener,
                errorListener);
        setRetryPolicy(new DefaultRetryPolicy(Config.TIMEOUT_POOLING, Config.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    }

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        Map<String, String> headers = new HashMap<String, String>();

        headers.put("Referer", "http://msg.inctalk.net/?identifier=IFRAME&HOST=inctalk.net&version=1.32");
        return headers;
    }
}


text:
package com.antarescraft.kloudy.hologuiapi.playerguicomponents;

import org.bukkit.Location;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.util.Vector;

import com.antarescraft.kloudy.hologuiapi.HoloGUIApi;
import com.antarescraft.kloudy.hologuiapi.PlayerData;
import com.antarescraft.kloudy.hologuiapi.guicomponents.TextBoxComponent;

import net.md_5.bungee.api.ChatColor;

public class PlayerGUITextBoxComponent extends PlayerGUIValueBoxComponent implements ValueHolder
{
	private String line;
	private String prevLine;
	private boolean lineVisible;

	public PlayerGUITextBoxComponent(Player player, TextBoxComponent guiComponent)
	{
		super(player, guiComponent);

		line = getTextBoxComponent().getPlayerTextBoxValue(player);
		prevLine = line;

		lineVisible = true;

		lines = new String[4];
		lines[0] = this.line;
		lines[1] = "▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇";
		lines[2] = "▇§l                                §r                                ▇";
		lines[3] = "▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇";

		componentEntityIds = new int[lines.length];
		armorstandLocations = new Location[componentEntityIds.length];
	}

	public TextBoxComponent getTextBoxComponent()
	{
		return (TextBoxComponent)guiComponent;
	}

	@Override
	public String getValue()
	{
		return line;
	}

	public void startEditing()
	{
		PlayerData playerData = PlayerData.getPlayerData(player);

		if(playerData.isSneaking())//sneaking, clear text
		{
			getTextBoxComponent().setPlayerTextBoxValue(player, "");

			String message = ChatColor.BOLD + "===============HoloGUI Text Box===============\n";
			message += " \n";
			message += ChatColor.GOLD + "" + ChatColor.ITALIC + "Cleared the text in the textbox\n" + ChatColor.RESET;
			message += " \n";
			message += ChatColor.WHITE + "" + ChatColor.BOLD + "=============================================";

			player.sendMessage(message);
		}
		else
		{
			PlayerGUITextBoxComponent textBox = playerData.getTextBoxEditor();

			if(textBox == null)
			{
				select();

				playerData.setPlayerTextBoxEditor(this);

				String message = ChatColor.BOLD + "===============HoloGUI Text Box===============\n";
				message += " \n";
				message += ChatColor.GOLD + "" + ChatColor.ITALIC + "Text box current value: \n" + ChatColor.RESET;
				message += " \n";
				message += getValue() + "\n";
				message += " \n";
				message += ChatColor.GREEN + "" + ChatColor.ITALIC + "Type a new value for this text box in chat and press 'Enter'.\n";
				message += ChatColor.GREEN + "" + ChatColor.ITALIC + "Click the text box again to cancel without setting a value.\n";
				message += "Crouch (shift) and click text box to clear the text.\n";
				message += " \n";
				message += ChatColor.WHITE + "" + ChatColor.BOLD + "=============================================";

				player.sendMessage(message);
			}
			else
			{
				if(this.equals(textBox))
				{
					cancelEditing();
				}
				else
				{
					String message = ChatColor.BOLD + "===============HoloGUI Text Box===============\n";
					message += " \n";
					message += ChatColor.RED + "" + ChatColor.ITALIC + "You are already editing another text box!\n";
					message += " \n";
					message += ChatColor.GOLD + "" + ChatColor.ITALIC + "Type into chat the value you would like the textbox to have to \nfinish editing the current text box.\n";
					message += "Click the current text box you are editing to cancel without\n";
					message += "setting a value.\n";
					message += "Crouch (shift) and click text box to clear the text.\n";
					message += " \n";
					message += ChatColor.WHITE + "" + ChatColor.BOLD + "=============================================";

					player.sendMessage(message);
				}
			}
		}
	}

	public void cancelEditing()
	{
		unselect();

		PlayerData.getPlayerData(player).setPlayerTextBoxEditor(null);

		String message = ChatColor.BOLD + "===============HoloGUI Text Box===============\n";
		message += " \n";
		message += ChatColor.GREEN + "" + ChatColor.ITALIC + "You have canceled editing the text box.\n";
		message += " \n";
		message += ChatColor.WHITE + "" + ChatColor.BOLD + "=============================================";

		player.sendMessage(message);
	}

	public void stopEditing(String newValue)
	{
		unselect();
		getTextBoxComponent().setPlayerTextBoxValue(player, newValue);

		String message = ChatColor.BOLD + "===============HoloGUI Text Box===============\n";
		message += " \n";
		message += ChatColor.GOLD + "" + ChatColor.ITALIC + "Text box value set to: \n" + ChatColor.RESET;
		message += " \n";
		message += newValue + "\n";
		message += " \n";
		message += ChatColor.WHITE + "" + ChatColor.BOLD + "=============================================";
		player.sendMessage(message);

		PlayerData.getPlayerData(player).setPlayerTextBoxEditor(null);
	}

	@Override
	public void updateComponentLines()
	{
		updateLabelText();

		line = getTextBoxComponent().getPlayerTextBoxValue(player);

		if(prevLine != null && !prevLine.equals(line))//don't update the line if it hasn't changed from the previous frame
		{
			String displayLine = line;
			if(displayLine.length() > 30)
			{
				displayLine = displayLine.substring(0, 31) + "...";
			}

			if(!lineVisible && !displayLine.equals(""))//line was invisible, but now has content so make visible
			{
				lineVisible = true;
				HoloGUIApi.packetManager.updateEntityCustomNameVisible(player, componentEntityIds[0], lineVisible);
			}
			else if(lineVisible && displayLine.equals(""))
			{
				lineVisible = false;
				HoloGUIApi.packetManager.updateEntityCustomNameVisible(player, componentEntityIds[0], lineVisible);
			}

			HoloGUIApi.packetManager.updateEntityText(player, componentEntityIds[0], displayLine);
		}

		lines[0] = line;
		prevLine = line;
	}

	@Override
	public void spawnEntities(Location lookLocation, boolean stationary)
	{
		Vector vect = lookLocation.getDirection().setY(0.25);
		vect = customNormalize(vect);

		double distance = guiComponent.getProperties().getDistance();
		Location lookOrigin = player.getLocation();
		if(stationary)
		{
			lookOrigin = lookLocation;
			distance = 15;
		}

		armorstandLocations[0] = calculateArmorStandLocation(2, lookOrigin, vect, distance, guiComponent.getLineHeight(),
				guiComponent.getProperties().getPosition().getY(), guiComponent.getProperties().getPosition().getX());

		if(stationary)
		{
			armorstandLocations[0].setX(armorstandLocations[0].getX() + (vect.getX() * -15));
			armorstandLocations[0].setZ(armorstandLocations[0].getZ() + (vect.getZ() * -15));
		}

		String displayLine = new String(line);
		if(displayLine.length() > 30)
		{
			displayLine = displayLine.substring(0, 31) + "...";
		}

		if(displayLine.equals("")) lineVisible = false;

		componentEntityIds[0] = HoloGUIApi.packetManager.spawnEntity(EntityType.ARMOR_STAND, player, armorstandLocations[0], displayLine, lineVisible);

		renderLabel(lookOrigin, vect, stationary);

		for(int i = 1; i < lines.length; i++)
		{
			armorstandLocations[i] = calculateArmorStandLocation(i, lookOrigin, vect, distance, guiComponent.getLineHeight(),
					guiComponent.getProperties().getPosition().getY(), guiComponent.getProperties().getPosition().getX());

			if(stationary)
			{
				armorstandLocations[i].setX(armorstandLocations[i].getX() + (vect.getX() * -15));
				armorstandLocations[i].setZ(armorstandLocations[i].getZ() + (vect.getZ() * -15));
			}

			componentEntityIds[i] = HoloGUIApi.packetManager.spawnEntity(EntityType.ARMOR_STAND, player, armorstandLocations[i] , lines[i], true);
		}
	}

	@Override
	public boolean equals(Object object)
	{
		if(object instanceof PlayerGUITextBoxComponent)
		{
			PlayerGUITextBoxComponent textBox = (PlayerGUITextBoxComponent)object;
			return textBox.getGUIComponent().getProperties().getId().equals(this.getGUIComponent().getProperties().getId());
		}

		return false;
	}
}


text:
Aws.config.update region: 'eu-west-2' # London

CASE_UPLOADS_S3_BUCKET = Aws::S3::Resource.new.bucket(Settings.case_uploads_s3_bucket)


text: <method [type]="method" [parameters]="request"></method>


text:
package sbt
package classpath

import java.io.{ ByteArrayInputStream, InputStream }
import java.net.{ Proxy, URL, URLConnection, URLStreamHandler }
import java.util.Enumeration

object RawURL {
  /**
   * Constructs a URL with scheme `raw` and path `file` that will return the bytes for `value` in the platform default encoding
   * when a connection to the URL is opened.
   */
  def apply(file: String, value: String): URL =
    apply(file, value.getBytes)

  /** Constructs a URL with scheme `raw` and path `file` that will return the bytes `value` when a connection to the URL is opened. */
  def apply(file: String, value: Array[Byte]): URL =
    apply(file)(new ByteArrayInputStream(value))

  /**
   * Constructs a URL with scheme `raw` and path `file` that will use `value` to construct the `InputStream` used when a connection
   * to the URL is opened.
   */
  def apply(file: String)(value: => InputStream): URL =
    new URL("raw", null, -1, file, new RawStreamHandler(value))

  private[this] final class RawStreamHandler(value: => InputStream) extends URLStreamHandler {
    override protected def openConnection(url: URL, p: Proxy): URLConnection =
      openConnection(url)
    override protected def openConnection(url: URL): URLConnection =
      new URLConnection(url) {
        private lazy val in = value
        def connect() { in }
        override def getInputStream = in
      }
  }
}

/** A ClassLoader that looks up resource requests in a `Map` prior to the base ClassLoader's resource lookups. */
trait RawResources extends FixedResources {
  /** The map from resource paths to the raw String content to provide via the URL returned by [[findResource]] or [[findResources]]. */
  protected def resources: Map[String, String]
  override protected final val resourceURL = resources.transform(RawURL.apply)
}

/** A ClassLoader that looks up resource requests in a `Map` prior to the base ClassLoader's resource lookups. */
trait FixedResources extends ClassLoader {
  /** The map from resource paths to URL to provide in [[findResource]] and [[findResources]]. */
  protected def resourceURL: Map[String, URL]

  override def findResource(s: String): URL = resourceURL.getOrElse(s, super.findResource(s))

  import java.util.Collections.{ enumeration, singletonList }
  override def findResources(s: String): Enumeration[URL] =
    {
      val sup = super.findResources(s)
      resourceURL.get(s) match {
        case Some(url) => new DualEnumeration(enumeration(singletonList(url)), sup)
        case None      => sup
      }
    }
}


text:
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.ResourceManager;
using Azure.ResourceManager.AppService.Models;

namespace Azure.ResourceManager.AppService
{
    /// <summary> A class to add extension methods to SubscriptionResource. </summary>
    internal partial class SubscriptionResourceExtensionClient : ArmResource
    {
        /// <summary>
        /// Description for List all apps that are assigned to a hostname.
        /// Request Path: /subscriptions/{subscriptionId}/providers/Microsoft.Web/listSitesAssignedToHostName
        /// Operation Id: ListSiteIdentifiersAssignedToHostName
        /// </summary>
        /// <param name="nameIdentifier"> Hostname information. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <returns> An async collection of <see cref="AppServiceIdentifierData" /> that may take multiple service requests to iterate over. </returns>
        public virtual AsyncPageable<AppServiceIdentifierData> GetAllSiteIdentifierDataAsync(AppServiceDomainNameIdentifier nameIdentifier, CancellationToken cancellationToken = default)
        {
            async Task<Page<AppServiceIdentifierData>> FirstPageFunc(int? pageSizeHint)
            {
                using var scope = DefaultClientDiagnostics.CreateScope("SubscriptionResourceExtensionClient.GetAllSiteIdentifierData");
                scope.Start();
                try
                {
                    var response = await DefaultRestClient.ListSiteIdentifiersAssignedToHostNameAsync(Id.SubscriptionId, nameIdentifier, cancellationToken: cancellationToken).ConfigureAwait(false);
                    return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
                }
                catch (Exception e)
                {
                    scope.Failed(e);
                    throw;
                }
            }
            async Task<Page<AppServiceIdentifierData>> NextPageFunc(string nextLink, int? pageSizeHint)
            {
                using var scope = DefaultClientDiagnostics.CreateScope("SubscriptionResourceExtensionClient.GetAllSiteIdentifierData");
                scope.Start();
                try
                {
                    var response = await DefaultRestClient.ListSiteIdentifiersAssignedToHostNameNextPageAsync(nextLink, Id.SubscriptionId, nameIdentifier, cancellationToken: cancellationToken).ConfigureAwait(false);
                    return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
                }
                catch (Exception e)
                {
                    scope.Failed(e);
                    throw;
                }
            }
            return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc);
        }

        /// <summary>
        /// Description for List all apps that are assigned to a hostname.
        /// Request Path: /subscriptions/{subscriptionId}/providers/Microsoft.Web/listSitesAssignedToHostName
        /// Operation Id: ListSiteIdentifiersAssignedToHostName
        /// </summary>
        /// <param name="nameIdentifier"> Hostname information. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <returns> A collection of <see cref="AppServiceIdentifierData" /> that may take multiple service requests to iterate over. </returns>
        public virtual Pageable<AppServiceIdentifierData> GetAllSiteIdentifierData(AppServiceDomainNameIdentifier nameIdentifier, CancellationToken cancellationToken = default)
        {
            Page<AppServiceIdentifierData> FirstPageFunc(int? pageSizeHint)
            {
                using var scope = DefaultClientDiagnostics.CreateScope("SubscriptionResourceExtensionClient.GetAllSiteIdentifierData");
                scope.Start();
                try
                {
                    var response = DefaultRestClient.ListSiteIdentifiersAssignedToHostName(Id.SubscriptionId, nameIdentifier, cancellationToken: cancellationToken);
                    return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
                }
                catch (Exception e)
                {
                    scope.Failed(e);
                    throw;
                }
            }
            Page<AppServiceIdentifierData> NextPageFunc(string nextLink, int? pageSizeHint)
            {
                using var scope = DefaultClientDiagnostics.CreateScope("SubscriptionResourceExtensionClient.GetAllSiteIdentifierData");
                scope.Start();
                try
                {
                    var response = DefaultRestClient.ListSiteIdentifiersAssignedToHostNameNextPage(nextLink, Id.SubscriptionId, nameIdentifier, cancellationToken: cancellationToken);
                    return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
                }
                catch (Exception e)
                {
                    scope.Failed(e);
                    throw;
                }
            }
            return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc);
        }
    }
}


text: A three.js experiment, inspired by the classic arcade game breakout


text:
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/media/router/providers/cast/cast_activity_manager.h"

#include <memory>
#include <string>
#include <tuple>
#include <utility>
#include <vector>

#include "base/bind.h"
#include "base/callback_helpers.h"
#include "base/json/json_reader.h"
#include "base/memory/raw_ptr.h"
#include "base/run_loop.h"
#include "base/strings/strcat.h"
#include "base/test/bind.h"
#include "base/test/mock_callback.h"
#include "base/test/values_test_util.h"
#include "base/values.h"
#include "chrome/browser/media/router/providers/cast/cast_session_client.h"
#include "chrome/browser/media/router/providers/cast/mirroring_activity.h"
#include "chrome/browser/media/router/providers/cast/mock_app_activity.h"
#include "chrome/browser/media/router/providers/cast/test_util.h"
#include "chrome/browser/media/router/providers/common/buffered_message_sender.h"
#include "chrome/browser/media/router/test/mock_mojo_media_router.h"
#include "chrome/browser/media/router/test/provider_test_helpers.h"
#include "components/cast_channel/cast_message_util.h"
#include "components/cast_channel/cast_test_util.h"
#include "components/media_router/common/media_source.h"
#include "components/media_router/common/test/mock_logger.h"
#include "components/media_router/common/test/test_helper.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/test/browser_task_environment.h"
#include "mojo/public/cpp/bindings/receiver.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "services/data_decoder/public/cpp/test_support/in_process_data_decoder.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "third_party/openscreen/src/cast/common/public/cast_streaming_app_ids.h"

using base::test::IsJson;
using base::test::ParseJson;
using base::test::ParseJsonDict;
using testing::_;
using testing::AnyNumber;
using testing::ByRef;
using testing::ElementsAre;
using testing::Invoke;
using testing::IsEmpty;
using testing::NiceMock;
using testing::Not;
using testing::Return;
using testing::WithArg;

namespace media_router {

namespace {
constexpr int kChannelId = 42;
constexpr int kChannelId2 = 43;
constexpr char kClientId[] = "theClientId";
constexpr char kOrigin[] = "https://google.com";
constexpr int kFrameTreeNodeId = 1;
constexpr int kFrameTreeNodeId2 = 2;
constexpr char kAppId1[] = "ABCDEFGH";
constexpr char kAppId2[] = "BBBBBBBB";
constexpr char kAppParams[] = R"(
{
  "requiredFeatures" : ["STREAM_TRANSFER"],
  "launchCheckerParams" : {
    "credentialsData" : {
      "credentialsType" : "mobile",
      "credentials" : "99843n2idsguyhga"
    }
  }
}
)";
constexpr char kPresentationId[] = "presentationId";
constexpr char kPresentationId2[] = "presentationId2";

std::string MakeSourceId(const std::string& app_id = kAppId1,
                         const std::string& app_params = "",
                         const std::string& client_id = kClientId) {
  return base::StrCat(
      {"cast:", app_id, "?clientId=", client_id, "&appParams=", app_params});
}

base::Value::Dict MakeReceiverStatus(const std::string& app_id,
                                     bool update_display_name = false) {
  return ParseJsonDict(R"({
        "applications": [{
          "appId": ")" +
                       app_id +
                       R"(",
          "displayName": "theDisplayName)" +
                       std::string(update_display_name ? "1" : "2") + R"(",
          "namespaces": [
            {"name": "urn:x-cast:com.google.cast.media"},
            {"name": "urn:x-cast:com.google.foo"},
          ],
          "sessionId": "theSessionId",
          "statusText": "theAppStatus",
          "transportId": "theTransportId",
        }],
      })");
}

class MockLaunchSessionCallback {
 public:
  MOCK_METHOD(void,
              Run,
              (const absl::optional<MediaRoute>& route,
               mojom::RoutePresentationConnectionPtr presentation_connections,
               const absl::optional<std::string>& error_message,
               media_router::mojom::RouteRequestResultCode result_code));
};

class MockMirroringActivity : public MirroringActivity {
 public:
  MockMirroringActivity(const MediaRoute& route,
                        const std::string& app_id,
                        OnStopCallback on_stop)
      : MirroringActivity(route,
                          app_id,
                          nullptr,
                          nullptr,
                          0,
                          CastSinkExtraData(),
                          std::move(on_stop)) {}

  MOCK_METHOD(void, CreateMojoBindings, (mojom::MediaRouter * media_router));
  MOCK_METHOD(void, OnSessionSet, (const CastSession& session));
  MOCK_METHOD(void,
              SendStopSessionMessageToClients,
              (const std::string& hash_token));
};

using MockAppActivityCallback = base::RepeatingCallback<void(MockAppActivity*)>;
using MockMirroringActivityCallback =
    base::RepeatingCallback<void(MockMirroringActivity*)>;
}  // namespace

// Test parameters are a boolean indicating whether the client connection should
// be closed by a leave_session message, and the URL used to create the test
// session.
class CastActivityManagerTest : public testing::Test,
                                public CastActivityFactoryForTest {
 public:
  CastActivityManagerTest()
      : socket_service_(content::GetUIThreadTaskRunner({})),
        message_handler_(&socket_service_),
        cast_streaming_app_id_(
            openscreen::cast::GetCastStreamingAudioVideoAppId()) {
    media_sink_service_.AddOrUpdateSink(sink_);
    socket_.set_id(kChannelId);
  }

  ~CastActivityManagerTest() override = default;

  void SetUp() override {
    CastActivityManager::SetActitityFactoryForTest(this);

    router_receiver_ = std::make_unique<mojo::Receiver<mojom::MediaRouter>>(
        &mock_router_, router_remote_.BindNewPipeAndPassReceiver());

    session_tracker_.reset(
        new CastSessionTracker(&media_sink_service_, &message_handler_,
                               socket_service_.task_runner()));
    manager_ = std::make_unique<CastActivityManager>(
        &media_sink_service_, session_tracker_.get(), &message_handler_,
        router_remote_.get(), &logger_, "theHashToken");

    ON_CALL(message_handler_, StopSession)
        .WillByDefault(WithArg<3>([this](auto callback) {
          std::move(callback).Run(stop_session_callback_arg_);
        }));

    RunUntilIdle();
  }

  void TearDown() override {
    // This is a no-op for many tests, but it serves as a good sanity check in
    // any case.
    RunUntilIdle();

    manager_.reset();
    CastActivityManager::SetActitityFactoryForTest(nullptr);
  }

  // from CastActivityFactoryForTest
  std::unique_ptr<AppActivity> MakeAppActivity(
      const MediaRoute& route,
      const std::string& app_id) override {
    auto activity = std::make_unique<NiceMock<MockAppActivity>>(route, app_id);
    app_activity_ = activity.get();
    app_activity_callback_.Run(activity.get());
    return activity;
  }

  // from CastActivityFactoryForTest
  std::unique_ptr<MirroringActivity> MakeMirroringActivity(
      const MediaRoute& route,
      const std::string& app_id,
      MirroringActivity::OnStopCallback on_stop) override {
    auto activity = std::make_unique<NiceMock<MockMirroringActivity>>(
        route, app_id, std::move(on_stop));
    mirroring_activity_ = activity.get();
    mirroring_activity_callback_.Run(activity.get());
    return activity;
  }

  // Run any pending events and verify expectations associated with them.  This
  // method is sometimes called when there are clearly no pending events simply
  // to check expectations for code executed synchronously.
  void RunUntilIdle() {
    task_environment_.RunUntilIdle();
    testing::Mock::VerifyAndClearExpectations(&message_handler_);
    testing::Mock::VerifyAndClearExpectations(&mock_router_);
  }

  void ExpectLaunchSessionSuccess(
      const absl::optional<MediaRoute>& route,
      mojom::RoutePresentationConnectionPtr presentation_connections,
      const absl::optional<std::string>&,
      media_router::mojom::RouteRequestResultCode) {
    ASSERT_TRUE(route);
    route_ = std::make_unique<MediaRoute>(*route);
    presentation_connections_ = std::move(presentation_connections);
  }

  void ExpectLaunchSessionFailure(
      const absl::optional<MediaRoute>& route,
      mojom::RoutePresentationConnectionPtr presentation_connections,
      const absl::optional<std::string>& error_message,
      media_router::mojom::RouteRequestResultCode result_code) {
    ASSERT_FALSE(route);
    LaunchSessionFailed();
  }

  MOCK_METHOD(void, LaunchSessionFailed, ());

  void CallLaunchSessionCommon(
      const std::string& app_id,
      const std::string& app_params,
      const std::string& client_id,
      mojom::MediaRouteProvider::CreateRouteCallback callback) {
    ExpectSingleRouteUpdate();
    // A launch session request is sent to the sink.
    const absl::optional<base::Value> json = base::JSONReader::Read(app_params);
    EXPECT_CALL(message_handler_,
                LaunchSession(kChannelId, app_id, kDefaultLaunchTimeout,
                              testing::ElementsAre("WEB"),
                              testing::Eq(testing::ByRef(json)), _))
        .WillOnce(WithArg<5>([this](auto callback) {
          launch_session_callback_ = std::move(callback);
        }));

    auto source = CastMediaSource::FromMediaSourceId(
        MakeSourceId(app_id, app_params, client_id));
    ASSERT_TRUE(source);

    // Callback needs to be invoked by running |launch_session_callback_|.
    manager_->LaunchSession(*source, sink_, kPresentationId, origin_,
                            kFrameTreeNodeId,
                            /*incognito*/ false, std::move(callback));

    RunUntilIdle();
  }

  void CallLaunchSessionSuccess(const std::string& app_id = kAppId1,
                                const std::string& app_params = "",
                                const std::string& client_id = kClientId) {
    app_activity_callback_ =
        base::BindLambdaForTesting([this](MockAppActivity* activity) {
          // TODO(crbug.com/1291744): Check parameters.
          EXPECT_CALL(*activity, AddClient);
          EXPECT_CALL(*activity, SendMessageToClient).Times(2);
          EXPECT_CALL(*activity, OnSessionSet).WillOnce([this]() {
            EXPECT_EQ(sink_, app_activity_->sink());
          });
          app_activity_callback_ = base::DoNothing();
        });

    CallLaunchSessionCommon(
        app_id, app_params, client_id,
        base::BindOnce(&CastActivityManagerTest::ExpectLaunchSessionSuccess,
                       base::Unretained(this)));
  }

  void CallLaunchSessionFailure(const std::string& app_id = kAppId1,
                                const std::string& app_params = "",
                                const std::string& client_id = kClientId) {
    CallLaunchSessionCommon(
        app_id, app_params, client_id,
        base::BindOnce(&CastActivityManagerTest::ExpectLaunchSessionFailure,
                       base::Unretained(this)));
  }

  void ReceiveLaunchSuccessResponseFromReceiver(
      const std::string& app_id = kAppId1) {
    cast_channel::LaunchSessionResponse response;
    response.result = cast_channel::LaunchSessionResponse::Result::kOk;
    response.receiver_status = MakeReceiverStatus(app_id);

    SetSessionForTest(sink_.id(),
                      CastSession::From(sink_, *response.receiver_status));

    std::move(launch_session_callback_).Run(std::move(response), nullptr);
    RunUntilIdle();
  }

  void LaunchAppSession(const std::string& app_id = kAppId1,
                        const std::string& app_params = "",
                        const std::string& client_id = kClientId) {
    CallLaunchSessionSuccess(app_id, app_params, client_id);

    // 3 things will happen after a launch session response is received:
    // (1) SDK client receives "receiver_action" and "new_session" message.
    // (2) Virtual connection is created.
    // (3) Route list will be updated.

    EXPECT_CALL(message_handler_,
                EnsureConnection(kChannelId, client_id, "theTransportId",
                                 cast_channel::VirtualConnectionType::kStrong));
    EXPECT_CALL(message_handler_,
                SendMediaRequest(kChannelId,
                                 // NOTE: MEDIA_GET_STATUS is translated to
                                 // GET_STATUS inside SendMediaRequest.
                                 IsJson(R"({"type": "MEDIA_GET_STATUS"})"),
                                 client_id, "theTransportId"));

    // MediaRouter is notified of new route.
    ExpectSingleRouteUpdate();

    ReceiveLaunchSuccessResponseFromReceiver(app_id);
  }

  void ExpectAppActivityStoppedTimes(int times) {
    EXPECT_CALL(*app_activity_, SendStopSessionMessageToClients).Times(times);

    if (times == 0) {
      EXPECT_CALL(message_handler_, StopSession).Times(0);
    } else {
      // TODO(crbug.com/1291744): Check other parameters
      EXPECT_CALL(message_handler_, StopSession(kChannelId, _, _, _))
          .Times(times);
    }
  }

  void LaunchNonSdkMirroringSession() {
    CallLaunchSessionSuccess(cast_streaming_app_id_, /* app_params */ "",
                             /* client_id */ "");
    mirroring_activity_callback_ =
        base::BindLambdaForTesting([this](MockMirroringActivity* activity) {
          EXPECT_CALL(*activity, OnSessionSet).WillOnce([this]() {
            EXPECT_EQ(sink_, mirroring_activity_->sink());
          });
          mirroring_activity_callback_ = base::DoNothing();
        });

    ResolveMirroringSessionLaunch();
  }

  void LaunchCastSdkMirroringSession() {
    CallLaunchSessionSuccess(cast_streaming_app_id_, kAppParams, kClientId);
    mirroring_activity_callback_ =
        base::BindLambdaForTesting([this](MockMirroringActivity* activity) {
          EXPECT_CALL(*activity, OnSessionSet).WillOnce([this]() {
            EXPECT_EQ(sink_, mirroring_activity_->sink());
          });
          mirroring_activity_callback_ = base::DoNothing();
        });
    // We expect EnsureConnection() to be called for both the sender client and
    // |message_handler_.source_id()|. The latter is captured in
    // ResolveMirroringSessionLaunch().
    //
    // CallLaunchSessionSuccess() calls VerifyAndClearExpectations() on
    // |message_handler_|, so this EXPECT_CALL() must come after that.
    EXPECT_CALL(message_handler_,
                EnsureConnection(kChannelId, kClientId, "theTransportId",
                                 cast_channel::VirtualConnectionType::kStrong));
    ResolveMirroringSessionLaunch();
  }

  void ResolveMirroringSessionLaunch() {
    // MediaRouter is notified of new route.
    ExpectSingleRouteUpdate();
    EXPECT_CALL(message_handler_,
                EnsureConnection(kChannelId, message_handler_.source_id(),
                                 "theTransportId",
                                 cast_channel::VirtualConnectionType::kStrong));

    ReceiveLaunchSuccessResponseFromReceiver();
    DCHECK(mirroring_activity_);
  }

  void AddRemoteMirroringSession() {
    auto session =
        CastSession::From(sink2_, MakeReceiverStatus(cast_streaming_app_id_));
    manager_->OnSessionAddedOrUpdated(sink2_, *session);
    SetSessionForTest(sink2_.id(), std::move(session));
    DCHECK(mirroring_activity_);
    DCHECK(!mirroring_activity_->route().is_local());
  }

  void ExpectMirroringActivityStoppedTimes(int times) {
    DCHECK(mirroring_activity_);
    EXPECT_CALL(message_handler_, StopSession).Times(times);
    EXPECT_CALL(*mirroring_activity_, SendStopSessionMessageToClients)
        .Times(times);
  }

  void TerminateSession(bool expect_success, const MediaRoute::Id& route_id) {
    stop_session_callback_arg_ = expect_success ? cast_channel::Result::kOk
                                                : cast_channel::Result::kFailed;
    manager_->TerminateSession(route_id,
                               MakeTerminateRouteCallback(expect_success));
  }

  void TerminateSession(bool expect_success) {
    TerminateSession(expect_success, route_->media_route_id());
  }

  mojom::MediaRouteProvider::TerminateRouteCallback MakeTerminateRouteCallback(
      bool expect_success) {
    return base::BindLambdaForTesting(
        [expect_success](const absl::optional<std::string>& error_text,
                         mojom::RouteRequestResultCode result_code) {
          if (expect_success) {
            EXPECT_FALSE(error_text.has_value());
            EXPECT_EQ(mojom::RouteRequestResultCode::OK, result_code);
          } else {
            EXPECT_TRUE(error_text.has_value());
            EXPECT_NE(mojom::RouteRequestResultCode::OK, result_code);
          }
        });
  }

  // Expect a call to OnRoutesUpdated() with a single route, which will
  // optionally be saved in the variable pointed to by |route_ptr|.
  void ExpectSingleRouteUpdate() {
    updated_route_ = absl::nullopt;
    EXPECT_CALL(mock_router_, OnRoutesUpdated(mojom::MediaRouteProviderId::CAST,
                                              ElementsAre(_)))
        .WillOnce(WithArg<1>(
            [this](const auto& routes) { updated_route_ = routes[0]; }));
  }

  // Expect a call to OnRoutesUpdated() with no routes.
  void ExpectEmptyRouteUpdate() {
    updated_route_ = absl::nullopt;
    EXPECT_CALL(mock_router_,
                OnRoutesUpdated(mojom::MediaRouteProviderId::CAST, IsEmpty()))
        .Times(1);
  }

  // Expect that OnRoutesUpdated() will not be called.
  void ExpectNoRouteUpdate() {
    updated_route_ = absl::nullopt;
    EXPECT_CALL(mock_router_, OnRoutesUpdated).Times(0);
  }

  std::unique_ptr<CastSession> MakeSession(const std::string& app_id,
                                           bool update_display_name = false) {
    return CastSession::From(sink_,
                             MakeReceiverStatus(app_id, update_display_name));
  }

  // Needed because CastSessionTracker::SetSessionForTest is private.
  void SetSessionForTest(const MediaSink::Id& sink_id,
                         std::unique_ptr<CastSession> session) {
    session_tracker_->SetSessionForTest(sink_id, std::move(session));
  }

 protected:
  content::BrowserTaskEnvironment task_environment_;
  data_decoder::test::InProcessDataDecoder in_process_data_decoder_;
  NiceMock<MockMojoMediaRouter> mock_router_;
  mojo::Remote<mojom::MediaRouter> router_remote_;
  std::unique_ptr<mojo::Receiver<mojom::MediaRouter>> router_receiver_;
  cast_channel::MockCastSocketService socket_service_;
  cast_channel::MockCastSocket socket_;
  NiceMock<cast_channel::MockCastMessageHandler> message_handler_;
  MediaSinkInternal sink_ = CreateCastSink(kChannelId);
  MediaSinkInternal sink2_ = CreateCastSink(kChannelId2);
  std::unique_ptr<MediaRoute> route_;
  cast_channel::LaunchSessionCallback launch_session_callback_;
  TestMediaSinkService media_sink_service_;
  MockCastAppDiscoveryService app_discovery_service_;
  std::unique_ptr<CastActivityManager> manager_;
  std::unique_ptr<CastSessionTracker> session_tracker_;
  raw_ptr<MockAppActivity> app_activity_ = nullptr;
  raw_ptr<MockMirroringActivity> mirroring_activity_ = nullptr;
  MockAppActivityCallback app_activity_callback_ = base::DoNothing();
  MockMirroringActivityCallback mirroring_activity_callback_ =
      base::DoNothing();
  const url::Origin origin_ = url::Origin::Create(GURL(kOrigin));
  const MediaSource::Id route_query_ = "theRouteQuery";
  absl::optional<MediaRoute> updated_route_;
  cast_channel::Result stop_session_callback_arg_ = cast_channel::Result::kOk;
  NiceMock<MockLogger> logger_;
  mojom::RoutePresentationConnectionPtr presentation_connections_;
  const std::string cast_streaming_app_id_;
};

TEST_F(CastActivityManagerTest, LaunchAppSession) {
  LaunchAppSession();
  EXPECT_EQ(RouteControllerType::kGeneric, route_->controller_type());
}

TEST_F(CastActivityManagerTest, LaunchAppSessionWithAppParams) {
  LaunchAppSession(kAppId1, kAppParams);
  EXPECT_EQ(RouteControllerType::kGeneric, route_->controller_type());
}

TEST_F(CastActivityManagerTest, LaunchSessionSuccessWhenUserAllowed) {
  CallLaunchSessionSuccess();

  cast_channel::LaunchSessionCallbackWrapper out_callback;

  cast_channel::LaunchSessionResponse response;
  response.result =
      cast_channel::LaunchSessionResponse::Result::kPendingUserAuth;
  std::move(launch_session_callback_).Run(std::move(response), &out_callback);

  EXPECT_FALSE(out_callback.callback.is_null());

  cast_channel::LaunchSessionResponse response2;
  response2.result = cast_channel::LaunchSessionResponse::Result::kUserAllowed;
  std::move(out_callback.callback).Run(std::move(response2), &out_callback);

  EXPECT_FALSE(out_callback.callback.is_null());

  cast_channel::LaunchSessionResponse response3;
  response3.result = cast_channel::LaunchSessionResponse::Result::kOk;
  response3.receiver_status = MakeReceiverStatus(kAppId1);

  std::move(out_callback.callback).Run(std::move(response3), &out_callback);

  EXPECT_TRUE(out_callback.callback.is_null());

  RunUntilIdle();

  EXPECT_EQ(RouteControllerType::kGeneric, route_->controller_type());
}

TEST_F(CastActivityManagerTest, LaunchMirroringSession) {
  LaunchNonSdkMirroringSession();
  EXPECT_EQ(RouteControllerType::kMirroring, route_->controller_type());
}

TEST_F(CastActivityManagerTest, LaunchMirroringSessionViaCastSdk) {
  LaunchCastSdkMirroringSession();
  EXPECT_EQ(RouteControllerType::kMirroring, route_->controller_type());
}

TEST_F(CastActivityManagerTest, LaunchSiteInitiatedMirroringSession) {
  // For a session initiated by a website with the mirroring source we should be
  // establishing a presentation connection, even if the client ID isn't set.
  CallLaunchSessionSuccess(cast_streaming_app_id_, /*app_params*/ "",
                           /*client_id*/ "");
  ReceiveLaunchSuccessResponseFromReceiver(cast_streaming_app_id_);
  EXPECT_FALSE(presentation_connections_.is_null());
  EXPECT_EQ(RouteControllerType::kMirroring, route_->controller_type());
}

TEST_F(CastActivityManagerTest, MirroringSessionStopped) {
  LaunchNonSdkMirroringSession();
  ExpectMirroringActivityStoppedTimes(1);
  ExpectEmptyRouteUpdate();
  mirroring_activity_->DidStop();
}

TEST_F(CastActivityManagerTest, LaunchSessionFails) {
  // 3 things will happen:
  // (1) Route is removed
  // (2) Issue will be sent.
  // (3) The PresentationConnection associated with the route will be closed
  //     with error.

  // A launch session request is sent to the sink.
  CallLaunchSessionFailure();

  EXPECT_CALL(
      *app_activity_,
      ClosePresentationConnections(
          blink::mojom::PresentationConnectionCloseReason::CONNECTION_ERROR));
  ExpectEmptyRouteUpdate();
  EXPECT_CALL(mock_router_, OnIssue);

  cast_channel::LaunchSessionResponse response;
  response.result = cast_channel::LaunchSessionResponse::Result::kError;
  std::move(launch_session_callback_).Run(std::move(response), nullptr);
  RunUntilIdle();
}

TEST_F(CastActivityManagerTest, LaunchSessionFailsWhenUserNotAllowed) {
  CallLaunchSessionFailure();

  cast_channel::LaunchSessionCallbackWrapper out_callback;
  cast_channel::LaunchSessionResponse response;
  response.result =
      cast_channel::LaunchSessionResponse::Result::kPendingUserAuth;
  std::move(launch_session_callback_).Run(std::move(response), &out_callback);

  EXPECT_FALSE(out_callback.callback.is_null());

  EXPECT_CALL(
      *app_activity_,
      ClosePresentationConnections(
          blink::mojom::PresentationConnectionCloseReason::CONNECTION_ERROR));
  ExpectEmptyRouteUpdate();

  cast_channel::LaunchSessionResponse response2;
  response2.result =
      cast_channel::LaunchSessionResponse::Result::kUserNotAllowed;
  std::move(out_callback.callback).Run(std::move(response2), &out_callback);
  EXPECT_TRUE(out_callback.callback.is_null());
}

TEST_F(CastActivityManagerTest,
       LaunchSessionFailsWhenNotificationsAreDisabledOnReceiver) {
  CallLaunchSessionFailure();

  EXPECT_CALL(
      *app_activity_,
      ClosePresentationConnections(
          blink::mojom::PresentationConnectionCloseReason::CONNECTION_ERROR));
  ExpectEmptyRouteUpdate();

  cast_channel::LaunchSessionResponse response;
  response.result =
      cast_channel::LaunchSessionResponse::Result::kNotificationDisabled;
  std::move(launch_session_callback_).Run(std::move(response), nullptr);
  RunUntilIdle();
}

TEST_F(CastActivityManagerTest, LaunchSessionFailsWhenSessionIsRemoved) {
  CallLaunchSessionFailure();
  manager_->OnSessionRemoved(sink_);

  // The launch session callback should still be called even if the session was
  // removed before receiving a response from the receiver.
  EXPECT_CALL(*this, LaunchSessionFailed());
  cast_channel::LaunchSessionResponse response;
  response.result = cast_channel::LaunchSessionResponse::Result::kError;
  std::move(launch_session_callback_).Run(std::move(response), nullptr);
}

TEST_F(CastActivityManagerTest, LaunchAppSessionFailsWithAppParams) {
  EXPECT_CALL(message_handler_, LaunchSession).Times(0);
  auto source =
      CastMediaSource::FromMediaSourceId(MakeSourceId(kAppId1, "invalidjson"));
  ASSERT_TRUE(source);

  // Callback will be invoked synchronously.
  manager_->LaunchSession(
      *source, sink_, kPresentationId, origin_, kFrameTreeNodeId,
      /*incognito*/ false,
      base::BindOnce(&CastActivityManagerTest::ExpectLaunchSessionFailure,
                     base::Unretained(this)));

  RunUntilIdle();
}

TEST_F(CastActivityManagerTest, LaunchSessionTerminatesExistingSessionOnSink) {
  LaunchAppSession();
  ExpectAppActivityStoppedTimes(1);

  {
    testing::InSequence dummy;

    // Existing route is terminated before new route is created.
    // MediaRouter is notified of terminated route.
    ExpectEmptyRouteUpdate();

    // After existing route is terminated, new route is created.
    // MediaRouter is notified of new route.
    ExpectSingleRouteUpdate();
  }

  // Launch a new session on the same sink.
  auto source = CastMediaSource::FromMediaSourceId(MakeSourceId(kAppId2));
  // Use LaunchSessionParsed() instead of LaunchSession() here because
  // LaunchSessionParsed() is called asynchronously and will fail the test.
  manager_->LaunchSessionParsed(
      // TODO(crbug.com/1291744): Verify that presentation ID is used correctly.
      *source, sink_, kPresentationId2, origin_,
      kFrameTreeNodeId2, /*incognito*/
      false,
      base::BindOnce(&CastActivityManagerTest::ExpectLaunchSessionSuccess,
                     base::Unretained(this)),
      data_decoder::DataDecoder::ValueOrError());

  // LaunchSession() should not be called until we notify |mananger_| that the
  // previous session was removed.
  EXPECT_CALL(message_handler_,
              LaunchSession(kChannelId, "BBBBBBBB", kDefaultLaunchTimeout,
                            testing::ElementsAre("WEB"),
                            /* absl::optional<base::Value> appParams */
                            testing::Eq(absl::nullopt), _))
      .WillOnce(WithArg<5>([this](auto callback) {
        launch_session_callback_ = std::move(callback);
      }));

  manager_->OnSessionRemoved(sink_);
}

TEST_F(CastActivityManagerTest, LaunchSessionTerminatesExistingSessionFromTab) {
  LaunchAppSession();
  ExpectAppActivityStoppedTimes(1);

  // Launch a new session from the same tab on a different sink.
  auto source = CastMediaSource::FromMediaSourceId(MakeSourceId(kAppId2));
  // Use LaunchSessionParsed() instead of LaunchSession() here because
  // LaunchSessionParsed() is called asynchronously and will fail the test.
  manager_->LaunchSessionParsed(
      *source, sink2_, kPresentationId2, origin_,
      kFrameTreeNodeId, /*incognito*/
      false,
      base::BindOnce(&CastActivityManagerTest::ExpectLaunchSessionSuccess,
                     base::Unretained(this)),
      data_decoder::DataDecoder::ValueOrError());
}

TEST_F(CastActivityManagerTest, LaunchSessionTerminatesPendingLaunchFromTab) {
  CallLaunchSessionFailure();
  // Stop session message not sent because session has not launched yet.
  ExpectAppActivityStoppedTimes(0);

  // Launch a new session from the same tab on a different sink.
  auto source = CastMediaSource::FromMediaSourceId(MakeSourceId(kAppId2));
  // Use LaunchSessionParsed() instead of LaunchSession() here because
  // LaunchSessionParsed() is called asynchronously and will fail the test.
  manager_->LaunchSessionParsed(
      *source, sink2_, kPresentationId2, origin_,
      kFrameTreeNodeId, /*incognito*/
      false,
      base::BindOnce(&CastActivityManagerTest::ExpectLaunchSessionSuccess,
                     base::Unretained(this)),
      data_decoder::DataDecoder::ValueOrError());
}

TEST_F(CastActivityManagerTest, AddRemoveNonLocalActivity) {
  auto session = MakeSession(kAppId1);
  ExpectSingleRouteUpdate();
  manager_->OnSessionAddedOrUpdated(sink_, *session);
  RunUntilIdle();
  ASSERT_TRUE(updated_route_);
  EXPECT_FALSE(updated_route_->is_local());

  ExpectEmptyRouteUpdate();
  manager_->OnSessionRemoved(sink_);
}

TEST_F(CastActivityManagerTest, UpdateNewlyCreatedSession) {
  LaunchAppSession();

  EXPECT_CALL(*app_activity_, OnSessionUpdated).WillOnce([this]() {
    EXPECT_EQ(sink_, app_activity_->sink());
  });
  auto session = MakeSession(kAppId1);
  ExpectSingleRouteUpdate();
  manager_->OnSessionAddedOrUpdated(sink_, *session);
  RunUntilIdle();
  ASSERT_TRUE(updated_route_);
  EXPECT_TRUE(updated_route_->is_local());
}

// This test is essentially the same as UpdateNewlyCreatedSession, but it uses
// mirroring, which at one point was handled differently enough that this test
// would have failed.
TEST_F(CastActivityManagerTest, UpdateNewlyCreatedMirroringSession) {
  LaunchCastSdkMirroringSession();

  ASSERT_TRUE(mirroring_activity_);
  auto session = MakeSession(cast_streaming_app_id_);
  ExpectSingleRouteUpdate();
  manager_->OnSessionAddedOrUpdated(sink_, *session);
  RunUntilIdle();
  ASSERT_TRUE(updated_route_);
  EXPECT_TRUE(updated_route_->is_local());
}

TEST_F(CastActivityManagerTest, OnSessionAddedOrUpdated) {
  LaunchAppSession();
  auto session = MakeSession(kAppId1);
  ExpectSingleRouteUpdate();
  EXPECT_CALL(*app_activity_, OnSessionUpdated(_, "theHashToken"));
  manager_->OnSessionAddedOrUpdated(sink_, *session);
}

// TODO(takumif): Add a test case to terminate a session and launch another.
TEST_F(CastActivityManagerTest, TerminateSession) {
  LaunchAppSession();
  ExpectAppActivityStoppedTimes(1);
  ExpectEmptyRouteUpdate();
  TerminateSession(true);
}

TEST_F(CastActivityManagerTest, TerminateSessionFails) {
  LaunchAppSession();
  ExpectAppActivityStoppedTimes(1);
  ExpectNoRouteUpdate();
  TerminateSession(false);
}

TEST_F(CastActivityManagerTest, DestructorClosesLocalMirroringSession) {
  LaunchNonSdkMirroringSession();
  ExpectMirroringActivityStoppedTimes(1);
  ExpectEmptyRouteUpdate();
  manager_.reset();
}

TEST_F(CastActivityManagerTest, DestructorIgnoresNonlocalMirroringSession) {
  AddRemoteMirroringSession();
  ExpectMirroringActivityStoppedTimes(0);
  manager_.reset();
}

TEST_F(CastActivityManagerTest, DestructorIgnoresAppSession) {
  LaunchAppSession();
  ExpectAppActivityStoppedTimes(0);
  manager_.reset();
}

TEST_F(CastActivityManagerTest, TerminateSessionBeforeLaunchResponse) {
  CallLaunchSessionFailure();
  // Stop session message not sent because session has not launched yet.
  ExpectAppActivityStoppedTimes(0);
  ExpectNoRouteUpdate();
  TerminateSession(true,
                   MediaRoute::GetMediaRouteId(
                       kPresentationId, sink_.id(),
                       MediaSource(MakeSourceId(kAppId1, "", kClientId))));
  ExpectEmptyRouteUpdate();
  ReceiveLaunchSuccessResponseFromReceiver();
}

TEST_F(CastActivityManagerTest, AppMessageFromReceiver) {
  LaunchAppSession();

  // Destination ID matches client ID.
  cast::channel::CastMessage message = cast_channel::CreateCastMessage(
      "urn:x-cast:com.google.foo", base::Value(base::Value::Type::DICTIONARY),
      "sourceId", "theClientId");

  EXPECT_CALL(*app_activity_, OnAppMessage(IsCastChannelMessage(message)));
  manager_->OnAppMessage(kChannelId, message);
}

TEST_F(CastActivityManagerTest, OnMediaStatusUpdated) {
  LaunchAppSession();

  const char status[] = R"({"foo": "bar"})";
  absl::optional<int> request_id(345);

  EXPECT_CALL(*app_activity_,
              SendMediaStatusToClients(IsJson(status), request_id));
  manager_->OnMediaStatusUpdated(sink_, ParseJson(status), request_id);
}

TEST_F(CastActivityManagerTest, SecondPendingRequestCancelsTheFirst) {
  auto source =
      CastMediaSource::FromMediaSourceId(MakeSourceId(kAppId1, "", kClientId));
  MockLaunchSessionCallback callback;
  // Launch a session so that the next launch request gets queued.
  LaunchAppSession();

  // Ignore StopSession() so that pending requests don't get executed.
  EXPECT_CALL(message_handler_, StopSession).WillRepeatedly([]() {});
  // The first request gets queued, then cancelled when the second request
  // replaces it.
  EXPECT_CALL(callback, Run)
      .WillOnce(WithArg<3>([](mojom::RouteRequestResultCode code) {
        EXPECT_EQ(mojom::RouteRequestResultCode::CANCELLED, code);
      }));
  for (int i = 0; i < 2; i++) {
    manager_->LaunchSession(*source, sink_, kPresentationId, origin_,
                            kFrameTreeNodeId,
                            /*incognito*/ false,
                            base::BindOnce(&MockLaunchSessionCallback::Run,
                                           base::Unretained(&callback)));
  }
}

}  // namespace media_router


text:
<resources>
    <string name="base">Base</string>
    <string name="keyboardNumber">123</string>
    <string name="keyboardAlphabetic">ABC</string>
	<string name="keyboardButtonSeg">Seg.</string>
	<string name="ok">OK</string>
	<string name="bannerItem">BannerItem</string>
	<string name="title"></string>
</resources>