text:
using Stashbox.Configuration;
using Stashbox.Exceptions;
using Stashbox.Lifetime;
using Stashbox.Tests.Utils;
using Stashbox.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Xunit;

namespace Stashbox.Tests
{

    public class LifetimeTests
    {
        [Theory]
        [ClassData(typeof(CompilerTypeTestData))]
        public void LifetimeTests_Resolve(CompilerType compilerType)
        {
            using IStashboxContainer container = new StashboxContainer(c => c.WithCompiler(compilerType));
            container.RegisterSingleton<ITest1, Test1>();
            container.Register<ITest2, Test2>();
            container.Register<ITest3, Test3>();

            var test1 = container.Resolve<ITest1>();
            test1.Name = "test1";
            var test2 = container.Resolve<ITest2>();
            var test3 = container.Resolve<ITest3>();

            Assert.NotNull(test1);
            Assert.NotNull(test2);
            Assert.NotNull(test3);
        }

        [Theory]
        [ClassData(typeof(CompilerTypeTestData))]
        public void LifetimeTests_Resolve_Parallel(CompilerType compilerType)
        {
            using IStashboxContainer container = new StashboxContainer(c => c.WithCompiler(compilerType));
            container.RegisterSingleton(typeof(ITest1), typeof(Test1));
            container.Register<ITest2, Test2>();
            container.Register<ITest3, Test3>();

            Parallel.For(0, 50000, (i) =>
            {
                var test1 = container.Resolve<ITest1>();
                test1.Name = "test1";
                var test2 = container.Resolve<ITest2>();
                var test3 = container.Resolve<ITest3>();

                Assert.NotNull(test1);
                Assert.NotNull(test2);
                Assert.NotNull(test3);
            });
        }

        [Theory]
        [ClassData(typeof(CompilerTypeTestData))]
        public void LifetimeTests_Resolve_Parallel_Lazy(CompilerType compilerType)
        {
            using IStashboxContainer container = new StashboxContainer(c => c.WithCompiler(compilerType));
            container.Register<ITest1, Test1>(context => context.WithSingletonLifetime());
            container.Register<ITest2, Test2>();
            container.Register<ITest3, Test3>();

            Parallel.For(0, 50000, (i) =>
            {
                var test1 = container.Resolve<Lazy<ITest1>>();
                test1.Value.Name = "test1";
                var test2 = container.Resolve<Lazy<ITest2>>();
                var test3 = container.Resolve<Lazy<ITest3>>();

                Assert.NotNull(test1.Value);
                Assert.NotNull(test2.Value);
                Assert.NotNull(test3.Value);
            });
        }

        [Theory]
        [ClassData(typeof(CompilerTypeTestData))]
        public void LifetimeTests_Per_Scoped_Resolution_Request_Dependency(CompilerType compilerType)
        {
            using var container = new StashboxContainer(c => c.WithCompiler(compilerType))
                    .Register<Test5>(context => context.WithPerScopedRequestLifetime())
                    .Register<Test6>()
                    .Register<Test7>();

            var inst1 = container.Resolve<Test7>();
            var inst2 = container.Resolve<Test7>();

            Assert.Same(inst1.Test5, inst1.Test6.Test5);
            Assert.Same(inst2.Test5, inst2.Test6.Test5);
            Assert.NotSame(inst1.Test5, inst2.Test6.Test5);
            Assert.NotSame(inst2.Test5, inst1.Test6.Test5);
        }

        [Theory]
        [ClassData(typeof(CompilerTypeTestData))]
        public void LifetimeTests_Per_Scoped_Resolution_Request_Dependency_Scoped(CompilerType compilerType)
        {
            using var container = new StashboxContainer(c => c.WithCompiler(compilerType))
                .Register<Test5>(context => context.WithPerScopedRequestLifetime())
                .RegisterScoped<Test6>()
                .Register<Test7>();

            using var scope = container.BeginScope();

            var inst1 = scope.Resolve<Test7>();
            var inst2 = scope.Resolve<Test7>();

            Assert.NotSame(inst1.Test5, inst1.Test6.Test5);
            Assert.NotSame(inst2.Test5, inst2.Test6.Test5);
            Assert.NotSame(inst1.Test5, inst2.Test6.Test5);
            Assert.NotSame(inst2.Test5, inst1.Test6.Test5);
        }

        [Theory]
        [ClassData(typeof(CompilerTypeTestData))]
        public void LifetimeTests_Per_Scoped_Resolution_Request_Dependency_WithNull(CompilerType compilerType)
        {
            using IStashboxContainer container = new StashboxContainer(c => c.WithCompiler(compilerType));
            container.Register<Test6>(context => context.WithPerScopedRequestLifetime());

            Assert.Null(container.ResolveOrDefault<Test6>());
        }

        [Theory]
        [ClassData(typeof(CompilerTypeTestData))]
        public void LifetimeTests_Per_Scoped_Resolution_Request(CompilerType compilerType)
        {
            using IStashboxContainer container = new StashboxContainer(c => c.WithCompiler(compilerType));
            container.Register<Test5>(context => context.WithPerScopedRequestLifetime());

            var inst1 = container.Resolve<Test5>();
            var inst2 = container.Resolve<Test5>();

            Assert.NotSame(inst1, inst2);
        }

        [Theory]
        [ClassData(typeof(CompilerTypeTestData))]
        public void LifetimeTests_Scoped_WithNull(CompilerType compilerType)
        {
            using IStashboxContainer container = new StashboxContainer(c => c.WithCompiler(compilerType));
            container.RegisterScoped<Test6>();

            Assert.Null(container.BeginScope().ResolveOrDefault<Test6>());
        }

        [Theory]
        [ClassData(typeof(CompilerTypeTestData))]
        public void LifetimeTests_DefinesScope_Generic(CompilerType compilerType)
        {
            using IStashboxContainer container = new StashboxContainer(c => c.WithCompiler(compilerType));
            container.Register<Test6>();
            container.Register<Test7>(c => c.DefinesScope());
            container.RegisterScoped<Test5>();

            using var scope = container.BeginScope();

            var inst1 = scope.Resolve<Test6>();
            var inst2 = scope.Resolve<Test7>();

            Assert.NotSame(inst1.Test5, inst2.Test5);
            Assert.Same(inst2.Test5, inst2.Test6.Test5);
        }

        [Theory]
        [ClassData(typeof(CompilerTypeTestData))]
        public void LifetimeTests_DefinesScope(CompilerType compilerType)
        {
            using IStashboxContainer container = new StashboxContainer(c => c.WithCompiler(compilerType));
            container.Register<Test6>();
            container.Register(typeof(Test7), c => c.DefinesScope());
            container.RegisterScoped<Test5>();

            using var scope = container.BeginScope();

            var inst1 = scope.Resolve<Test6>();
            var inst2 = scope.Resolve<Test7>();

            Assert.NotSame(inst1.Test5, inst2.Test5);
            Assert.Same(inst2.Test5, inst2.Test6.Test5);
        }

        [Theory]
        [ClassData(typeof(CompilerTypeTestData))]
        public void LifetimeTests_Per_Request(CompilerType compilerType)
        {
            using IStashboxContainer container = new StashboxContainer(c => c.WithCompiler(compilerType));
            container.Register<Test5>(c => c.WithPerRequestLifetime());
            container.Register<Test6>();
            container.Register<Test7>();

            var inst = container.Resolve<Test7>();
            var t5 = container.Resolve<Test5>();

            Assert.NotNull(inst.Test5);
            Assert.NotNull(inst.Test6.Test5);
            Assert.Same(inst.Test5, inst.Test6.Test5);
            Assert.NotSame(t5, inst.Test5);
        }

        [Theory]
        [ClassData(typeof(CompilerTypeTestData))]
        public void LifetimeTests_Per_Request_WithScope(CompilerType compilerType)
        {
            using IStashboxContainer container = new StashboxContainer(c => c.WithCompiler(compilerType));
            container.Register<Test5>(c => c.WithPerRequestLifetime());
            container.Register<Test6>(c => c.WithScopedLifetime());
            container.Register<Test7>();

            using var scope = container.BeginScope();

            var inst = scope.Resolve<Test7>();
            var t5 = scope.Resolve<Test5>();

            Assert.NotNull(inst.Test5);
            Assert.NotNull(inst.Test6.Test5);
            Assert.Same(inst.Test5, inst.Test6.Test5);
            Assert.NotSame(t5, inst.Test5);
        }

        [Theory]
        [ClassData(typeof(CompilerTypeTestData))]
        public void LifetimeTests_Per_Request_Enumerable(CompilerType compilerType)
        {
            using IStashboxContainer container = new StashboxContainer(c => c.WithCompiler(compilerType));
            container.Register<Test5>(c => c.WithPerRequestLifetime());
            container.Register<Test6>();
            container.Register<Test7>();

            var inst = container.ResolveAll<Test7>().First();
            var t5 = container.ResolveAll<Test5>().First();

            Assert.NotNull(inst.Test5);
            Assert.NotNull(inst.Test6.Test5);
            Assert.Same(inst.Test5, inst.Test6.Test5);
            Assert.NotSame(t5, inst.Test5);
        }

        [Theory]
        [ClassData(typeof(CompilerTypeTestData))]
        public void LifetimeTests_Per_Request_Wrapper_Enumerable(CompilerType compilerType)
        {
            using IStashboxContainer container = new StashboxContainer(c => c.WithCompiler(compilerType));
            container.Register<Test5>(c => c.WithPerRequestLifetime());
            container.Register<Test6>();
            container.Register<Test9>();

            var inst = container.Resolve<Test9>();
            var t5 = container.Resolve<Test5>();

            Assert.NotNull(inst.Test5);
            Assert.NotNull(inst.Test6.Test5);
            Assert.Same(inst.Test5.First(), inst.Test6.Test5);
            Assert.NotSame(t5, inst.Test5.First());
        }

        [Theory]
        [ClassData(typeof(CompilerTypeTestData))]
        public void LifetimeTests_Per_Request_Wrapper_Lazy(CompilerType compilerType)
        {
            using IStashboxContainer container = new StashboxContainer(c => c.WithCompiler(compilerType));
            container.Register<Test5>(c => c.WithPerRequestLifetime());
            container.Register<Test6>();
            container.Register<Test10>();

            var inst = container.Resolve<Test10>();
            var t5 = container.Resolve<Test5>();

            Assert.NotNull(inst.Test5);
            Assert.NotNull(inst.Test6.Test5);
            Assert.Same(inst.Test5.Value, inst.Test6.Test5);
            Assert.NotSame(t5, inst.Test5.Value);
        }

        [Theory]
        [InlineData(true)]
        [InlineData(false)]
        public void LifetimeTests_Shorter_Lifetime_Not_Resolvable_From_Longer_Direct(bool enabledValidation)
        {
            using IStashboxContainer container = new StashboxContainer(c =>
            {
                if (enabledValidation)
                    c.WithLifetimeValidation();
            });
            container.RegisterSingleton<Test6>();
            container.RegisterScoped<Test5>();

            using var scope = container.BeginScope();

            if (enabledValidation)
            {
                var exception = Assert.Throws<LifetimeValidationFailedException>(() => scope.Resolve<Test6>());
                Assert.Equal(typeof(Test5), exception.Type);
                Assert.Contains("The life-span of", exception.Message);
            }
            else
            {
                Assert.NotNull(scope.Resolve<Test6>());
            }
        }

        [Fact]
        public void LifetimeTests_Named_Scope_Lifetime_Not_Resolvable_From_Longer_Direct()
        {
            using IStashboxContainer container = new StashboxContainer(c => c.WithLifetimeValidation());
            container.RegisterSingleton<Test6>();
            container.Register<Test5>(c => c.WithLifetime(Lifetimes.NamedScope("A")));

            using var scope = container.BeginScope("A");

            var exception = Assert.Throws<LifetimeValidationFailedException>(() => scope.Resolve<Test6>());
            Assert.Equal(typeof(Test5), exception.Type);
            Assert.Contains("The life-span of", exception.Message);
        }

        [Fact]
        public void LifetimeTests_Named_Scope_Lifetime_Not_Resolvable_From_Singleton()
        {
            using IStashboxContainer container = new StashboxContainer();
            container.RegisterSingleton<Test6>();
            container.Register<Test5>(c => c.WithLifetime(Lifetimes.NamedScope("A")));

            using var scope = container.BeginScope("A");

            var exception = Assert.Throws<ResolutionFailedException>(() => scope.Resolve<Test6>());
            Assert.Equal(typeof(Test5), exception.Type);
            Assert.Contains("The scope 'A' was not found to resolve", exception.Message);
        }

        [Theory]
        [InlineData(true)]
        [InlineData(false)]
        public void LifetimeTests_Shorter_Lifetime_Not_Resolvable_From_Longer_InDirect(bool enabledValidation)
        {
            using IStashboxContainer container = new StashboxContainer(c =>
            {
                if (enabledValidation)
                    c.WithLifetimeValidation();
            });
            container.RegisterSingleton<Test8>();
            container.Register<Test6>();
            container.RegisterScoped<Test5>();

            using var scope = container.BeginScope();

            if (enabledValidation)
            {
                var exception = Assert.Throws<LifetimeValidationFailedException>(() => scope.Resolve<Test8>());
                Assert.Equal(typeof(Test5), exception.Type);
                Assert.Contains("The life-span of", exception.Message);
            }
            else
            {
                Assert.NotNull(scope.Resolve<Test8>());
            }
        }

        [Fact]
        public void LifetimeTests_Named_Scope_Lifetime_Not_Resolvable_From_Longer_InDirect()
        {
            using IStashboxContainer container = new StashboxContainer(c => c.WithLifetimeValidation());
            container.RegisterSingleton<Test8>();
            container.Register<Test6>();
            container.Register<Test5>(c => c.InNamedScope("A"));

            using var scope = container.BeginScope("A");

            var exception = Assert.Throws<LifetimeValidationFailedException>(() => scope.Resolve<Test8>());
            Assert.Equal(typeof(Test5), exception.Type);
            Assert.Contains("The life-span of", exception.Message);
        }

        [Theory]
        [InlineData(true)]
        [InlineData(false)]
        public void LifetimeTests_Scoped_Is_Not_Resolvable_From_Root_Direct(bool enabledValidation)
        {
            using IStashboxContainer container = new StashboxContainer(c =>
            {
                if (enabledValidation)
                    c.WithLifetimeValidation();
            });

            container.RegisterScoped<Test5>();

            if (enabledValidation)
            {
                var exception = Assert.Throws<LifetimeValidationFailedException>(() => container.Resolve<Test5>());
                Assert.Equal(typeof(Test5), exception.Type);
                Assert.Contains("from the root scope", exception.Message);
            }
            else
            {
                Assert.NotNull(container.Resolve<Test5>());
            }
        }

        [Fact]
        public void LifetimeTests_Named_Scoped_Is_Not_Resolvable_From_Root_Direct()
        {
            using IStashboxContainer container = new StashboxContainer();
            container.Register<Test5>(c => c.InNamedScope("A"));

            Assert.Throws<ResolutionFailedException>(() => container.Resolve<Test5>());
        }

        [Theory]
        [InlineData(true)]
        [InlineData(false)]
        public void LifetimeTests_Scoped_Is_Not_Resolvable_From_Root_InDirect(bool enabledValidation)
        {
            using IStashboxContainer container = new StashboxContainer(c =>
            {
                if (enabledValidation)
                    c.WithLifetimeValidation();
            });

            container.Register<Test6>();
            container.RegisterScoped<Test5>();

            if (enabledValidation)
            {
                var exception = Assert.Throws<LifetimeValidationFailedException>(() => container.Resolve<Test6>());
                Assert.Equal(typeof(Test5), exception.Type);
                Assert.Contains("from the root scope", exception.Message);
            }
            else
            {
                Assert.NotNull(container.Resolve<Test6>());
            }
        }

        [Theory]
        [InlineData(true)]
        [InlineData(false)]
        public void LifetimeTests_Scoped_Is_Not_Resolvable_From_Root_AfterResolved(bool enabledValidation)
        {
            using IStashboxContainer container = new StashboxContainer(c =>
            {
                if (enabledValidation)
                    c.WithLifetimeValidation();
            });

            container.Register<Test6>();
            container.RegisterScoped<Test5>();

            if (enabledValidation)
            {
                using var scope = container.BeginScope();
                scope.Resolve<Test6>();
                var exception = Assert.Throws<LifetimeValidationFailedException>(() => container.Resolve<Test6>());
                Assert.Equal(typeof(Test5), exception.Type);
                Assert.Contains("from the root scope", exception.Message);
            }
            else
            {
                using var scope = container.BeginScope();
                scope.Resolve<Test6>();
                Assert.NotNull(container.Resolve<Test6>());
            }
        }

        [Fact]
        public void LifetimeTests_Named_Scoped_Is_Not_Resolvable_From_Root_AfterResolved()
        {
            using IStashboxContainer container = new StashboxContainer();

            container.Register<Test6>();
            container.Register<Test5>(c => c.InNamedScope("A"));

            using var scope = container.BeginScope("A");
            scope.Resolve<Test6>();
            var exception = Assert.Throws<ResolutionFailedException>(() => container.Resolve<Test6>());
            Assert.Equal(typeof(Test6), exception.Type);
            Assert.Contains("found with unresolvable parameter", exception.Message);
        }

        [Fact]
        public void LifetimeTests_PerRequest_With_Singleton()
        {
            using IStashboxContainer container = new StashboxContainer();

            container.Register<Test6>(c => c.WithSingletonLifetime());
            container.Register<Test5>(c => c.WithPerRequestLifetime());
            container.Register<Test7>();

            var inst = container.Resolve<Test7>();

            Assert.Same(inst.Test5, inst.Test6.Test5);
        }

        interface ITest1 { string Name { get; set; } }

        interface ITest2 { string Name { get; set; } }

        interface ITest3 { string Name { get; set; } }

        class Test1 : ITest1
        {
            public string Name { get; set; }
        }

        class Test2 : ITest2
        {
            public ITest1 Test1 { get; }
            public string Name { get; set; }

            public Test2(ITest1 test1)
            {
                Test1 = test1;
                Shield.EnsureNotNull(test1, nameof(test1));
                Shield.EnsureNotNullOrEmpty(test1.Name, nameof(test1.Name));
                Shield.EnsureTypeOf<Test1>(test1);
            }
        }

        class Test3 : ITest3
        {
            public ITest1 Test1 { get; }
            public ITest2 Test2 { get; }
            public string Name { get; set; }

            public Test3(ITest1 test1, ITest2 test2)
            {
                Test1 = test1;
                Test2 = test2;
                Shield.EnsureNotNull(test1, nameof(test1));
                Shield.EnsureNotNull(test2, nameof(test2));
                Shield.EnsureNotNullOrEmpty(test1.Name, nameof(test1.Name));

                Shield.EnsureTypeOf<Test1>(test1);
                Shield.EnsureTypeOf<Test2>(test2);
            }
        }

        class Test4
        {
            public static bool IsConstructed;

            public Test4()
            {
                if (IsConstructed)
                    throw new InvalidOperationException();

                IsConstructed = true;
            }
        }

        class Test5
        {
        }

        class Test6
        {
            public Test5 Test5 { get; }

            public Test6(Test5 test5)
            {
                Test5 = test5;
            }
        }

        class Test7
        {
            public Test5 Test5 { get; }
            public Test6 Test6 { get; }

            public Test7(Test5 test5, Test6 test6)
            {
                Test5 = test5;
                Test6 = test6;
            }
        }

        class Test8
        {
            public Test6 Test6 { get; }

            public Test8(Test6 test6)
            {
                Test6 = test6;
            }
        }

        class Test9
        {
            public IEnumerable<Test5> Test5 { get; }
            public Test6 Test6 { get; }

            public Test9(IEnumerable<Test5> test5, Test6 test6)
            {
                Test5 = test5;
                Test6 = test6;
            }
        }

        class Test10
        {
            public Lazy<Test5> Test5 { get; }
            public Test6 Test6 { get; }

            public Test10(Lazy<Test5> test5, Test6 test6)
            {
                Test5 = test5;
                Test6 = test6;
            }
        }
    }
}


text:
package com.kawansoft.app.util.proxy;

import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.Proxy.Type;
import java.net.ProxySelector;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Iterator;
import java.util.List;

/**
 *
 * Class to detect the HTTP(s) system proxy in use
 *
 * @author SafeLogic
 *
 */
public class ProxyDetector
{
    /** Boolean value */
    public static boolean DEBUG = false;

    /** The Proxy itself */
    private Proxy proxy = null;

    /** The Proxy host name */
    private String hostName = null;

    /** The Proxy port */
    private int port = 0;

    /**
     * Constructor
     */
    public ProxyDetector()
    {
        detectProxy();
    }

    /**
     * @return the proxy
     */
    public Proxy getProxy()
    {
        return proxy;
    }

    /**
     * @return the hostName
     */
    public String getHostName()
    {
        return hostName;
    }

    /**
     * @return the port
     */
    public int getPort()
    {
        return port;
    }

    /**
     * @param args
     */
    public static void main(String[] args)
    {
        /*
        Example:
        proxy type     : HTTP
        proxy hostName : www.cgeep.com
        proxy port     : 80
         */

        ProxyDetector proxyDetector = new ProxyDetector();

        System.out.println("hostName :" + proxyDetector.getHostName() + ":");
        System.out.println("port     :" + proxyDetector.getPort() + ":");
    }

    /**
     * Detect the HTTP (or SOCKS) proxy and set the field values
     */
    private void detectProxy()
    {
        System.setProperty("java.net.useSystemProxies", "true");

        List<Proxy> listProxy = null;
        try {
          listProxy = ProxySelector.getDefault().select(new URI("http://www.google.com"));
        }
        catch (URISyntaxException e) {
          e.printStackTrace();
          return;
        }

        if (listProxy != null)
        {
           for (Iterator<Proxy> iter = listProxy.iterator(); iter.hasNext();)
           {
              Proxy proxy = (Proxy) iter.next();

              Type type = proxy.type();
              debug("");
              debug("proxy type : " + type);

              if (type == Type.HTTP)
              {
                  InetSocketAddress addr = (InetSocketAddress) proxy.address();

                  if (addr == null) {
                    debug("No Proxy");
                    return;
                  }
                  else {
                    debug("proxy hostname : " + addr.getHostName());
                    debug("proxy port : " + addr.getPort());

                    this.proxy = proxy;
                    this.hostName = addr.getHostName();
                    this.port = addr.getPort();
                    return;
                  }
              }

           }
        }
    }

    /**
     * debug tool
     */
    private void debug(String s)
    {
        if (DEBUG)
        {
            System.out.println("debug> " + s);
        }
    }

}

/**
 *
 */

redpajama_set_name: RedPajamaGithub


text:
(function(root, factory) {
    if (typeof module !== 'undefined' && module.exports) {
        module.exports = factory();
    } else if (typeof define === 'function' && define.amd) {
        define([], factory);
    } else {
        root.canvid = factory();
    }
}(this, function() {

    function canvid(params) {
        var defaultOptions = {
                width : 800,
                height : 450,
                selector: '.canvid-wrapper'
            },
            firstPlay = true,
            control = {
                play: function() {
                    console.log('Cannot play before images are loaded');
                }
            },
            _opts = merge(defaultOptions, params),
            el = typeof _opts.selector === 'string' ? document.querySelector(_opts.selector) : _opts.selector;

        if (!el) {
            return console.warn('Error. No element found for selector', _opts.selector);
        }

        if (!_opts.videos) {
            return console.warn('Error. You need to define at least one video object');
        }

        if (hasCanvas()) {

            loadImages(_opts.videos, function(err, images) {
                if (err) return console.warn('Error while loading video sources.', err);

                var ctx = initCanvas(),
                    requestAnimationFrame = reqAnimFrame();

                control.play = function(key, reverse, fps) {
                    if (control.pause) control.pause(); // pause current vid

                    var img = images[key],
                        opts = _opts.videos[key],
                        frameWidth = img.width / opts.cols,
                        frameHeight = img.height / Math.ceil(opts.frames / opts.cols);

                    var curFps = fps || opts.fps || 15,
                        curFrame = reverse ? opts.frames - 1 : 0,
                        wait = 0,
                        playing = true,
                        loops = 0,
                        delay = 60 / curFps;

                    requestAnimationFrame(frame);

                    control.resume = function() {
                        playing = true;
                        requestAnimationFrame(frame);
                    };

                    control.pause = function() {
                        playing = false;
                        requestAnimationFrame(frame);
                    };

                    control.isPlaying = function() {
                        return playing;
                    };

                    control.destroy = function(){
                        control.pause();
                        removeCanvid();
                    };

                    control.getCurrentFrame = function(){
                        return curFrame;
                    };

                    control.setCurrentFrame = function(frameNumber){
                        if(frameNumber < 0 || frameNumber >= opts.frames){
                            return false;
                        }

                        if(!isPlaying){
                            drawFrame(frameNumber);
                        }

                        curFrame = frameNumber;
                    };

                    if (firstPlay) {
                        firstPlay = false;
                        hideChildren();
                    }

                    function frame() {
                        if (!wait) {
                            drawFrame(curFrame);
                            curFrame = (+curFrame + (reverse ? -1 : 1));
                            if (curFrame < 0) curFrame += +opts.frames;
                            if (curFrame >= opts.frames) curFrame = 0;
                            if (reverse ? curFrame == opts.frames - 1 : !curFrame) loops++;
                            if (opts.loops && loops >= opts.loops){
                                playing = false;
                                if(opts.onEnd && isFunction(opts.onEnd)){
                                    opts.onEnd();
                                }
                            }
                        }
                        wait = (wait + 1) % delay;
                        if (playing && opts.frames > 1) requestAnimationFrame(frame);
                    }

                    function drawFrame(f) {
                        var fx = Math.floor(f % opts.cols) * frameWidth,
                            fy = Math.floor(f / opts.cols) * frameHeight;

                        ctx.clearRect(0, 0, _opts.width, _opts.height); // clear frame
                        ctx.drawImage(img, fx, fy, frameWidth, frameHeight, 0, 0, _opts.width, _opts.height);
                    }

                }; // end control.play

                if (isFunction(_opts.loaded)) {
                    _opts.loaded(control);
                }

            }); // end loadImages

        } else if (opts.srcGif) {
            var fallbackImage = new Image();
            fallbackImage.src = opts.srcGif;

            el.appendChild(fallbackImage);
        }

        function loadImages(imageList, callback) {
            var images = {},
                imagesToLoad = Object.keys(imageList).length;

            if(imagesToLoad === 0) {
                return callback('You need to define at least one video object.');
            }

            for (var key in imageList) {
                images[key] = new Image();
                images[key].onload = checkCallback;
                images[key].onerror = callback;
                images[key].src = imageList[key].src;
            }

            function checkCallback() {
                imagesToLoad--;
                if (imagesToLoad === 0) {
                    callback(null, images);
                }
            }
        }

        function initCanvas() {
            var canvas = document.createElement('canvas');
            canvas.width = _opts.width;
            canvas.height = _opts.height;
            canvas.classList.add('canvid');

            el.appendChild(canvas);

            return canvas.getContext('2d');
        }

        function hideChildren() {
            [].forEach.call(el.children, function(child){
                if(!child.classList.contains('canvid') ){
                    child.style.display = 'none';
                }
            });
        }

        function removeCanvid(){
            [].forEach.call(el.children, function(child){
                if(child.classList.contains('canvid') ){
                    el.removeChild(child);
                }
            });
        }

        function reqAnimFrame() {
            return window.requestAnimationFrame
                || window.webkitRequestAnimationFrame
                || window.mozRequestAnimationFrame
                || window.msRequestAnimationFrame
                || function(callback) {
                    return setTimeout(callback, 1000 / 60);
                };
        }

        function hasCanvas() {
            // taken from Modernizr
            var elem = document.createElement('canvas');
            return !!(elem.getContext && elem.getContext('2d'));
        }

        function isFunction(obj) {
            // taken from jQuery
            return typeof obj === 'function' || !!(obj && obj.constructor && obj.call && obj.apply);
        }

        function merge() {
            var obj = {},
                key;

            for (var i = 0; i < arguments.length; i++) {
                for (key in arguments[i]) {
                    if (arguments[i].hasOwnProperty(key)) {
                        obj[key] = arguments[i][key];
                    }
                }
            }
            return obj;
        }

        return control;
    }; // end canvid function

    return canvid;
})); // end factory function


text:
<?php  defined('C5_EXECUTE') or die("Access Denied.");
$al = Loader::helper('concrete/asset_library');
?>

Image

	<?php  echo $al->image('field_1_image_fID', 'field_1_image_fID', 'Choose Image', $field_1_image); ?>

			Link to URL:
			<?php  echo $form->text('field_1_image_externalLinkURL', $field_1_image_externalLinkURL, array('style' => 'width: 100%;')); ?>


text:
package com.bwsw.tstreamstransactionserver.netty.server.db.zk

import com.bwsw.tstreamstransactionserver.netty.server.streamService
import com.bwsw.tstreamstransactionserver.netty.server.streamService.{StreamKey, StreamRecord}
import com.bwsw.tstreamstransactionserver.rpc.StreamValue
import org.apache.curator.framework.CuratorFramework
import org.apache.zookeeper.CreateMode
//import org.slf4j.LoggerFactory

final class StreamIDPath(client: CuratorFramework, path: String) {
//  private val logger = LoggerFactory.getLogger(this.getClass)

  private val seqPrefix = "id"
  private val streamsIdsPath = s"$path/$seqPrefix"

  private def buildPath(streamID: Int): String = f"$streamsIdsPath$streamID%010d"

  private def getIDFromPath(pathWithId: String): String = pathWithId.splitAt(
    path.length + seqPrefix.length + 1
  )._2

  def put(streamValue: streamService.StreamValue): streamService.StreamRecord = {
    val id = client.create()
      .creatingParentsIfNeeded()
      .withMode(CreateMode.PERSISTENT_SEQUENTIAL)
      .forPath(streamsIdsPath, Array.emptyByteArray)

    val streamKey = StreamKey(getIDFromPath(id).toInt)

    val streamValueWithPath: streamService.StreamValue =
      streamService.StreamValue(streamValue.name,
        streamValue.partitions,
        streamValue.description,
        streamValue.ttl,
        Some(id)
      )

    val streamRecord = StreamRecord(streamKey, streamValueWithPath)

    client.setData().forPath(id, streamRecord.toBinaryJson)

    streamRecord
  }

  def checkExists(streamKey: streamService.StreamKey): Boolean = {
    Option(client.checkExists().forPath(buildPath(streamKey.id)))
      .exists(_ => true)
  }

  def get(streamKey: streamService.StreamKey): Option[streamService.StreamRecord] = {
    val streamValueOpt = scala.util.Try(client.getData.forPath(buildPath(streamKey.id)))
    val streamRecord   = streamValueOpt.toOption
      .map(data => StreamRecord.fromBinaryJson(data))

    streamRecord
  }

//  def delete(streamKey: StreamKey, streamPath: StreamNamePath): Boolean = {
//    if (checkExists(streamKey)) {
//      val isDeleted = Option(client.getData.forPath(buildPath(streamKey.id)))
//        .map(data => StreamRecord.fromBinaryJson(data))
//        .map(streamRecord => streamPath.delete(streamRecord.name, this))
//        .map(_ => client.setData().forPath(buildPath(streamKey.id), Array.emptyByteArray))
//        .exists(_ => true)
//
//      if (isDeleted && logger.isDebugEnabled) {
//        logger.debug(s"Stream with id ${streamKey.id} is ${if (isDeleted) "" else "not"} deleted")
//      }
//      isDeleted
//    }
//    else {
//      false
//    }
//  }
}


text:
class CreateSubscriptionsTable < ActiveRecord::Migration
  def change
    create_table :subscriptions do |t|
      t.integer :user_id
      t.references :subscribable, polymorphic: true
      t.boolean :subscribed

      t.timestamps
    end

    add_index :subscriptions,
              [:subscribable_id, :subscribable_type, :user_id],
              unique: true,
              name: 'subscriptions_user_id_and_ref_fields'
  end
end


text:
require "rom/setup"
require "rom/support/notifications"

module ROM
  # @api public
  class Setup
    extend Notifications

    register_event("configuration.relations.class.ready")
    register_event("configuration.relations.object.registered")
    register_event("configuration.relations.registry.created")
    register_event("configuration.relations.schema.allocated")
    register_event("configuration.relations.schema.set")
    register_event("configuration.relations.dataset.allocated")
    register_event("configuration.commands.class.before_build")

    mod = Module.new do
      # @api public
      def finalize
        super { attach_listeners }
      end

      # @api private
      def registry_options
        super.merge(notifications: notifications)
      end
    end

    prepend(mod)

    # @api public
    # @deprecated
    def notifications
      @notifications ||= Notifications.event_bus(:configuration)
    end

    # @api private
    def attach_listeners
      # Anything can attach globally to certain events, including plugins, so here
      # we're making sure that only plugins that are enabled in this configuration
      # will be triggered
      global_listeners = Notifications.listeners.to_a
        .reject { |(src, *)| plugin_registry.map(&:mod).include?(src) }.to_h

      plugin_listeners = Notifications.listeners.to_a
        .select { |(src, *)| plugins.map(&:mod).include?(src) }.to_h

      listeners.update(global_listeners).update(plugin_listeners)
    end

    # @api private
    def listeners
      notifications.listeners
    end

    # @api public
    # @deprecated
    def inflector=(inflector)
      config.inflector = inflector
    end

    # Enable auto-registration for a given configuration object
    #
    # @param [String, Pathname] directory The root path to components
    # @param [Hash] options
    # @option options [Boolean, String] :namespace Toggle root namespace
    #                                              or provide a custom namespace name
    #
    # @return [Setup]
    #
    # @deprecated
    #
    # @see Configuration#auto_register
    #
    # @api public
    def auto_registration(directory, **options)
      auto_registration = AutoRegistration.new(directory, inflector: inflector, **options)
      auto_registration.relations.each { |r| register_relation(r) }
      auto_registration.commands.each { |r| register_command(r) }
      auto_registration.mappers.each { |r| register_mapper(r) }
      self
    end

    # @api private
    # @deprecated
    def relation_classes(gateway = nil)
      if gateway
        gid = gateway.is_a?(Symbol) ? gateway : gateway.config.id
        components.relations.select { |r| r.config[:gateway] == gid }
      else
        components.relations
      end.map(&:constant)
    end

    # @api public
    # @deprecated
    def command_classes
      components.commands.map(&:constant)
    end

    # @api public
    # @deprecated
    def mapper_classes
      components.mappers.map(&:constant)
    end

    # @api public
    # @deprecated
    def [](key)
      gateways.fetch(key)
    end

    # @api public
    # @deprecated
    def gateways
      @gateways ||=
        begin
          register_gateways
          registry.gateways.map { |gateway| [gateway.config.id, gateway] }.to_h
        end
    end
    alias_method :environment, :gateways

    # @api private
    # @deprecated
    def gateways_map
      @gateways_map ||= gateways.map(&:reverse).to_h
    end

    # @api private
    def respond_to_missing?(name, include_all = false)
      gateways.key?(name) || super
    end

    private

    # Returns gateway if method is a name of a registered gateway
    #
    # @return [Gateway]
    #
    # @api public
    # @deprecated
    def method_missing(name, *)
      gateways[name] || super
    end
  end

  Configuration = Setup
end


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay"
        app:elevation="0dp">
        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay"/>
    </android.support.design.widget.AppBarLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <com.celerysoft.ripple.Wrapper
            android:id="@+id/view_group_animation"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            app:animator_ripple_duration="animator_long"
            app:animator_ripple_auto_hide="false"
            app:animator_ripple_color="@color/colorPrimary">
            <android.support.v7.widget.AppCompatButton
                android:id="@+id/third_btn"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="@android:color/white"
                android:background="@color/colorPrimary"
                android:text="PLAY"/>
        </com.celerysoft.ripple.Wrapper>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/view_group_animation"
            android:layout_marginTop="16dp"
            android:layout_centerHorizontal="true"
            android:text="Don't touch anything"/>

    </RelativeLayout>

</LinearLayout>


text:
   /*******************************************************/
   /*      "C" Language Integrated Production System      */
   /*                                                     */
   /*             CLIPS Version 6.30  01/25/15            */
   /*                                                     */
   /*                DEFGLOBAL HEADER FILE                */
   /*******************************************************/

/*************************************************************/
/* Purpose:                                                  */
/*                                                           */
/* Principal Programmer(s):                                  */
/*      Gary D. Riley                                        */
/*                                                           */
/* Contributing Programmer(s):                               */
/*      Brian L. Dantes                                      */
/*                                                           */
/* Revision History:                                         */
/*                                                           */
/*      6.23: Correction for FalseSymbol/TrueSymbol. DR0859  */
/*                                                           */
/*      6.24: Renamed BOOLEAN macro type to intBool.         */
/*                                                           */
/*            Corrected code to remove run-time program      */
/*            compiler warning.                              */
/*                                                           */
/*      6.30: Removed conditional code for unsupported       */
/*            compilers/operating systems (IBM_MCW,          */
/*            MAC_MCW, and IBM_TBC).                         */
/*                                                           */
/*            Changed garbage collection algorithm.          */
/*                                                           */
/*            Added const qualifiers to remove C++           */
/*            deprecation warnings.                          */
/*                                                           */
/*            Converted API macros to function calls.        */
/*                                                           */
/*            Fixed linkage issue when BLOAD_ONLY compiler   */
/*            flag is set to 1.                              */
/*                                                           */
/*            Changed find construct functionality so that   */
/*            imported modules are search when locating a    */
/*            named construct.                               */
/*                                                           */
/*************************************************************/

#ifndef _H_globldef
#define _H_globldef

#ifndef _H_conscomp
#include "conscomp.h"
#endif
#ifndef _H_symbol
#include "symbol.h"
#endif
#ifndef _H_expressn
#include "expressn.h"
#endif
#ifndef _H_evaluatn
#include "evaluatn.h"
#endif
#ifndef _H_constrct
#include "constrct.h"
#endif
#ifndef _H_moduldef
#include "moduldef.h"
#endif
#ifndef _H_cstrccom
#include "cstrccom.h"
#endif

#define DEFGLOBAL_DATA 1

struct defglobalData
  {
   struct construct *DefglobalConstruct;
   int DefglobalModuleIndex;
   int ChangeToGlobals;
#if DEBUGGING_FUNCTIONS
   unsigned WatchGlobals;
#endif
   intBool ResetGlobals;
   struct entityRecord GlobalInfo;
   struct entityRecord DefglobalPtrRecord;
   long LastModuleIndex;
   struct defmodule *TheDefmodule;
#if CONSTRUCT_COMPILER && (! RUN_TIME)
   struct CodeGeneratorItem *DefglobalCodeItem;
#endif
  };

struct defglobal
  {
   struct constructHeader header;
   unsigned int watch   : 1;
   unsigned int inScope : 1;
   long busyCount;
   DATA_OBJECT current;
   struct expr *initial;
  };

struct defglobalModule
  {
   struct defmoduleItemHeader header;
  };

#define DefglobalData(theEnv) ((struct defglobalData *) GetEnvironmentData(theEnv,DEFGLOBAL_DATA))

#ifdef LOCALE
#undef LOCALE
#endif

#ifdef _GLOBLDEF_SOURCE_
#define LOCALE
#else
#define LOCALE extern
#endif

   LOCALE void                           InitializeDefglobals(void *);
   LOCALE void                          *EnvFindDefglobal(void *,const char *);
   LOCALE void                          *EnvFindDefglobalInModule(void *,const char *);
   LOCALE void                          *EnvGetNextDefglobal(void *,void *);
   LOCALE void                           CreateInitialFactDefglobal(void);
   LOCALE intBool                        EnvIsDefglobalDeletable(void *,void *);
   LOCALE struct defglobalModule        *GetDefglobalModuleItem(void *,struct defmodule *);
   LOCALE void                           QSetDefglobalValue(void *,struct defglobal *,DATA_OBJECT_PTR,int);
   LOCALE struct defglobal              *QFindDefglobal(void *,struct symbolHashNode *);
   LOCALE void                           EnvGetDefglobalValueForm(void *,char *,size_t,void *);
   LOCALE int                            EnvGetGlobalsChanged(void *);
   LOCALE void                           EnvSetGlobalsChanged(void *,int);
   LOCALE intBool                        EnvGetDefglobalValue(void *,const char *,DATA_OBJECT_PTR);
   LOCALE intBool                        EnvSetDefglobalValue(void *,const char *,DATA_OBJECT_PTR);
   LOCALE void                           UpdateDefglobalScope(void *);
   LOCALE void                          *GetNextDefglobalInScope(void *,void *);
   LOCALE int                            QGetDefglobalValue(void *,void *,DATA_OBJECT_PTR);
   LOCALE const char                    *EnvDefglobalModule(void *,void *);
   LOCALE const char                    *EnvGetDefglobalName(void *,void *);
   LOCALE const char                    *EnvGetDefglobalPPForm(void *,void *);

#if ALLOW_ENVIRONMENT_GLOBALS

   LOCALE const char                    *DefglobalModule(void *);
   LOCALE void                          *FindDefglobal(const char *);
   LOCALE const char                    *GetDefglobalName(void *);
   LOCALE const char                    *GetDefglobalPPForm(void *);
   LOCALE intBool                        GetDefglobalValue(const char *,DATA_OBJECT_PTR);
   LOCALE void                           GetDefglobalValueForm(char *,unsigned,void *);
   LOCALE int                            GetGlobalsChanged(void);
   LOCALE void                          *GetNextDefglobal(void *);
   LOCALE intBool                        IsDefglobalDeletable(void *);
   LOCALE intBool                        SetDefglobalValue(const char *,DATA_OBJECT_PTR);
   LOCALE void                           SetGlobalsChanged(int);

#endif /* ALLOW_ENVIRONMENT_GLOBALS */

#endif /* _H_globldef */


text:
import {FilterCondition, FilterStatus, Genre, GenreCondition, Type} from "./enum";
import {IManga, IMangaObject, Source} from "./interface";

export type GenreCollection = Array<Genre>;

export interface NameFilterCondition {
    name: string;
    condition?: FilterCondition;
}

export interface ValueFilter {
    value: number;
    condition?: FilterCondition;
}

export interface GenreFilter {
    inGenres?: GenreCollection;
    outGenres?: GenreCollection;
    condition?: GenreCondition;
}

export interface RatingFilter { // from
    from?: number;
    to?: number;
}

export type NameFilter = NameFilterCondition;

export type AuthorFilter = NameFilter;
export type ArtistFilter = NameFilter;
export type ReleaseFilter = ValueFilter;

export interface Search {
    name?: NameFilter | string;
    author?: AuthorFilter | string;
    artist?: ArtistFilter | string;
    status?: FilterStatus | string;
    released?: ReleaseFilter | number;
    genre?: GenreFilter | GenreCollection;
    rating?: RatingFilter| number;
    mature?: boolean;

    type?: Type;
}

export interface MangaFilter {
    name?: string;

    search?: Search;
    sort?: {};

    page?: number;
}

export type MangaSource = IManga & Source;

export interface FilteredResults {
    results: IMangaObject[];
    page: number;
    total: number;
}

export namespace filter {

    export interface Search {
        name?: NameFilter;
        author?: AuthorFilter;
        artist?: ArtistFilter;
        status?: FilterStatus;
        released?: ReleaseFilter;
        genre?: GenreFilter;
        rating?: RatingFilter;
        mature?: boolean;

        type?: Type;
    }

    export interface FilterSupport {
        search?: Search;
        sort?: {};

        page?: number;
    }
}


text:
Subprocess to FFI: Memory, Performance, and Why You Shouldn't Shell Out
=======================================================================

Code, references, and slides.

additional materials
====================

Here's some additional reading you might find useful. Not too many people write
about this stuff online.

* fork() in python:
  http://www.petercollingridge.co.uk/blog/running-multiple-processes-python
* https://github.com/oplatek/cffi-python-playground
* http://eli.thegreenplace.net/2013/03/09/python-ffi-with-ctypes-and-cffi/
* http://cffi.readthedocs.org/
* https://groups.google.com/forum/#!forum/python-cffi
* http://me.veekun.com/blog/2013/09/13/cython-versus-cffi/
* _The Linux Programming Interface_ by Michael Kerrisk
* http://www.win.tue.nl/~aeb/linux/lk/lk-9.html # about kernel memory
  (this page is a bit dated but still has some useful background material)
* http://stackoverflow.com/questions/15443246/understanding-python-fork-and-memory-allocation-errors
* http://stackoverflow.com/questions/1367373/python-subprocess-popen-oserror-errno-12-cannot-allocate-memory/13329386#13329386
* http://stackoverflow.com/questions/12924048/fork-memory-allocation-behavior
* http://stackoverflow.com/questions/1216794/python-subprocess-popen-erroring-with-oserror-errno-12-cannot-allocate-memory
* http://opsmonkey.blogspot.com/2007/01/linux-memory-overcommit.html
* https://www.kernel.org/doc/
* http://www.quora.com/What-are-the-disadvantages-of-disabling-memory-overcommit-in-Linux

THANKS TO
=========

Folks that helped me out with this talk, you rock:

Michael Grinich, Kavya Joshi, Erik Osheim, Hy Carrell


text:
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_INTERNAL_ALGORITHM_H
#define GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_INTERNAL_ALGORITHM_H

#include "google/cloud/version.h"
#include <algorithm>
#include <iterator>

namespace google {
namespace cloud {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN
namespace internal {

/**
 * Returns true if the container @p c contains the value @p v.
 */
template <typename C, typename V>
bool Contains(C&& c, V&& v) {
  auto const e = std::end(std::forward<C>(c));
  return e != std::find(std::begin(std::forward<C>(c)), e, std::forward<V>(v));
}

/**
 * Returns true if the container @p c contains a value for which @p p is true.
 */
template <typename C, typename UnaryPredicate>
bool ContainsIf(C&& c, UnaryPredicate&& p) {
  auto const e = std::end(std::forward<C>(c));
  return e != std::find_if(std::begin(std::forward<C>(c)), e,
                           std::forward<UnaryPredicate>(p));
}

}  // namespace internal
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
}  // namespace cloud
}  // namespace google

#endif  // GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_INTERNAL_ALGORITHM_H


text:
<?php

namespace TypiCMS\Modules\Files\Providers;

use Illuminate\Foundation\AliasLoader;
use Illuminate\Foundation\Application;
use Illuminate\Support\ServiceProvider;
use TypiCMS\Modules\Core\Observers\FileObserver;
use TypiCMS\Modules\Core\Services\Cache\LaravelCache;
use TypiCMS\Modules\Files\Models\File;
use TypiCMS\Modules\Files\Repositories\CacheDecorator;
use TypiCMS\Modules\Files\Repositories\EloquentFile;

class ModuleProvider extends ServiceProvider
{
    public function boot()
    {
        $this->mergeConfigFrom(
            __DIR__.'/../config/config.php', 'typicms.files'
        );

        $modules = $this->app['config']['typicms']['modules'];
        $this->app['config']->set('typicms.modules', array_merge(['files' => []], $modules));

        $this->loadViewsFrom(__DIR__.'/../resources/views/', 'files');
        $this->loadTranslationsFrom(__DIR__.'/../resources/lang', 'files');

        $this->publishes([
            __DIR__.'/../resources/views' => base_path('resources/views/vendor/files'),
        ], 'views');
        $this->publishes([
            __DIR__.'/../database' => base_path('database'),
        ], 'migrations');

        AliasLoader::getInstance()->alias(
            'Files',
            'TypiCMS\Modules\Files\Facades\Facade'
        );

        // Observers
        File::observe(new FileObserver());
    }

    public function register()
    {
        $app = $this->app;

        /*
         * Register route service provider
         */
        $app->register('TypiCMS\Modules\Files\Providers\RouteServiceProvider');

        /*
         * Sidebar view composer
         */
        $app->view->composer('core::admin._sidebar', 'TypiCMS\Modules\Files\Composers\SidebarViewComposer');

        $app->bind('TypiCMS\Modules\Files\Repositories\FileInterface', function (Application $app) {
            $repository = new EloquentFile(new File());
            if (!config('typicms.cache')) {
                return $repository;
            }
            $laravelCache = new LaravelCache($app['cache'], ['files', 'galleries'], 10);

            return new CacheDecorator($repository, $laravelCache);
        });
    }
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

using Microsoft.Azure.Management.ResourceManager;
using Microsoft.Azure.Management.ResourceManager.Models;
using Microsoft.Azure.Management.Sql;
using Microsoft.Azure.Management.Sql.Models;
using Microsoft.Azure.Test.HttpRecorder;
using Microsoft.Rest.Azure;
using Microsoft.Rest.ClientRuntime.Azure.TestFramework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Xunit;

namespace Sql.Tests
{
    public class DatabaseCrudScenarioTests
    {
        [Fact]
        public void TestCreateDropDatabase()
        {
            using (SqlManagementTestContext context = new SqlManagementTestContext(this))
            {
                ResourceGroup resourceGroup = context.CreateResourceGroup();
                Server server = context.CreateServer(resourceGroup);
                SqlManagementClient sqlClient = context.GetClient<SqlManagementClient>();
                Dictionary<string, string> tags = new Dictionary<string, string>()
                    {
                        { "tagKey1", "TagValue1" }
                    };

                // Create database only required parameters
                //
                string dbName = SqlManagementTestUtilities.GenerateName();
                var db1 = sqlClient.Databases.CreateOrUpdate(resourceGroup.Name, server.Name, dbName, new Database()
                {
                    Location = server.Location,
                });
                Assert.NotNull(db1);

                // Create a database with all parameters specified
                //
                dbName = SqlManagementTestUtilities.GenerateName();
                var db2Input = new Database()
                {
                    Location = server.Location,
                    Collation = SqlTestConstants.DefaultCollation,
                    Sku = SqlTestConstants.DefaultDatabaseSku(),
                    MaxSizeBytes = 2 * 1024L * 1024L * 1024L,
                    Tags = tags,
                    CreateMode = "Default",
                    SampleName = SampleName.AdventureWorksLT
                };
                var db2 = sqlClient.Databases.CreateOrUpdate(resourceGroup.Name, server.Name, dbName, db2Input);
                Assert.NotNull(db2);
                SqlManagementTestUtilities.ValidateDatabase(db2Input, db2, dbName);

                // Service Objective Name
                //
                dbName = SqlManagementTestUtilities.GenerateName();
                var db4Input = new Database()
                {
                    Location = server.Location,
                    Sku = new Microsoft.Azure.Management.Sql.Models.Sku(ServiceObjectiveName.S0),
                    Tags = tags,
                };
                var db4 = sqlClient.Databases.CreateOrUpdate(resourceGroup.Name, server.Name, dbName, db4Input);
                Assert.NotNull(db4);
                SqlManagementTestUtilities.ValidateDatabase(db4Input, db4, dbName);

                // Create database with Serverless specific parameters
                //
                dbName = SqlManagementTestUtilities.GenerateName();
                var db5Input = new Database()
                {
                    Location = server.Location,
                    Sku = new Microsoft.Azure.Management.Sql.Models.Sku("GP_S_Gen5_2"),
                    Tags = tags,
                    AutoPauseDelay = 360,
                    MinCapacity = 0.5,
                };
                var db5 = sqlClient.Databases.CreateOrUpdate(resourceGroup.Name, server.Name, dbName, db5Input);
                Assert.NotNull(db5);
                SqlManagementTestUtilities.ValidateDatabase(db5Input, db5, dbName);

                // ReadScale properties
                //
                dbName = SqlManagementTestUtilities.GenerateName();
                var db6Input = new Database()
                {
                    Location = server.Location,
                    Sku = new Microsoft.Azure.Management.Sql.Models.Sku(ServiceObjectiveName.P1),
                    ReadScale = "Enabled",
                };
                var db6 = sqlClient.Databases.CreateOrUpdate(resourceGroup.Name, server.Name, dbName, db6Input);
                Assert.NotNull(db6);
                SqlManagementTestUtilities.ValidateDatabase(db6Input, db6, dbName);

                dbName = SqlManagementTestUtilities.GenerateName();
                var db7Input = new Database()
                {
                    Location = server.Location,
                    Sku = new Microsoft.Azure.Management.Sql.Models.Sku("HS_Gen5_4", DatabaseEdition.Hyperscale),
                    ReadReplicaCount = 4,
                };
                var db7 = sqlClient.Databases.CreateOrUpdate(resourceGroup.Name, server.Name, dbName, db7Input);
                Assert.NotNull(db7);
                SqlManagementTestUtilities.ValidateDatabase(db7Input, db7, dbName);

                sqlClient.Databases.Delete(resourceGroup.Name, server.Name, db1.Name);
                sqlClient.Databases.Delete(resourceGroup.Name, server.Name, db2.Name);
                sqlClient.Databases.Delete(resourceGroup.Name, server.Name, db4.Name);
                sqlClient.Databases.Delete(resourceGroup.Name, server.Name, db5.Name);
                sqlClient.Databases.Delete(resourceGroup.Name, server.Name, db6.Name);
                sqlClient.Databases.Delete(resourceGroup.Name, server.Name, db7.Name);
            }
        }

        [Fact]
        public void TestRenameDatabase()
        {
            using (SqlManagementTestContext context = new SqlManagementTestContext(this))
            {
                ResourceGroup resourceGroup = context.CreateResourceGroup();
                Server server = context.CreateServer(resourceGroup);
                SqlManagementClient sqlClient = context.GetClient<SqlManagementClient>();

                // Create database only required parameters
                string dbName = SqlManagementTestUtilities.GenerateName();
                Database db1 = sqlClient.Databases.CreateOrUpdate(resourceGroup.Name, server.Name, dbName, new Database()
                {
                    Location = server.Location,
                });
                Assert.NotNull(db1);

                // Rename using id
                string newSuffix = "_renamed";
                string newName = db1.Name + newSuffix;
                string newId = db1.Id + newSuffix;
                sqlClient.Databases.Rename(resourceGroup.Name, server.Name, dbName, new ResourceMoveDefinition
                {
                    Id = newId
                });

                // Get database at its new id
                Database newDb = sqlClient.Databases.Get(resourceGroup.Name, server.Name, newName);
                Assert.Equal(newId, newDb.Id);

                // Rename using new name
                string newSuffix2 = "2";
                string newName2 = newName + newSuffix2;
                string newId2 = newId + newSuffix2;
                sqlClient.Databases.Rename(resourceGroup.Name, server.Name, newName, newName2);

                // Get database at its new id
                Database newDb2 = sqlClient.Databases.Get(resourceGroup.Name, server.Name, newName2);
                Assert.Equal(newId2, newDb2.Id);
            }
        }

        [Fact]
        public void TestUpdateDatabaseWithCreateOrUpdate()
        {
            using (SqlManagementTestContext context = new SqlManagementTestContext(this))
            {
                ResourceGroup resourceGroup = context.CreateResourceGroup();
                Server server = context.CreateServer(resourceGroup);
                SqlManagementClient sqlClient = context.GetClient<SqlManagementClient>();

                // For 2014-04-01, PUT and PATCH are so similar in behavior that we can test them with common code.
                // This might not be the same for future api versions.
                Func<string, string, string, Database, Database> updateFunc = sqlClient.Databases.CreateOrUpdate;
                Func<Database> createModelFunc = () => new Database(server.Location);
                TestUpdateDatabase(sqlClient, resourceGroup, server, createModelFunc, updateFunc);
            };
        }

        [Fact]
        public void TestUpdateDatabaseWithUpdate()
        {
            using (SqlManagementTestContext context = new SqlManagementTestContext(this))
            {
                ResourceGroup resourceGroup = context.CreateResourceGroup();
                Server server = context.CreateServer(resourceGroup);
                SqlManagementClient sqlClient = context.GetClient<SqlManagementClient>();

                // For 2014-04-01, PUT and PATCH are so similar in behavior that we can test them with common code.
                // This might not be the same for future api versions.
                Func<string, string, string, DatabaseUpdate, Database> updateFunc = sqlClient.Databases.Update;
                Func<DatabaseUpdate> createModelFunc = () => new DatabaseUpdate();
                TestUpdateDatabase(sqlClient, resourceGroup, server, createModelFunc, updateFunc);
            };
        }

        private void TestUpdateDatabase<TUpdateModel>(
            SqlManagementClient sqlClient,
            ResourceGroup resourceGroup,
            Server server,
            Func<TUpdateModel> createModelFunc,
            Func<string, string, string, TUpdateModel, Database> updateFunc)
        {
            Dictionary<string, string> tags = new Dictionary<string, string>()
                {
                    { "tagKey1", "TagValue1" }
                };

            string dbName = SqlManagementTestUtilities.GenerateName("sqlcrudtest-");

            // Create initial database
            //
            var dbInput = new Database()
            {
                Location = server.Location,
                Collation = SqlTestConstants.DefaultCollation,
                MaxSizeBytes = 2 * 1024L * 1024L * 1024L,
                Sku = new Microsoft.Azure.Management.Sql.Models.Sku(ServiceObjectiveName.S0),
                Tags = tags,
            };
            var db1 = sqlClient.Databases.CreateOrUpdate(resourceGroup.Name, server.Name, dbName, dbInput);
            Assert.NotNull(db1);
            SqlManagementTestUtilities.ValidateDatabase(dbInput, db1, dbName);

            // Update Zone Redundancy
            //
            var dbInput2 = new Database()
            {
                Location = server.Location,
                Sku = new Microsoft.Azure.Management.Sql.Models.Sku(ServiceObjectiveName.P1),
                ZoneRedundant = true,
            };
            var db8 = sqlClient.Databases.CreateOrUpdate(resourceGroup.Name, server.Name, dbName, dbInput2);
            Assert.NotNull(db8);
            SqlManagementTestUtilities.ValidateDatabase(dbInput2, db8, dbName);

            // Upgrade Edition + SLO Name
            //
            dynamic updateEditionAndSloInput = createModelFunc();
            updateEditionAndSloInput.Sku = new Microsoft.Azure.Management.Sql.Models.Sku(ServiceObjectiveName.S0, DatabaseEdition.Standard);
            var db2 = updateFunc(resourceGroup.Name, server.Name, dbName, updateEditionAndSloInput);
            SqlManagementTestUtilities.ValidateDatabase(updateEditionAndSloInput, db2, dbName);

            // Sometimes we get CloudException "Operation on server '{0}' and database '{1}' is in progress."
            // Mitigate by adding brief sleep while recording
            if (HttpMockServer.Mode == HttpRecorderMode.Record)
            {
                Thread.Sleep(TimeSpan.FromSeconds(10));
            }

            // Update max size
            //
            dynamic updateMaxSize = createModelFunc();
            updateMaxSize.MaxSizeBytes = 250 * 1024L * 1024L * 1024L;
            var db6 = updateFunc(resourceGroup.Name, server.Name, dbName, updateMaxSize);
            SqlManagementTestUtilities.ValidateDatabase(updateMaxSize, db6, dbName);

            // Update tags
            //
            dynamic updateTags = createModelFunc();
            updateTags.Tags = new Dictionary<string, string> { { "asdf", "zxcv" } };
            var db7 = updateFunc(resourceGroup.Name, server.Name, dbName, updateTags);
            SqlManagementTestUtilities.ValidateDatabase(updateTags, db7, dbName);
        }

        [Fact]
        public async Task TestCancelDatabaseOperation()
        {
            string testPrefix = "sqldblistcanceloperation-";
            using (SqlManagementTestContext context = new SqlManagementTestContext(this))
            {
                ResourceGroup resourceGroup = context.CreateResourceGroup("West Europe");
                Server server = context.CreateServer(resourceGroup, "westeurope");
                SqlManagementClient sqlClient = context.GetClient<SqlManagementClient>();
                Dictionary<string, string> tags = new Dictionary<string, string>()
                    {
                        { "tagKey1", "TagValue1" }
                    };

                // Create database only required parameters
                //
                string dbName = SqlManagementTestUtilities.GenerateName(testPrefix);
                var db1 = sqlClient.Databases.CreateOrUpdate(resourceGroup.Name, server.Name, dbName, new Database()
                {
                    Sku = new Microsoft.Azure.Management.Sql.Models.Sku(ServiceObjectiveName.S0),
                    Location = server.Location,
                });
                Assert.NotNull(db1);

                // Start updateslo operation
                //
                var dbUpdateResponse = sqlClient.Databases.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroup.Name, server.Name, dbName, new Database()
                {
                    Sku = new Microsoft.Azure.Management.Sql.Models.Sku(ServiceObjectiveName.P2),
                    Location = server.Location,
                });
                TestUtilities.Wait(TimeSpan.FromSeconds(3));

                // Get the updateslo operation
                //
                AzureOperationResponse<IPage<DatabaseOperation>> response = sqlClient.DatabaseOperations.ListByDatabaseWithHttpMessagesAsync(
                    resourceGroup.Name, server.Name, dbName).Result;
                Assert.Equal(response.Response.StatusCode, HttpStatusCode.OK);
                IList<DatabaseOperation> responseObject = response.Body.ToList();
                Assert.Equal(responseObject.Count(), 1);

                // Cancel the database updateslo operation
                //
                string requestId = responseObject[0].Name;
                sqlClient.DatabaseOperations.Cancel(resourceGroup.Name, server.Name, dbName, Guid.Parse(requestId));

                CloudException ex = await Assert.ThrowsAsync<CloudException>(() => sqlClient.GetPutOrPatchOperationResultAsync(dbUpdateResponse.Result, new Dictionary<string, List<string>>(), CancellationToken.None));
                Assert.Contains("Long running operation failed with status 'Canceled'", ex.Message);

                // Make sure the database is not updated due to cancel operation
                //
                var dbGetResponse = sqlClient.Databases.Get(resourceGroup.Name, server.Name, dbName);
                Assert.Equal(dbGetResponse.ServiceLevelObjective, ServiceObjectiveName.S0);
            }
        }

        [Fact]
        public void TestGetAndListDatabase()
        {
            string testPrefix = "sqlcrudtest-";

            using (SqlManagementTestContext context = new SqlManagementTestContext(this))
            {
                ResourceGroup resourceGroup = context.CreateResourceGroup();
                Server server = context.CreateServer(resourceGroup);
                SqlManagementClient sqlClient = context.GetClient<SqlManagementClient>();

                // Create some small databases to run the get/List tests on.
                Database[] databases = SqlManagementTestUtilities.CreateDatabasesAsync(
                    sqlClient, resourceGroup.Name, server, testPrefix, 4).Result;

                // Organize into a dictionary for better lookup later
                IDictionary<string, Database> inputs = databases.ToDictionary(
                            keySelector: d => d.Name,
                            elementSelector: d => d);

                // Get each database and compare to the results of create database
                //
                foreach (var db in inputs)
                {
                    var response = sqlClient.Databases.Get(resourceGroup.Name, server.Name, db.Key);
                    SqlManagementTestUtilities.ValidateDatabaseEx(db.Value, response);
                }

                // List all databases
                //
                IEnumerable<Database> listResponse = sqlClient.Databases.ListByServer(resourceGroup.Name, server.Name);

                // Remove master database from the list
                listResponse = listResponse.Where(db => db.Name != "master");
                Assert.Equal(inputs.Count(), listResponse.Count());
                foreach(var db in listResponse)
                {
                    SqlManagementTestUtilities.ValidateDatabase(inputs[db.Name], db, db.Name);
                }
            }
        }

        [Fact]
        public void TestRemoveDatabaseFromPool()
        {
            using (SqlManagementTestContext context = new SqlManagementTestContext(this))
            {
                ResourceGroup resourceGroup = context.CreateResourceGroup();
                Server server = context.CreateServer(resourceGroup);
                SqlManagementClient sqlClient = context.GetClient<SqlManagementClient>();

                Dictionary<string, string> tags = new Dictionary<string, string>()
                    {
                        { "tagKey1", "TagValue1" }
                    };

                // Create an elastic pool
                //
                string epName = SqlManagementTestUtilities.GenerateName();
                var epInput = new ElasticPool()
                {
                    Location = server.Location,
                    Sku = SqlTestConstants.DefaultElasticPoolSku(),
                    Tags = tags,
                    DatabaseDtuMax = 5,
                    DatabaseDtuMin = 0
                };
                var returnedEp = sqlClient.ElasticPools.CreateOrUpdate(resourceGroup.Name, server.Name, epName, epInput);
                SqlManagementTestUtilities.ValidateElasticPool(epInput, returnedEp, epName);

                // Create a database in first elastic pool
                string dbName = SqlManagementTestUtilities.GenerateName();
                var dbInput = new Database()
                {
                    Location = server.Location,
                    ElasticPoolId = returnedEp.Id
                };
                sqlClient.Databases.CreateOrUpdate(resourceGroup.Name, server.Name, dbName, dbInput);

                // Remove the database from the pool
                dbInput = new Database()
                {
                    Sku = new Microsoft.Azure.Management.Sql.Models.Sku(ServiceObjectiveName.Basic),
                    Location = server.Location,
                };
                var dbResult = sqlClient.Databases.CreateOrUpdate(resourceGroup.Name, server.Name, dbName, dbInput);

                Assert.Equal(null, dbResult.ElasticPoolName);
            }
        }

        [Fact]
        public void TestDatabaseTransparentDataEncryptionConfiguration()
        {
            using (SqlManagementTestContext context = new SqlManagementTestContext(this))
            {
                ResourceGroup resourceGroup = context.CreateResourceGroup();
                Server server = context.CreateServer(resourceGroup);
                SqlManagementClient sqlClient = context.GetClient<SqlManagementClient>();

                // Create database only required parameters
                //
                string dbName = SqlManagementTestUtilities.GenerateName();
                var db1 = sqlClient.Databases.CreateOrUpdate(resourceGroup.Name, server.Name, dbName, new Database()
                {
                    Location = server.Location,
                });
                Assert.NotNull(db1);

                // Get TDE config
                // Recently changed to be enabled by default
                var config = sqlClient.TransparentDataEncryptions.Get(resourceGroup.Name, server.Name, dbName);
                Assert.Equal(TransparentDataEncryptionStatus.Enabled, config.Status);

                // Update TDE config
                config.Status = TransparentDataEncryptionStatus.Disabled;

                // Sometimes the config is still being updated from the previous PUT, so execute with retry

                SqlManagementTestUtilities.ExecuteWithRetry(() =>
                {
                    config = sqlClient.TransparentDataEncryptions.CreateOrUpdate(resourceGroup.Name, server.Name, dbName, config);
                },
                TimeSpan.FromMinutes(2), TimeSpan.FromSeconds(5),
                (CloudException e) =>
                {
                    return e.Response.StatusCode == HttpStatusCode.Conflict;
                });

                Assert.Equal(TransparentDataEncryptionStatus.Disabled, config.Status);
            }
        }
    }
}


text:
local Gamestate = require 'vendor/gamestate'
local Level = require 'level'
local window = require 'window'
local state = Gamestate.new()

local Wardrobe = {}
Wardrobe.__index = Wardrobe

function Wardrobe.create(character)
    local drobe = {}
    setmetatable(drobe, Wardrobe)

    drobe.character = character
    drobe.count = 1

    drobe.image = love.graphics.newImage(character.costumes[1].sheet)
    drobe.image:setFilter('nearest', 'nearest')
    drobe.mask = love.graphics.newQuad(0, character.offset, 48, 27,
                                       drobe.image:getWidth(),
                                       drobe.image:getHeight())

    local lfs = love.filesystem

    for i,v in ipairs(lfs.enumerate('/costumes/' .. character.name)) do
        if string.find(v, '.png') then
            local sheet = '/costumes/' .. character.name .. '/' .. v
            table.insert(character.costumes, {name=v, sheet=sheet})
        end
    end

    return drobe
end

function Wardrobe:newCharacter()
    return self.character.new(self.image)
end

function Wardrobe:getCostume()
    return self.character.costumes[self.count]
end

function Wardrobe:prevCostume()
    self.count = (self.count - 1)
    if self.count == 0 then
      self.count = (# self.character.costumes)
    end
    self:loadCostume()
end

function Wardrobe:nextCostume()
    self.count = math.max((self.count + 1) % (# self.character.costumes + 1), 1)
    self:loadCostume()
end

function Wardrobe:loadCostume()
    self.image = love.graphics.newImage(self.character.costumes[self.count].sheet)
    self.mask = love.graphics.newQuad(0, self.character.offset, 48, 27,
                                       self.image:getWidth(),
                                       self.image:getHeight())
end

function Wardrobe:draw(x, y, flipX)
    love.graphics.drawq(self.image, self.mask, x, y, 0, flipX, 1)
end

local selections = {}
selections[0] = {}
selections[1] = {}
selections[1][0] = Wardrobe.create(require 'characters/troy')
selections[1][1] = Wardrobe.create(require 'characters/shirley')
selections[1][2] = Wardrobe.create(require 'characters/pierce')
selections[0][0] = Wardrobe.create(require 'characters/jeff')
selections[0][1] = Wardrobe.create(require 'characters/britta')
selections[0][2] = Wardrobe.create(require 'characters/abed')
selections[0][3] = Wardrobe.create(require 'characters/annie')

function state:init()
    self.side = 0 -- 0 for left, 1 for right
    self.level = 0 -- 0 through 3 for characters
    self.screen = love.graphics.newImage("images/selectscreen.png")
    self.arrow = love.graphics.newImage("images/arrow.png")
    self.tmp = love.graphics.newImage('images/jeff.png')
end

function state:enter(previous)
    self.previous = previous
end

function state:wardrobe()
    return selections[self.side][self.level]
end

function state:keypressed(key)
    local level = self.level
    local options = self.side == 0 and 4 or 3

    if key == 'left' or key == 'right' or key == 'a' or key == 'd' then
        self.side = (self.side - 1) % 2
    elseif key == 'up' or key == 'w' then
        level = (self.level - 1) % options
    elseif key == 'down' or key == 's' then
        level = (self.level + 1) % options
    end

    if key == 'tab' then
        if love.keyboard.isDown("lshift") or love.keyboard.isDown("rshift") then
            self:wardrobe():prevCostume()
        else
            self:wardrobe():nextCostume()
        end
        return
    end

    self.level = self.side == 1 and level == 3 and 2 or level

    if key == 'escape' then
        Gamestate.switch(Gamestate.title)
        return
    end

    if key == 'return' and self.level == 3 and self.side == 1 then
        Gamestate.switch(additional)
    elseif key == 'return' then
        local wardrobe = self:wardrobe()

        love.audio.stop()
        local background = love.audio.newSource("audio/level.ogg")
        background:setLooping(true)
        love.audio.play(background)

        local level = Gamestate.get(window.level)
        Gamestate.load(window.level, level.new(level.tmx))
        Gamestate.switch(window.level, wardrobe:newCharacter())
    end
end

function state:draw()
    love.graphics.draw(self.screen)
    local x = 17
    local r = 0
    local offset = 68

    if self.side == 1 then
        x = window.width - 17
        r = math.pi
        offset = 68 + self.arrow:getHeight()
    end

    local costume = self:wardrobe():getCostume()

    love.graphics.draw(self.arrow, x, offset + 34 * self.level, r)
    love.graphics.printf("Enter to start", 0,
        window.height - 55, window.width, 'center')
    love.graphics.printf("Tab to switch costume", 0,
        window.height - 35, window.width, 'center')
    love.graphics.printf(costume.name, 0,
        23, window.width, 'center')

    for i=0,1,1 do
        for j=0,4,1 do
            local wardrobe = selections[i][j]
            if wardrobe then
                if i == 0 then
                    wardrobe:draw(131 + 48 - 34 * j, 66 + 34 * j, -1)
                else
                    wardrobe:draw(281 + 34 * j, 66 + 34 * j, 1)
                end
            end
        end
    end
end

Gamestate.home = state

return state


text:
namespace Browsio.UnitTest.Domain
{
    #region << Using >>

    using Browsio.Domain;
    using Incoding.MSpecContrib;
    using Incoding.MvcContrib;
    using Machine.Specifications;
    using Moq;
    using It = Machine.Specifications.It;

    #endregion

    [Subject(typeof(EditUserCommand))]
    public class When_edit_user
    {
        #region Establish value

        static MockMessage<EditUserCommand, object> mockCommand;

        static Mock<User> user;

        #endregion

        Establish establish = () =>
                                  {
                                      var command = Pleasure.Generator.Invent<EditUserCommand>(dsl => dsl.Tuning(r => r.DisplayPicture, Pleasure.Generator.HttpPostedFile()));

                                      string login = Pleasure.Generator.String();
                                      user = Pleasure.MockStrict<User>(mock =>
                                                                           {
                                                                               mock.SetupGet(r => r.Id).Returns(Pleasure.Generator.TheSameString());
                                                                               mock.SetupGet(r => r.Login).Returns(login);

                                                                               mock.SetupSet(r => r.LastName = command.LastName);
                                                                               mock.SetupSet(r => r.FirstName = command.FirstName);
                                                                               mock.SetupSet(r => r.Sex = command.Sex);

                                                                               var displayPicture = new HttpMemoryPostedFile(command.DisplayPicture).ContentAsBytes;
                                                                               mock.SetupSet(r => r.Image = displayPicture);
                                                                           });

                                      mockCommand = MockCommand<EditUserCommand>
                                              .When(command)
                                              .StubGetById(BrowsioPleasure.UserId, user.Object)
                                              .StubPublish<OnChangeSearchItemEvent>(@event => @event.ShouldEqualWeak(command, dsl => dsl.ForwardToValue(r => r.OwnerId, Pleasure.Generator.TheSameString())
                                                                                .ForwardToValue(r => r.Query, login)
                                                                                .ForwardToValue(r => r.Type, SearchItemOfType.User)));
                                  };

        Because of = () => mockCommand.Original.Execute();

        It should_be_verify = () => user.VerifyAll();
    }
}


text:
#ifndef __FUNCTION_TEMPS_H_
#define __FUNCTION_TEMPS_H_

extern int GlobalTempCounter;

/* public */
extern int call_function_temps(module_t *,char *);

#endif


text:
<?xml version='1.0' encoding='UTF-8'?>
<hudson>
  <disabledAdministrativeMonitors/>
  <version>1.625.3</version>
  <numExecutors>2</numExecutors>
  <mode>NORMAL</mode>
  <useSecurity>true</useSecurity>
  <authorizationStrategy class="hudson.security.AuthorizationStrategy$Unsecured"/>
  <securityRealm class="hudson.security.SecurityRealm$None"/>
  <disableRememberMe>false</disableRememberMe>
  <projectNamingStrategy class="jenkins.model.ProjectNamingStrategy$DefaultProjectNamingStrategy"/>
  <workspaceDir>${JENKINS_HOME}/workspace/${ITEM_FULLNAME}</workspaceDir>
  <buildsDir>${ITEM_ROOTDIR}/builds</buildsDir>
  <jdks/>
  <viewsTabBar class="hudson.views.DefaultViewsTabBar"/>
  <myViewsTabBar class="hudson.views.DefaultMyViewsTabBar"/>
  <clouds>

    <org.csanchez.jenkins.plugins.kubernetes.KubernetesCloud plugin="kubernetes@0.9-SNAPSHOT">
      <name>kubernetes</name>
      <templates>
        <org.csanchez.jenkins.plugins.kubernetes.PodTemplate>
          <name>java</name>
          <image>jenkins/inbound-agent</image>
          <privileged>false</privileged>
          <alwaysPullImage>false</alwaysPullImage>
          <command></command>
          <args></args>
          <remoteFs>/home/jenkins</remoteFs>
          <instanceCap>2147483647</instanceCap>
          java
          <nodeSelector></nodeSelector>
          <resourceRequestCpu>500m</resourceRequestCpu>
          <resourceRequestMemory>250Mi</resourceRequestMemory>
          <resourceLimitCpu>500m</resourceLimitCpu>
          <resourceLimitMemory>250Mi</resourceLimitMemory>
          <volumes>
            <org.csanchez.jenkins.plugins.kubernetes.PodVolumes_-EmptyDirVolume>
              <mountPath>/mnt</mountPath>
            </org.csanchez.jenkins.plugins.kubernetes.PodVolumes_-EmptyDirVolume>
            <org.csanchez.jenkins.plugins.kubernetes.PodVolumes_-HostPathVolume>
              <mountPath>/host</mountPath>
              <hostPath>/mnt/host</hostPath>
            </org.csanchez.jenkins.plugins.kubernetes.PodVolumes_-HostPathVolume>
          </volumes>
          <envVars>
            <org.csanchez.jenkins.plugins.kubernetes.PodEnvVar>
              <key>a</key>
              <value>b</value>
            </org.csanchez.jenkins.plugins.kubernetes.PodEnvVar>
            <org.csanchez.jenkins.plugins.kubernetes.PodEnvVar>
              <key>c</key>
              <value>d</value>
            </org.csanchez.jenkins.plugins.kubernetes.PodEnvVar>
          </envVars>
          <annotations>
            <org.csanchez.jenkins.plugins.kubernetes.PodAnnotation>
              <key>aa</key>
              <value>bb</value>
            </org.csanchez.jenkins.plugins.kubernetes.PodAnnotation>
          </annotations>
          <imagePullSecrets>
            <org.csanchez.jenkins.plugins.kubernetes.PodImagePullSecret>
              <name></name>
            </org.csanchez.jenkins.plugins.kubernetes.PodImagePullSecret>
          </imagePullSecrets>
        </org.csanchez.jenkins.plugins.kubernetes.PodTemplate>
      </templates>
      <serverUrl>https://104.196.147.109</serverUrl>
      <skipTlsVerify>true</skipTlsVerify>
      <namespace>default</namespace>
      <jenkinsUrl></jenkinsUrl>
      <credentialsId>7243dcca-e49c-41d5-9d9e-1bca49d8f741</credentialsId>
      <containerCap>10</containerCap>
      <retentionTimeout>5</retentionTimeout>
    </org.csanchez.jenkins.plugins.kubernetes.KubernetesCloud>

  </clouds>
  <quietPeriod>5</quietPeriod>
  <scmCheckoutRetryCount>0</scmCheckoutRetryCount>
  <views>
    <hudson.model.AllView>
      <owner class="hudson" reference="../../.."/>
      <name>All</name>
      <filterExecutors>false</filterExecutors>
      <filterQueue>false</filterQueue>
      <properties class="hudson.model.View$PropertyList"/>
    </hudson.model.AllView>
  </views>
  <primaryView>All</primaryView>
  <slaveAgentPort>0</slaveAgentPort>

  <nodeProperties/>
  <globalNodeProperties/>
</hudson>


text:
import { Component, Input, Output,EventEmitter} from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';

@IonicPage()
@Component({
  selector: 'page-searchbar',
  templateUrl: 'searchbar.html'
})

export class SearchbarPage {
  @Input() private placeholderMsg : string = '';
  @Output() private searchContent = new EventEmitter<string>();
  private inputText : string = '';//搜索框输入的文本
  constructor(public navCtrl: NavController, public navParams: NavParams) {}

  sendToParent(){
    this.searchContent.emit(this.inputText);
  }
}


text:
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateAlbumsTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::create('albums', function(Blueprint $table)
        {
            $table->increments('id')->unsigned();
            $table->string('albumname');
            $table->integer('user_id')->unsigned();
            $table->timestamps();
            $table->foreign('user_id')->references('id')->on('users')->onDelete('CASCADE')->onUpdate('CASCADE');
        });
	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
		//
		Schema::drop('albums');
	}

}


text:
package zclsyntax

import (
	"github.com/zclconf/go-cty/cty"
	"github.com/zclconf/go-zcl/zcl"
)

// ParseTraversalAbs parses an absolute traversal that is assumed to consume
// all of the remaining tokens in the peeker. The usual parser recovery
// behavior is not supported here because traversals are not expected to
// be parsed as part of a larger program.
func (p *parser) ParseTraversalAbs() (zcl.Traversal, zcl.Diagnostics) {
	var ret zcl.Traversal
	var diags zcl.Diagnostics

	// Absolute traversal must always begin with a variable name
	varTok := p.Read()
	if varTok.Type != TokenIdent {
		diags = append(diags, &zcl.Diagnostic{
			Severity: zcl.DiagError,
			Summary:  "Variable name required",
			Detail:   "Must begin with a variable name.",
			Subject:  &varTok.Range,
		})
		return ret, diags
	}

	varName := string(varTok.Bytes)
	ret = append(ret, zcl.TraverseRoot{
		Name:     varName,
		SrcRange: varTok.Range,
	})

	for {
		next := p.Peek()

		if next.Type == TokenEOF {
			return ret, diags
		}

		switch next.Type {
		case TokenDot:
			// Attribute access
			dot := p.Read() // eat dot
			nameTok := p.Read()
			if nameTok.Type != TokenIdent {
				if nameTok.Type == TokenStar {
					diags = append(diags, &zcl.Diagnostic{
						Severity: zcl.DiagError,
						Summary:  "Attribute name required",
						Detail:   "Splat expressions (.*) may not be used here.",
						Subject:  &nameTok.Range,
						Context:  zcl.RangeBetween(varTok.Range, nameTok.Range).Ptr(),
					})
				} else {
					diags = append(diags, &zcl.Diagnostic{
						Severity: zcl.DiagError,
						Summary:  "Attribute name required",
						Detail:   "Dot must be followed by attribute name.",
						Subject:  &nameTok.Range,
						Context:  zcl.RangeBetween(varTok.Range, nameTok.Range).Ptr(),
					})
				}
				return ret, diags
			}

			attrName := string(nameTok.Bytes)
			ret = append(ret, zcl.TraverseAttr{
				Name:     attrName,
				SrcRange: zcl.RangeBetween(dot.Range, nameTok.Range),
			})
		case TokenOBrack:
			// Index
			open := p.Read() // eat open bracket
			next := p.Peek()

			switch next.Type {
			case TokenNumberLit:
				tok := p.Read() // eat number
				numVal, numDiags := p.numberLitValue(tok)
				diags = append(diags, numDiags...)

				close := p.Read()
				if close.Type != TokenCBrack {
					diags = append(diags, &zcl.Diagnostic{
						Severity: zcl.DiagError,
						Summary:  "Unclosed index brackets",
						Detail:   "Index key must be followed by a closing bracket.",
						Subject:  &close.Range,
						Context:  zcl.RangeBetween(open.Range, close.Range).Ptr(),
					})
				}

				ret = append(ret, zcl.TraverseIndex{
					Key:      numVal,
					SrcRange: zcl.RangeBetween(open.Range, close.Range),
				})

				if diags.HasErrors() {
					return ret, diags
				}

			case TokenOQuote:
				str, _, strDiags := p.parseQuotedStringLiteral()
				diags = append(diags, strDiags...)

				close := p.Read()
				if close.Type != TokenCBrack {
					diags = append(diags, &zcl.Diagnostic{
						Severity: zcl.DiagError,
						Summary:  "Unclosed index brackets",
						Detail:   "Index key must be followed by a closing bracket.",
						Subject:  &close.Range,
						Context:  zcl.RangeBetween(open.Range, close.Range).Ptr(),
					})
				}

				ret = append(ret, zcl.TraverseIndex{
					Key:      cty.StringVal(str),
					SrcRange: zcl.RangeBetween(open.Range, close.Range),
				})

				if diags.HasErrors() {
					return ret, diags
				}

			default:
				if next.Type == TokenStar {
					diags = append(diags, &zcl.Diagnostic{
						Severity: zcl.DiagError,
						Summary:  "Attribute name required",
						Detail:   "Splat expressions ([*]) may not be used here.",
						Subject:  &next.Range,
						Context:  zcl.RangeBetween(varTok.Range, next.Range).Ptr(),
					})
				} else {
					diags = append(diags, &zcl.Diagnostic{
						Severity: zcl.DiagError,
						Summary:  "Index value required",
						Detail:   "Index brackets must contain either a literal number or a literal string.",
						Subject:  &next.Range,
						Context:  zcl.RangeBetween(varTok.Range, next.Range).Ptr(),
					})
				}
				return ret, diags
			}

		default:
			diags = append(diags, &zcl.Diagnostic{
				Severity: zcl.DiagError,
				Summary:  "Invalid character",
				Detail:   "Expected an attribute access or an index operator.",
				Subject:  &next.Range,
				Context:  zcl.RangeBetween(varTok.Range, next.Range).Ptr(),
			})
			return ret, diags
		}
	}
}


text:
<?php
/** GARRISON MODIFIED 4/20/2013 **/
function to_currency($number)
{
	$CI =& get_instance();
	$currency_symbol = $CI->config->item('currency_symbol') ? $CI->config->item('currency_symbol') : '$';
	$thousands_separator = $CI->config->item('thousands_separator') ? $CI->config->item('thousands_separator') : '';
	$decimal_point = $CI->config->item('decimal_point') ? $CI->config->item('decimal_point') : '.';
	if($number >= 0)
	{
		if($CI->config->item('currency_side') !== 'currency_side')
			return $currency_symbol.number_format($number, 2, $decimal_point, $thousands_separator);
		else
			return number_format($number, 2, $decimal_point, $thousands_separator).$currency_symbol;
	}
    else
    {
    	if($CI->config->item('currency_side') !== 'currency_side')
    		return '-'.$currency_symbol.number_format(abs($number), 2, $decimal_point, $thousands_separator);
    	else
    		return '-'.number_format(abs($number), 2, $decimal_point, $thousands_separator).$currency_symbol;
    }
}
/** END MODIFIED **/

function to_currency_no_money($number)
{
	return number_format($number, 2, '.', '');
}
?>