text:
package org.keycloak.testsuite;

import io.undertow.Undertow;
import org.apache.catalina.startup.Tomcat;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.keycloak.OAuth2Constants;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
import org.keycloak.protocol.oidc.OIDCLoginProtocolService;
import org.keycloak.proxy.ProxyServerBuilder;
import org.keycloak.representations.idm.RealmRepresentation;
import org.keycloak.services.managers.RealmManager;
import org.keycloak.testsuite.pages.LoginPage;
import org.keycloak.testsuite.rule.AbstractKeycloakRule;
import org.keycloak.testsuite.rule.WebResource;
import org.keycloak.testsuite.rule.WebRule;
import org.openqa.selenium.WebDriver;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.Enumeration;
import java.util.regex.Matcher;

@Ignore
public class ProxyTest {
    static String logoutUri = OIDCLoginProtocolService.logoutUrl(UriBuilder.fromUri("http://localhost:8081/auth"))
            .queryParam(OAuth2Constants.REDIRECT_URI, "http://localhost:8080/customer-portal").build("demo").toString();

    @ClassRule
    public static AbstractKeycloakRule keycloakRule = new AbstractKeycloakRule() {
        @Override
        protected void configure(KeycloakSession session, RealmManager manager, RealmModel adminRealm) {
            RealmRepresentation representation = KeycloakServer.loadJson(getClass().getResourceAsStream("/demorealm.json"), RealmRepresentation.class);
            RealmModel realm = manager.importRealm(representation);
       }
    };

    public static class SendUsernameServlet extends HttpServlet {
        @Override
        protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
            String requestURI = req.getRequestURI();
            resp.setContentType("text/plain");
            OutputStream stream = resp.getOutputStream();
            stream.write(req.getRequestURL().toString().getBytes());
            stream.write("\n".getBytes());
            Integer count = (Integer)req.getSession().getAttribute("counter");
            if (count == null) count = new Integer(0);
            req.getSession().setAttribute("counter", new Integer(count.intValue() + 1));
            stream.write(("count:"+count).getBytes());

            Enumeration<String> headers = req.getHeaderNames();
            while (headers.hasMoreElements()) {
                String name = headers.nextElement();
                System.out.println(name +": " + req.getHeader(name));
            }

            if (requestURI.contains("/bearer")) {
                Client client = ClientBuilder.newClient();

                try {
                    String appBase = "http://localhost:8080/customer-portal";
                    WebTarget target = client.target(appBase + "/call-bearer");

                    Response response = null;
                    response = target.request()
                            .header(HttpHeaders.AUTHORIZATION, "Bearer CRAP")
                            .get();
                    Assert.assertEquals(401, response.getStatus());
                    response.close();
                    response = target.request()
                            .header(HttpHeaders.AUTHORIZATION, "Bearer " + req.getHeader("KEYCLOAK_ACCESS_TOKEN"))
                            .get();
                    Assert.assertEquals(200, response.getStatus());
                    String data = response.readEntity(String.class);
                    response.close();
                    stream.write(data.getBytes());
                } finally {
                    client.close();
                }

            } else if (requestURI.contains("/call-bearer")) {
                stream.write("bearer called".getBytes());
            }
        }
        @Override
        protected void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
            doGet(req, resp);
        }
    }
    public static class SendError extends HttpServlet {
        @Override
        protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
            resp.setContentType("text/plain");
            OutputStream stream = resp.getOutputStream();
            stream.write("access error".getBytes());
        }
        @Override
        protected void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
            doGet(req, resp);
        }
    }

    static Tomcat tomcat = null;

    public static void initTomcat() throws Exception {
        URL dir = ProxyTest.class.getResource("/tomcat-test/webapp/WEB-INF/web.xml");
        File webappDir = new File(dir.getFile()).getParentFile().getParentFile();
        tomcat = new Tomcat();
        String baseDir = getBaseDirectory();
        tomcat.setBaseDir(baseDir);
        tomcat.setPort(8082);

        tomcat.addWebapp("/customer-portal", webappDir.toString());
        System.out.println("configuring app with basedir: " + webappDir.toString());

        tomcat.start();
        //tomcat.getServer().await();
    }

    public static void shutdownTomcat() throws Exception {
        tomcat.stop();
        tomcat.destroy();
    }

    static Undertow proxyServer = null;

    @BeforeClass
    public static void initProxy() throws Exception {
        initTomcat();
        InputStream is = ProxyTest.class.getResourceAsStream("/proxy-config.json");
        proxyServer = ProxyServerBuilder.build(is);
        proxyServer.start();

    }

    @AfterClass
    public static void shutdownProxy() throws Exception {
        shutdownTomcat();
        if (proxyServer != null) proxyServer.stop();
    }

    @Rule
    public WebRule webRule = new WebRule(this);
    @WebResource
    protected WebDriver driver;
    @WebResource
    protected LoginPage loginPage;

    public static final String LOGIN_URL = OIDCLoginProtocolService.authUrl(UriBuilder.fromUri("http://localhost:8081/auth")).build("demo").toString();

    @Test
    public void testHttp() throws Exception {
        String baseUrl = "http://localhost:8080";
        testit(baseUrl);

    }

    @Test
    public void testHttps() throws Exception {
        String baseUrl = "https://localhost:8443";
        testit(baseUrl);

    }

    public void testit(String baseUrl) {
        driver.navigate().to(baseUrl + "/customer-portal/users");
        System.out.println("Current url: " + driver.getCurrentUrl());
        Assert.assertTrue(driver.getCurrentUrl().startsWith(LOGIN_URL));
        String loginPageSource = driver.getPageSource();
        loginPage.login("bburke@redhat.com", "password");
        System.out.println("Current url: " + driver.getCurrentUrl());
        Assert.assertEquals(driver.getCurrentUrl(), baseUrl + "/customer-portal/users");
        String pageSource = driver.getPageSource();
        System.out.println(pageSource);
        Assert.assertTrue(pageSource.contains("customer-portal/users"));
        Assert.assertTrue(pageSource.contains("count:0"));
        driver.navigate().to(baseUrl + "/customer-portal/users");
        Assert.assertEquals(driver.getCurrentUrl(), baseUrl + "/customer-portal/users");
        pageSource = driver.getPageSource();
        System.out.println(pageSource);
        Assert.assertTrue(pageSource.contains("customer-portal/users"));
        Assert.assertTrue(pageSource.contains("count:1")); // test http session

        driver.navigate().to(baseUrl + "/customer-portal/bearer");
        pageSource = driver.getPageSource();
        Assert.assertTrue(pageSource.contains("bearer called"));

        driver.navigate().to(baseUrl + "/customer-portal/users/deny");
        Assert.assertEquals(driver.getCurrentUrl(), baseUrl + "/customer-portal/users/deny");
        pageSource = driver.getPageSource();
        System.out.println(pageSource);
        Assert.assertTrue(pageSource.contains("access error"));

        driver.navigate().to(baseUrl + "/customer-portal/admins");
        Assert.assertEquals(driver.getCurrentUrl(), baseUrl + "/customer-portal/admins");
        pageSource = driver.getPageSource();
        System.out.println(pageSource);
        Assert.assertTrue(pageSource.contains("access error"));

        // test logout

        String logoutUri = OIDCLoginProtocolService.logoutUrl(UriBuilder.fromUri("http://localhost:8081/auth"))
                .queryParam(OAuth2Constants.REDIRECT_URI, baseUrl + "/customer-portal/users").build("demo").toString();
        driver.navigate().to(logoutUri);
        Assert.assertTrue(driver.getCurrentUrl().startsWith(LOGIN_URL));
        driver.navigate().to(baseUrl + "/customer-portal/users");
        String currentUrl = driver.getCurrentUrl();
        Assert.assertTrue(currentUrl.startsWith(LOGIN_URL));

        // test unsecured page
        driver.navigate().to(baseUrl + "/customer-portal") ;
        pageSource = driver.getPageSource();
        System.out.println(pageSource);
        Assert.assertTrue(pageSource.contains("customer-portal"));
        driver.navigate().to(baseUrl + "/customer-portal/users/permit") ;
        pageSource = driver.getPageSource();
        System.out.println(pageSource);
        Assert.assertTrue(pageSource.contains("customer-portal/users/permit"));
    }

    private static String getBaseDirectory() {
        String dirPath = null;
        String relativeDirPath = "testsuite" + File.separator + "proxy" + File.separator + "target";

        if (System.getProperties().containsKey("maven.home")) {
            dirPath = System.getProperty("user.dir").replaceFirst("testsuite.proxy.*", Matcher.quoteReplacement(relativeDirPath));
        } else {
            for (String c : System.getProperty("java.class.path").split(File.pathSeparator)) {
                if (c.contains(File.separator + "testsuite" + File.separator + "proxy")) {
                    dirPath = c.replaceFirst("testsuite.proxy.*", Matcher.quoteReplacement(relativeDirPath));
                    break;
                }
            }
        }

        String absolutePath = new File(dirPath).getAbsolutePath();
        return absolutePath;
    }

}


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

<title>Source code</title>
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

001package io.ebean.config;
002
003/**
004 * The mode to use for multi-tenancy.
005 */
006public enum TenantMode {
007
008  /**
009   * No multi-tenancy.
010   */
011  NONE(false, true),
012
013  /**
014   * Each Tenant has their own Database (javax.sql.DataSource)
015   */
016  DB(true, false),
017
018  /**
019   * Each Tenant has their own Database schema.
020   */
021  SCHEMA(true, false),
022
023  /**
024   * Each Tenant has their own Database but with in connection pool
025   */
026  CATALOG(true, false),
027
028  /**
029   * Tenants share tables but have a discriminator/partition column that partitions the data.
030   */
031  PARTITION(false, true),
032
033  /**
034   * Each Tenant has their own Database (javax.sql.DataSource), and there is also one master-database
035   * (that holds configuration e.g.)
036   */
037  DB_WITH_MASTER(true, true);
038
039  boolean dynamicDataSource;
040  boolean ddlEnabled;
041
042  TenantMode(boolean dynamicDataSource, boolean ddlEnabled) {
043    this.dynamicDataSource = dynamicDataSource;
044    this.ddlEnabled = ddlEnabled;
045  }
046
047  /**
048   * Return true if the DataSource is not available on bootup.
049   */
050  public boolean isDynamicDataSource() {
051    return dynamicDataSource;
052  }
053
054  /**
055   * Returns true, if DDL is enabled.
056   */
057  public boolean isDdlEnabled() {
058    return ddlEnabled;
059  }
060
061}

redpajama_set_name: RedPajamaGithub


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package br.faccamp.controle;

import br.faccamp.Util.ConversaoArquivo;
import br.faccamp.modelo.Alternativas;
import br.faccamp.modelo.Pergunta;
import br.faccamp.modelo.repositorios.PerguntasRepository;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PreDestroy;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Eduardo
 */
@ManagedBean ( name = "vizualizacaoAlternativas" )
@ViewScoped
public class VisualizacaoAlternativas implements Serializable {

    private List<Alternativas> alternativas;
    private Pergunta pergunta;
    private String arquivoImagem;
    private File File;

    /**
     * @return the alternativas
     */
    public List<Alternativas> getAlternativas() {

       FacesContext fc = FacesContext . getCurrentInstance ();
       ExternalContext ec = fc.getExternalContext();
       HttpSession session = ( HttpSession )ec.getSession( false );

        Long id = (Long) session.getAttribute("IdPergunta");

        EntityManager manager = this.getManager();
        PerguntasRepository repository = new PerguntasRepository(manager);
        this.setAlternativas(repository.ObterAlternativasPergunta(id));

        return alternativas;
    }

    /**
     * @param alternativas the alternativas to set
     */
    public void setAlternativas(List<Alternativas> alternativas) {
        this.alternativas = alternativas;
    }

    private EntityManager getManager()
    {
        FacesContext fc = FacesContext.getCurrentInstance();
        ExternalContext ec = fc.getExternalContext();
        HttpServletRequest request = (HttpServletRequest) ec.getRequest();
        return (EntityManager) request.getAttribute("EntityManager");
    }

    /**
     * @return the pergunta
     */
    public Pergunta getPergunta()
    {
       FacesContext fc = FacesContext . getCurrentInstance ();
       ExternalContext ec = fc.getExternalContext();
       HttpSession session = ( HttpSession )ec.getSession( false );

       long id = (Long) session.getAttribute("IdPergunta");

       EntityManager manager = this.getManager();
       PerguntasRepository repository = new PerguntasRepository(manager);
       this.setPergunta(repository.procura(id));

       return this.pergunta;
    }

    /**
     * @param pergunta the pergunta to set
     */
    public void setPergunta(Pergunta pergunta) {
        this.pergunta = pergunta;
    }

    @PreDestroy
    public void destroy()
    {
        // remove o arquivo temporario
        this.File.delete();
    }

    /**
     * @return the arquivoImagem
     */
    public String getArquivoImagem() {

       if (this.pergunta.getFoto() == null)
           return "";

       FacesContext ctx = FacesContext.getCurrentInstance();

       ServletContext servletContext =  (ServletContext)ctx.getExternalContext().getContext();

       String path = servletContext.getRealPath("/resources/imagens");

       ConversaoArquivo conver = new ConversaoArquivo();

       File fileAux;

       try
       {
            fileAux = conver.getFile(this.pergunta.getFoto(), this.pergunta.getExt(), path, "imagemTep" );

       }
       catch (IOException ex)
       {
           return null;
       }

       this.arquivoImagem = fileAux.getName();
       this.File = fileAux;

       return arquivoImagem;
    }

    /**
     * @param arquivoImagem the arquivoImagem to set
     */
    public void setArquivoImagem(String arquivoImagem) {
        this.arquivoImagem = arquivoImagem;
    }

}


text:
from __future__ import unicode_literals

from django.db import migrations, models
import wagtail.core.blocks
import wagtail.core.fields
import wagtail.images.blocks

class Migration(migrations.Migration):

    dependencies = [
        ('pages', '0019_auto_20171102_1856'),
    ]

    operations = [
        migrations.AlterField(
            model_name='standardindexpage',
            name='template_string',
            field=models.CharField(choices=[('pages/standard_index_page.html', 'Default Template'), ('pages/standard_index_page_grid.html', 'Grid Also In This Section')], default='pages/standard_index_page.html', max_length=255),
        ),
        migrations.AlterField(
            model_name='standardpage',
            name='body',
            field=wagtail.core.fields.StreamField((('paragraph', wagtail.core.blocks.RichTextBlock()), ('image', wagtail.images.blocks.ImageChooserBlock()), ('html', wagtail.core.blocks.RawHTMLBlock()))),
        ),
        migrations.AlterField(
            model_name='videogallerypagecarouselitem',
            name='embed_url',
            field=models.URLField(blank=True, verbose_name='Embed URL'),
        ),
        migrations.AlterField(
            model_name='videogallerypagecarouselitem',
            name='link_external',
            field=models.URLField(blank=True, verbose_name='External link'),
        ),
    ]


text:
define(function () {

    /**
     * Typecast a value to a String, using an empty string value for null or
     * undefined.
     */
    /**
     * Description
     * @method toString
     * @param {} val
     * @return ConditionalExpression
     */
    function toString(val){
        return val == null ? '' : val.toString();
    }

    return toString;

});


text:
MAPS.ME uses maps in its own vector format, MWM. It contains classified features sorted and simplified by zoom level.
For car routing, it needs a separate routing index in a `.mwm.routing` file. We build maps for the entire planet:

* [daily.mapswithme.com/direct/latest](http://direct.mapswithme.com/direct/latest/) - official maps bundled with releases.

## Building

For building maps, you need compiled Generator Tool and, for routing indices, OSRM backend.
See [INSTALL.md](INSTALL.md) for compilation instructions. We usually use this line:

    CONFIG=gtool omim/tools/unix/build_omim.sh -cro

Scripts described here require OSM C Tools, which are maintained as a submodule of the omim repository.

### A Single Region

Having built a generator tool, prepare a source file in pbf/o5m/bz2 format, and run:

    omim/tools/unix/generate_mwm.sh source.pbf

In some minutes it will create a similarly-named `.mwm` file in the same directory as the original file.
Specify `TARGET` variable for changing that (e.g. `TARGET=.`). The script runs `generator_tool` twice,
see `find_generator_tool.sh` script for an algorithm on how it finds it. All temporary files are created
with `mktemp` and then removed.

The resulting file won't have any coastlines, though MAPS.ME will overlay zoomed-in map with a low-quality
generalized coastline. To add a detailed coastline, you would need a `WorldCoasts.geom` file and
a [border polygon](http://wiki.openstreetmap.org/wiki/Osmosis/Polygon_Filter_File_Format) for a source
file area. Having that, run (and prepare to wait a bit longer):

    COASTS=WorldCoasts.geom BORDER=source.poly omim/tools/unix/generate_mwm.sh source.pbf

A car routing index will be built when you specify a second parameter: either a full path to a Lua script
with a routing profile, or any gibberish, in which case a default `car.lua` from omim repository
would be used. For example:

    omim/tools/unix/generate_mwm.sh source.pbf asdf

Inter-mwm navigation requires another index inside a `.mwm.routing` file. To build it, you would need
border polygons for not only the source region, but all regions neighbouring it. The source border polygon
must have the same name as the source file (e.g. `Armenia.poly` for `Armenia.pbf`), and in the target
directory shouldn't be a `borders` subdirectory. With all that, just use this line:

    BORDERS_PATH=/path/to/polygons omim/tools/unix/generate_mwm.sh source.pbf asd

### The Planet

To create a bunch of MWM files for the entire planet, splitting it by border polygons, we have
a different script, `generate_planet.sh`. It will print a short help when run without arguments.
The usual line we use is:

    TARGET=/opt/mwm/151231 omim/tools/unix/generate_planet.sh -a

This is a shortcut for following options:

* `-u`: update a planet file from osm.org (use `-U` when you need to download one, specify `PLANET`
variable if it's not in `$HOME/planet/planet-latest.o5m`).
* `-l`: filter and process coastlines, creating `WorldCoasts.geom` and `.rawgeom` files.
* `-w`: generate overview maps, `World.mwm` and `WorldCoasts.mwm`.
* `-r`: generate routing indices, `.mwm.routing` file for each `.mwm`.

All border polygons from `BORDERS_PATH` are processed into MWM files by default. You can
specify only required polygons in `REGIONS` variable, or set it to empty value, so no regular
MWM files are created. The whole process takes 15 hours on a 40-core server, so we suggest
you specify your e-mail address in a `MAIL` variable and get a mail when the generation
is finished.

If a previous run ended with an error, the next one will ignore arguments and continue with
the same arguments as the previous time. Set `-c` option to ignore the stored status.

Log files for each region and the entire process (`generate_planet.log`) are written to
`logs` subdirectory of the target. Intermediate data requires around 250 MB of space, and
to clean it during the process, specify `KEEP_INTDIR=` empty variable.

#### Steps

The planet generation process is divided in several steps, which are printed during the
script run, along with timestamps. To start generation from a specific step, specify it
in the `MODE` variable (and make sure you don't have stored status, or run with `-c`
option).

* Step 1 (`coast`): updating planet file.
* Step 2: filtering and processing coast lines. If there was a merge error, the script
prints way identifiers, waits 40 minutes and tries again from step 1.
* Step R: preparing `.osrm` files for routing indices. PBF files for each region are
cut out of the planet, then OSRM backend scripts process each of these. Can work
asynchronously if `ASYNC_PBF=1` variable is set.
* Step 3 (`inter`): generating intermediate data for the planet.
* Step 4 (`features`): generating features for each region, splitting the planet.
* Step 5 (`mwm`): building the resulting MWMs.
* Step 6 (`routing`): building `.mwm.routing` files out of MWMs and `.osrm` files.
* Step 7 (`resources`): updating resource and map lists.
* Step 8 (`test`): calling `test_planet.sh` to run routing tests.

### Variables

Almost every default in the script can be redefined with environment variables.
You will have to use some of these, unless you are using our map-building servers.

* `GENERATOR_TOOL`: a location of `generator_tool` program. Example: `~/omim-build-debug/out/debug/generator_tool`.
* `BUILD_PATH`: a path to either `generator_tool` or its build directory. Example: `~/omim-build-debug`.
* `PLANET`: pa ath or name of the planet file. If there is no file, specify `-U` option,
and it will be downloaded. Should be in o5m format. Default is `~/planet/planet-latest.o5m`.
* `TARGET`: a target path for `mwm` and `routing` files. Some temporary subdirectories
will be created inside: `logs`, `borders` and `intermediate_data`.
* `MAIL`: comma-separated e-mail addresses, which will receive notifications about
finished or failed generation.
* `OSMCTOOLS`: a path to pre-compiled OSM C Tools: `osmconvert`, `osmupdate` and
`osmfilter`. If these were not found, it will compile sources from the repo.
* `OMIM_PATH`: a path to the omim repository root. Will be guessed when the
script is not moved from `omim/tools/unix`. It is needed for locating a data
directory (`omim/data`, can be overridden with `DATA_PATH`), generator tool
build path (see `BUILD_PATH`) and OSRM backend scripts (see `OSRM_PATH`).
* `OSRM_PATH`: a path to `omim/3party/osrm/osrm-backend`. Needed for searching
for a routing profile (`$OSRM_PATH/profiles.car.lua` by default, but can be
overridden with `PROFILE`) and for osrm executables (`$OSRM_PATH/build`,
or set `OSRM_BUILD_PATH`).
* `DATA_PATH`: a path to classificators and border polygons; the latter can
be redefined with `BORDERS_PATH`.
* `INTDIR`: a temporary directory that is created when the script starts, and
removed when `KEEP_INTDIR` is clean and the script ends. Contains `status` file
that keeps script arguments for resuming processing, and `osrm_done` file,
which is a flag for successful OSRM indices building process.
* `KEEP_INTDIR`: if empty (by default it is not), the temporary directory will
be deleted when the script finishes. Note that it might have `WorldCoasts.geom`
file, built on step 2, which is required for generating coastlines (step 4).
* `NODE_STORAGE` (or `NS`): where is a node cache kept: in memory (`mem`, which
is the default), or on disk (`map`). Tests show that for a complete world,
with `map` the process eats some hundreds of gigabytes and crashes, while with
`mem` the memory consumption is stable at around 40 GB.
* `ASYNC_PBF`: by default, pbf files for routing are built between steps 2 and 3,
but if this flag is set (e.g. to `1`), they are built asynchronously. But
it can fail due to low memory.
* `MERGE_INTERVAL`: delay in minutes between attempts to merge a coast line.
Default is 40.
* `REGIONS`: a list of `.poly` files for regions to be built. One for each line.
* `DELTA_WITH`: a path to an older map directory, to compare with the freshly
generated data in the testing step.
Can be empty. Example: `$(ls ../../data/borders/{UK*,Ireland}.poly)`.

### Testing

To test that the generator is not broken, you don't have to wait for 20 hours processing
the whole planet: instead download [a 150 MB extract](http://osmz.ru/mwm/islands/) with
some islands and the corresponding script `islands.sh` and put these into `omim/tools/unix`.
Run the script with options for `generate_planet`, e.g.

    omim/tools/unix/islands.sh -lwr

In a half an hour you'll get files for 4 regions in a `target` subdirectory. Note that
you can build both generator tool and OSRM backend with the `build_omim.sh` script.


text:
#ifndef __NUC_H__
#define __NUC_H__

#include <stdio.h>
#include <ctype.h>
#include "seq.h"

enum nucleotide {NUC_A=0, NUC_C, NUC_G, NUC_T,
		 NUC_M, /* [M]ethyl: A or C */
		 NUC_K, /* [K]eto: G or T */
		 NUC_R, /* pu[R]ine: A or G */
		 NUC_Y, /* p[Y]rimidine: C or T */
		 NUC_W, /* [W]eak: A or T */
		 NUC_S, /* [S]trong: G or C */
		 NUC_GAP, NUC_N, NUM_NUCS};

/* the number of "true" nucleotides, i.e. not gaps or ambiguity chars */
#define NUM_REAL_NUCS 4

char nuc_id_to_char(const unsigned char id);

unsigned char nuc_char_to_id(const char nuc);

int nuc_is_real(const unsigned char id);

int nuc_is_ambi(const unsigned char id);

unsigned char nuc_comp(const unsigned char nuc_id);

char *nuc_ids_to_str(char *buf, const unsigned char *ids, const long len);

int nuc_ids_have_n(unsigned char *ids, const long len);

unsigned char *nuc_str_to_ids(unsigned char *buf, const char *str,
			      const long len);

void nuc_ids_revcomp(unsigned char *nuc_ids, const long len);

#endif


text:
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NonSilo.Tests.Utilities;
using NSubstitute;
using NSubstitute.ExceptionExtensions;
using Orleans;
using Orleans.Configuration;
using Orleans.Runtime;
using Orleans.Runtime.MembershipService;
using TestExtensions;
using Xunit;
using Xunit.Abstractions;
using static Orleans.Runtime.MembershipService.SiloHealthMonitor;

namespace NonSilo.Tests.Membership
{
    [TestCategory("BVT"), TestCategory("Membership")]
    public class SiloHealthMonitorTests
    {
        private readonly ITestOutputHelper _output;
        private readonly LoggerFactory _loggerFactory;
        private readonly ILocalSiloDetails _localSiloDetails;
        private readonly SiloAddress _localSilo;
        private readonly List<DelegateAsyncTimer> _timers;
        private readonly Channel<(TimeSpan? DelayOverride, TaskCompletionSource<bool> Completion)> _timerCalls;
        private readonly DelegateAsyncTimerFactory _timerFactory;
        private readonly ILocalSiloHealthMonitor _localSiloHealthMonitor;
        private readonly IRemoteSiloProber _prober;
        private readonly IClusterMembershipService _membershipService;
        private ClusterMembershipOptions _clusterMembershipOptions;
        private readonly IOptionsMonitor<ClusterMembershipOptions> _optionsMonitor;
        private readonly Channel<ProbeResult> _probeResults;
        private readonly SiloHealthMonitor _monitor;
        private ClusterMembershipSnapshot _membershipSnapshot;

        public SiloHealthMonitorTests(ITestOutputHelper output)
        {
            MessagingStatisticsGroup.Init();
            _output = output;
            _loggerFactory = new LoggerFactory(new[] { new XunitLoggerProvider(_output) });

            _localSiloDetails = Substitute.For<ILocalSiloDetails>();
            _localSilo = Silo("127.0.0.1:100@100");
            _localSiloDetails.SiloAddress.Returns(_localSilo);
            _localSiloDetails.DnsHostName.Returns("MyServer11");
            _localSiloDetails.Name.Returns(Guid.NewGuid().ToString("N"));

            _timers = new List<DelegateAsyncTimer>();
            _timerCalls = Channel.CreateUnbounded<(TimeSpan? DelayOverride, TaskCompletionSource<bool> Completion)>();
            _timerFactory = new DelegateAsyncTimerFactory(
                (period, name) =>
                {
                    var t = new DelegateAsyncTimer(
                        overridePeriod =>
                        {
                            var task = new TaskCompletionSource<bool>();
                            _timerCalls.Writer.TryWrite((overridePeriod, task));
                            return task.Task;
                        });
                    _timers.Add(t);
                    return t;
                });

            _localSiloHealthMonitor = Substitute.For<ILocalSiloHealthMonitor>();
            _localSiloHealthMonitor.GetLocalHealthDegradationScore(default).ReturnsForAnyArgs(0);

            _prober = Substitute.For<IRemoteSiloProber>();

            _membershipService = Substitute.For<IClusterMembershipService>();

            _clusterMembershipOptions = new ClusterMembershipOptions();
            _optionsMonitor = Substitute.For<IOptionsMonitor<ClusterMembershipOptions>>();
            _optionsMonitor.CurrentValue.ReturnsForAnyArgs(info => _clusterMembershipOptions);

            _probeResults = Channel.CreateBounded<ProbeResult>(new BoundedChannelOptions(1) { FullMode = BoundedChannelFullMode.Wait });
            Func<SiloHealthMonitor, ProbeResult, Task> onProbeResult = (mon, res) => _probeResults.Writer.WriteAsync(res).AsTask();

            _membershipSnapshot = Snapshot(
                1,
                Member(_localSilo, SiloStatus.Active),
                Member(Silo("127.0.0.200:100@100"), SiloStatus.Active));
            _membershipService.CurrentSnapshot.ReturnsForAnyArgs(info => _membershipSnapshot);

            _monitor = new SiloHealthMonitor(
                Silo("127.0.0.200:100@100"),
                onProbeResult,
                _optionsMonitor,
                _loggerFactory,
                _prober,
                _timerFactory,
                _localSiloHealthMonitor,
                _membershipService,
                _localSiloDetails);
        }

        private async Task Shutdown()
        {
            var stopTask = _monitor.StopAsync(CancellationToken.None);

            Task.Run(async () =>
            {
                while (!stopTask.IsCompleted && await _timerCalls.Reader.WaitToReadAsync())
                {
                    while (_timerCalls.Reader.TryRead(out var timerCall))
                    {
                        timerCall.Completion.TrySetResult(false);
                    }
                }
            }).Ignore();

            await stopTask;
            _timerCalls.Writer.TryComplete();
        }

        [Fact]
        public async Task SiloHealthMonitor_SuccessfulProbe()
        {
            _prober.Probe(default, default).ReturnsForAnyArgs(Task.CompletedTask);
            _prober.ProbeIndirectly(default, default, default, default).ThrowsForAnyArgs(new InvalidOperationException("No"));

            _monitor.Start();

            // Let a timer complete
            var timerCall = await _timerCalls.Reader.ReadAsync();
            timerCall.Completion.TrySetResult(true);

            // Check the resulting probe result.
            var probeResult = await _probeResults.Reader.ReadAsync();
            Assert.Equal(ProbeResultStatus.Succeeded, probeResult.Status);
            Assert.Equal(0, probeResult.FailedProbeCount);
            Assert.True(probeResult.IsDirectProbe);
            Assert.Equal(0, probeResult.IntermediaryHealthDegradationScore);

            await Shutdown();
        }

        [Fact]
        public async Task SiloHealthMonitor_FailedProbe()
        {
            _clusterMembershipOptions.ProbeTimeout = TimeSpan.FromSeconds(2);

            _prober.Probe(default, default).ReturnsForAnyArgs(info => Task.Delay(TimeSpan.FromSeconds(3)));
            _prober.ProbeIndirectly(default, default, default, default).ThrowsForAnyArgs(new InvalidOperationException("No"));
            _monitor.Start();

            // Let a timer complete
            var timerCall = await _timerCalls.Reader.ReadAsync();
            timerCall.Completion.TrySetResult(true);

            var probeResult = await _probeResults.Reader.ReadAsync();
            Assert.Equal(ProbeResultStatus.Failed, probeResult.Status);
            Assert.Equal(1, probeResult.FailedProbeCount);
            Assert.True(probeResult.IsDirectProbe);
            Assert.Equal(0, probeResult.IntermediaryHealthDegradationScore);

            // Throw directly, instead of timing out the probe
            _prober.Probe(default, default).ThrowsForAnyArgs(new Exception("nope"));
            timerCall = await _timerCalls.Reader.ReadAsync();
            timerCall.Completion.TrySetResult(true);

            probeResult = await _probeResults.Reader.ReadAsync();
            Assert.Equal(ProbeResultStatus.Failed, probeResult.Status);
            Assert.Equal(2, probeResult.FailedProbeCount);
            Assert.True(probeResult.IsDirectProbe);
            Assert.Equal(0, probeResult.IntermediaryHealthDegradationScore);

            await Shutdown();
        }

        [Fact]
        public async Task SiloHealthMonitor_Indirect_FailedProbe()
        {
            _clusterMembershipOptions.ProbeTimeout = TimeSpan.FromSeconds(2);
            _clusterMembershipOptions.EnableIndirectProbes = true;

            _prober.Probe(default, default).ThrowsForAnyArgs(info => new Exception("nonono!"));
            _prober.ProbeIndirectly(default, default, default, default).ReturnsForAnyArgs(new IndirectProbeResponse
            {
                FailureMessage = "fail",
                IntermediaryHealthScore = 0,
                ProbeResponseTime = TimeSpan.FromSeconds(1),
                Succeeded = false
            });
            _monitor.Start();

            // Let a timer complete
            var timerCall = await _timerCalls.Reader.ReadAsync();
            timerCall.Completion.TrySetResult(true);

            var probeResult = await _probeResults.Reader.ReadAsync();
            Assert.Equal(ProbeResultStatus.Failed, probeResult.Status);
            Assert.Equal(1, probeResult.FailedProbeCount);
            Assert.True(probeResult.IsDirectProbe);
            Assert.Equal(0, probeResult.IntermediaryHealthDegradationScore);

            timerCall = await _timerCalls.Reader.ReadAsync();
            timerCall.Completion.TrySetResult(true);

            var otherSilo = Silo("127.0.0.1:1234@1234");
            _membershipSnapshot = Snapshot(2, Member(_localSilo, SiloStatus.Active), Member(_monitor.SiloAddress, SiloStatus.Active), Member(otherSilo, SiloStatus.Joining));

            // There is only one other active silo (the target silo), so an indirect probe cannot be performed.
            probeResult = await _probeResults.Reader.ReadAsync();
            Assert.Equal(ProbeResultStatus.Failed, probeResult.Status);
            Assert.Equal(2, probeResult.FailedProbeCount);
            Assert.True(probeResult.IsDirectProbe);
            Assert.Equal(0, probeResult.IntermediaryHealthDegradationScore);

            // Make the other silo active so that there is an intermediary to use for an indirect probe.
            _membershipSnapshot = Snapshot(3, Member(_localSilo, SiloStatus.Active), Member(_monitor.SiloAddress, SiloStatus.Active), Member(otherSilo, SiloStatus.Active));

            _prober.ClearReceivedCalls();
            timerCall = await _timerCalls.Reader.ReadAsync();
            timerCall.Completion.TrySetResult(true);

            // Since there is another active silo, an indirect probe will be performed.
            probeResult = await _probeResults.Reader.ReadAsync();
            Assert.Equal(ProbeResultStatus.Failed, probeResult.Status);
            Assert.Equal(3, probeResult.FailedProbeCount);
            Assert.False(probeResult.IsDirectProbe);
            Assert.Equal(0, probeResult.IntermediaryHealthDegradationScore);

            // Ensure that the correct intermediary was selected.
            var probeCall = _prober.ReceivedCalls().Single();
            var args = probeCall.GetArguments();
            var intermediary = Assert.IsType<SiloAddress>(args[0]);
            Assert.Equal(otherSilo, intermediary);

            // Ensure that negative results from unhealthy intermediaries are not considered.
            _prober.ProbeIndirectly(default, default, default, default).ReturnsForAnyArgs(new IndirectProbeResponse
            {
                FailureMessage = "fail",
                IntermediaryHealthScore = 1,
                ProbeResponseTime = TimeSpan.FromSeconds(1),
                Succeeded = false
            });

            _prober.ClearReceivedCalls();
            timerCall = await _timerCalls.Reader.ReadAsync();
            timerCall.Completion.TrySetResult(true);

            // The number of failed probes should not be incremented, the status should be "unknown", and the health score should be 1.
            probeResult = await _probeResults.Reader.ReadAsync();
            Assert.Equal(ProbeResultStatus.Unknown, probeResult.Status);
            Assert.Equal(3, probeResult.FailedProbeCount);
            Assert.False(probeResult.IsDirectProbe);
            Assert.Equal(1, probeResult.IntermediaryHealthDegradationScore);

            // Ensure that the correct intermediary was selected.
            probeCall = _prober.ReceivedCalls().Single();
            args = probeCall.GetArguments();
            intermediary = Assert.IsType<SiloAddress>(args[0]);
            Assert.Equal(otherSilo, intermediary);

            // After seeing that the chosen intermediary is unhealthy, a subsequent probe should be
            // performed directly (since there are no other silos to use as an intermediary).
            _prober.ClearReceivedCalls();
            timerCall = await _timerCalls.Reader.ReadAsync();
            timerCall.Completion.TrySetResult(true);

            probeResult = await _probeResults.Reader.ReadAsync();
            Assert.Equal(ProbeResultStatus.Failed, probeResult.Status);
            Assert.Equal(4, probeResult.FailedProbeCount);
            Assert.True(probeResult.IsDirectProbe);
            Assert.Equal(0, probeResult.IntermediaryHealthDegradationScore);

            // Ensure that it was the target that was probed directly.
            probeCall = _prober.ReceivedCalls().Single();
            args = probeCall.GetArguments();
            var target = Assert.IsType<SiloAddress>(args[0]);
            Assert.Equal(_monitor.SiloAddress, target);

            await Shutdown();
        }

        private static ClusterMembershipSnapshot Snapshot(long version, params ClusterMember[] members)
            => new ClusterMembershipSnapshot(
                ImmutableDictionary.CreateRange(
                    members.Select(m => new KeyValuePair<SiloAddress, ClusterMember>(m.SiloAddress, m))),
                new MembershipVersion(version));

        private static SiloAddress Silo(string value) => SiloAddress.FromParsableString(value);

        private static ClusterMember Member(SiloAddress address, SiloStatus status) => new ClusterMember(address, status, address.ToString());
    }
}


text:
@implementation SetCounter

- (id)init
{
    self = [super init];
    if (self) {
        // Initialization code here.
    }

    return self;
}

+ (Class)transformedValueClass
{
    return [NSNumber self];
}

+ (BOOL) allowsReverseTransformation
{
    return NO;
}

- (id)transformedValue:(id)value
{
    return [NSNumber numberWithInt:[value count]];
}

- (void)dealloc
{
    [super dealloc];
}

@end


text:
default_server_conf = """[server]
# WARNING! Change default variable of jwt_secret. You should change it periodically
# It only affects to current authentication tokens, you can change safetely anytime
# When it changes user are just forced to log in again
jwt_secret: {jwt_secret}
jwt_expire_minutes: 120

ssl_enabled: False
port: 9300
# Public port where files will be served. If empty will be used "port"
public_port:
host_name: localhost

# Authorize timeout are seconds the client has to upload/download files until authorization expires
authorize_timeout: 1800

# Just for disk storage adapter
# updown_secret is the key used to generate the upload/download authorization token
disk_storage_path: ~/.conan_server/data
disk_authorize_timeout: 1800
updown_secret: {updown_secret}

# Enable the revisions mechanism in the server
revisions: False

# Check docs.conan.io to implement a different authenticator plugin for conan_server
# if custom_authenticator is not specified, [users] section will be used to authenticate
# the users.
#
# custom_authenticator: my_authenticator

# name/version@user/channel: user1, user2, user3
#
# The rules are applied in order.
# If a rule matches your package, then the server wont look further.
# Place your more restrictive rules first.
#
# Example: All versions of opencv package from lasote user in testing channel is only
# writeable by default_user and default_user2. Rest of packages are not writtable by anything
# except the author.
#
#   opencv/2.3.4@lasote/testing: default_user, default_user2
#
[write_permissions]

# name/version@user/channel: user1, user2, user3
# The rules are applied in order. If a rule applies to a conan, system wont look further.
#
# Example:
#  All versions of opencv package from lasote user in testing channel are only
#    readable by default_user and default_user2.
#  All versions of internal package from any user/channel are only readable by
#    authenticated users.
#  Rest of packages are world readable.
#
#   opencv/*@lasote/testing: default_user default_user2
#   internal/*@*/*: ?
#   */*@*/*: *
#
# By default all users can read all blocks
#
[read_permissions]
*/*@*/*: *

[users]
#default_user: defaultpass
demo: demo

"""


text:
.cmdbar {
	height: 38px;
	border-bottom: 1px solid #333;
	background-color: #E3E6E8;
}
.cmdbar .cmd {
	height: 30px;
	right: 0px;
	z-index: 870;
	overflow: hidden;
	padding-right: 12px;
	cursor: default;
	background-color: #E3E6E8;
	font-size: 12px;
	position: relative;
	float: right;
	margin-top: 6px;
}
.cmdbar .cmd div {
	padding-left: 15px;
	margin-left: 6px;
	background-repeat: no-repeat;
	background-position: center center;
	height: 28px;
	line-height: 24px;
	background-size: 24px 24px;
	float: left;
	border: 1px solid #e3e6e9;
	border-radius: 5px;
	margin-right: 6px;
	padding-right: 15px;
}
.cmdbar .cmd div:hover {
	color: #00F;
	border: 1px solid #ccc;
	border-radius: 5px;
}
.cmdbar .cmd .btn{
	font-size:12px;
	display:inline-block;
	color:#000000;
	padding:0 5px 0 5px;
	cursor: default;
	text-align: center;
	height: 25px;
	border: 1px solid #ababab;
	border-radius: 4px;
	line-height: 25px;
	text-align: center;
	margin: 1px 6px 0 6px;
	background-repeat: no-repeat;
	background-color: transparent;
	background-image: url(../../images/button/btn_silver.png);
	background-repeat: repeat-x;
}
.cmdbar .cmd .btn:hover {
	font-size:12px;
	display:inline-block;
	color:#000000;
	padding:0 5px 0 5px;
	cursor: default;
	text-align: center;
	height: 25px;
	border: 1px solid #4e9beb;
	border-radius: 4px;
	line-height: 25px;
	text-align: center;
	margin: 1px 6px 0 6px;
	background-repeat: no-repeat;
	background-color: transparent;
	background-image: url(../../images/button/btn_active_bg2.png);
	background-repeat: repeat-x;
}
.cmdbar .cmd  .btn.gray:hover {
	background-image: url(../../images/button/btn_silver.png);
	border: 1px solid #ababab;
}
.cmdbar .cmd .upload{
	background-image: url(../../images/file/up.png);
	overflow: hidden;
	position: relative;
}
.cmdbar .cmd .upload input {
	height:25px;
	cursor:default;
	right: 0px;
	position: absolute;
	width: 20px;
	opacity: 0;
	margin: 0;
	padding: 0;
}
.cmdbar .cmd .rmDoc{
	background-image: url(../../images/win_cmd/delete_red.png);
}
.cmdbar .cmd .viewDoc{
	background-image: url(../../images/file/view.png);
}
.cmdbar .cmd .download{
	background-image: url(../../images/file/download.png);
}
.cmdbar .cmd .btn.gray{
	color:#999999;
}
.cmdbar .cmd .add {
	background-image: url(../../images/win_cmd/add24.png);
}
.cmdbar .cmd .nav {
	background-image: url(../../images/win_cmd/nav_green3.png);
}
.cmdbar .cmd .edit {
	background-image: url(../../images/win_cmd/modify.png);
}
.cmdbar .cmd .delete {
	background-image: url(../../images/win_cmd/delete_red.png);
}
.cmdbar .cmd .folder {
	background-image: url(../../images/win_cmd/folder.png);
	background-size: 24px 24px;
}
.cmdbar .cmd .search {
	background-image: url(../../images/win_cmd/search.png);
}
.cmdbar .cmd .filterData {
	background-image: url(../../images/win_cmd/search.png);
}
.cmdbar .cmd .refresh {
	background-image: url(../../images/win_cmd/refresh.png);
}
.cmdbar .cmd .import {
	background-image: url(../../images/win_cmd/import.png);
}
.cmdbar .cmd .export {
	background-image: url(../../images/win_cmd/export.png);
}
.cmdbar .cmd .pre {
	background-image: url(../../images/win_cmd/pre1.png);
}
.cmdbar .cmd .next {
	background-image: url(../../images/win_cmd/next1.png);
}
.cmdbar .cmd .save {
	background-image: url(../../images/win_cmd/save.png);
}
.cmdbar .cmd .update {
	background-image: url(../../images/win_cmd/update.png);
}
.cmdbar .cmd .cancel {
	background-image: url(../../images/win_cmd/exit.png);
}
.cmdbar .cmd .addItem {
	background-image: url(../../images/win_cmd/addItem.png);
	background-size: 22px 22px;
}
.cmdbar .cmd .rmItem {
	background-image: url(../../images/win_cmd/rmItem.png);
	background-size: 22px 22px;
}
.cmdbar .cmd .commit {
	background-image: url(../../images/win_cmd/commit.png);
}
.cmdbar .cmd .lock {
	background-image: url(../../images/win_cmd/lock.png);
}
.cmdbar .cmd .unlock {
	background-image: url(../../images/win_cmd/unlock.png);
}
.cmdbar .cmd .gray {
	-webkit-filter: grayscale(100%);
}
.cmdbar .cmd .hide {
	display:none;
}
.cmdbar .cmd .add.gray{
	background-image: url(../../images_gray/win_cmd/add24.png);
}
.cmdbar .cmd .edit.gray{
	background-image: url(../../images_gray/win_cmd/modify.png);
}
.cmdbar .cmd .delete.gray{
	background-image: url(../../images_gray/win_cmd/delete_red.png);
}
.cmdbar .cmd .folder.gray{
	background-image: url(../../images_gray/win_cmd/folder.png);
	background-size: 24px 24px;
}
.cmdbar .cmd .search.gray{
	background-image: url(../../images_gray/win_cmd/search.png);
}
.cmdbar .cmd .filterData.gray{
	background-image: url(../../images_gray/win_cmd/search.png);
}
.cmdbar .cmd .refresh.gray{
	background-image: url(../../images_gray/win_cmd/refresh.png);
}
.cmdbar .cmd .import.gray{
	background-image: url(../../images_gray/win_cmd/import.png);
}
.cmdbar .cmd .export.gray{
	background-image: url(../../images_gray/win_cmd/export.png);
}
.cmdbar .cmd .pre.gray{
	background-image: url(../../images_gray/win_cmd/pre1.png);
}
.cmdbar .cmd .next.gray{
	background-image: url(../../images_gray/win_cmd/next1.png);
}
.cmdbar .cmd .save.gray{
	background-image: url(../../images_gray/win_cmd/save.png);
}
.cmdbar .cmd .update.gray{
	background-image: url(../../images_gray/win_cmd/update.png);
}
.cmdbar .cmd .cancel.gray{
	background-image: url(../../images_gray/win_cmd/exit.png);
}
.cmdbar .cmd .addItem.gray{
	background-image: url(../../images_gray/win_cmd/addItem.png);
	background-size: 22px 22px;
}
.cmdbar .cmd .rmItem.gray{
	background-image: url(../../images_gray/win_cmd/rmItem.png);
	background-size: 22px 22px;
}
.cmdbar .cmd .commit.gray{
	background-image: url(../../images_gray/win_cmd/commit.png);
}
.cmdbar .cmd .lock.gray{
	background-image: url(../../images_gray/win_cmd/lock.png);
}
.cmdbar .cmd .unlock.gray{
	background-image: url(../../images_gray/win_cmd/unlock.png);
}


text:
package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
	"time"
)

var dest = "dist"

// Release is read from the RELEASE file and contains options for the build.
type Release struct {
	Cgo  bool     `json:"cgo"`
	Arch []string `json:"arch"`
}

func main() {
	files, err := ioutil.ReadDir("nodes")
	if err != nil {
		log.Fatal(err)
	}

	os.Mkdir(dest, os.ModePerm)

	for _, dir := range files {
		path := filepath.Join("nodes", dir.Name())
		if !dir.IsDir() || !strings.HasPrefix(dir.Name(), "stampzilla-") {
			continue
		}
		if _, err := os.Stat(filepath.Join("nodes", dir.Name(), "RELEASE")); os.IsNotExist(err) {
			continue
		}

		log.Println("found RELEASE file", dir.Name())

		release, _ := loadReleaseFromFile(filepath.Join("nodes", dir.Name(), "RELEASE"))
		build(path, release)
	}

	fmt.Println("Building stampzilla cli")
	build("cmd/stampzilla", nil)
}

func build(path string, release *Release) {
	for _, goos := range []string{"linux"} {
		arch := []string{"amd64", "arm", "arm64"}
		if release != nil && len(release.Arch) > 0 {
			arch = release.Arch
		}

		for _, goarch := range arch {
			binName := filepath.Base(fmt.Sprintf("%s-%s-%s", path, goos, goarch))
			cgo := "0"
			if release != nil && release.Cgo {
				cgo = "1"
			}

			fmt.Printf("building %s...\n", binName)
			cmd := exec.Command("go", getArgs(path, binName)...) // #nosec
			cmd.Env = os.Environ()
			cmd.Env = append(cmd.Env, "GOOS="+goos, "GOARCH="+goarch, "CGO_ENABLED="+cgo)
			stdoutStderr, err := cmd.CombinedOutput()
			if err != nil {
				log.Println(string(stdoutStderr))
				log.Fatal(err)
			}
		}
	}
	fmt.Printf("done\n")
}

func getArgs(path, binName string) []string {
	m := []string{
		"build",
		"-ldflags",
		"-X github.com/stampzilla/stampzilla-go/v2/pkg/build.Version=" + os.Getenv("TRAVIS_TAG") + ` -X "github.com/stampzilla/stampzilla-go/v2/pkg/build.BuildTime=` + time.Now().Format(time.RFC3339) + `" -X github.com/stampzilla/stampzilla-go/v2/pkg/build.Commit=` + os.Getenv("TRAVIS_COMMIT"),
		"-o",
		filepath.Join(dest, binName),
	}
	filesToBuild, err := filepath.Glob(filepath.Join(path, "*.go"))
	if err != nil {
		log.Fatal(err)
	}
	m = append(m, filesToBuild...)
	return m
}

func loadReleaseFromFile(file string) (*Release, error) {
	f, err := os.Open(file)
	if err != nil {
		return nil, err
	}
	defer f.Close()
	var release *Release
	err = json.NewDecoder(f).Decode(&release)
	return release, err
}


text:
#ifndef __EFFEKSEER_BINARY_READER_H__
#define __EFFEKSEER_BINARY_READER_H__

#include "../Effekseer.Base.h"

namespace Effekseer
{

enum class BinaryReaderStatus
{
	Reading,
	Complete,
	Failed,
};

/**
	@brief	utility for reading binary data
*/
template <bool IsValidationEnabled>
class BinaryReader
{
private:
	uint8_t* data_ = nullptr;
	size_t size_ = 0;
	size_t offset = 0;
	BinaryReaderStatus status_ = BinaryReaderStatus::Reading;

public:
	BinaryReader(uint8_t* data, size_t size)
	{
		data_ = data;
		size_ = size;
	}

	template <typename T>
	bool Read(T& value)
	{
		if (IsValidationEnabled)
		{

			if (offset + sizeof(T) > size_ || status_ == BinaryReaderStatus::Failed)
			{
				status_ = BinaryReaderStatus::Failed;
				return false;
			}
		}

		memcpy(&value, data_ + offset, sizeof(T));
		offset += sizeof(T);
		return true;
	}

	/**
@brief	read with validation
*/
	template <typename T>
	bool Read(T& value, const T& min_, const T& max_)
	{
		if (IsValidationEnabled)
		{
			if (offset + sizeof(T) > size_ || status_ == BinaryReaderStatus::Failed)
			{
				status_ = BinaryReaderStatus::Failed;
				return false;
			}
		}

		memcpy(&value, data_ + offset, sizeof(T));
		offset += sizeof(T);

		if (IsValidationEnabled)
		{
			if (value < min_ || value > max_)
			{
				status_ = BinaryReaderStatus::Failed;
				return false;
			}
		}

		return true;
	}

	/**
		@brief	read with validation
	*/
	template <typename T, typename U>
	bool Read(T& value, const U& min_, const U& max_)
	{
		if (IsValidationEnabled)
		{
			if (offset + sizeof(T) > size_ || status_ == BinaryReaderStatus::Failed)
			{
				status_ = BinaryReaderStatus::Failed;
				return false;
			}
		}

		memcpy(&value, data_ + offset, sizeof(T));
		offset += sizeof(T);

		if (IsValidationEnabled)
		{
			if (static_cast<U>(value) < min_ || static_cast<U>(value) > max_)
			{
				status_ = BinaryReaderStatus::Failed;
				return false;
			}
		}

		return true;
	}

	template <typename T>
	bool Read(T* value, int32_t count)
	{
		if (IsValidationEnabled)
		{
			if (count < 0 || offset + sizeof(T) * count > size_ || status_ == BinaryReaderStatus::Failed)
			{
				status_ = BinaryReaderStatus::Failed;
				return false;
			}
		}

		memcpy(value, data_ + offset, sizeof(T) * count);
		offset += sizeof(T) * count;
		return true;
	}

	template <typename T, typename _Alloc>
	bool Read(std::vector<T, _Alloc>& value, int32_t count)
	{
		if (IsValidationEnabled)
		{
			if (count < 0 || offset + sizeof(T) * count > size_ || status_ == BinaryReaderStatus::Failed)
			{
				status_ = BinaryReaderStatus::Failed;
				return false;
			}
		}

		value.resize(count);

		if (value.size() > 0)
		{
			memcpy(value.data(), data_ + offset, sizeof(T) * count);
		}

		offset += sizeof(T) * count;
		return true;
	}

	BinaryReaderStatus GetStatus() const
	{
		if (status_ == BinaryReaderStatus::Failed)
			return status_;

		return offset == size_ ? BinaryReaderStatus::Complete : BinaryReaderStatus::Reading;
	}

	void AddOffset(size_t length)
	{
		offset += length;
	}

	size_t GetOffset() const
	{
		return offset;
	}
};

} // namespace Effekseer

#endif // __EFFEKSEER_READER_H__


text:
<?php

// include wp-load
define('WP_USE_THEMES', false);
require_once('../../../wp-load.php');

//GET vars
$poststring = (isset($_GET['allposts'])) ? $_GET['allposts'] : 0;
$position = (isset($_GET['postid'])) ? $_GET['postid'] : 0;
$url = (isset($_GET['place'])) ? $_GET['place'] : 0;
$url = base64_decode( $url );

$catalog_pages = unserialize( $poststring );
$catalog_page = get_post( $catalog_pages[$position] );
$catalog_page_content = imgmap_replace_shortcode( $catalog_page->post_content );
echo '<head>
<link rel="stylesheet" id="imgmap_style-css" href="http://holiday.tekserve.com/wp-content/plugins/imagemapper/imgmap_style.css?ver=3.9.1" type="text/css" media="all">
<link rel="stylesheet" id="tekserve-catalog-imagemap-css" href="http://holiday.tekserve.com/wp-content/plugins/tekserve_wp_catalog/css/imagemap.css?ver=3.9.1" type="text/css" media="all">
<script type="text/javascript" src="' . $url . '/js/jquery.imagemapster.min.js"></script>
<script type="text/javascript" src="' . $url . '/js/imagemapper_script.js?ver=3.9.1"></script>
</head>';
echo $catalog_page_content;
?>


text:
package org.elasticsearch.xpack.security.authc;

import org.elasticsearch.Version;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.UUIDs;
import org.elasticsearch.common.settings.SecureString;
import org.elasticsearch.test.XContentTestUtils;
import org.elasticsearch.xcontent.XContentType;
import org.elasticsearch.xpack.core.security.authc.Authentication;
import org.elasticsearch.xpack.core.security.index.RestrictedIndicesNames;
import org.elasticsearch.xpack.security.test.SecurityMocks;

import java.io.IOException;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Because {@link TokenService} is {@code final}, we can't mock it.
 * Instead, we use this class to control the client that underlies the token service and trigger certain conditions
 */
public class TokenServiceMock {
    public final TokenService tokenService;
    public final Client client;

    public final class MockToken {
        public final String baseToken;
        public final SecureString encodedToken;
        public final String hashedToken;

        public MockToken(String baseToken, SecureString encodedToken, String hashedToken) {
            this.baseToken = baseToken;
            this.encodedToken = encodedToken;
            this.hashedToken = hashedToken;
        }
    }

    public TokenServiceMock(TokenService tokenService, Client client) {
        this.tokenService = tokenService;
        this.client = client;
    }

    public MockToken mockAccessToken() throws Exception {
        final String uuid = UUIDs.randomBase64UUID();
        final SecureString encoded = new SecureString(tokenService.prependVersionAndEncodeAccessToken(Version.CURRENT, uuid).toCharArray());
        final String hashedToken = TokenService.hashTokenString(uuid);
        return new MockToken(uuid, encoded, hashedToken);
    }

    public void defineToken(MockToken token, Authentication authentication) throws IOException {
        defineToken(token, authentication, true);
    }

    public void defineToken(MockToken token, Authentication authentication, boolean valid) throws IOException {
        Instant expiration = Instant.now().plusSeconds(TimeUnit.MINUTES.toSeconds(20));
        final UserToken userToken = new UserToken(token.hashedToken, Version.CURRENT, authentication, expiration, Map.of());
        final Map<String, Object> document = new HashMap<>();
        document.put("access_token", Map.of("user_token", userToken, "invalidated", valid == false));

        SecurityMocks.mockGetRequest(
            client,
            RestrictedIndicesNames.SECURITY_TOKENS_ALIAS,
            "token_" + token.hashedToken,
            XContentTestUtils.convertToXContent(document, XContentType.JSON)
        );
    }
}


text:
trap 'ret=$?; test $ret -ne 0 && printf "failed\n\n" >&2; exit $ret' EXIT

set -e

##### Functions and Helpers #####

fancy_echo() {
  local fmt="$1"; shift

  # shellcheck disable=SC2059
  printf "\n$fmt\n" "$@"
}

append_to_zshrc() {
  local text="$1" zshrc
  local skip_new_line="${2:-0}"

  if [ -w "$HOME/.zshrc.local" ]; then
    zshrc="$HOME/.zshrc.local"
  else
    zshrc="$HOME/.zshrc"
  fi

  if ! grep -Fqs "$text" "$zshrc"; then
    if [ "$skip_new_line" -eq 1 ]; then
      printf "%s\n" "$text" >> "$zshrc"
    else
      printf "\n%s\n" "$text" >> "$zshrc"
    fi
  fi
}

cask_install_or_upgrade() {
  if ! cask_is_installed "$1"; then
    fancy_echo "Installing %s ..." "$1"
    brew install --cask --appdir="/Applications" "$@" || true
  fi
}

cask_is_installed() {
  local name="$(cask_expand_alias "$1")"

  brew list --cask -1 | grep -Fqx "$name"
}

cask_expand_alias() {
  brew info --cask "$1" 2>/dev/null | head -1 | awk '{gsub(/:/, ""); print $1}'
}

brew_install_or_upgrade() {
  if brew_is_installed "$1"; then
    if brew_is_upgradable "$1"; then
      fancy_echo "Upgrading %s ..." "$1"
      brew upgrade "$@"
    else
      fancy_echo "Already using the latest version of %s. Skipping ..." "$1"
    fi
  else
    fancy_echo "Installing %s ..." "$1"
    brew install "$@"
  fi
}

brew_is_installed() {
  local name="$(brew_expand_alias "$1")"

  brew list --formula -1 | grep -Fqx "$name"
}

brew_is_upgradable() {
  local name="$(brew_expand_alias "$1")"

  ! brew outdated --quiet "$name" >/dev/null
}

brew_tap() {
  fancy_echo "Tapping %s..." "$1"
  brew tap "$1" 2> /dev/null
}

brew_expand_alias() {
  brew info "$1" 2>/dev/null | head -1 | awk '{gsub(/:/, ""); print $1}'
}

brew_launchctl_restart() {
  local name="$(brew_expand_alias "$1")"
  local domain="homebrew.mxcl.$name"
  local plist="$domain.plist"

  fancy_echo "Restarting %s ..." "$1"
  mkdir -p "$HOME/Library/LaunchAgents"
  ln -sfv "/usr/local/opt/$name/$plist" "$HOME/Library/LaunchAgents"

  if launchctl list | grep -Fq "$domain"; then
    launchctl unload "$HOME/Library/LaunchAgents/$plist" >/dev/null
  fi
  launchctl load "$HOME/Library/LaunchAgents/$plist" >/dev/null
}

gem_install_or_update() {
  if gem list "$1" --installed > /dev/null; then
    fancy_echo "Updating %s ..." "$1"
    gem update "$@"
  else
    fancy_echo "Installing %s ..." "$1"
    gem install "$@"
    rbenv rehash
  fi
}

install_or_update_homebrew() {
  if ! command -v brew >/dev/null; then
    fancy_echo "Installing Homebrew ..."
    /bin/bash -c \
      "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"

    append_to_zshrc '# recommended by brew doctor'

    append_to_zshrc 'export PATH="/usr/local/bin:$PATH"' 1

    export PATH="/usr/local/bin:$PATH"
  else
    fancy_echo "Homebrew already installed."
  fi
  fancy_echo "Updating Homebrew formulas ..."
  brew update
}

install_ruby() {
  append_to_zshrc 'eval "$(rbenv init - --no-rehash zsh)"' 1
  ruby_version="2.6.9"
  eval "$(rbenv init - zsh)"

  if ! rbenv versions | grep -Fq "$ruby_version"; then
    rbenv install -s "$ruby_version"
  fi

  rbenv global "$ruby_version"
  rbenv shell "$ruby_version"

  gem update --system
}

install_bundler_1_17_3() {
  gem install bundler --version 1.17.3
  rbenv rehash

  fancy_echo "Configuring Bundler ..."
  number_of_cores=$(sysctl -n hw.ncpu)
  bundle config --global jobs $((number_of_cores - 1))
}

 # PostgreSQL 9.6 hit EoL and is no longer supported by brew. This step now downloads the PG App - https://postgresapp.com/ - to install 9.6
 # You will need to manually start the Database however. See the StartingPostgresApp.md guide in this repo.
 install_postgresql() {
  # brew_install_or_upgrade 'postgresql@9.6'
  # brew link postgresql@9.6 --force
  # brew_launchctl_restart 'postgresql'
  # if [ `psql -U postgres -c "select 1" &> /dev/null` ]; then
  #   /usr/local/bin/createuser -U `whoami` --superuser postgres
  # fi

  if [ -z `psql --version`]; then
    fancy_echo 'Installing psql via PostgresApp...'
    # Download the postgresapp DMG via curl
    # --location to follow redirects
    # --output to write the output to a file
    curl https://github.com/PostgresApp/PostgresApp/releases/download/v2.5.2/Postgres-2.5.2-9.6-10-11-12-13-14.dmg --location --output ~/Downloads/postgres-2.5.2.dmg
    MOUNT_POINT=$(hdiutil attach ~/Downloads/postgres-2.5.2.dmg -nobrowse | grep "Postgres-2.5.2" | awk '{print $3}')
    sudo cp -R $MOUNT_POINT/Postgres.app /Applications
    hdiutil unmount $MOUNT_POINT
    sudo mkdir -p /etc/paths.d && echo /Applications/Postgres.app/Contents/Versions/latest/bin | sudo tee /etc/paths.d/postgresapp
    fancy_echo 'Installed psql via PostgresApp BUT needs to be started manually'
  else
    fancy_echo 'Already installed Psql. Skipping'
  fi
}

##### Start Installation #####

if [ ! -d "$HOME/.bin/" ]; then
  mkdir "$HOME/.bin"
fi

if [ ! -f "$HOME/.zshrc" ]; then
  touch "$HOME/.zshrc"
fi

append_to_zshrc 'export PATH="$HOME/.bin:$PATH"'

# Install packages
install_or_update_homebrew
brew_install_or_upgrade 'git'
install_postgresql
brew_install_or_upgrade 'redis'
brew_launchctl_restart 'redis'
brew_install_or_upgrade 'sops'
brew_install_or_upgrade 'n'
sudo n stable
brew_install_or_upgrade 'yarn'
brew_install_or_upgrade 'rbenv'
brew_install_or_upgrade 'ruby-build'
brew_install_or_upgrade 'openssl'
brew_install_or_upgrade 'elasticsearch@6'
brew_install_or_upgrade 'redpanda-data/tap/redpanda'
brew services start elasticsearch@6

brew unlink openssl && brew link openssl --force

brew_tap 'homebrew/cask'
cask_install_or_upgrade 'chromedriver'

# Install applications
cask_install_or_upgrade 'google-chrome'
install_ruby
install_bundler_1_17_3

# Setup Google Cloud Platform/Kubernetes Tooling
cask_install_or_upgrade 'google-cloud-sdk'
gcloud components install kubectl docker-credential-gcr pubsub-emulator
brew_install_or_upgrade 'helm'
append_to_zshrc 'source /usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/path.zsh.inc'


text:
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace Provider.Models
{
    public class Tool
    {
        public Tool()
        {
            Outcomes = new HashSet<Outcome>();
        }

        public int ToolId { get; set; }
        [Required]
        public string Name { get; set; }
        [DataType(DataType.Html)]
        public string Description { get; set; }
        [DataType(DataType.Html)]
        public string Content { get; set; }
        public virtual ICollection<Outcome> Outcomes { get; set; }
    }

    public class ToolUser
    {
        public string ConsumerName { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string ReturnUrl { get; set; }
        public string Roles { get; set; }
    }

    public class PostScoreModel
    {
        public string ConsumerName { get; set; }
        public string ContextTitle { get; set; }
        public int OutcomeId { get; set; }
        public double? Score { get; set; }
        public int ToolId { get; set; }
    }
}


text:
Enforce `@click` is accompanied by at least one of `@keyup`, `@keydown`, or `@keypress`. Coding for the keyboard is important for users with physical disabilities who cannot use a mouse, AT compatibility, and screenreader users. This does not apply for interactive or hidden elements.

## Rule Details

Examples of **incorrect** code for this rule:

```js
html` <div @click="${onClick}"></div> `;
```

Examples of **correct** code for this rule:

```js
html` <button @click="${onClick}"></button> `;
```

```js
html` <div @click="${onClick}" @keyup="${onKeyup}"></div> `;
```

### Options

The `allowList` option lets you specify tag names to exclude from this rule. the `allowCustomElements` option (true by default) excludes all custom-elements from this rule.

```json
{
  "rules": {
    "lit-a11y/click-events-have-key-events": [
      "error",
      {
        "allowList": ["foo-button"],
        "allowCustomElements": false
      }
    ]
  }
}
```

Examples of **incorrect** code with `allowCustomElements: false`:

```js
html` <custom-element @click="${onClick}"></custom-element> `;
```

Examples of **correct** code with `allowCustomElements: false, allowList: ['custom-element']`:

```js
html` <custom-element @click="${onClick}"></custom-element> `;
```

## Further Reading

- [WCAG 2.1.1](https://www.w3.org/WAI/WCAG21/Understanding/keyboard)


text:
package org.openkilda.messaging.payload.yflow;

import org.openkilda.model.MeterId;
import org.openkilda.model.SwitchId;

import lombok.NonNull;
import lombok.Value;

import java.io.Serializable;

@Value
public class YFlowEndpointResources implements Serializable {
    @NonNull SwitchId switchId;
    @NonNull MeterId meterId;
}


text: google-site-verification: google1e7a078c6e8529c5.html


text:
namespace base {
class SequencedTaskRunner;
}  // namespace base

namespace media {
class CancellationHelper;

// OffloadableVideoDecoder implementations must have synchronous execution of
// Reset() and Decode() (true for all current software decoders); this allows
// for serializing these operations on the offloading sequence. With
// serializing, multiple Decode() events can be queued on the offload thread,
// and Reset() does not need to wait for |reset_cb| to return.
class MEDIA_EXPORT OffloadableVideoDecoder : public VideoDecoder {
 public:
  enum class OffloadState {
    kOffloaded,  // Indicates the VideoDecoder is being used with
                 // OffloadingVideoDecoder and that callbacks provided to
                 // VideoDecoder methods should not be bound to the current
                 // loop.

    kNormal,  // Indicates the VideoDecoder is being used as a normal
              // VideoDecoder, meaning callbacks should always be asynchronous.
  };

  ~OffloadableVideoDecoder() override {}

  // Called by the OffloadingVideoDecoder when closing the decoder and switching
  // task runners. Will be called on the task runner that Initialize() was
  // called on. Upon completion of this method implementing decoders must be
  // ready to be Initialized() on another thread.
  virtual void Detach() = 0;
};

// Wrapper for OffloadableVideoDecoder implementations that runs the wrapped
// decoder on a task pool other than the caller's thread.
//
// Offloading allows us to avoid blocking the media sequence for Decode() when
// it's known that decoding may take a long time; e.g., high-resolution VP9
// decodes may occasionally take upwards of > 100ms per frame, which is enough
// to exhaust the audio buffer and lead to underflow in some circumstances.
//
// Offloading also allows better pipelining of Decode() calls. The normal decode
// sequence is Decode(buffer) -> DecodeComplete() -> WaitFor(buffer)-> (repeat);
// this sequence generally involves thread hops as well. When offloading we can
// take advantage of the serialization of operations on the offloading sequence
// to make this Decode(buffer) -> DecodeComplete() -> Decode(buffer) by queuing
// the next Decode(buffer) before the previous one completes.
//
// I.e., we are no longer wasting cycles waiting for the recipient of the
// decoded frame to acknowledge that receipt, request the next muxed buffer, and
// then queue the next decode. Those operations now happen in parallel with the
// decoding of the previous buffer on the offloading sequence. Improving the
// total throughput that a decode can achieve.
//
// E.g., without parallel offloading, over 4000 frames, a 4K60 VP9 clip spent
// ~11.7 seconds of aggregate time just waiting for frames. With parallel
// offloading the same clip spent only ~3.4 seconds.
//
// Optionally decoders which are aware of the wrapping may choose to not rebind
// callbacks to the offloaded thread since they will already be bound by the
// OffloadingVideoDecoder; this simply avoids extra hops for completed tasks.
class MEDIA_EXPORT OffloadingVideoDecoder : public VideoDecoder {
 public:
  // Offloads |decoder| for VideoDecoderConfigs provided to Initialize() using
  // |supported_codecs| with a coded width >= |min_offloading_width|.
  //
  // E.g. if a width of 1024 is specified, and VideoDecoderConfig has a coded
  // size of 1280x720 we will use offloading. Conversely if the width was
  // 640x480, we would not use offloading.
  OffloadingVideoDecoder(int min_offloading_width,
                         std::vector<VideoCodec> supported_codecs,
                         std::unique_ptr<OffloadableVideoDecoder> decoder);

  OffloadingVideoDecoder(const OffloadingVideoDecoder&) = delete;
  OffloadingVideoDecoder& operator=(const OffloadingVideoDecoder&) = delete;

  ~OffloadingVideoDecoder() override;

  // VideoDecoder implementation.
  bool IsOptimizedForRTC() const override;
  VideoDecoderType GetDecoderType() const override;
  void Initialize(const VideoDecoderConfig& config,
                  bool low_delay,
                  CdmContext* cdm_context,
                  InitCB init_cb,
                  const OutputCB& output_cb,
                  const WaitingCB& waiting_cb) override;
  void Decode(scoped_refptr<DecoderBuffer> buffer, DecodeCB decode_cb) override;
  void Reset(base::OnceClosure reset_cb) override;
  int GetMaxDecodeRequests() const override;

 private:
  // VideoDecoderConfigs given to Initialize() with a coded size that has width
  // greater than or equal to this value will be offloaded.
  const int min_offloading_width_;

  // Codecs supported for offloading.
  const std::vector<VideoCodec> supported_codecs_;

  // Indicates if Initialize() has been called.
  bool initialized_ = false;

  SEQUENCE_CHECKER(sequence_checker_);

  // A helper class for managing Decode() and Reset() calls to the offloaded
  // decoder; it owns the given OffloadableVideoDecoder and is always destructed
  // on |offload_task_runner_| when used.
  std::unique_ptr<CancellationHelper> helper_;

  // High resolution decodes may block the media thread for too long, in such
  // cases offload the decoding to a task pool.
  scoped_refptr<base::SequencedTaskRunner> offload_task_runner_;

  // NOTE: Weak pointers must be invalidated before all other member variables.
  base::WeakPtrFactory<OffloadingVideoDecoder> weak_factory_{this};
};

}  // namespace media

#endif  // MEDIA_FILTERS_OFFLOADING_VIDEO_DECODER_H_


text:
<?php

namespace Pasinter\CoreBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class MessageType extends AbstractType
{
        /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('body')
            ->add('thread')
            ->add('sender')
        ;
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Pasinter\CoreBundle\Entity\Message'
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'pasinter_corebundle_message';
    }
}


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

$(function() {
    initCurrentBook(currentBookJSON);
    initCurrentUser(currentUserJSON);

    userFacebookFunctions = new _readroom.userFacebookModel();
    //userBooks = new _readroom.booksCollection();

    Backbone.emulateJSON = true;
    // creo una instancia del router
    router = new _readroom.router;
    socialRouter = new _readroom.socialRouter;

    bookDescriptionView = new _readroom.bookDescriptionView({el: $("#book-description")});

    // inicializo la entidad history de Backbone para poder uilizar las rutas
    Backbone.history.start();

    //router.initFacebook();

});

/*
 * Incializo el usuario si existe
 */

var initCurrentBook = function(book) {
    currentBook = new _readroom.bookModel();

    if(book != null) {
       currentBook.set(book);
    }
};

var initCurrentUser = function(user) {
    currentUser = new _readroom.userModel();

    if(user != null) {
       currentUser.set(user);
    }
};


text:
<?php

namespace Acme\UserBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class SearchType extends AbstractType
{
    protected $className;

    public function __construct ($className)
    {
        $this->className = $className;
    }

        /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('username', 'genemu_jqueryautocomplete_entity', array(
            'class' => $this->className,
            'property' => 'username',
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'acme_userbundle_search';
    }
}


text:
from __future__ import absolute_import, division, print_function

from sentry.constants import STATUS_CHOICES
from sentry.models import EventUser, User
from sentry.utils.auth import find_users

def get_user_tag(project, key, value):
    if key == 'id':
        lookup = 'ident'
    elif key == 'ip':
        lookup = 'ip_address'
    else:
        lookup = key

    # TODO(dcramer): do something with case of multiple matches
    try:
        euser = EventUser.objects.filter(
            project=project,
            **{lookup: value}
        )[0]
    except IndexError:
        return '{}:{}'.format(key, value)

    return euser.tag_value

def parse_query(project, query, user):
    # TODO(dcramer): handle query being wrapped in quotes
    tokens = query.split(' ')

    results = {'tags': {}, 'query': []}

    tokens_iter = iter(tokens)
    for token in tokens_iter:
        # ignore empty tokens
        if not token:
            continue

        if ':' not in token:
            results['query'].append(token)
            continue

        key, value = token.split(':', 1)
        if not value:
            results['query'].append(token)
            continue

        if value[0] == '"':
            nvalue = value
            while nvalue[-1] != '"':
                try:
                    nvalue = tokens_iter.next()
                except StopIteration:
                    break
                value = '%s %s' % (value, nvalue)

            if value.endswith('"'):
                value = value[1:-1]
            else:
                value = value[1:]

        if key == 'is':
            try:
                results['status'] = STATUS_CHOICES[value]
            except KeyError:
                pass
        elif key == 'assigned':
            if value == 'me':
                results['assigned_to'] = user
            else:
                try:
                    results['assigned_to'] = find_users(value)[0]
                except IndexError:
                    # XXX(dcramer): hacky way to avoid showing any results when
                    # an invalid user is entered
                    results['assigned_to'] = User(id=0)
        elif key == 'first-release':
            results['first_release'] = value
        elif key == 'release':
            results['tags']['sentry:release'] = value
        elif key == 'user':
            if ':' in value:
                comp, value = value.split(':', 1)
            else:
                comp = 'id'
            results['tags']['sentry:user'] = get_user_tag(
                project, comp, value)
        elif key.startswith('user.'):
            results['tags']['sentry:user'] = get_user_tag(
                project, key.split('.', 1)[1], value)
        else:
            results['tags'][key] = value

    results['query'] = ' '.join(results['query'])

    return results


text:
<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android" >

    <solid
        android:color="#E6000000" />

    <corners
        android:radius="25dp"/>

</shape>


text:
[![Build Status](https://travis-ci.org/berezovskyi/lambda-test-java.svg?branch=master)](https://travis-ci.org/berezovskyi/lambda-test-java) [![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg)](https://raw.githubusercontent.com/berezovskyi/lambda-test-java/master/LICENSE)

All test functions are fed with the following input:

    {
        "operation": "create",
        "tableName": "evts-at-rest-python",
        "payload": {
            "Item": {
                "name": "FTW",
                "count": "1"
            }
        }
    }


text:
class MouseEvent
{
public:
	int m_event_type;
    int m_x, m_y;

    bool          m_leftDown;
    bool          m_middleDown;
    bool          m_rightDown;

    bool          m_controlDown;
    bool          m_shiftDown;
    bool          m_altDown;
    bool          m_metaDown;

    int           m_wheelRotation;
    int           m_wheelDelta;
    int           m_linesPerAction;

    bool LeftDown() const { return (m_event_type == 1); }
    bool MiddleDown() const { return (m_event_type == 6); }
    bool RightDown() const { return (m_event_type == 4); }
    bool LeftUp() const { return (m_event_type == 2); }
    bool MiddleUp() const { return (m_event_type == 7); }
    bool RightUp() const { return (m_event_type == 5); }
    bool LeftDClick() const { return (m_event_type == 3); }
    bool LeftIsDown() const { return m_leftDown; }
    bool MiddleIsDown() const { return m_middleDown; }
    bool RightIsDown() const { return m_rightDown; }
    bool Dragging() const{ return (m_event_type == 8) && (m_leftDown || m_middleDown || m_rightDown);}
    bool Moving() const{ return (m_event_type == 8) && !(m_leftDown || m_middleDown || m_rightDown);}
    int GetX() const { return m_x; }
    int GetY() const { return m_y; }
    int GetWheelRotation() const { return m_wheelRotation; }
    int GetWheelDelta() const { return m_wheelDelta; }
    int GetLinesPerAction() const { return m_linesPerAction; }
};


text:
{{<govuk_template}}

{{$head}}
  {{>includes/elements_head}}

    <link href="/public/stylesheets/application.css" media="screen" rel="stylesheet" type="text/css" />

{{/head}}

{{$propositionHeader}}
  {{>includes/govuk_firstregprop}}
{{/propositionHeader}}

{{$headerClass}}with-proposition{{/headerClass}}

{{$content}}

  Back

   to the previous question

  {{#vars}}

  <input type="hidden" name="isnew" value="{{isnew}}">
  <input type="hidden" name="importer" value="{{importer}}">
  <input type="hidden" name="vat" value="{{vat}}">
  <input type="hidden" name="iseu" value="{{iseu}}">
  <input type="hidden" name="type" value="{{type}}">
  <input type="hidden" name="speedo" value="{{speedo}}">
  <input type="hidden" name="isnew" value="{{isnew}}">
  <input type="hidden" name="iva" value="{{iva}}">
  <input type="hidden" name="nssta" value="{{nssta}}">
  <input type="hidden" name="ec" value="{{ec}}">
  <input type="hidden" name="isuk" value="{{isuk}}">
  {{/vars}}
  <input type="hidden" name="nextlink" value="answers">

Choose address

  <form method="get" action="chosen-address" class="form">

Postcode

{{postcode}}  Change

Select your address from the list

      <select class="input-select" name="udprn">
      <option>{{result.length}} addresses were found</option>
      {{#result}}

          <option value="{{udprn}}">{{line_1}}, {{line_2}}</option>

      {{/result}}
      </select>

    Enter the address manually

      <input type="submit" class="button" value="Select address">

    </form>

{{/content}}

{{$bodyEnd}}
  {{>includes/elements_scripts}}
{{/bodyEnd}}

{{/govuk_template}}


text:
{% extends "base/micro.html" %}

{% block title %}
Node Update | SwarmOps - Docker管理平台
{% endblock %}

{% block container %}
<form class="form-horizontal" role="form" id="UpdateNodeForm">

  <input type="hidden" class="form-control" id="UpdateNodeID" name="node_id">
  <input type="hidden" class="form-control" id="UpdateNodeType" name="UpdateNodeType" value="ui">

    更新节点标签

      <input type="text" class="form-control" id="UpdateNodeLabels" name="node_labels" placeholder="节点标签, 请输入k/v键值对, 多对标签以逗号分隔, 例如ipaddr=NodeIp, environment=dev">

    更新节点角色

<input type="radio" id="UpdateNodeRoleWorker" name="node_role" value="Worker">设定为Worker工作节点

<input type="radio" id="UpdateNodeRoleManager" name="node_role" value="Manager">设定为Manager管理节点

      <button type="button" onclick=UpdateNode() class="btn btn-info">更新节点</button>

</form>
{% endblock %}

{% block script %}

{% endblock %}


text:
class ADSR extends Module {
  constructor(moduleLabel, ...pins) {
    super(moduleLabel, ...pins);

    this.gateOpen = false;

    this.gainNode = actx.createGain();
    this.gainNode.gain.value = 0;

    // constant "voltage" source (replace with reusable/shareable source soon)
    var bufferSource = actx.createBufferSource();
    var buffer = actx.createBuffer(1, 1, actx.sampleRate);
    var bufferData = buffer.getChannelData(0);
    bufferData[0] = 1;
    bufferSource.buffer = buffer;
    bufferSource.loop = true;
    bufferSource.connect(this.gainNode);
    bufferSource.start();

    // gate node, detects change in input and triggers stuff
    this.gateNode = actx.createScriptProcessor(256, 1, 1);
    this.gateNode.onaudioprocess = function(ev) {
      var inputBuffer = ev.inputBuffer;
      var inputSample = inputBuffer.getChannelData(0)[0];
      if(inputSample > 0.5) {
        if(!this.gateOpen) {
          this.triggerStart();
          this.gateOpen = true;
        }
      } else {
        if(this.gateOpen) {
          this.triggerEnd();
          this.gateOpen = false;
        }
      }
    }.bind(this);

    // hack! for now, create a gain node so i've got something to connect the script processor to
    this.dummyNode = actx.createGain();
    this.dummyNode.gain.value = 0;
    this.dummyNode.connect(actx.destination);
    this.gateNode.connect(this.dummyNode);

    this.attack = 0.01;
    this.decay = 0.05;
    this.sustain = 0.3;
    this.release = 0.3;

    this.addSocket("gate", Socket.IN, this.gateNode);
    this.addSocket("out", Socket.OUT, this.gainNode);
  }

  triggerStart() {
    var now = actx.currentTime;
    this.gainNode.gain.cancelScheduledValues(now);
    this.gainNode.gain.setValueAtTime(0, now);
    this.gainNode.gain.linearRampToValueAtTime(1, now + this.attack);
    this.gainNode.gain.linearRampToValueAtTime(this.sustain, now + this.attack + this.decay);
  }

  triggerEnd() {
    var now = actx.currentTime;
    this.gainNode.gain.cancelScheduledValues(now);
    this.gainNode.gain.setValueAtTime(this.gainNode.gain.value, now);
    this.gainNode.gain.linearRampToValueAtTime(0, now + this.release);
  }
}


text:
loglunatic -- logstash for lunatics
Copyright (c) 2013, Alex Wilson, the University of Queensland
Distributed under a BSD license -- see the LICENSE file in the root of the distribution.
]]

local ffi = require("ffi")
local bit = require("bit")
local r = require("lunatic/reactor")

ffi.cdef[[
int pipe(int fildes[2]);
int write(int fd, const void *buf, int bytes);
int fork(void);
int execvp(const char *file, char *const argv[]);
int dup2(int oldfd, int newfd);
int close(int fd);
int waitpid(int pid, int *stat_loc, int options);
int kill(int pid, int sig);
int usleep(uint32_t usecs);
]]

local function write(str)
	return ffi.C.write(1, str, #str)
end

local function pipe(tbl)
	local command = tbl.command or tbl
	local fds = ffi.new("int[?]", 2)

	local ret = ffi.C.pipe(fds)
	if ret < 0 then error("pipe failed") end

	local pid = ffi.C.fork()
	if pid == -1 then
		error("fork failed")
	elseif pid == 0 then
		ffi.C.dup2(fds[1], 1)
		ffi.C.close(fds[0])
		ffi.C.close(fds[1])

		local args = ffi.new("char *[?]", 4)
		args[0] = ffi.new("char[?]", 5, "sh")
		args[1] = ffi.new("char[?]", 3, "-c")
		args[2] = ffi.new("char[?]", #command + 1, command)
		args[3] = nil
		ffi.C.execvp("sh", args)
	else
		local fd = fds[0]
		ffi.C.close(fds[1])
		local chan = r.Channel.new(fd)
		chan.pid = pid
		chan.command = command
		chan.on_close = function(ch, rtor)
			io.write("input pipe: " .. ch.command .. "/"..ch.fd.."/"..ch.pid..": closing...\n")
			ffi.C.close(ch.fd)
                       ffi.C.kill(ch.pid, 15)
                       ffi.C.usleep(10000)
                       ffi.C.kill(ch.pid, 9)
			local sl = ffi.new("int[?]", 1)
			ffi.C.waitpid(ch.pid, sl, 0)
		end
		return chan
	end
end

return pipe


text:
import { Component, OnInit, AfterContentChecked, AfterContentInit, AfterViewChecked, AfterViewInit, OnChanges, OnDestroy } from '@angular/core';

@Component({
  selector: 'nlg-parallax-scroll',
  templateUrl: './parallax-scroll.component.html',
  styleUrls: ['./parallax-scroll.component.scss']
})
export class ParallaxScrollCSSComponent implements OnInit, AfterContentChecked, AfterContentInit, AfterViewChecked, AfterViewInit, OnChanges, OnDestroy  {

  metas = {
    title: 'Parallax Scroll - CSS',
    subTitle: '',
    subExtra: '',
    links: {
      down: 'https://github.com/NoLogig/Inspiration-Station/archive/master.zip',
      git: 'https://github.com/NoLogig/Inspiration-Station/tree/master/src/app/pages/layouts/parallax/scroll-parallax',
      live: 'https://inspiration-station.herokuapp.com/parallax-scroll',
    }
  };

  constructor() { }

  /* ########################### */
  /* ####  Livecycle Hooks  #### */
  /* ########################### */

  ngOnInit(): void {              console.log('SplitScreen Init'); }
  ngAfterViewChecked(): void {    console.log('SplitScreen ViewChecked'); }
  ngAfterContentChecked(): void { console.log('SplitScreen ContentChecked'); }
  ngAfterContentInit(): void {    console.log('SplitScreen ContentInit'); }
  ngAfterViewInit(): void {       console.log('SplitScreen ViewInit'); }
  ngOnChanges(): void {           console.log('SplitScreen Changes'); }
  ngOnDestroy(): void {           console.log('SplitScreen Destroy'); }

}


text:
import pytest
import unittest
from selenium.webdriver.common.by import By
from selenium.common.exceptions import WebDriverException
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.remote.webelement import WebElement

@pytest.mark.ignore_phantomjs
class ExecutingAsyncJavaScriptTests(unittest.TestCase):

    def testShouldNotTimeoutIfCallbackInvokedImmediately(self):
        self._loadPage("ajaxy_page")
        result = self.driver.execute_async_script("arguments[arguments.length - 1](123);")
        self.assertTrue(type(result) == int)
        self.assertEqual(123, result)

    def testShouldBeAbleToReturnJavascriptPrimitivesFromAsyncScripts_NeitherNoneNorUndefined(self):
        self._loadPage("ajaxy_page")
        self.assertEqual(123, self.driver.execute_async_script(
            "arguments[arguments.length - 1](123);"))
        self.assertEqual("abc", self.driver.execute_async_script("arguments[arguments.length - 1]('abc');"))
        self.assertFalse(bool(self.driver.execute_async_script("arguments[arguments.length - 1](false);")))
        self.assertTrue(bool(self.driver.execute_async_script("arguments[arguments.length - 1](true);")))

    # @Ignore(value = SELENESE, reason = "SeleniumRC cannot return null values.")
    def testShouldBeAbleToReturnJavascriptPrimitivesFromAsyncScripts_NullAndUndefined(self):
        self._loadPage("ajaxy_page")
        self.assertTrue(self.driver.execute_async_script("arguments[arguments.length - 1](null)") is None)
        self.assertTrue(self.driver.execute_async_script("arguments[arguments.length - 1]()") is None)

    # @Ignore(value = SELENESE, reason = "Selenium cannot return arrays")
    def testShouldBeAbleToReturnAnArrayLiteralFromAnAsyncScript(self):
        self._loadPage("ajaxy_page")
        result = self.driver.execute_async_script("arguments[arguments.length - 1]([]);")
        self.assertTrue("Expected not to be null!", result is not None)
        self.assertTrue(type(result) == list)
        self.assertTrue(len(result) == 0)

    # @Ignore(value = SELENESE, reason = "Selenium cannot return arrays")
    def testShouldBeAbleToReturnAnArrayObjectFromAnAsyncScript(self):
        self._loadPage("ajaxy_page")

        result = self.driver.execute_async_script("arguments[arguments.length - 1](new Array());")
        self.assertTrue("Expected not to be null!", result is not None)
        self.assertTrue(type(result) == list)
        self.assertTrue(len(result) == 0)

    # @Ignore(value = ANDROID, SELENESE,
    #  reason = "Android does not properly handle arrays; Selenium cannot return arrays")
    def testShouldBeAbleToReturnArraysOfPrimitivesFromAsyncScripts(self):
        self._loadPage("ajaxy_page")

        result = self.driver.execute_async_script(
            "arguments[arguments.length - 1]([null, 123, 'abc', true, false]);")

        self.assertTrue(result is not None)
        self.assertTrue(type(result) == list)
        self.assertFalse(bool(result.pop()))
        self.assertTrue(bool(result.pop()))
        self.assertEqual("abc", result.pop())
        self.assertEqual(123, result.pop())
        self.assertTrue(result.pop() is None)
        self.assertTrue(len(result) == 0)

    # @Ignore(value = SELENESE, reason = "Selenium cannot return elements from scripts")
    def testShouldBeAbleToReturnWebElementsFromAsyncScripts(self):
        self._loadPage("ajaxy_page")

        result = self.driver.execute_async_script("arguments[arguments.length - 1](document.body);")
        self.assertTrue(type(result) == WebElement)
        self.assertEqual("body", result.tag_name.lower())

    # @Ignore(value = ANDROID, SELENESE,
    #  reason = "Android does not properly handle arrays; Selenium cannot return elements")
    def testShouldBeAbleToReturnArraysOfWebElementsFromAsyncScripts(self):
        self._loadPage("ajaxy_page")

        result = self.driver.execute_async_script(
            "arguments[arguments.length - 1]([document.body, document.body]);")
        self.assertTrue(result is not None)
        self.assertTrue(type(result) == list)

        list_ = result
        self.assertEqual(2, len(list_))
        self.assertTrue(type(list_[0]) == WebElement)
        self.assertTrue(type(list_[1]) == WebElement)
        self.assertEqual("body", list_[0].tag_name)
        # self.assertEqual(list_[0], list_[1])

    def testShouldTimeoutIfScriptDoesNotInvokeCallback(self):
        self._loadPage("ajaxy_page")
        try:
            # Script is expected to be async and explicitly callback, so this should timeout.
            self.driver.execute_async_script("return 1 + 2;")
            self.fail("Should have thrown a TimeOutException!")
        except TimeoutException:
            pass

    def testShouldTimeoutIfScriptDoesNotInvokeCallbackWithAZeroTimeout(self):
        self._loadPage("ajaxy_page")
        try:
            self.driver.execute_async_script("window.setTimeout(function() {}, 0);")
            self.fail("Should have thrown a TimeOutException!")
        except TimeoutException:
            pass

    def testShouldNotTimeoutIfScriptCallsbackInsideAZeroTimeout(self):
        self._loadPage("ajaxy_page")
        self.driver.execute_async_script(
            """var callback = arguments[arguments.length - 1];
            window.setTimeout(function() { callback(123); }, 0)""")

    def testShouldTimeoutIfScriptDoesNotInvokeCallbackWithLongTimeout(self):
        self.driver.set_script_timeout(0.5)
        self._loadPage("ajaxy_page")
        try:
            self.driver.execute_async_script(
                """var callback = arguments[arguments.length - 1];
                window.setTimeout(callback, 1500);""")
            self.fail("Should have thrown a TimeOutException!")
        except TimeoutException:
            pass

    def testShouldDetectPageLoadsWhileWaitingOnAnAsyncScriptAndReturnAnError(self):
        self._loadPage("ajaxy_page")
        self.driver.set_script_timeout(0.1)
        try:
            self.driver.execute_async_script("window.location = '" + self._pageURL("dynamic") + "';")
            self.fail('Should have throw a WebDriverException')
        except WebDriverException:
            pass

    def testShouldCatchErrorsWhenExecutingInitialScript(self):
        self._loadPage("ajaxy_page")
        try:
            self.driver.execute_async_script("throw Error('you should catch this!');")
            self.fail("Should have thrown a WebDriverException")
        except WebDriverException:
            pass

    # @Ignore(value = ANDROID, CHROME,
    #  reason = "Android: Emulator is too slow and latency causes test to fall out of sync with app;"
    #      + "Chrome: Click is not working")
    def testShouldBeAbleToExecuteAsynchronousScripts(self):
        self._loadPage("ajaxy_page")

        typer = self.driver.find_element(by=By.NAME, value="typer")
        typer.send_keys("bob")
        self.assertEqual("bob", typer.get_attribute("value"))

        self.driver.find_element(by=By.ID, value="red").click()
        self.driver.find_element(by=By.NAME, value="submit").click()

        self.assertEqual(1, len(self.driver.find_elements(by=By.TAG_NAME, value='div')),
                         "There should only be 1 DIV at this point, which is used for the butter message")
        self.driver.set_script_timeout(10)
        text = self.driver.execute_async_script(
            """var callback = arguments[arguments.length - 1];
            window.registerListener(arguments[arguments.length - 1]);""")
        self.assertEqual("bob", text)
        self.assertEqual("", typer.get_attribute("value"))

        self.assertEqual(2, len(self.driver.find_elements(by=By.TAG_NAME, value='div')),
                         "There should be 1 DIV (for the butter message) + 1 DIV (for the new label)")

    def testShouldBeAbleToPassMultipleArgumentsToAsyncScripts(self):
        self._loadPage("ajaxy_page")
        result = self.driver.execute_async_script("""
            arguments[arguments.length - 1](arguments[0] + arguments[1]);""", 1, 2)
        self.assertEqual(3, result)

    # TODO DavidBurns Disabled till Java WebServer is used
    # def testShouldBeAbleToMakeXMLHttpRequestsAndWaitForTheResponse(self):
    #    script = """
    #        var url = arguments[0];
    #        var callback = arguments[arguments.length - 1];
    #        // Adapted from http://www.quirksmode.org/js/xmlhttp.html
    #        var XMLHttpFactories = [
    #          function () return new XMLHttpRequest(),
    #          function () return new ActiveXObject('Msxml2.XMLHTTP'),
    #          function () return new ActiveXObject('Msxml3.XMLHTTP'),
    #          function () return new ActiveXObject('Microsoft.XMLHTTP')
    #        ];
    #        var xhr = false;
    #        while (!xhr && XMLHttpFactories.length)
    #          try{
    #            xhr = XMLHttpFactories.shift().call();
    #           }catch (e)
    #
    #        if (!xhr) throw Error('unable to create XHR object');
    #        xhr.open('GET', url, true);
    #        xhr.onreadystatechange = function()
    #          if (xhr.readyState == 4) callback(xhr.responseText);
    #
    #        xhr.send('');""" # empty string to stop firefox 3 from choking
    #
    #    self._loadPage("ajaxy_page")
    #    self.driver.set_script_timeout(3)
    #    response = self.driver.execute_async_script(script, pages.sleepingPage + "?time=2")
    #    htm = "<title>Done</title>Slept for 2s"
    #    self.assertTrue(response.strip() == htm)

    def _pageURL(self, name):
        return self.webserver.where_is(name + '.html')

    def _loadSimplePage(self):
        self._loadPage("simpleTest")

    def _loadPage(self, name):
        self.driver.get(self._pageURL(name))