text:
using System.Globalization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace Microsoft.AspNetCore.Rewrite.Tests.CodeRules;

public class MiddlewareTests
{
    [Fact]
    public async Task CheckRewritePath()
    {
        var options = new RewriteOptions().AddRewrite("(.*)", "http://example.com/$1", skipRemainingRules: false);
        using var host = new HostBuilder()
            .ConfigureWebHost(webHostBuilder =>
            {
                webHostBuilder
                .UseTestServer()
                .Configure(app =>
                {
                    app.UseRewriter(options);
                    app.Run(context => context.Response.WriteAsync(
                        context.Request.Scheme +
                        "://" +
                        context.Request.Host +
                        context.Request.Path +
                        context.Request.QueryString));
                });
            }).Build();

        await host.StartAsync();

        var server = host.GetTestServer();

        var response = await server.CreateClient().GetStringAsync("foo");

        Assert.Equal("http://example.com/foo", response);
    }

    [Fact]
    public async Task CheckRewritePathWithSkipRemaining()
    {
        var options = new RewriteOptions().AddRewrite("(.*)", "http://example.com/$1", skipRemainingRules: true);
        using var host = new HostBuilder()
            .ConfigureWebHost(webHostBuilder =>
            {
                webHostBuilder
                .UseTestServer()
                .Configure(app =>
                {
                    app.UseRewriter(options);
                    app.Run(context => context.Response.WriteAsync(
                        context.Request.Scheme +
                        "://" +
                        context.Request.Host +
                        context.Request.Path +
                        context.Request.QueryString));
                });
            }).Build();

        await host.StartAsync();

        var server = host.GetTestServer();

        var response = await server.CreateClient().GetStringAsync("foo");

        Assert.Equal("http://example.com/foo", response);
    }

    [Fact]
    public async Task CheckRewritePath_MultipleRulesWithSkipRemaining()
    {
        var options = new RewriteOptions()
            .AddRewrite("(.*)", "http://example.com/$1", skipRemainingRules: true)
            .AddRewrite("(.*)", "http://example.com/42", skipRemainingRules: false);
        using var host = new HostBuilder()
            .ConfigureWebHost(webHostBuilder =>
            {
                webHostBuilder
                .UseTestServer()
                .Configure(app =>
                {
                    app.UseRewriter(options);
                    app.Run(context => context.Response.WriteAsync(
                        context.Request.Scheme +
                        "://" +
                        context.Request.Host +
                        context.Request.Path +
                        context.Request.QueryString));
                });
            }).Build();

        await host.StartAsync();

        var server = host.GetTestServer();

        var response = await server.CreateClient().GetStringAsync("foo");

        Assert.Equal("http://example.com/foo", response);
    }

    [Fact]
    public async Task CheckRewritePath_MultipleRules()
    {
        var options = new RewriteOptions()
            .AddRewrite("(.*)", "http://example.com/$1s", skipRemainingRules: false)
            .AddRewrite("(.*)", "http://example.com/$1/42", skipRemainingRules: false);
        using var host = new HostBuilder()
            .ConfigureWebHost(webHostBuilder =>
            {
                webHostBuilder
                .UseTestServer()
                .Configure(app =>
                {
                    app.UseRewriter(options);
                    app.Run(context => context.Response.WriteAsync(
                        context.Request.Scheme +
                        "://" +
                        context.Request.Host +
                        context.Request.Path +
                        context.Request.QueryString));
                });
            }).Build();

        await host.StartAsync();

        var server = host.GetTestServer();

        var response = await server.CreateClient().GetStringAsync("foo");

        Assert.Equal("http://example.com/foos/42", response);
    }

    [Theory]
    [InlineData("(.*)", "http://example.com/$1", null, "path", "http://example.com/path")]
    [InlineData("(.*)", "http://example.com", null, "", "http://example.com/")]
    [InlineData("(z*)", "$1", null, "path", "/")]
    [InlineData("(z*)", "http://example.com/$1", null, "path", "http://example.com/")]
    [InlineData("(z*)", "$1", "http://example.com/pathBase", "/pathBase/path", "/pathBase")]
    [InlineData("path/(.*)", "path?value=$1", null, "path/value", "/path?value=value")]
    [InlineData("path/(.*)", "path?param=$1", null, "path/value?param1=OtherValue", "/path?param1=OtherValue&param=value")]
    [InlineData("path/(.*)", "http://example.com/pathBase/path?param=$1", "http://example.com/pathBase", "path/value?param1=OtherValue", "http://example.com/pathBase/path?param1=OtherValue&param=value")]
    [InlineData("path/(.*)", "http://hoψst.com/pÂthBase/path?parãm=$1", "http://example.com/pathBase", "path/value?päram1=OtherValüe", "http://xn--host-cpd.com/p%C3%82thBase/path?p%C3%A4ram1=OtherVal%C3%BCe&parãm=value")]
    public async Task CheckRedirectPath(string pattern, string replacement, string baseAddress, string requestUrl, string expectedUrl)
    {
        var options = new RewriteOptions().AddRedirect(pattern, replacement, statusCode: StatusCodes.Status301MovedPermanently);
        using var host = new HostBuilder()
            .ConfigureWebHost(webHostBuilder =>
            {
                webHostBuilder
                .UseTestServer()
                .Configure(app =>
                {
                    app.UseRewriter(options);
                });
            }).Build();

        await host.StartAsync();

        var server = host.GetTestServer();
        if (!string.IsNullOrEmpty(baseAddress))
        {
            server.BaseAddress = new Uri(baseAddress);
        }

        var response = await server.CreateClient().GetAsync(requestUrl);

        Assert.Equal(expectedUrl, response.Headers.Location.OriginalString);
    }

    [Fact]
    public async Task RewriteRulesCanComeFromConfigureOptions()
    {
        using var host = new HostBuilder()
            .ConfigureWebHost(webHostBuilder =>
            {
                webHostBuilder
                .UseTestServer()
                .ConfigureServices(services =>
                {
                    services.Configure<RewriteOptions>(options =>
                    {
                        options.AddRedirect("(.*)", "http://example.com/$1", statusCode: StatusCodes.Status301MovedPermanently);
                    });
                })
                .Configure(app =>
                {
                    app.UseRewriter();
                });
            }).Build();

        await host.StartAsync();

        var server = host.GetTestServer();

        var response = await server.CreateClient().GetAsync("foo");

        Assert.Equal("http://example.com/foo", response.Headers.Location.OriginalString);
    }

    [Fact]
    public async Task CheckRedirectPathWithQueryString()
    {
        var options = new RewriteOptions().AddRedirect("(.*)", "http://example.com/$1", statusCode: StatusCodes.Status301MovedPermanently);
        using var host = new HostBuilder()
            .ConfigureWebHost(webHostBuilder =>
            {
                webHostBuilder
                .UseTestServer()
                .Configure(app =>
                {
                    app.UseRewriter(options);
                });
            }).Build();

        await host.StartAsync();

        var server = host.GetTestServer();

        var response = await server.CreateClient().GetAsync("foo?bar=1");

        Assert.Equal("http://example.com/foo?bar=1", response.Headers.Location.OriginalString);
    }

    [Theory]
    [InlineData(StatusCodes.Status301MovedPermanently)]
    [InlineData(StatusCodes.Status302Found)]
    [InlineData(StatusCodes.Status307TemporaryRedirect)]
    [InlineData(StatusCodes.Status308PermanentRedirect)]
    public async Task CheckRedirectToHttpsStatus(int statusCode)
    {
        var options = new RewriteOptions().AddRedirectToHttps(statusCode: statusCode);
        using var host = new HostBuilder()
            .ConfigureWebHost(webHostBuilder =>
            {
                webHostBuilder
                .UseTestServer()
                .Configure(app =>
                {
                    app.UseRewriter(options);
                });
            }).Build();

        await host.StartAsync();

        var server = host.GetTestServer();

        var response = await server.CreateClient().GetAsync(new Uri("http://example.com"));

        Assert.Equal("https://example.com/", response.Headers.Location.OriginalString);
        Assert.Equal(statusCode, (int)response.StatusCode);
    }

    [Theory]
    [InlineData(null)]
    [InlineData(123)]
    public async Task CheckRedirectToHttpsSslPort(int? sslPort)
    {
        var options = new RewriteOptions().AddRedirectToHttps(statusCode: StatusCodes.Status302Found, sslPort: sslPort);
        using var host = new HostBuilder()
            .ConfigureWebHost(webHostBuilder =>
            {
                webHostBuilder
                .UseTestServer()
                .Configure(app =>
                {
                    app.UseRewriter(options);
                });
            }).Build();

        await host.StartAsync();

        var server = host.GetTestServer();

        var response = await server.CreateClient().GetAsync(new Uri("http://example.com"));

        if (sslPort.HasValue)
        {
            Assert.Equal($"https://example.com:{sslPort.GetValueOrDefault().ToString(CultureInfo.InvariantCulture)}/", response.Headers.Location.OriginalString);
        }
        else
        {
            Assert.Equal("https://example.com/", response.Headers.Location.OriginalString);
        }
    }

    [Theory]
    [InlineData(null, "example.com", "example.com/")]
    [InlineData(null, "example.com/path", "example.com/path")]
    [InlineData(null, "example.com/path?name=value", "example.com/path?name=value")]
    [InlineData(null, "hoψst.com", "xn--host-cpd.com/")]
    [InlineData(null, "hoψst.com/path", "xn--host-cpd.com/path")]
    [InlineData(null, "hoψst.com/path?name=value", "xn--host-cpd.com/path?name=value")]
    [InlineData(null, "example.com/pãth", "example.com/p%C3%A3th")]
    [InlineData(null, "example.com/path?näme=valüe", "example.com/path?n%C3%A4me=val%C3%BCe")]
    [InlineData("example.com/pathBase", "example.com/pathBase/path", "example.com/pathBase/path")]
    [InlineData("example.com/pathBase", "example.com/pathBase", "example.com/pathBase")]
    [InlineData("example.com/pâthBase", "example.com/pâthBase/path", "example.com/p%C3%A2thBase/path")]
    public async Task CheckRedirectToHttpsUrl(string baseAddress, string hostPathAndQuery, string expectedHostPathAndQuery)
    {
        var options = new RewriteOptions().AddRedirectToHttps();
        using var host = new HostBuilder()
            .ConfigureWebHost(webHostBuilder =>
            {
                webHostBuilder
                .UseTestServer()
                .Configure(app =>
                {
                    app.UseRewriter(options);
                });
            }).Build();

        await host.StartAsync();

        var server = host.GetTestServer();
        if (!string.IsNullOrEmpty(baseAddress))
        {
            server.BaseAddress = new Uri("http://" + baseAddress);
        }

        var response = await server.CreateClient().GetAsync(new Uri("http://" + hostPathAndQuery));

        Assert.Equal("https://" + expectedHostPathAndQuery, response.Headers.Location.OriginalString);
    }

    [Theory]
    [InlineData("http://example.com/test", "http://www.example.com/")]
    [InlineData("http://example.com/test", "https://www.example.com/")]
    [InlineData("https://example.com/test", "http://www.example.com/")]
    [InlineData("https://example.com/test", "https://www.example.com/")]
    public async Task CheckRedirectUsesConfiguredScheme(string hostSchemePathAndQuery, string redirectReplacement)
    {
        var options = new RewriteOptions().AddRedirect("test", redirectReplacement);
        using var host = new HostBuilder()
            .ConfigureWebHost(webHostBuilder =>
            {
                webHostBuilder
                .UseTestServer()
                .Configure(app =>
                {
                    app.UseRewriter(options);
                });
            }).Build();

        await host.StartAsync();

        var server = host.GetTestServer();
        server.BaseAddress = new Uri("http://example.com");
        var response = await server.CreateClient().GetAsync(new Uri(hostSchemePathAndQuery));

        // Regardless of whether we GET with http or https, the redirect should honor
        // the scheme specified in the configuration.
        Assert.Equal(redirectReplacement, response.Headers.Location.OriginalString);
    }

    [Fact]
    public async Task CheckPermanentRedirectToHttps()
    {
        var options = new RewriteOptions().AddRedirectToHttpsPermanent();
        using var host = new HostBuilder()
            .ConfigureWebHost(webHostBuilder =>
            {
                webHostBuilder
                .UseTestServer()
                .Configure(app =>
                {
                    app.UseRewriter(options);
                });
            }).Build();

        await host.StartAsync();

        var server = host.GetTestServer();

        var response = await server.CreateClient().GetAsync(new Uri("http://example.com"));

        Assert.Equal("https://example.com/", response.Headers.Location.OriginalString);
        Assert.Equal(StatusCodes.Status301MovedPermanently, (int)response.StatusCode);
    }

    [Theory]
    [InlineData(25, "https://example.com:25/")]
    [InlineData(-25, "https://example.com/")]
    public async Task CheckRedirectToHttpsWithSslPort(int sslPort, string expected)
    {
        var options = new RewriteOptions().AddRedirectToHttps(statusCode: StatusCodes.Status301MovedPermanently, sslPort: sslPort);
        using var host = new HostBuilder()
            .ConfigureWebHost(webHostBuilder =>
            {
                webHostBuilder
                .UseTestServer()
                .Configure(app =>
                {
                    app.UseRewriter(options);
                });
            }).Build();

        await host.StartAsync();

        var server = host.GetTestServer();

        var response = await server.CreateClient().GetAsync(new Uri("http://example.com"));

        Assert.Equal(expected, response.Headers.Location.OriginalString);
        Assert.Equal(StatusCodes.Status301MovedPermanently, (int)response.StatusCode);
    }

    [Theory]
    [InlineData(StatusCodes.Status301MovedPermanently)]
    [InlineData(StatusCodes.Status302Found)]
    [InlineData(StatusCodes.Status307TemporaryRedirect)]
    [InlineData(StatusCodes.Status308PermanentRedirect)]
    public async Task CheckRedirectToWwwWithStatusCode(int statusCode)
    {
        var options = new RewriteOptions().AddRedirectToWww(statusCode: statusCode);
        using var host = new HostBuilder()
            .ConfigureWebHost(webHostBuilder =>
            {
                webHostBuilder
                .UseTestServer()
                .Configure(app =>
                {
                    app.UseRewriter(options);
                });
            }).Build();

        await host.StartAsync();

        var server = host.GetTestServer();

        var response = await server.CreateClient().GetAsync(new Uri("https://example.com"));

        Assert.Equal("https://www.example.com/", response.Headers.Location.OriginalString);
        Assert.Equal(statusCode, (int)response.StatusCode);
    }

    [Theory]
    [InlineData("http://example.com", "http://www.example.com/")]
    [InlineData("https://example.com", "https://www.example.com/")]
    [InlineData("http://example.com:8081", "http://www.example.com:8081/")]
    [InlineData("http://example.com:8081/example?q=1", "http://www.example.com:8081/example?q=1")]
    public async Task CheckRedirectToWww(string requestUri, string redirectUri)
    {
        var options = new RewriteOptions().AddRedirectToWww();
        using var host = new HostBuilder()
            .ConfigureWebHost(webHostBuilder =>
            {
                webHostBuilder
                .UseTestServer()
                .Configure(app =>
                {
                    app.UseRewriter(options);
                });
            }).Build();

        await host.StartAsync();

        var server = host.GetTestServer();

        var response = await server.CreateClient().GetAsync(new Uri(requestUri));

        Assert.Equal(redirectUri, response.Headers.Location.OriginalString);
        Assert.Equal(StatusCodes.Status307TemporaryRedirect, (int)response.StatusCode);
    }

    [Fact]
    public async Task CheckPermanentRedirectToWww()
    {
        var options = new RewriteOptions().AddRedirectToWwwPermanent();
        using var host = new HostBuilder()
            .ConfigureWebHost(webHostBuilder =>
            {
                webHostBuilder
                .UseTestServer()
                .Configure(app =>
                {
                    app.UseRewriter(options);
                });
            }).Build();

        await host.StartAsync();

        var server = host.GetTestServer();

        var response = await server.CreateClient().GetAsync(new Uri("https://example.com"));

        Assert.Equal("https://www.example.com/", response.Headers.Location.OriginalString);
        Assert.Equal(StatusCodes.Status308PermanentRedirect, (int)response.StatusCode);
    }

    [Theory]
    [InlineData("http://www.example.com")]
    [InlineData("https://www.example.com")]
    [InlineData("http://www.example.com:8081")]
    [InlineData("https://www.example.com:8081")]
    [InlineData("https://www.example.com:8081/example?q=1")]
    [InlineData("http://localhost")]
    [InlineData("https://localhost")]
    [InlineData("http://localhost:8081")]
    [InlineData("https://localhost:8081")]
    [InlineData("https://localhost:8081/example?q=1")]
    public async Task CheckNoRedirectToWww(string requestUri)
    {
        var options = new RewriteOptions().AddRedirectToWww();
        using var host = new HostBuilder()
            .ConfigureWebHost(webHostBuilder =>
            {
                webHostBuilder
                .UseTestServer()
                .Configure(app =>
                {
                    app.UseRewriter(options);
                });
            }).Build();

        await host.StartAsync();

        var server = host.GetTestServer();

        var response = await server.CreateClient().GetAsync(new Uri(requestUri));

        Assert.Null(response.Headers.Location);
    }

    [Theory]
    [InlineData(StatusCodes.Status301MovedPermanently)]
    [InlineData(StatusCodes.Status302Found)]
    [InlineData(StatusCodes.Status307TemporaryRedirect)]
    [InlineData(StatusCodes.Status308PermanentRedirect)]
    public async Task CheckRedirectToNonWwwWithStatusCode(int statusCode)
    {
        var options = new RewriteOptions().AddRedirectToNonWww(statusCode: statusCode);
        using var host = new HostBuilder()
            .ConfigureWebHost(webHostBuilder =>
            {
                webHostBuilder
                .UseTestServer()
                .Configure(app =>
                {
                    app.UseRewriter(options);
                });
            }).Build();

        await host.StartAsync();

        var server = host.GetTestServer();

        var response = await server.CreateClient().GetAsync(new Uri("https://www.example.com"));

        Assert.Equal("https://example.com/", response.Headers.Location.OriginalString);
        Assert.Equal(statusCode, (int)response.StatusCode);
    }

    [Theory]
    [InlineData("http://www.example.com", "http://example.com/")]
    [InlineData("https://www.example.com", "https://example.com/")]
    [InlineData("http://www.example.com:8081", "http://example.com:8081/")]
    [InlineData("http://www.example.com:8081/example?q=1", "http://example.com:8081/example?q=1")]
    public async Task CheckRedirectToNonWww(string requestUri, string redirectUri)
    {
        var options = new RewriteOptions().AddRedirectToNonWww();
        using var host = new HostBuilder()
            .ConfigureWebHost(webHostBuilder =>
            {
                webHostBuilder
                .UseTestServer()
                .Configure(app =>
                {
                    app.UseRewriter(options);
                });
            }).Build();

        await host.StartAsync();

        var server = host.GetTestServer();

        var response = await server.CreateClient().GetAsync(new Uri(requestUri));

        Assert.Equal(redirectUri, response.Headers.Location.OriginalString);
        Assert.Equal(StatusCodes.Status307TemporaryRedirect, (int)response.StatusCode);
    }

    [Fact]
    public async Task CheckPermanentRedirectToNonWww()
    {
        var options = new RewriteOptions().AddRedirectToNonWwwPermanent();
        using var host = new HostBuilder()
            .ConfigureWebHost(webHostBuilder =>
            {
                webHostBuilder
                .UseTestServer()
                .Configure(app =>
                {
                    app.UseRewriter(options);
                });
            }).Build();

        await host.StartAsync();

        var server = host.GetTestServer();

        var response = await server.CreateClient().GetAsync(new Uri("https://www.example.com"));

        Assert.Equal("https://example.com/", response.Headers.Location.OriginalString);
        Assert.Equal(StatusCodes.Status308PermanentRedirect, (int)response.StatusCode);
    }

    [Fact]
    public async Task CheckIfEmptyStringRedirectCorrectly()
    {
        var options = new RewriteOptions().AddRedirect("(.*)", "$1", statusCode: StatusCodes.Status301MovedPermanently);
        using var host = new HostBuilder()
            .ConfigureWebHost(webHostBuilder =>
            {
                webHostBuilder
                .UseTestServer()
                .Configure(app =>
                {
                    app.UseRewriter(options);
                });
            }).Build();

        await host.StartAsync();

        var server = host.GetTestServer();

        var response = await server.CreateClient().GetAsync("");
        Assert.Equal("/", response.Headers.Location.OriginalString);
    }

    [Fact]
    public async Task RewriteAfterUseRoutingHitsOriginalEndpoint()
    {
        // This is an edge case where users setup routing incorrectly, but we don't want to accidentally change behavior in case someone
        // relies on it, so we have this test
        var options = new RewriteOptions().AddRewrite("(.*)", "$1s", skipRemainingRules: false);
        using var host = new HostBuilder()
            .ConfigureWebHost(webHostBuilder =>
            {
                webHostBuilder
                .UseTestServer()
                .ConfigureServices(s =>
                {
                    s.AddRouting();
                })
                .Configure(app =>
                {
                    app.UseRouting();
                    app.UseRewriter(options);

                    app.UseEndpoints(endpoints =>
                    {
                        endpoints.MapGet("/foos", context => context.Response.WriteAsync("bad"));
                        endpoints.MapGet("/foo", context => context.Response.WriteAsync($"{context.GetEndpoint()?.DisplayName} from {context.Request.Path}"));
                    });
                });
            }).Build();

        await host.StartAsync();

        var server = host.GetTestServer();

        var response = await server.CreateClient().GetStringAsync("foo");

        Assert.Equal("HTTP: GET /foo from /foos", response);
    }

    [Fact]
    public async Task CheckIfEmptyStringRewriteCorrectly()
    {
        var options = new RewriteOptions().AddRewrite("(.*)", "$1", skipRemainingRules: false);
        using var host = new HostBuilder()
            .ConfigureWebHost(webHostBuilder =>
            {
                webHostBuilder
                .UseTestServer()
                .Configure(app =>
                {
                    app.UseRewriter(options);
                    app.Run(context => context.Response.WriteAsync(
                            context.Request.Path +
                            context.Request.QueryString));
                });
            }).Build();

        await host.StartAsync();

        var server = host.GetTestServer();

        var response = await server.CreateClient().GetStringAsync("");

        Assert.Equal("/", response);
    }

    [Fact]
    public async Task SettingPathBase()
    {
        var options = new RewriteOptions().AddRedirect("(.*)", "$1");
        using var host = new HostBuilder()
            .ConfigureWebHost(webHostBuilder =>
            {
                webHostBuilder
                .UseTestServer()
                .Configure(app =>
                {
                    app.UseRewriter(options);
                    app.Run(context => context.Response.WriteAsync(
                            context.Request.Path +
                            context.Request.QueryString));
                });
            }).Build();

        await host.StartAsync();

        var server = host.GetTestServer();
        server.BaseAddress = new Uri("http://localhost:5000/foo");

        var response = await server.CreateClient().GetAsync("");

        Assert.Equal("/foo", response.Headers.Location.OriginalString);
    }

    [Theory]
    [InlineData("http://example.com")]
    [InlineData("https://example.com")]
    [InlineData("http://example.com:8081")]
    [InlineData("https://example.com:8081")]
    [InlineData("https://example.com:8081/example?q=1")]
    public async Task CheckNoRedirectToWwwInNonWhitelistedDomains(string requestUri)
    {
        var options = new RewriteOptions().AddRedirectToWww("example2.com");
        using var host = new HostBuilder()
            .ConfigureWebHost(webHostBuilder =>
            {
                webHostBuilder
                .UseTestServer()
                .Configure(app =>
                {
                    app.UseRewriter(options);
                });
            }).Build();

        await host.StartAsync();

        var server = host.GetTestServer();

        var response = await server.CreateClient().GetAsync(new Uri(requestUri));

        Assert.Null(response.Headers.Location);
    }

    [Theory]
    [InlineData("http://example.com/", "http://www.example.com/")]
    [InlineData("https://example.com/", "https://www.example.com/")]
    [InlineData("http://example.com:8081", "http://www.example.com:8081/")]
    [InlineData("http://example.com:8081/example?q=1", "http://www.example.com:8081/example?q=1")]
    public async Task CheckRedirectToWwwInWhitelistedDomains(string requestUri, string redirectUri)
    {
        var options = new RewriteOptions().AddRedirectToWww("example.com");
        using var host = new HostBuilder()
            .ConfigureWebHost(webHostBuilder =>
            {
                webHostBuilder
                .UseTestServer()
                .Configure(app =>
                {
                    app.UseRewriter(options);
                });
            }).Build();

        await host.StartAsync();

        var server = host.GetTestServer();

        var response = await server.CreateClient().GetAsync(new Uri(requestUri));

        Assert.Equal(redirectUri, response.Headers.Location.OriginalString);
        Assert.Equal(StatusCodes.Status307TemporaryRedirect, (int)response.StatusCode);
    }

    [Fact]
    public async Task CheckPermanentRedirectToWwwInWhitelistedDomains()
    {
        var options = new RewriteOptions().AddRedirectToWwwPermanent("example.com");
        using var host = new HostBuilder()
            .ConfigureWebHost(webHostBuilder =>
            {
                webHostBuilder
                .UseTestServer()
                .Configure(app =>
                {
                    app.UseRewriter(options);
                });
            }).Build();

        await host.StartAsync();

        var server = host.GetTestServer();

        var response = await server.CreateClient().GetAsync(new Uri("https://example.com"));

        Assert.Equal("https://www.example.com/", response.Headers.Location.OriginalString);
        Assert.Equal(StatusCodes.Status308PermanentRedirect, (int)response.StatusCode);
    }

    [Theory]
    [InlineData(StatusCodes.Status301MovedPermanently)]
    [InlineData(StatusCodes.Status302Found)]
    [InlineData(StatusCodes.Status307TemporaryRedirect)]
    [InlineData(StatusCodes.Status308PermanentRedirect)]
    public async Task CheckRedirectToWwwWithStatusCodeInWhitelistedDomains(int statusCode)
    {
        var options = new RewriteOptions().AddRedirectToWww(statusCode: statusCode, "example.com");
        using var host = new HostBuilder()
            .ConfigureWebHost(webHostBuilder =>
            {
                webHostBuilder
                .UseTestServer()
                .Configure(app =>
                {
                    app.UseRewriter(options);
                });
            }).Build();

        await host.StartAsync();

        var server = host.GetTestServer();

        var response = await server.CreateClient().GetAsync(new Uri("https://example.com"));

        Assert.Equal("https://www.example.com/", response.Headers.Location.OriginalString);
        Assert.Equal(statusCode, (int)response.StatusCode);
    }

    [Theory]
    [InlineData("(.*)", "http://example.com/g")]
    [InlineData("/", "no rule")]
    public async Task Rewrite_WorksAfterUseRoutingIfGlobalRouteBuilderUsed(string regex, string output)
    {
        var options = new RewriteOptions().AddRewrite(regex, "http://example.com/g", skipRemainingRules: false);
        var builder = WebApplication.CreateBuilder();
        builder.WebHost.UseTestServer();
        await using var app = builder.Build();

        app.UseRouting();

        app.UseRewriter(options);

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapGet("/foo", context => context.Response.WriteAsync(
                "no rule"));

            endpoints.MapGet("/g", context => context.Response.WriteAsync(
                context.Request.Scheme +
                "://" +
                context.Request.Host +
                context.Request.Path +
                context.Request.QueryString));
        });

        await app.StartAsync();

        var server = app.GetTestServer();

        var response = await server.CreateClient().GetStringAsync("foo");

        Assert.Equal(output, response);
    }

    [Theory]
    [InlineData("(.*)", "http://example.com/g")]
    [InlineData("/", "no rule")]
    public async Task RewriteFromOptions_WorksAfterUseRoutingIfGlobalRouteBuilderUsed(string regex, string output)
    {
        var builder = WebApplication.CreateBuilder();
        builder.WebHost.UseTestServer();
        builder.Services.Configure<RewriteOptions>(options =>
        {
            options.AddRewrite(regex, "http://example.com/g", skipRemainingRules: false);
        });
        await using var app = builder.Build();

        app.UseRouting();
        app.UseRewriter();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapGet("/foo", context => context.Response.WriteAsync(
                "no rule"));

            endpoints.MapGet("/g", context => context.Response.WriteAsync(
                context.Request.Scheme +
                "://" +
                context.Request.Host +
                context.Request.Path +
                context.Request.QueryString));
        });

        await app.StartAsync();

        var server = app.GetTestServer();

        var response = await server.CreateClient().GetStringAsync("foo");

        Assert.Equal(output, response);
    }

    [Fact]
    public async Task RewriteSkipRemaing_WorksAfterUseRoutingIfGlobalRouteBuilderUsed()
    {
        var builder = WebApplication.CreateBuilder();
        builder.WebHost.UseTestServer();
        builder.Services.Configure<RewriteOptions>(options =>
        {
            options.AddRewrite("(.*)", "http://example.com/g", skipRemainingRules: true);
        });
        await using var app = builder.Build();
        app.UseRouting();

        app.UseRewriter();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapGet("/foo", context => context.Response.WriteAsync(
                "no rule"));

            endpoints.MapGet("/g", context => context.Response.WriteAsync(
                context.Request.Scheme +
                "://" +
                context.Request.Host +
                context.Request.Path +
                context.Request.QueryString));
        });

        await app.StartAsync();

        var server = app.GetTestServer();

        var response = await server.CreateClient().GetStringAsync("foo");

        Assert.Equal("http://example.com/g", response);
    }

    [Fact]
    public async Task RewriteWithMultipleRules_WorksAfterUseRoutingIfGlobalRouteBuilderUsed()
    {
        var builder = WebApplication.CreateBuilder();
        builder.WebHost.UseTestServer();
        builder.Services.Configure<RewriteOptions>(options =>
        {
            options.AddRewrite("(.*)", "http://example.com/g", skipRemainingRules: false)
                .AddRewrite("(.*)", "http://example.com/$1/h", skipRemainingRules: false);
        });
        await using var app = builder.Build();
        app.UseRouting();

        app.UseRewriter();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapGet("/foo", context => context.Response.WriteAsync(
                "no rule"));

            endpoints.MapGet("/g/h", context => context.Response.WriteAsync(
                context.Request.Scheme +
                "://" +
                context.Request.Host +
                context.Request.Path +
                context.Request.QueryString));
        });

        await app.StartAsync();

        var server = app.GetTestServer();

        var response = await server.CreateClient().GetStringAsync("foo");

        Assert.Equal("http://example.com/g/h", response);
    }

    [Fact]
    public async Task RewriteWithMultipleRulesAndSkip_WorksAfterUseRoutingIfGlobalRouteBuilderUsed()
    {
        var builder = WebApplication.CreateBuilder();
        builder.WebHost.UseTestServer();
        builder.Services.Configure<RewriteOptions>(options =>
        {
            options.AddRewrite("(.*)", "http://example.com/g", skipRemainingRules: true)
                .AddRewrite("(.*)", "http://example.com/$1/h", skipRemainingRules: false);
        });
        await using var app = builder.Build();
        app.UseRouting();

        app.UseRewriter();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapGet("/foo", context => context.Response.WriteAsync(
                "no rule"));

            endpoints.MapGet("/g", context => context.Response.WriteAsync(
                context.Request.Scheme +
                "://" +
                context.Request.Host +
                context.Request.Path +
                context.Request.QueryString));
        });

        await app.StartAsync();

        var server = app.GetTestServer();

        var response = await server.CreateClient().GetStringAsync("foo");

        Assert.Equal("http://example.com/g", response);
    }

    [Fact]
    public async Task Rewrite_WorksWithoutUseRoutingWithWebApplication()
    {
        var builder = WebApplication.CreateBuilder();
        builder.WebHost.UseTestServer();
        builder.Services.Configure<RewriteOptions>(options =>
        {
            options.AddRewrite("(.*)", "http://example.com/g", skipRemainingRules: true);
        });
        await using var app = builder.Build();

        app.UseRewriter();

        app.MapGet("/foo", context => context.Response.WriteAsync(
            "no rule"));

        app.MapGet("/g", context => context.Response.WriteAsync(
            context.Request.Scheme +
            "://" +
            context.Request.Host +
            context.Request.Path +
            context.Request.QueryString));

        await app.StartAsync();

        var server = app.GetTestServer();

        var response = await server.CreateClient().GetStringAsync("foo");

        Assert.Equal("http://example.com/g", response);
    }
}


text:
Python control for Eufy LED bulbs
=================================

A simple Python API for controlling LED bulbs from [Eufy](https://www.eufylife.com/).

Example use
-----------

This will connect to a bulb and turn it on at 50% brightness and the coldest colour temperature.
```
import lakeside

bulb = lakeside.bulb(ip_address, access_code, type)
bulb.connect()
bulb.set_state(power=True, brightness=50, temperature=100)
```

The ip, access code and type can be obtained by doing:

```
import lakeside

devices = lakeside.get_devices(username, password)
```

where username and password are the credentials used in the Eufy app.

This is not an officially supported Google project.

redpajama_set_name: RedPajamaGithub


text:
/* prng.h -- Pseudo Random Numbers
 *
 * Copyright (C) 2010,2011 Olaf Bergmann <bergmann@tzi.org>
 *
 * This file is part of the CoAP library libcoap. Please see
 * README for terms of use.
 */

/**
 * @file protocols/libcoap/prng.h
 * @brief Pseudo Random Numbers
 */

#ifndef _COAP_PRNG_H_
#define _COAP_PRNG_H_

#include <protocols/libcoap/config.h>

/**
 * @defgroup prng Pseudo Random Numbers
 * @{
 */

#ifndef WITH_CONTIKI
#include <stdlib.h>

/**
 * Fills \p buf with \p len random bytes. This is the default
 * implementation for prng().  You might want to change prng() to use
 * a better PRNG on your specific platform.
 */
static inline int coap_prng_impl(unsigned char *buf, size_t len)
{
	while (len--) {
		*buf++ = rand() & 0xFF;
	}
	return 1;
}
#else							/* WITH_CONTIKI */
#include <string.h>

/**
 * Fills \p buf with \p len random bytes. This is the default
 * implementation for prng().  You might want to change prng() to use
 * a better PRNG on your specific platform.
 */
static inline int contiki_prng_impl(unsigned char *buf, size_t len)
{
	unsigned short v = random_rand();
	while (len > sizeof(v)) {
		memcpy(buf, &v, sizeof(v));
		len -= sizeof(v);
		buf += sizeof(v);
		v = random_rand();
	}

	memcpy(buf, &v, len);
	return 1;
}

#define prng(Buf,Length) contiki_prng_impl((Buf), (Length))
#define prng_init(Value) random_init((unsigned short)(Value))
#endif							/* WITH_CONTIKI */

#ifndef prng
/**
 * Fills \p Buf with \p Length bytes of random data.
 *
 * @hideinitializer
 */
#define prng(Buf,Length) coap_prng_impl((Buf), (Length))
#endif

#ifndef prng_init
/**
 * Called to set the PRNG seed. You may want to re-define this to
 * allow for a better PRNG.
 *
 * @hideinitializer
 */
#define prng_init(Value) srand((unsigned long)(Value))
#endif

/** @} */

#endif							/* _COAP_PRNG_H_ */


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

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>com.squareup.moshi</groupId>
    <artifactId>moshi-parent</artifactId>
    <version>1.1.0-SNAPSHOT</version>
  </parent>

  <artifactId>moshi</artifactId>
  <name>Moshi</name>

  <dependencies>
    <dependency>
      <groupId>com.squareup.okio</groupId>
      <artifactId>okio</artifactId>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.assertj</groupId>
      <artifactId>assertj-core</artifactId>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>


text:
//
// MODULE: sqlInterface.h
//
// PURPOSE: function prototype for sqlInterface.cpp
//
//
 /*Change Log
 * Methods Changed: Removed setOfCQD
 */

#ifndef _SQLINTERFACE_DEFINED
#define _SQLINTERFACE_DEFINED
#include "CDesc.h"
#include "CSrvrConnect.h"

extern SQLRETURN AllocAssignValueBuffer(SQLItemDescList_def *SQLDesc,  SQLValueList_def *SQLValueList,
										long totalMemLen, 	long maxRowCount, BYTE *&VarBuffer);
extern SQLRETURN CopyValueList(SQLValueList_def *outValueList, const SQLValueList_def *inValueList);

extern SQLRETURN EXECUTE(SRVR_STMT_HDL* pSrvrStmt);

extern SQLRETURN FREESTATEMENT(SRVR_STMT_HDL* pSrvrStmt);

extern SQLRETURN PREPARE(SRVR_STMT_HDL* pSrvrStmt);

extern SQLRETURN FETCH(SRVR_STMT_HDL *pSrvrStmt);

extern SQLRETURN GETSQLERROR(SRVR_STMT_HDL *pSrvrStmt,
							 odbc_SQLSvc_SQLError *SQLError);

extern SQLRETURN EXECDIRECT(SRVR_STMT_HDL* pSrvrStmt);

extern SQLRETURN EXECUTESPJRS(SRVR_STMT_HDL* pSrvrStmt);

extern SQLRETURN GETSQLWARNING(SRVR_STMT_HDL *pSrvrStmt,
							   ERROR_DESC_LIST_def *sqlWarning);

extern SQLRETURN CANCEL(SRVR_STMT_HDL *pSrvrStmt);

extern SQLRETURN CLEARDIAGNOSTICS(SRVR_STMT_HDL *pSrvrStmt);

extern SQLRETURN ALLOCSQLMXHDLS(SRVR_STMT_HDL *pSrvrStmt);

extern SQLRETURN ALLOCSQLMXHDLS_SPJRS(SRVR_STMT_HDL *pSrvrStmt, SQLSTMT_ID *callpStmt, const char *RSstmtName);

extern SQLRETURN EXECUTECALL(SRVR_STMT_HDL *pSrvrStmt);

extern SQLRETURN CONNECT(SRVR_CONNECT_HDL *pSrvrConnect);

extern SQLRETURN DISCONNECT(SRVR_CONNECT_HDL *pSrvrConnect);

extern SQLRETURN SWITCHCONTEXT(SRVR_CONNECT_HDL *pSrvrConnect, long *sqlcode);

extern SQLRETURN GETSQLCODE(SRVR_STMT_HDL *pSrvrStmt);

SQLRETURN SET_DATA_PTR(SRVR_STMT_HDL *pSrvrStmt, SRVR_STMT_HDL::DESC_TYPE descType);

SQLRETURN _SQL_WaitCloseOnErr (SRVR_STMT_HDL *pSrvrStmt, long int *retcode );

SQLRETURN _SQL_Wait (SRVR_STMT_HDL *pSrvrStmt, long int *retcode );

#endif


text:
eQEP Device Tree Overlays
=========================

The device tree has existed in the kernel for a few years now to aid in creating drivers for new hardware, but allowing new devices to reuse all existing code.  In the ARM space, they were practically ignored.  With the surge of new ARM boards coming out, every vendor had a branch of the kernel dedicated to their board.  Linus Torvalds decided enough was enough and demanded that the ARM people adopt the device tree to keep the influx of changes to the kernel at a sane level.

Starting with kernel 3.8, ARM Linux uses the device tree and makes use of device tree overlays.  These are loaded in runtime to augment to configuration of a board while the kernel is booted.  This makes configuration of IO more friendly because you don't have to recompile your board's base overlay. Since overlays are applied during runtime, you don't have to reboot either.  Three device tree overlays have been provided, one each for eQEP0, eQEP1, and eQEP2.

Device trees and device tree overlays have become the standard for the Linux kernel, therefore the driver depends on the device tree, requiring kernel 3.8+ to be used, which is available out of the box with Angstrom, Debian, Ubuntu, and others.

eQEP driver configuration
-------------------------
Each device tree overlay contains a few settings for configuring the eQEP hardware.  If any of these fields are not specified, the driver falls back on the default value for that field.

__count_mode__ - Sets the counting mode of the eQEP unit.  Mode 0 (default) is for standard quadrature encoder pulse train. see (http://en.wikipedia.org/wiki/File:Quadrature_Diagram.svg).  Mode 1 is a bit more rare.  The encoder produces a clock and a direction signal.  eQEPx_chA becomes the encoder clock input and eQEPx_chb becomes the direction input.

__swap_inputs__ - Setting to zero (default) has no effect on the inputs.  Setting to 1 causes the eQEP hardware to switch the channel a and b inputs

__invert_qa__ - Setting to zero (default) has no effect on the input.  Setting to 1 inverts the channel a input

__invert_qb__ - Setting to zero (default) has no effect on the input.  Setting to 1 inverts the channel b input

__invert_qi__ - Setting to zero (default) has no effect on the input.  Setting to 1 inverts the index signal input

__invert_qs__ - Setting to zero (default) has no effect on the input.  Setting to 1 inverts the strobe signal input

Note on index and strobe inputs: At the moment, the driver does not provide any support for them.  They each can be used for two purposes.  Both inputs support latching the position to an internal register on the rising or falling edge of the input signal and both provide an option to reset the position counter when they are triggered as well.  TI mentions that this is useful because some encoders that are used for position sensing provide an index output, which is triggered once per complete rotation of the encoder.  At the moment, I have offered no support for these inputs.  If this becomes something that the community desires, by all means shoot me a message and i'll work on it.

Loading a Device Tree Overlay
-------------------------------------------

The dtbo/ sub directory contains several precompiled device tree overlays.  They are the compiled versions of the .dts files in this directory.  The dts files are human-readable and if the settings are not what your application requires, read the "Compiling a Device Tree Overlay" section

Copy the bone_eqepX-00A0.dtbo files to the /lib/firmware directory on the beaglebone.  To load a device tree overlay, for instance eqep1

```bash
echo bone_eqep1 > /sys/devices/bone_capemgr.*/slots
```

The eQEP driver will now load for eQEP 1 and the sysfs interface will be registered.

You can now proceed over to the api/ folder and try out some demos of the driver

Compiling a Device Tree Overlay
-------------------------------------------

First you need to fetch a version of the device tree compiler that supports overlays.  The current Ubuntu and Debian device-tree-compiler packages do not support this.  The following script only works on Debian and its derived distributions, such as Ubuntu.

```bash
wget -c https://raw.github.com/RobertCNelson/tools/master/pkgs/dtc.sh
chmod +x dtc.sh
./dtc.sh
```

To compile one of the provided device tree overlays, for instance bone_eqep1

```bash
dtc -O dtb -o bone_eqep1-00A0.dtbo -b 0 -@ bone_eqep1.dts
```


text:
#ifndef AppAuth_Bridging_Header_h
#define AppAuth_Bridging_Header_h

#import "AppAuth.h"

#endif /* AppAuth_Bridging_Header_h */


text:
package polymorphichelpers

import (
	"fmt"
	"sort"
	"time"

	appsv1 "k8s.io/api/apps/v1"
	appsv1beta1 "k8s.io/api/apps/v1beta1"
	appsv1beta2 "k8s.io/api/apps/v1beta2"
	batchv1 "k8s.io/api/batch/v1"
	"k8s.io/api/core/v1"
	corev1 "k8s.io/api/core/v1"
	extensionsv1beta1 "k8s.io/api/extensions/v1beta1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/labels"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/watch"
	"k8s.io/kubernetes/pkg/apis/apps"
	"k8s.io/kubernetes/pkg/apis/batch"
	api "k8s.io/kubernetes/pkg/apis/core"
	apiv1 "k8s.io/kubernetes/pkg/apis/core/v1"
	"k8s.io/kubernetes/pkg/apis/extensions"
	coreclient "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/internalversion"
)

// GetFirstPod returns a pod matching the namespace and label selector
// and the number of all pods that match the label selector.
func GetFirstPod(client coreclient.PodsGetter, namespace string, selector string, timeout time.Duration, sortBy func([]*v1.Pod) sort.Interface) (*api.Pod, int, error) {
	options := metav1.ListOptions{LabelSelector: selector}

	podList, err := client.Pods(namespace).List(options)
	if err != nil {
		return nil, 0, err
	}
	pods := []*v1.Pod{}
	for i := range podList.Items {
		pod := podList.Items[i]
		externalPod := &v1.Pod{}
		apiv1.Convert_core_Pod_To_v1_Pod(&pod, externalPod, nil)
		pods = append(pods, externalPod)
	}
	if len(pods) > 0 {
		sort.Sort(sortBy(pods))
		internalPod := &api.Pod{}
		apiv1.Convert_v1_Pod_To_core_Pod(pods[0], internalPod, nil)
		return internalPod, len(podList.Items), nil
	}

	// Watch until we observe a pod
	options.ResourceVersion = podList.ResourceVersion
	w, err := client.Pods(namespace).Watch(options)
	if err != nil {
		return nil, 0, err
	}
	defer w.Stop()

	condition := func(event watch.Event) (bool, error) {
		return event.Type == watch.Added || event.Type == watch.Modified, nil
	}
	event, err := watch.Until(timeout, w, condition)
	if err != nil {
		return nil, 0, err
	}
	pod, ok := event.Object.(*api.Pod)
	if !ok {
		return nil, 0, fmt.Errorf("%#v is not a pod event", event)
	}
	return pod, 1, nil
}

// SelectorsForObject returns the pod label selector for a given object
func SelectorsForObject(object runtime.Object) (namespace string, selector labels.Selector, err error) {
	switch t := object.(type) {
	case *extensions.ReplicaSet:
		namespace = t.Namespace
		selector, err = metav1.LabelSelectorAsSelector(t.Spec.Selector)
		if err != nil {
			return "", nil, fmt.Errorf("invalid label selector: %v", err)
		}
	case *extensionsv1beta1.ReplicaSet:
		namespace = t.Namespace
		selector, err = metav1.LabelSelectorAsSelector(t.Spec.Selector)
		if err != nil {
			return "", nil, fmt.Errorf("invalid label selector: %v", err)
		}
	case *appsv1.ReplicaSet:
		namespace = t.Namespace
		selector, err = metav1.LabelSelectorAsSelector(t.Spec.Selector)
		if err != nil {
			return "", nil, fmt.Errorf("invalid label selector: %v", err)
		}
	case *appsv1beta2.ReplicaSet:
		namespace = t.Namespace
		selector, err = metav1.LabelSelectorAsSelector(t.Spec.Selector)
		if err != nil {
			return "", nil, fmt.Errorf("invalid label selector: %v", err)
		}

	case *api.ReplicationController:
		namespace = t.Namespace
		selector = labels.SelectorFromSet(t.Spec.Selector)
	case *corev1.ReplicationController:
		namespace = t.Namespace
		selector = labels.SelectorFromSet(t.Spec.Selector)

	case *apps.StatefulSet:
		namespace = t.Namespace
		selector, err = metav1.LabelSelectorAsSelector(t.Spec.Selector)
		if err != nil {
			return "", nil, fmt.Errorf("invalid label selector: %v", err)
		}
	case *appsv1.StatefulSet:
		namespace = t.Namespace
		selector, err = metav1.LabelSelectorAsSelector(t.Spec.Selector)
		if err != nil {
			return "", nil, fmt.Errorf("invalid label selector: %v", err)
		}
	case *appsv1beta1.StatefulSet:
		namespace = t.Namespace
		selector, err = metav1.LabelSelectorAsSelector(t.Spec.Selector)
		if err != nil {
			return "", nil, fmt.Errorf("invalid label selector: %v", err)
		}
	case *appsv1beta2.StatefulSet:
		namespace = t.Namespace
		selector, err = metav1.LabelSelectorAsSelector(t.Spec.Selector)
		if err != nil {
			return "", nil, fmt.Errorf("invalid label selector: %v", err)
		}

	case *extensions.DaemonSet:
		namespace = t.Namespace
		selector, err = metav1.LabelSelectorAsSelector(t.Spec.Selector)
		if err != nil {
			return "", nil, fmt.Errorf("invalid label selector: %v", err)
		}
	case *extensionsv1beta1.DaemonSet:
		namespace = t.Namespace
		selector, err = metav1.LabelSelectorAsSelector(t.Spec.Selector)
		if err != nil {
			return "", nil, fmt.Errorf("invalid label selector: %v", err)
		}
	case *appsv1.DaemonSet:
		namespace = t.Namespace
		selector, err = metav1.LabelSelectorAsSelector(t.Spec.Selector)
		if err != nil {
			return "", nil, fmt.Errorf("invalid label selector: %v", err)
		}
	case *appsv1beta2.DaemonSet:
		namespace = t.Namespace
		selector, err = metav1.LabelSelectorAsSelector(t.Spec.Selector)
		if err != nil {
			return "", nil, fmt.Errorf("invalid label selector: %v", err)
		}

	case *extensions.Deployment:
		namespace = t.Namespace
		selector, err = metav1.LabelSelectorAsSelector(t.Spec.Selector)
		if err != nil {
			return "", nil, fmt.Errorf("invalid label selector: %v", err)
		}
	case *extensionsv1beta1.Deployment:
		namespace = t.Namespace
		selector, err = metav1.LabelSelectorAsSelector(t.Spec.Selector)
		if err != nil {
			return "", nil, fmt.Errorf("invalid label selector: %v", err)
		}
	case *appsv1.Deployment:
		namespace = t.Namespace
		selector, err = metav1.LabelSelectorAsSelector(t.Spec.Selector)
		if err != nil {
			return "", nil, fmt.Errorf("invalid label selector: %v", err)
		}
	case *appsv1beta1.Deployment:
		namespace = t.Namespace
		selector, err = metav1.LabelSelectorAsSelector(t.Spec.Selector)
		if err != nil {
			return "", nil, fmt.Errorf("invalid label selector: %v", err)
		}
	case *appsv1beta2.Deployment:
		namespace = t.Namespace
		selector, err = metav1.LabelSelectorAsSelector(t.Spec.Selector)
		if err != nil {
			return "", nil, fmt.Errorf("invalid label selector: %v", err)
		}

	case *batch.Job:
		namespace = t.Namespace
		selector, err = metav1.LabelSelectorAsSelector(t.Spec.Selector)
		if err != nil {
			return "", nil, fmt.Errorf("invalid label selector: %v", err)
		}
	case *batchv1.Job:
		namespace = t.Namespace
		selector, err = metav1.LabelSelectorAsSelector(t.Spec.Selector)
		if err != nil {
			return "", nil, fmt.Errorf("invalid label selector: %v", err)
		}

	case *api.Service:
		namespace = t.Namespace
		if t.Spec.Selector == nil || len(t.Spec.Selector) == 0 {
			return "", nil, fmt.Errorf("invalid service '%s': Service is defined without a selector", t.Name)
		}
		selector = labels.SelectorFromSet(t.Spec.Selector)
	case *corev1.Service:
		namespace = t.Namespace
		if t.Spec.Selector == nil || len(t.Spec.Selector) == 0 {
			return "", nil, fmt.Errorf("invalid service '%s': Service is defined without a selector", t.Name)
		}
		selector = labels.SelectorFromSet(t.Spec.Selector)

	default:
		return "", nil, fmt.Errorf("selector for %T not implemented", object)
	}

	return namespace, selector, nil
}


text:
#include "absl/container/flat_hash_map.h"

#ifndef TENSORFLOW_COMPILER_XLA_SERVICE_GPU_KERNEL_THUNK_H_
#define TENSORFLOW_COMPILER_XLA_SERVICE_GPU_KERNEL_THUNK_H_

#include <memory>
#include <string>
#include <vector>

#include "absl/types/span.h"
#include "tensorflow/compiler/xla/service/buffer_assignment.h"
#include "tensorflow/compiler/xla/service/gpu/buffer_allocations.h"
#include "tensorflow/compiler/xla/service/gpu/launch_dimensions.h"
#include "tensorflow/compiler/xla/service/gpu/thunk.h"
#include "tensorflow/compiler/xla/service/hlo_instruction.h"
#include "tensorflow/compiler/xla/stream_executor/stream_executor.h"
#include "tensorflow/compiler/xla/types.h"

namespace xla {
namespace gpu {

class GpuExecutable;

// This class stores everything that StreamExecutor needs for launching a
// kernel. It implements the ExecuteOnStream interface for GpuExecutable to
// invoke the corresponding kernel.
//
// This is thread-compatible.
class KernelThunk : public Thunk {
 public:
  // Constructs a thunk for the given kernel.
  //
  // `hlo_instruction` is as in Thunk. Other arguments are as the class members.
  KernelThunk(ThunkInfo thunk_info,
              absl::Span<const BufferAllocation* const> args,
              const std::string& kernel_name,
              const LaunchDimensions& launch_dimensions,
              std::vector<mlir::Value> values);
  KernelThunk(const KernelThunk&) = delete;
  KernelThunk& operator=(const KernelThunk&) = delete;
  ~KernelThunk() override = default;

  std::string ToStringExtra(int indent) const override;

  Status Initialize(const GpuExecutable& executable,
                    se::StreamExecutor* executor) override;
  Status ExecuteOnStream(const ExecuteParams& params) override;

  void ClearCompileTimeInfo() override {
    Thunk::ClearCompileTimeInfo();
    for (auto& value : values_) {
      value = nullptr;
    }
  }

  const std::vector<const BufferAllocation*>& arguments() const {
    return args_;
  }
  const std::string& kernel_name() const { return kernel_name_; }
  const LaunchDimensions& launch_dimensions() const {
    return launch_dimensions_;
  }
  absl::Span<const mlir::Value> values() const { return values_; }

 private:
  // Buffers passed to the kernel as arguments.
  const std::vector<const BufferAllocation*> args_;

  // Entry kernel name for the computation.
  const std::string kernel_name_;

  // The thread and block dimension used to launch the kernel.
  const LaunchDimensions launch_dimensions_;

  // mlir::Value(s) corresponding to the buffer allocation arguments.
  std::vector<mlir::Value> values_;

  mutable absl::Mutex mutex_;

  // Loaded kernels for each `StreamExecutor`.  Requires pointer stability of
  // values.
  absl::flat_hash_map<se::StreamExecutor*, std::unique_ptr<se::KernelBase>>
      kernel_cache_ ABSL_GUARDED_BY(mutex_);
};

}  // namespace gpu
}  // namespace xla

#endif  // TENSORFLOW_COMPILER_XLA_SERVICE_GPU_KERNEL_THUNK_H_


text:
package gui.components.resources;

import ddiff.ProgressMessager;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Font;

import javax.swing.BorderFactory;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRootPane;
import javax.swing.SwingConstants;
import javax.swing.border.BevelBorder;

/**
 * Splash screen used in long operations to inform the user about progress.
 */
public class SplashScreen extends JDialog implements ProgressMessager {

    private static final long serialVersionUID = 1L;

    static void close() {
        SplashScreen.close();
    }
    /**
     * Message of current ArchTrace status
     */
    JLabel statusLabel;
    /**
     * Message of current memory usage
     */
    JLabel memoryLabel;

    /**
     * Construct a modal splash screen
     */
    public SplashScreen(JFrame owner) {
        super(owner, true);
        this.setLocationRelativeTo(owner);
        this.init();
    }

    /**
     * Construct a non-modal splash screen
     */
    public SplashScreen() {
        super();
        this.init();
    }

    /**
     * Create/Configure the splash screen
     */
    private void init() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(BorderFactory.createEtchedBorder());
        panel.setBackground(new Color(245, 245, 245));

        memoryLabel = new JLabel();
        memoryLabel.setHorizontalAlignment(SwingConstants.RIGHT);
        panel.add(memoryLabel, BorderLayout.NORTH);

        JLabel mainLabel = new JLabel("IDIFF", SwingConstants.CENTER);
        mainLabel.setFont(new Font("SansSerif", Font.PLAIN, 72));
        panel.add(mainLabel, BorderLayout.CENTER);

        statusLabel = new JLabel();
        statusLabel.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));
        panel.add(statusLabel, BorderLayout.SOUTH);

        this.setUndecorated(true);
        this.setContentPane(panel);
        this.setSize(400, 200);
        this.setLocationRelativeTo(null);
        this.getRootPane().setWindowDecorationStyle(JRootPane.NONE);
    }

    /**
     * Write a new status message
     * @param message
     */
    public void setStatus(String message) {
        statusLabel.setText(message);
        updateMemory();
    }

    /**
     * Update the memory message
     */
    public void updateMemory() {
        long memory = Runtime.getRuntime().totalMemory();
        memoryLabel.setText("Memory used: " + Long.toString(Math.round(memory / Math.pow(2, 20))) + " MB");
    }

    /**
     * @param message
     * @see edu.uci.ics.archtrace.connectors.ConnectionListener#connectionStarted(java.lang.String)
     */
    public void connectionStarted(String message) {
        setStatus(message);
    }

    /**
     * @param message
     * @see edu.uci.ics.archtrace.connectors.ConnectionListener#connectionProgress(java.lang.String)
     */
    public void connectionProgress(String message) {
        setStatus(message);
    }

    /**
     * @param message
     * @see edu.uci.ics.archtrace.connectors.ConnectionListener#connectionFinished(java.lang.String)
     */
    public void connectionFinished(String message) {
        setStatus(message);
    }

    /**
     * @param visible
     * @see java.awt.Component#setVisible(boolean)
     */
    @Override
    public void setVisible(boolean visible) {
        this.setLocationRelativeTo(this.getOwner());
        this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        super.setVisible(visible);
    }

    @Override
    public void setMessage(String message) {
        setStatus(message);
        System.out.println(message);
    }
}


text:
/**
 * \file
 * \brief morecore() is a sbrk() equivalent.
 */

/*
 * Copyright (c) 2007, 2008, 2011, ETH Zurich.
 * All rights reserved.
 *
 * This file is distributed under the terms in the attached LICENSE file.
 * If you do not find this file, copies can be found by writing to:
 * ETH Zurich D-INFK, Universitaetstrasse 6, CH-8092 Zurich. Attn: Systems Group.
 */

#include <assert.h>
#include <k_r_malloc.h>
#include <stddef.h>
#include <barrelfish/barrelfish.h>
#include <barrelfish/core_state.h>

Header *get_malloc_freep(void);

typedef void *(*morecore_alloc_func_t)(size_t bytes, size_t *retbytes);
typedef void (*morecore_free_func_t)(void *base, size_t bytes);

morecore_alloc_func_t sys_morecore_alloc;
morecore_free_func_t sys_morecore_free;

/**
 * \brief sbrk() equivalent.
 *
 * This function tries to allocate at least the amount given by 'nu'
 * in sizeof(::Header) byte units. In some cases, it will allocate
 * less, if no more memory was available. In any case, It returns a
 * pointer to the freelist header of the memory region.  NULL is
 * returned when out of memory.
 *
 * \param nu    Number of memory units (1 unit == sizeof(::Header) bytes)
 *
 * \return Pointer to freelist header of new memory region or NULL on out of
 * memory.
 */
Header *morecore(unsigned nu)
{
    Header *up;
    size_t nb = nu * sizeof(Header);

    // Allocate requested number of pages and insert freelist header
    assert(sys_morecore_alloc);
    up = (Header *)sys_morecore_alloc(nb, &nb);
    if (up == NULL) {
        return NULL;
    }
    assert(nb % sizeof(Header) == 0);
    up->s.size = nb / sizeof(Header);

    // Add header to freelist
    __free_locked((void *)(up + 1));
    return get_malloc_freep();
}

/**
 * \brief sbrk() garbage collector.
 *
 * Tries to free up pages at the end of the segment, so to shorten the
 * segment and return memory to the operating system.
 */
void lesscore(void)
{
#if defined(__arm__) || defined(__aarch64__)
    // Not implemented

#else
    struct morecore_state *state = get_morecore_state();
    genvaddr_t gvaddr =
        vregion_get_base_addr(&state->mmu_state.vregion)
        + state->mmu_state.offset;
    void *eaddr = (void*)vspace_genvaddr_to_lvaddr(gvaddr);

    assert(sys_morecore_free);

    // Deallocate from end of segment
    Header *prevp = state->header_freep, *p;
    for(p = prevp->s.ptr;; prevp = p, p = p->s.ptr) {
        if(p + p->s.size == eaddr) {
            prevp->s.ptr = p->s.ptr;
            state->header_freep = prevp;

            // Give back the memory
            sys_morecore_free(p, p->s.size * sizeof(Header));
            break;
        }

        if (p == state->header_freep) {	/* wrapped around free list */
            break;
        }
    }
#endif
}


text:
package bridge

import (
	"github.com/stellar/gateway/protocols"
	b "github.com/stellar/go/build"
)

// InflationOperationBody represents inflation operation
type InflationOperationBody struct {
	Source *string
}

// ToTransactionMutator returns go-stellar-base TransactionMutator
func (op InflationOperationBody) ToTransactionMutator() b.TransactionMutator {
	var mutators []interface{}

	if op.Source != nil {
		mutators = append(mutators, b.SourceAccount{*op.Source})
	}

	return b.Inflation(mutators...)
}

// Validate validates if operation body is valid.
func (op InflationOperationBody) Validate() error {
	if op.Source != nil && !protocols.IsValidAccountID(*op.Source) {
		return protocols.NewInvalidParameterError("source", *op.Source, "Source must be a public key (starting with `G`).")
	}

	return nil
}


text:
import igv from 'igv'
import * as React from 'react'
import * as M from '@material-ui/core'

import Code from 'components/Code'

const useStyles = M.makeStyles(() => ({
  root: {
    position: 'relative',
    zIndex: 1,
  },
}))

interface IgvEssential {
  options: igv.IgvBrowserOptions
}

export interface IgvProps extends React.HTMLProps<HTMLDivElement> {
  options: igv.IgvBrowserOptions
}

// XXX: consider using components/EChartsChart (may require some adjustments)
function Igv({ options, ...props }: IgvProps) {
  const containerRef = React.useRef<HTMLDivElement | null>(null)
  const classes = useStyles()

  const [error, setError] = React.useState<Error | null>(null)

  React.useEffect(() => {
    let browser: igv.IgvBrowser
    async function initIgv() {
      if (!containerRef.current) return
      try {
        browser = await igv.createBrowser(containerRef.current, options)
        return () => browser && igv.removeBrowser(browser)
      } catch (e) {
        // eslint-disable-next-line no-console
        console.error(e)
        if (e instanceof Error) {
          setError(e)
        } else {
          setError(new Error('Unexpected'))
        }
        // XXX: should NOT set state in dispose callback
        return () => setError(null)
      }
    }
    initIgv()
  }, [containerRef, options])

  if (error)
    return (

        <M.Typography variant="h6" gutterBottom>
          Unexpected Error
        </M.Typography>
        <M.Typography variant="body1" gutterBottom>
          Something went wrong while loading preview
        </M.Typography>
        {error.message !== 'Unexpected' && (
          <M.Typography variant="body1" gutterBottom>
            {error.message}
          </M.Typography>
        )}

    )

  return

}

export default ({ options }: IgvEssential, props: React.HTMLProps<HTMLDivElement>) => (
  <Igv options={options} {...props} />
)


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.datafactory.models;

import com.azure.core.annotation.Fluent;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeName;

/** The data stored in text format. */
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
@JsonTypeName("TextFormat")
@Fluent
public final class TextFormat extends DatasetStorageFormat {
    /*
     * The column delimiter. Type: string (or Expression with resultType string).
     */
    @JsonProperty(value = "columnDelimiter")
    private Object columnDelimiter;

    /*
     * The row delimiter. Type: string (or Expression with resultType string).
     */
    @JsonProperty(value = "rowDelimiter")
    private Object rowDelimiter;

    /*
     * The escape character. Type: string (or Expression with resultType string).
     */
    @JsonProperty(value = "escapeChar")
    private Object escapeChar;

    /*
     * The quote character. Type: string (or Expression with resultType string).
     */
    @JsonProperty(value = "quoteChar")
    private Object quoteChar;

    /*
     * The null value string. Type: string (or Expression with resultType string).
     */
    @JsonProperty(value = "nullValue")
    private Object nullValue;

    /*
     * The code page name of the preferred encoding. If miss, the default value is ΓÇ£utf-8ΓÇ¥, unless BOM denotes
     * another Unicode encoding. Refer to the ΓÇ£NameΓÇ¥ column of the table in the following link to set supported
     * values: https://msdn.microsoft.com/library/system.text.encoding.aspx. Type: string (or Expression with
     * resultType string).
     */
    @JsonProperty(value = "encodingName")
    private Object encodingName;

    /*
     * Treat empty column values in the text file as null. The default value is true. Type: boolean (or Expression with
     * resultType boolean).
     */
    @JsonProperty(value = "treatEmptyAsNull")
    private Object treatEmptyAsNull;

    /*
     * The number of lines/rows to be skipped when parsing text files. The default value is 0. Type: integer (or
     * Expression with resultType integer).
     */
    @JsonProperty(value = "skipLineCount")
    private Object skipLineCount;

    /*
     * When used as input, treat the first row of data as headers. When used as output,write the headers into the
     * output as the first row of data. The default value is false. Type: boolean (or Expression with resultType
     * boolean).
     */
    @JsonProperty(value = "firstRowAsHeader")
    private Object firstRowAsHeader;

    /** Creates an instance of TextFormat class. */
    public TextFormat() {
    }

    /**
     * Get the columnDelimiter property: The column delimiter. Type: string (or Expression with resultType string).
     *
     * @return the columnDelimiter value.
     */
    public Object columnDelimiter() {
        return this.columnDelimiter;
    }

    /**
     * Set the columnDelimiter property: The column delimiter. Type: string (or Expression with resultType string).
     *
     * @param columnDelimiter the columnDelimiter value to set.
     * @return the TextFormat object itself.
     */
    public TextFormat withColumnDelimiter(Object columnDelimiter) {
        this.columnDelimiter = columnDelimiter;
        return this;
    }

    /**
     * Get the rowDelimiter property: The row delimiter. Type: string (or Expression with resultType string).
     *
     * @return the rowDelimiter value.
     */
    public Object rowDelimiter() {
        return this.rowDelimiter;
    }

    /**
     * Set the rowDelimiter property: The row delimiter. Type: string (or Expression with resultType string).
     *
     * @param rowDelimiter the rowDelimiter value to set.
     * @return the TextFormat object itself.
     */
    public TextFormat withRowDelimiter(Object rowDelimiter) {
        this.rowDelimiter = rowDelimiter;
        return this;
    }

    /**
     * Get the escapeChar property: The escape character. Type: string (or Expression with resultType string).
     *
     * @return the escapeChar value.
     */
    public Object escapeChar() {
        return this.escapeChar;
    }

    /**
     * Set the escapeChar property: The escape character. Type: string (or Expression with resultType string).
     *
     * @param escapeChar the escapeChar value to set.
     * @return the TextFormat object itself.
     */
    public TextFormat withEscapeChar(Object escapeChar) {
        this.escapeChar = escapeChar;
        return this;
    }

    /**
     * Get the quoteChar property: The quote character. Type: string (or Expression with resultType string).
     *
     * @return the quoteChar value.
     */
    public Object quoteChar() {
        return this.quoteChar;
    }

    /**
     * Set the quoteChar property: The quote character. Type: string (or Expression with resultType string).
     *
     * @param quoteChar the quoteChar value to set.
     * @return the TextFormat object itself.
     */
    public TextFormat withQuoteChar(Object quoteChar) {
        this.quoteChar = quoteChar;
        return this;
    }

    /**
     * Get the nullValue property: The null value string. Type: string (or Expression with resultType string).
     *
     * @return the nullValue value.
     */
    public Object nullValue() {
        return this.nullValue;
    }

    /**
     * Set the nullValue property: The null value string. Type: string (or Expression with resultType string).
     *
     * @param nullValue the nullValue value to set.
     * @return the TextFormat object itself.
     */
    public TextFormat withNullValue(Object nullValue) {
        this.nullValue = nullValue;
        return this;
    }

    /**
     * Get the encodingName property: The code page name of the preferred encoding. If miss, the default value is
     * ΓÇ£utf-8ΓÇ¥, unless BOM denotes another Unicode encoding. Refer to the ΓÇ£NameΓÇ¥ column of the table in the
     * following link to set supported values: https://msdn.microsoft.com/library/system.text.encoding.aspx. Type:
     * string (or Expression with resultType string).
     *
     * @return the encodingName value.
     */
    public Object encodingName() {
        return this.encodingName;
    }

    /**
     * Set the encodingName property: The code page name of the preferred encoding. If miss, the default value is
     * ΓÇ£utf-8ΓÇ¥, unless BOM denotes another Unicode encoding. Refer to the ΓÇ£NameΓÇ¥ column of the table in the
     * following link to set supported values: https://msdn.microsoft.com/library/system.text.encoding.aspx. Type:
     * string (or Expression with resultType string).
     *
     * @param encodingName the encodingName value to set.
     * @return the TextFormat object itself.
     */
    public TextFormat withEncodingName(Object encodingName) {
        this.encodingName = encodingName;
        return this;
    }

    /**
     * Get the treatEmptyAsNull property: Treat empty column values in the text file as null. The default value is true.
     * Type: boolean (or Expression with resultType boolean).
     *
     * @return the treatEmptyAsNull value.
     */
    public Object treatEmptyAsNull() {
        return this.treatEmptyAsNull;
    }

    /**
     * Set the treatEmptyAsNull property: Treat empty column values in the text file as null. The default value is true.
     * Type: boolean (or Expression with resultType boolean).
     *
     * @param treatEmptyAsNull the treatEmptyAsNull value to set.
     * @return the TextFormat object itself.
     */
    public TextFormat withTreatEmptyAsNull(Object treatEmptyAsNull) {
        this.treatEmptyAsNull = treatEmptyAsNull;
        return this;
    }

    /**
     * Get the skipLineCount property: The number of lines/rows to be skipped when parsing text files. The default value
     * is 0. Type: integer (or Expression with resultType integer).
     *
     * @return the skipLineCount value.
     */
    public Object skipLineCount() {
        return this.skipLineCount;
    }

    /**
     * Set the skipLineCount property: The number of lines/rows to be skipped when parsing text files. The default value
     * is 0. Type: integer (or Expression with resultType integer).
     *
     * @param skipLineCount the skipLineCount value to set.
     * @return the TextFormat object itself.
     */
    public TextFormat withSkipLineCount(Object skipLineCount) {
        this.skipLineCount = skipLineCount;
        return this;
    }

    /**
     * Get the firstRowAsHeader property: When used as input, treat the first row of data as headers. When used as
     * output,write the headers into the output as the first row of data. The default value is false. Type: boolean (or
     * Expression with resultType boolean).
     *
     * @return the firstRowAsHeader value.
     */
    public Object firstRowAsHeader() {
        return this.firstRowAsHeader;
    }

    /**
     * Set the firstRowAsHeader property: When used as input, treat the first row of data as headers. When used as
     * output,write the headers into the output as the first row of data. The default value is false. Type: boolean (or
     * Expression with resultType boolean).
     *
     * @param firstRowAsHeader the firstRowAsHeader value to set.
     * @return the TextFormat object itself.
     */
    public TextFormat withFirstRowAsHeader(Object firstRowAsHeader) {
        this.firstRowAsHeader = firstRowAsHeader;
        return this;
    }

    /** {@inheritDoc} */
    @Override
    public TextFormat withSerializer(Object serializer) {
        super.withSerializer(serializer);
        return this;
    }

    /** {@inheritDoc} */
    @Override
    public TextFormat withDeserializer(Object deserializer) {
        super.withDeserializer(deserializer);
        return this;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    @Override
    public void validate() {
        super.validate();
    }
}


text:
.indented {
	margin-top: -1em;
	padding-top: 1em;
}

.indented:hover,
.indented:focus {
	background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACAQMAAACjTyRkAAAAAXNSR0IArs4c6QAAAAZQTFRFt9BTt7eL4xrPVQAAAAF0Uk5TAEDm2GYAAAABYktHRACIBR1IAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH2gsOCiIz/YtxKwAAABl0RVh0Q29tbWVudABDcmVhdGVkIHdpdGggR0lNUFeBDhcAAAAMSURBVAjXY2hgYAAAAYQAgSjdetcAAAAASUVORK5CYII=) 0 0 repeat-y;
}

a#new:target + a + .comment,
a:target + .comment {
	/* background-color: #F6F6EB; */
	border-color: #000;
	-moz-transition: border-color 2s ease-out, background-color 0.5s ease;
	transition: border-color 2s ease-out, background-color 0.5s ease;
}

a:target + .comment > .submitted,
a#new:target + a + .comment > .submitted {
	font-weight: bold;
}

.indented {
	transition: margin-left 0.5s;
}

.widen-comment {
	margin-left: 0;
}


text:
/*
 * Description:
 *     What is this file about?
 *
 * Revision history:
 *     xxxx-xx-xx, author, first version
 *     xxxx-xx-xx, author, fix bug about xxx
 */

# include "asio_net_provider.h"
# include <dsn/tool/providers.common.h>
# include "lockp.std.h"
# include "native_aio_provider.win.h"
# include "native_aio_provider.posix.h"
# include "native_aio_provider.linux.h"
# include "simple_perf_counter.h"
# include "simple_perf_counter_v2_atomic.h"
# include "simple_perf_counter_v2_fast.h"
# include "simple_task_queue.h"
# include "network.sim.h"
# include "simple_logger.h"
# include "empty_aio_provider.h"
#include "http_message_parser.h"

namespace dsn {
    namespace tools {
        void register_common_providers()
        {
            register_component_provider<env_provider>("dsn::env_provider");
            register_component_provider<memory_provider>("dsn::default_memory_provider");
            register_component_provider<task_worker>("dsn::task_worker");
            register_component_provider<screen_logger>("dsn::tools::screen_logger");
            register_component_provider<simple_logger>("dsn::tools::simple_logger");
            register_component_provider<std_lock_provider>("dsn::tools::std_lock_provider");
            register_component_provider<std_lock_nr_provider>("dsn::tools::std_lock_nr_provider");
            register_component_provider<std_rwlock_nr_provider>("dsn::tools::std_rwlock_nr_provider");
            register_component_provider<std_semaphore_provider>("dsn::tools::std_semaphore_provider");
            register_component_provider<asio_network_provider>("dsn::tools::asio_network_provider");
            register_component_provider<asio_udp_provider>("dsn::tools::asio_udp_provider");
            register_component_provider<sim_network_provider>("dsn::tools::sim_network_provider");
            register_component_provider<simple_task_queue>("dsn::tools::simple_task_queue");
            register_component_provider<simple_timer_service>("dsn::tools::simple_timer_service");

            register_message_header_parser<dsn_message_parser>(NET_HDR_DSN);
            register_message_header_parser<http_message_parser>(NET_HDR_HTTP);
#if defined(_WIN32)
            register_component_provider<native_win_aio_provider>("dsn::tools::native_aio_provider");
#elif defined(__linux__)
            register_component_provider<native_linux_aio_provider>("dsn::tools::native_aio_provider");
            register_component_provider<native_posix_aio_provider>("dsn::tools::posix_aio_provider");
#else
            register_component_provider<native_posix_aio_provider>("dsn::tools::native_aio_provider");
#endif
            register_component_provider<empty_aio_provider>("dsn::tools::empty_aio_provider");

            ::dsn::tools::internal_use_only::register_component_provider(
                "dsn::tools::simple_perf_counter",
                simple_perf_counter_factory,
                PROVIDER_TYPE_MAIN
                );
            ::dsn::tools::internal_use_only::register_component_provider(
                "dsn::tools::simple_perf_counter_v2_atomic",
                simple_perf_counter_v2_atomic_factory,
                PROVIDER_TYPE_MAIN
                );
            ::dsn::tools::internal_use_only::register_component_provider(
                "dsn::tools::simple_perf_counter_v2_fast",
                simple_perf_counter_v2_fast_factory,
                PROVIDER_TYPE_MAIN
                );
        }
    }
}


text:
/*
 |=   _    _       _          _
 |=  | |  (_)_ __ | |__  __ _| |_ ___
 |=  | |__| | '  \| '_ \/ _` |  _/ -_)
 |=  |____|_|_|_|_|_.__/\__,_|\__\___|
 |=
 */

#import "REDependence.h"

@interface REReactiveObject : NSObject

- (REDependence *)addDependenceFromSource:(id)source block:(void(^)(id source))block;
- (REDependence *)addDependenceFromSource:(id)source queue:(dispatch_queue_t)queue block:(void(^)(id source))block;
- (REDependence *)addDependenceFromSource:(id)source name:(const void *)name block:(void(^)(id source))block;
- (REDependence *)addDependenceFromSource:(id)source name:(const void *)name queue:(dispatch_queue_t)queue block:(void(^)(id source))block;

- (void)removeDependenceFromSource:(id)source;
- (void)removeDependenceFromSource:(id)source name:(const void *)name;

- (void)push;

@end


text:
Well done, Path Seeker. You have discovered the second piece of the shovel:

#The Ancient Scroll

![](http://i1098.photobucket.com/albums/g380/shovelmaster1/scroll_zps5urprbos.jpg "The Ancient Scroll")

If you remain curious, and locate all 3 pieces, YOUR name could be added to this illustrious scroll as the NEXT Shovel Master.

![](http://i1098.photobucket.com/albums/g380/shovelmaster1/sponge_zpspjgjfc8u.gif "")

Fork or clone this repo, add your name to the list below, and submit a pull request.

#Path Seekers:

1. Emma Ritcey

2. Torey Hickman

3. Zach Barton - Shovel Master Emeritus

4.

5.


text:
"""Special configuration for AllAuth."""

from allauth.account.adapter import DefaultAccountAdapter
from .utils import allow_new_users

class AccountAdapter(DefaultAccountAdapter):

    """Account Adapter which has a special case for first login."""

    def get_login_redirect_url(self, request):
        """Get the redirect URL for the request."""
        threshold = 90  # seconds

        time_passed = (request.user.last_login - request.user.date_joined)
        if time_passed.seconds < threshold:
            return '/member/%s/edit' % request.user.pk
        else:
            return '/'

    def is_open_for_signup(self, request):
        """
        Check whether or not the site is open for signups.

        Next to simply returning True/False you can also intervene the
        regular flow by raising an ImmediateHttpResponse

        (Comment reproduced from the overridden method.)
        """
        return allow_new_users(request)


text:
<?php

namespace Crucial\Service\ChargifyV2\Direct\Utility;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Psr7\Response;
use Crucial\Service\ChargifyV2\Direct;

class AuthRequest
{
    /**
     * @var Direct
     */
    protected $direct;

    /**
     * @var Client
     */
    protected $httpClient;

    /**
     * @var Response|false
     */
    protected $lastResponse;

    /**
     * @param Direct $direct
     */
    public function __construct(Direct $direct)
    {
        $this->direct     = $direct;
        $this->httpClient = $direct->getService()->getHttpClient();
    }

    /**
     * Test if credentials are correct
     *
     * @return bool
     */
    public function test()
    {
        $response = $this->request();
        $body     = trim((string)$response->getBody());

        // invalid If body contains 'Incorrect signature'
        $bodyIsInvalid = (0 === strcasecmp('Incorrect signature', $body));

        // invalid if chargify does not redirect us
        $locationHeader    = $response->getHeader('Location');
        $locationIsInvalid = empty($locationHeader);

        // invalid if status code is 200
        $statusCodeIsInvalid = ($response->getStatusCode() == 200);

        if ($bodyIsInvalid || $locationIsInvalid || $statusCodeIsInvalid) {
            return false;
        }

        return true;
    }

    /**
     * @return Client
     */
    public function getHttpClient()
    {
        return $this->httpClient;
    }

    /**
     * @return Response|false
     */
    public function getLastResponse()
    {
        return $this->lastResponse;
    }

    /**
     * @return Response|false|null
     */
    protected function request()
    {
        try {
            $response = $this->httpClient->post($this->direct->getSignupAction(), [
                'form_params' => [
                    'secure' => [
                        'api_id'    => $this->direct->getApiId(),
                        'timestamp' => $this->direct->getTimeStamp(),
                        'nonce'     => $this->direct->getNonce(),
                        'signature' => $this->direct->getRequestSignature(),
                        'data'      => $this->direct->getDataStringEncoded()
                    ]
                ]
            ]);
        } catch (RequestException $e) {
            if ($e->hasResponse()) {
                $response = $e->getResponse();
            } else {
                $response = false;
            }
        }

        $this->lastResponse = $response;

        return $response;
    }
}


text:
from ..models import Citation
from ..utils import HomepageRedirectError
from furl import furl

class DetectDeadLink:
    def __init__(self):
        pass

    def apply(self, citation: Citation) -> Citation:
        if 'url' not in citation or 'parsedUrl' not in citation.raw or 'downloaded' not in citation.raw:
            return citation

        origUrl = citation.raw['parsedUrl']
        finalUrl = furl(citation.raw['downloaded'].url.strip('/'))

        if finalUrl.path.segments and finalUrl.path.segments[-1] == '':
            finalUrl.path.segments.pop()

        if len(origUrl.path.segments) > 3 and len(finalUrl.path.segments) < 2:
            raise HomepageRedirectError(citation.url)

        return citation


text:
<?php
/**
 * @author Martin Tawse martin.tawse@gmail.com
 * Date: 31/01/2015
 */

namespace Blogger\BlogBundle\Entity;

use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\Email;
use Symfony\Component\Validator\Constraints\Length;
//use Symfony\Component\Validator\Constraints\MaxLength;

class Enquiry
{
    protected $name;

    protected $email;

    protected $subject;

    protected $body;

    public static function loadValidatorMetadata(ClassMetadata $metadata)
    {
        $metadata->addPropertyConstraint('name', new NotBlank());

        $metadata->addPropertyConstraint('email', new Email());

        $metadata->addPropertyConstraint('subject', new NotBlank());
//        $metadata->addPropertyConstraint('subject', new Length());
//
//        $metadata->addPropertyConstraint('body', new MinLength(50));
    }

    /**
     * @param mixed $body
     */
    public function setBody($body)
    {
        $this->body = $body;
    }

    /**
     * @return mixed
     */
    public function getBody()
    {
        return $this->body;
    }

    /**
     * @param mixed $email
     */
    public function setEmail($email)
    {
        $this->email = $email;
    }

    /**
     * @return mixed
     */
    public function getEmail()
    {
        return $this->email;
    }

    /**
     * @param mixed $name
     */
    public function setName($name)
    {
        $this->name = $name;
    }

    /**
     * @return mixed
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * @param mixed $subject
     */
    public function setSubject($subject)
    {
        $this->subject = $subject;
    }

    /**
     * @return mixed
     */
    public function getSubject()
    {
        return $this->subject;
    }

}