text:
describe('valdr', function () {

  var valdr, $rootScope, valdrEvents, valdrClasses, sizeValidator, requiredValidator,
    personConstraints = {
      'Person': {
        'firstName': {
          'size': {
            'min': 0,
            'max': 10,
            'message': 'size'
          }
        }
      }
    },
    addressConstraints = {
      'Address': {
        'street': {
          'required': {
            'message': 'required'
          }
        }
      }
    };

  beforeEach(module('valdr'));

  beforeEach(inject(
    function (_valdr_, _$rootScope_, _valdrEvents_, _valdrClasses_, _valdrSizeValidator_, _valdrRequiredValidator_) {
    valdr = _valdr_;
    $rootScope = _$rootScope_;
    valdrEvents = _valdrEvents_;
    valdrClasses = _valdrClasses_;
    sizeValidator = _valdrSizeValidator_;
    requiredValidator = _valdrRequiredValidator_;
  }));

  describe('addConstraints()', function () {

    it('should add initial constraints', function () {
      // when
      valdr.addConstraints(personConstraints);

      // then
      expect(valdr.getConstraints()).toEqual(personConstraints);
    });

    it('should extend initial constraints', function () {
      // when
      valdr.addConstraints(personConstraints);
      valdr.addConstraints(addressConstraints);

      // then
      expect(valdr.getConstraints().Person).toEqual(personConstraints.Person);
      expect(valdr.getConstraints().Address).toEqual(addressConstraints.Address);
    });

    it('should broadcast event when constraints change', function () {
      // given
      spyOn($rootScope, '$broadcast');

      // when
      valdr.addConstraints(personConstraints);

      // then
      expect($rootScope.$broadcast).toHaveBeenCalledWith(valdrEvents.revalidate);
    });
  });

  describe('removeConstraints()', function () {

    it('should remove single constraint', function () {
      // given
      valdr.addConstraints(personConstraints);
      valdr.addConstraints(addressConstraints);

      // when
      valdr.removeConstraints('Person');

      // then
      expect(valdr.getConstraints()).toEqual(addressConstraints);
    });

    it('should remove multiple constraints', function () {
      // given
      valdr.addConstraints(personConstraints);
      valdr.addConstraints(addressConstraints);

      // when
      valdr.removeConstraints(['Person', 'Address']);

      // then
      expect(valdr.getConstraints()).toEqual({});
    });

    it('should broadcast event when constraints change', function () {
      // given
      valdr.addConstraints(personConstraints);
      spyOn($rootScope, '$broadcast');

      // when
      valdr.removeConstraints('Person');

      // then
      expect($rootScope.$broadcast).toHaveBeenCalledWith(valdrEvents.revalidate);
    });
  });

  describe('validate()', function () {

    it('should not validate if no constraints are defined', function () {
      // when
      var validationResult = valdr.validate('Person', 'firstName', 'Hanueli');

      // then
      expect(validationResult.valid).toBe(true);
      expect(validationResult.violations).toBeUndefined();
      expect(validationResult.validationResults).toBeUndefined();
    });

    it('should validate with correct validator', function () {
      // given
      valdr.addConstraints(personConstraints);
      spyOn(sizeValidator, 'validate').andCallThrough();

      // when
      var validationResult = valdr.validate('Person', 'firstName', 'Hanueli');

      // then
      expect(validationResult.valid).toBe(true);
      expect(validationResult.violations).toBeUndefined();
      expect(validationResult.validationResults.length).toBe(1);
      expect(sizeValidator.validate).toHaveBeenCalled();
    });

    it('should return true if no validator is available for a constraint', function () {
      // given
      valdr.addConstraints({
        'Person': {
          'firstName': {
            'ThereIsNoValidatorForThisConstraint': {}
          }
        }
      });

      // when
      var validationResult = valdr.validate('Person', 'firstName', 'Hanueli');

      // then
      expect(validationResult.valid).toBe(true);
    });

    it('should return invalid state and message if validation fails', function () {
      // given
      valdr.addConstraints(personConstraints);
      spyOn(sizeValidator, 'validate').andCallThrough();

      // when
      var validationResult = valdr.validate('Person', 'firstName', 'Hanueli with a name that is too long');

      // then
      expect(sizeValidator.validate).toHaveBeenCalled();
      expect(validationResult.valid).toBe(false);
      expect(validationResult.violations[0].message).toBe('size');
      expect(validationResult.violations[0].field).toBe('firstName');
      expect(validationResult.violations[0].type).toBe('Person');
      expect(validationResult.violations[0].value).toBe('Hanueli with a name that is too long');
      expect(validationResult.violations[0].max).toBe(10);
      expect(validationResult.violations[0].min).toBe(0);
    });

    it('should return invalid state and message if multiple validations fail', function () {
      // given
      valdr.addConstraints({
        'Person': {
          'firstName': {
            'size': {
              'min': 2,
              'max': 10,
              'message': 'size'
            },
            'required': {
              'message': 'required'
            }
          }
        }
      });
      spyOn(sizeValidator, 'validate').andCallThrough();
      spyOn(requiredValidator, 'validate').andCallThrough();

      // when
      var validationResult = valdr.validate('Person', 'firstName', undefined);

      // then
      expect(sizeValidator.validate).toHaveBeenCalled();
      expect(requiredValidator.validate).toHaveBeenCalled();
      expect(validationResult.valid).toBe(false);
      expect(validationResult.violations[0].message).toBe('required');
    });

  });

  describe('setClasses()', function () {

    it('should add the given classes to the valdrClasses and broadcast an event', function () {
      // given
      spyOn($rootScope, '$broadcast');
      var newClass = 'is-valid';
      expect(valdrClasses.valid).toBe('ng-valid');
      expect(valdrClasses.invalid).toBe('ng-invalid');

      // when
      valdr.setClasses({ valid: newClass });

      // then
      expect($rootScope.$broadcast).toHaveBeenCalledWith(valdrEvents.revalidate);
      expect(valdrClasses.valid).toBe(newClass);
      expect(valdrClasses.invalid).toBe('ng-invalid');

      // cleanup to prevent side-effects
      valdr.setClasses({ valid: 'ng-valid' });
    });

  });
});

describe('valdrProvider', function () {

  it('should load the constraints via $http', function () {
    // given
    var $httpBackend, apiUrl = '/api/validation';

    // when
    module('valdr');
    module(function (valdrProvider) {
      valdrProvider.setConstraintUrl(apiUrl);
    });
    inject(function (_$httpBackend_) {
      $httpBackend = _$httpBackend_;
      $httpBackend.expect('GET', apiUrl).respond(200, {});
    });

    /*jshint unused:false */
    inject(function (valdr) {
      // injecting the valdr service triggers the loading and therefore the GET to the apiUrl
      $httpBackend.flush();

      // then
      $httpBackend.verifyNoOutstandingExpectation();
      $httpBackend.verifyNoOutstandingRequest();
    });
  });

  it('should support to use aliases for constraint names', function () {
    // given
    module('valdr');
    module(function (valdrProvider) {
      valdrProvider.addConstraints({
        'Person': {
          'firstName': {
            'sizeBetween': {
              'min': 0,
              'max': 10
            },
            'secondSizeBetween': {
              'min': 10,
              'max': 20
            }
          }
        }
      });
      valdrProvider.addConstraintAlias('size', 'sizeBetween');
      valdrProvider.addConstraintAlias('size', 'secondSizeBetween');
    });

    inject(function (valdr, valdrSizeValidator) {
      // when
      spyOn(valdrSizeValidator, 'validate').andCallThrough();
      var validationResult = valdr.validate('Person', 'firstName', 'Hanueli');

      // then
      expect(validationResult.valid).toBe(false);
      expect(validationResult.violations).toBeDefined();
      expect(validationResult.violations.length).toBe(1);
      expect(validationResult.validationResults.length).toBe(2);
      expect(valdrSizeValidator.validate).toHaveBeenCalled();
    });
  });

  describe('custom validators', function () {

    it('should allow to add custom validators', function () {
      // given
      module('valdr');

      module(function ($provide) {
        $provide.factory('customValidator', function () {
          return {
            name: 'custom',
            validate: function (value) {
              return value === 'Hanueli';
            }
          };
        });
      });

      module(function (valdrProvider) {
        valdrProvider.addValidator('customValidator');
        valdrProvider.addConstraints({
          'Person': {
            'firstName': {
              'custom': {}
            }
          }
        });
      });

      inject(function (valdr, customValidator) {
        // when
        spyOn(customValidator, 'validate').andCallThrough();
        var validationResult = valdr.validate('Person', 'firstName', 'Hanueli');

        // then
        expect(validationResult.valid).toBe(true);
        expect(validationResult.violations).toBeUndefined();
        expect(customValidator.validate).toHaveBeenCalled();
      });
    });

  });

});


text:
<?php

namespace Swing;

class Kernel
{
    private $router;

    function __construct()
    {
        $this->router = new Router();
    }

    public function run(): void
    {
        $this->registerRoutes();

        $route = $this->router->match();

        if ($route) {
            try {
                $this->router->dispatchAction($route);
            } catch (\Exception $e) {
                echo $e->getMessage();
            }
        } else {
            echo 'Nothing here';
        }
    }

    /**
     * Routes registration
     *
     * Path Syntax:
     * :id - mandatory
     * [:id] - optional
     *
     * Action Syntax:
     * Controller#action
     * ['Controller', 'action']
     * Callback - for direct action execution
     */
    private function registerRoutes(): void
    {
//        $this->router->map('GET', '/news/[:id]', function ($id) {
//            $id++;
//            echo json_encode(['result' => $id]);
//        });

        $this->router->map('GET', '/news/[:id]', ['News', 'get']);
        $this->router->map('POST', '/news/:id', 'News#update');
        $this->router->map('POST', '/news', 'News#create');
        $this->router->map('DELETE', '/news/:id', 'News#delete');
    }
}

redpajama_set_name: RedPajamaGithub


text:
package easylog.core;

import net.bytebuddy.ByteBuddy;
import net.bytebuddy.dynamic.loading.ClassLoadingStrategy;
import net.bytebuddy.implementation.MethodDelegation;
import net.bytebuddy.implementation.bind.annotation.AllArguments;
import net.bytebuddy.implementation.bind.annotation.Origin;
import net.bytebuddy.implementation.bind.annotation.RuntimeType;
import net.bytebuddy.implementation.bind.annotation.SuperCall;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import java.lang.reflect.Method;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.function.Supplier;

import static net.bytebuddy.matcher.ElementMatchers.isAnnotatedWith;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class LoggingInterceptorTest {

    private TestObject testObject;
    private TestLoggerFactory loggerFactory;

    @Mock
    private LogMessageParser logMessageParserMock;

    @Before
    public void before() throws Exception {
        loggerFactory = new TestLoggerFactory();

        testObject = new ByteBuddy()
                .subclass(TestObject.class)
                .name("TestProxy")
                .method(isAnnotatedWith(Log.class).or(isAnnotatedWith(Logs.class))).intercept(MethodDelegation.to(new LogInterceptor(loggerFactory)))
                .make()
                .load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
                .getLoaded()
                .newInstance();

        testObject.messages = loggerFactory.messages;
    }

    @Test
    public void defaultDetailedBeforeAfter1() throws Exception {
        testObject.defaultDetailedBeforeAfter1("Blah", 123);

        assertThat(loggerFactory.messages).containsExactly(
                "[TRACE] Enter easylog.core.TestObject.defaultDetailedBeforeAfter1(Blah, 123).",
                "[TRACE] Exit easylog.core.TestObject.defaultDetailedBeforeAfter1(Blah, 123) with result 492.");
    }

    @Test
    public void defaultDetailedBeforeAfter2() throws Exception {
        testObject.defaultDetailedBeforeAfter2("Blah", 123);

        assertThat(loggerFactory.messages).containsExactly(
                "[TRACE] Enter easylog.core.TestObject.defaultDetailedBeforeAfter2(Blah, 123).",
                "[INFO] Exit easylog.core.TestObject.defaultDetailedBeforeAfter2(Blah, 123) with result 492.");
    }

    @Test
    public void defaultDetailedBefore() throws Exception {
        testObject.defaultDetailedBefore("Blah", 123);

        assertThat(loggerFactory.messages).containsExactly(
                "[TRACE] Enter easylog.core.TestObject.defaultDetailedBefore(Blah, 123).");
    }

    @Test
    public void defaultDetailedAfter() throws Exception {
        testObject.defaultDetailedAfter("Blah", 123);

        assertThat(loggerFactory.messages).containsExactly(
                "[INFO] Exit easylog.core.TestObject.defaultDetailedAfter(Blah, 123) with result 492.");
    }

    @Test
    public void simpleBefore() throws Exception {
        testObject.simpleBefore("Blah", 123);

        assertThat(loggerFactory.messages).containsExactly(
                "[INFO] Enter easylog.core.TestObject.simpleBefore.");
    }

    @Test
    public void simpleAfter() throws Exception {
        testObject.simpleAfter("Blah", 123);

        assertThat(loggerFactory.messages).containsExactly(
                "[INFO] Exit easylog.core.TestObject.simpleAfter.");
    }

    @Test
    public void simpleAfterException() throws Exception {
        assertThatExceptionOfType(RuntimeException.class)
                .isThrownBy(() -> testObject.simpleAfterException("Blah", 123))
                .withMessage("ERROR");

        assertThat(loggerFactory.messages).hasSize(1);
        assertThat(loggerFactory.messages.get(0)).startsWith(
                "[INFO] Error in easylog.core.TestObject.simpleAfterException:\n");
    }

    @Test
    public void detailedVoidMethodBeforeAfter() throws Exception {
        testObject.detailedVoidMethodBeforeAfter("Blah", 123);

        assertThat(loggerFactory.messages).containsExactly(
                "[INFO] Enter easylog.core.TestObject.detailedVoidMethodBeforeAfter(Blah, 123).",
                "[INFO] Exit easylog.core.TestObject.detailedVoidMethodBeforeAfter(Blah, 123).");
    }

    @Test
    public void detailedVoidMethodAfterException() throws Exception {
        assertThatExceptionOfType(RuntimeException.class)
                .isThrownBy(() -> testObject.detailedVoidMethodAfterException("Blah", 123))
                .withMessage("ERROR");

        assertThat(loggerFactory.messages).hasSize(1);
        assertThat(loggerFactory.messages.get(0)).startsWith(
                "[INFO] Error in easylog.core.TestObject.detailedVoidMethodAfterException(Blah, 123):\n");
    }

    @Test
    public void detailedMethodAfterException() throws Exception {
        assertThatExceptionOfType(RuntimeException.class)
                .isThrownBy(() -> testObject.detailedMethodAfterException("Blah", 123))
                .withMessage("ERROR");

        assertThat(loggerFactory.messages).hasSize(1);
        assertThat(loggerFactory.messages.get(0)).startsWith(
                "[INFO] Error in easylog.core.TestObject.detailedMethodAfterException(Blah, 123):\n");
    }

    @Test
    public void customMessageBefore() throws Exception {
        testObject.customMessageBefore("Blah", 123);

        assertThat(loggerFactory.messages).containsExactly("[INFO] B_TEST!!!");
    }

    @Test
    public void customMessageAfter() throws Exception {
        testObject.customMessageAfter("Blah", 123);

        assertThat(loggerFactory.messages).containsExactly("[INFO] A_TEST!!!");
    }

    @Test
    public void customMessageAfterException() throws Exception {
        assertThatExceptionOfType(RuntimeException.class)
                .isThrownBy(() -> testObject.customMessageAfterException("Blah", 123))
                .withMessage("ERROR");

        assertThat(loggerFactory.messages).containsExactly("[INFO] AE_TEST!!!");
    }

    @Test
    public void futureWithoutResultDetailed() throws ExecutionException, InterruptedException {
        CompletableFuture<Void> future = testObject.futureWithoutResultDetailed();

        future.get();

        assertThat(loggerFactory.messages).containsExactly("CALLED", "[INFO] Exit easylog.core.TestObject.futureWithoutResultDetailed().");
    }

    @Test
    public void futureWithResultDetailed() throws ExecutionException, InterruptedException {
        CompletableFuture<Integer> future = testObject.futureWithResultDetailed();

        Integer value = future.get();

        assertThat(value).isEqualTo(123);
        assertThat(loggerFactory.messages).containsExactly("[INFO] Exit easylog.core.TestObject.futureWithResultDetailed() with result 123.");
    }

    @Test
    public void messageParser() throws Exception {
        testObject = new ByteBuddy()
                .subclass(TestObject.class)
                .name("TestProxy")
                .method(isAnnotatedWith(Log.class).or(isAnnotatedWith(Logs.class))).intercept(MethodDelegation.to(new LogInterceptor(loggerFactory, logMessageParserMock)))
                .make()
                .load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
                .getLoaded()
                .newInstance();

        when(logMessageParserMock.parse(any(Scope.class), anyString())).thenReturn("LOG!");

        testObject.customMessageBefore("Blah", 123);

        assertThat(loggerFactory.messages).containsExactly("[INFO] LOG!");
    }

    @Test
    public void messageParser_throws_exception() throws Exception {
        testObject = new ByteBuddy()
                .subclass(TestObject.class)
                .name("TestProxy")
                .method(isAnnotatedWith(Log.class).or(isAnnotatedWith(Logs.class))).intercept(MethodDelegation.to(new LogInterceptor(loggerFactory, logMessageParserMock)))
                .make()
                .load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
                .getLoaded()
                .newInstance();

        when(logMessageParserMock.parse(any(Scope.class), anyString())).thenThrow(new RuntimeException("MPEX"));

        testObject.customMessageBefore("Blah", 123);

        assertThat(loggerFactory.messages).hasSize(1);
        assertThat(loggerFactory.messages.get(0)).startsWith(
                "[WARN] Error creating a log entry for 'easylog.core.TestObject.customMessageBefore' at position BEFORE:\njava.lang.RuntimeException: MPEX");
    }

    public static class TestLoggerFactory implements LoggerFactory {

        List<String> messages = new ArrayList<>();

        @Override
        public Logger getLogger(Class<?> clazz) {
            return new Logger() {
                @Override
                public boolean isEnabled(LogLevel level) {
                    return true;
                }

                @Override
                public void log(LogLevel level, String message, Throwable throwable) {
                    log(level, () -> message);
                }

                @Override
                public void log(LogLevel level, Supplier<String> messageSupplier) {
                    messages.add(MessageFormat.format("[{0}] {1}", level.toString(), messageSupplier.get()));
                }
            };
        }
    }

    public static class LogInterceptor {
        private TestLoggerFactory loggerFactory;
        private LogMessageParser logMessageParser;

        public LogInterceptor(TestLoggerFactory loggerFactory) {
            this(loggerFactory, null);
        }

        public LogInterceptor(TestLoggerFactory loggerFactory, LogMessageParser logMessageParser) {
            this.loggerFactory = loggerFactory;
            this.logMessageParser = logMessageParser;
        }

        @RuntimeType
        public Object interceptSuper(@SuperCall Callable<?> zuper, @AllArguments Object[] allArguments, @Origin Method method, @Origin Class clazz) throws Throwable {
            LoggingInterceptor interceptor = new LoggingInterceptor(loggerFactory);
            interceptor.setLogMessageParser(logMessageParser);

            return interceptor.intercept(new MyInvocationContext(method, zuper, allArguments, clazz));
        }
    }

    public static class MyInvocationContext implements InvocationContext {

        private Method method;
        private Callable<?> zuper;
        private Object[] arguments;
        private Class<?> targetClass;

        public MyInvocationContext(Method method, Callable<?> zuper, Object[] arguments, Class<?> targetClass) {
            this.method = method;
            this.zuper = zuper;
            this.arguments = arguments;
            this.targetClass = targetClass;
        }

        @Override
        public Class<?> getTargetClass() {
            return targetClass;
        }

        @Override
        public Method getMethod() {
            return method;
        }

        @Override
        public Object[] getArguments() {
            return arguments;
        }

        @Override
        public Object proceed() throws Exception {
            return zuper.call();
        }
    }
}


text:
module MonteCarloGui where

import MonteCarloPi
import Graphics.UI.Gtk hiding (fill,drawPoint)
import Graphics.UI.Gtk.Glade
import Graphics.Rendering.Cairo
import Graphics.UI.Gtk.Gdk.Events
import Data.IORef
import System.Random

monteCarloGui :: IO ()
monteCarloGui = do initGUI
                   ioref <- newIORef (0,0)
                   Just xml <- xmlNew "montecarlo.glade"
                   window   <- xmlGetWidget xml castToWindow "MonteCarloGui"
                   onDestroy window mainQuit
                   goButton <- xmlGetWidget xml castToButton "go"
                   runs <- xmlGetWidget xml castToEntry "runs"
                   circleArea <- xmlGetWidget xml castToDrawingArea "circle"
                   total <- xmlGetWidget xml castToLabel "total"
                   hits <- xmlGetWidget xml castToLabel "hits"
                   piLabel <- xmlGetWidget xml castToLabel "pi"
                   widgetShowAll window
                   circleDraw <- widgetGetDrawWindow circleArea
                   renderWithDrawable circleDraw paint
                   onExpose circleArea (\x -> do renderWithDrawable circleDraw paint
                                                 return (eventSent x))
                   onClicked goButton (go ioref circleArea (total,hits,piLabel) runs)
                   onEntryActivate runs (go ioref circleArea (total,hits,piLabel) runs)
                   mainGUI

go :: IORef (Int,Int) -> DrawingArea -> (Label,Label,Label) -> Entry -> IO ()
go ref d (t,h,pi) runs = do text <- get runs entryText
                            if ((reads text :: [(Int,String)]) /= [])
                               then go' (read text) ref d (t,h,pi)
                               else return ()

go' :: Int -> IORef (Int,Int) -> DrawingArea -> (Label,Label,Label) -> IO ()
go' 0 ref _ (t,h,pi) = do (total,hits) <- readIORef ref
                          set t [ labelText := "Total = " ++ (show total)]
                          set h [ labelText := "Hits = " ++ (show hits)]
                          set pi [ labelText := "Pi is approx " ++ (show (4.0*(fromIntegral hits / fromIntegral total)))]

go' n ref circle (t,h,pi) = do circleDraw <- widgetGetDrawWindow circle
                               (total,hits) <- readIORef ref
                               x <- randomRIO (0,500)
                               y <- randomRIO (0,500)
                               green <- return (isInCircle (fromIntegral x,fromIntegral y) (circleInSquare (fromIntegral 500)))
                               shade <- randomRIO (0.4,1.0)
                               renderWithDrawable circleDraw (drawPoint (x,y) green shade)
                               onExpose circle (\e -> do renderWithDrawable circleDraw (drawPoint (x,y) green shade)
                                                         return (eventSent e))
                               writeIORef ref (total+1,if green then hits+1 else hits)
                               go' (n-1) ref circle (t,h,pi)

drawPoint :: (Int,Int) -> Bool -> Double -> Render ()
drawPoint (x,y) green shade = do setSourceRGB (if green then 0.0 else shade) (if green then shade else 0.0) 0.0
                                 moveTo (fromIntegral x) (fromIntegral y)
                                 lineTo ((fromIntegral x)-1) ((fromIntegral y)-1)
                                 stroke


text:
package browse

import (
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"net/url"
	"os"
	"path/filepath"
	"sort"
	"testing"
	"text/template"
	"time"

	"github.com/mholt/caddy/middleware"
)

// "sort" package has "IsSorted" function, but no "IsReversed";
func isReversed(data sort.Interface) bool {
	n := data.Len()
	for i := n - 1; i > 0; i-- {
		if !data.Less(i, i-1) {
			return false
		}
	}
	return true
}

func TestSort(t *testing.T) {
	// making up []fileInfo with bogus values;
	// to be used to make up our "listing"
	fileInfos := []FileInfo{
		{
			Name:    "fizz",
			Size:    4,
			ModTime: time.Now().AddDate(-1, 1, 0),
		},
		{
			Name:    "buzz",
			Size:    2,
			ModTime: time.Now().AddDate(0, -3, 3),
		},
		{
			Name:    "bazz",
			Size:    1,
			ModTime: time.Now().AddDate(0, -2, -23),
		},
		{
			Name:    "jazz",
			Size:    3,
			ModTime: time.Now(),
		},
	}
	listing := Listing{
		Name:    "foobar",
		Path:    "/fizz/buzz",
		CanGoUp: false,
		Items:   fileInfos,
	}

	// sort by name
	listing.Sort = "name"
	listing.applySort()
	if !sort.IsSorted(byName(listing)) {
		t.Errorf("The listing isn't name sorted: %v", listing.Items)
	}

	// sort by size
	listing.Sort = "size"
	listing.applySort()
	if !sort.IsSorted(bySize(listing)) {
		t.Errorf("The listing isn't size sorted: %v", listing.Items)
	}

	// sort by Time
	listing.Sort = "time"
	listing.applySort()
	if !sort.IsSorted(byTime(listing)) {
		t.Errorf("The listing isn't time sorted: %v", listing.Items)
	}

	// reverse by name
	listing.Sort = "name"
	listing.Order = "desc"
	listing.applySort()
	if !isReversed(byName(listing)) {
		t.Errorf("The listing isn't reversed by name: %v", listing.Items)
	}

	// reverse by size
	listing.Sort = "size"
	listing.Order = "desc"
	listing.applySort()
	if !isReversed(bySize(listing)) {
		t.Errorf("The listing isn't reversed by size: %v", listing.Items)
	}

	// reverse by time
	listing.Sort = "time"
	listing.Order = "desc"
	listing.applySort()
	if !isReversed(byTime(listing)) {
		t.Errorf("The listing isn't reversed by time: %v", listing.Items)
	}
}

func TestBrowseTemplate(t *testing.T) {
	tmpl, err := template.ParseFiles("testdata/photos.tpl")
	if err != nil {
		t.Fatalf("An error occured while parsing the template: %v", err)
	}

	b := Browse{
		Next: middleware.HandlerFunc(func(w http.ResponseWriter, r *http.Request) (int, error) {
			t.Fatalf("Next shouldn't be called")
			return 0, nil
		}),
		Root: "./testdata",
		Configs: []Config{
			{
				PathScope: "/photos",
				Template:  tmpl,
			},
		},
	}

	req, err := http.NewRequest("GET", "/photos/", nil)
	if err != nil {
		t.Fatalf("Test: Could not create HTTP request: %v", err)
	}

	rec := httptest.NewRecorder()

	code, err := b.ServeHTTP(rec, req)
	if code != http.StatusOK {
		t.Fatalf("Wrong status, expected %d, got %d", http.StatusOK, code)
	}

	respBody := rec.Body.String()
	expectedBody := `<!DOCTYPE html>

<title>Template</title>

Header

/photos/

test.html

test2.html

test3.html

`

	if respBody != expectedBody {
		t.Fatalf("Expected body: %v got: %v", expectedBody, respBody)
	}

}

func TestBrowseJson(t *testing.T) {

	b := Browse{
		Next: middleware.HandlerFunc(func(w http.ResponseWriter, r *http.Request) (int, error) {
			t.Fatalf("Next shouldn't be called")
			return 0, nil
		}),
		Root: "./testdata",
		Configs: []Config{
			{
				PathScope: "/photos/",
			},
		},
	}

	//Getting the listing from the ./testdata/photos, the listing returned will be used to validate test results
	testDataPath := b.Root + "/photos/"
	file, err := os.Open(testDataPath)
	if err != nil {
		if os.IsPermission(err) {
			t.Fatalf("Os Permission Error")
		}
	}
	defer file.Close()

	files, err := file.Readdir(-1)
	if err != nil {
		t.Fatalf("Unable to Read Contents of the directory")
	}
	var fileinfos []FileInfo

	for i, f := range files {
		name := f.Name()

		// Tests fail in CI environment because all file mod times are the same for
		// some reason, making the sorting unpredictable. To hack around this,
		// we ensure here that each file has a different mod time.
		chTime := f.ModTime().Add(-(time.Duration(i) * time.Second))
		if err := os.Chtimes(filepath.Join(testDataPath, name), chTime, chTime); err != nil {
			t.Fatal(err)
		}

		if f.IsDir() {
			name += "/"
		}

		url := url.URL{Path: name}

		fileinfos = append(fileinfos, FileInfo{
			IsDir:   f.IsDir(),
			Name:    f.Name(),
			Size:    f.Size(),
			URL:     url.String(),
			ModTime: chTime,
			Mode:    f.Mode(),
		})
	}
	listing := Listing{Items: fileinfos} // this listing will be used for validation inside the tests

	tests := []struct {
		QueryUrl       string
		SortBy         string
		OrderBy        string
		Limit          int
		shouldErr      bool
		expectedResult []FileInfo
	}{
		//test case 1: testing for default sort and  order and without the limit parameter, default sort is by name and the default order is ascending
		//without the limit query entire listing will be produced
		{"/", "", "", -1, false, listing.Items},
		//test case 2: limit is set to 1, orderBy and sortBy is default
		{"/?limit=1", "", "", 1, false, listing.Items[:1]},
		//test case 3 : if the listing request is bigger than total size of listing then it should return everything
		{"/?limit=100000000", "", "", 100000000, false, listing.Items},
		//test case 4 : testing for negative limit
		{"/?limit=-1", "", "", -1, false, listing.Items},
		//test case 5 : testing with limit set to -1 and order set to descending
		{"/?limit=-1&order=desc", "", "desc", -1, false, listing.Items},
		//test case 6 : testing with limit set to 2 and order set to descending
		{"/?limit=2&order=desc", "", "desc", 2, false, listing.Items},
		//test case 7 : testing with limit set to 3 and order set to descending
		{"/?limit=3&order=desc", "", "desc", 3, false, listing.Items},
		//test case 8 : testing with limit set to 3 and order set to ascending
		{"/?limit=3&order=asc", "", "asc", 3, false, listing.Items},
		//test case 9 : testing with limit set to 1111111 and order set to ascending
		{"/?limit=1111111&order=asc", "", "asc", 1111111, false, listing.Items},
		//test case 10 : testing with limit set to default and order set to ascending and sorting by size
		{"/?order=asc&sort=size", "size", "asc", -1, false, listing.Items},
		//test case 11 : testing with limit set to default and order set to ascending and sorting by last modified
		{"/?order=asc&sort=time", "time", "asc", -1, false, listing.Items},
		//test case 12 : testing with limit set to 1 and order set to ascending and sorting by last modified
		{"/?order=asc&sort=time&limit=1", "time", "asc", 1, false, listing.Items},
		//test case 13 : testing with limit set to -100 and order set to ascending and sorting by last modified
		{"/?order=asc&sort=time&limit=-100", "time", "asc", -100, false, listing.Items},
		//test case 14 : testing with limit set to -100 and order set to ascending and sorting by size
		{"/?order=asc&sort=size&limit=-100", "size", "asc", -100, false, listing.Items},
	}

	for i, test := range tests {
		var marsh []byte
		req, err := http.NewRequest("GET", "/photos"+test.QueryUrl, nil)

		if err == nil && test.shouldErr {
			t.Errorf("Test %d didn't error, but it should have", i)
		} else if err != nil && !test.shouldErr {
			t.Errorf("Test %d errored, but it shouldn't have; got '%v'", i, err)
		}

		req.Header.Set("Accept", "application/json")
		rec := httptest.NewRecorder()

		code, err := b.ServeHTTP(rec, req)

		if code != http.StatusOK {
			t.Fatalf("Wrong status, expected %d, got %d", http.StatusOK, code)
		}
		if rec.HeaderMap.Get("Content-Type") != "application/json; charset=utf-8" {
			t.Fatalf("Expected Content type to be application/json; charset=utf-8, but got %s ", rec.HeaderMap.Get("Content-Type"))
		}

		actualJSONResponse := rec.Body.String()
		copyOflisting := listing
		if test.SortBy == "" {
			copyOflisting.Sort = "name"
		} else {
			copyOflisting.Sort = test.SortBy
		}
		if test.OrderBy == "" {
			copyOflisting.Order = "asc"
		} else {
			copyOflisting.Order = test.OrderBy
		}

		copyOflisting.applySort()

		limit := test.Limit
		if limit <= len(copyOflisting.Items) && limit > 0 {
			marsh, err = json.Marshal(copyOflisting.Items[:limit])
		} else { // if the 'limit' query is empty, or has the wrong value, list everything
			marsh, err = json.Marshal(copyOflisting.Items)
		}

		if err != nil {
			t.Fatalf("Unable to Marshal the listing ")
		}
		expectedJSON := string(marsh)

		if actualJSONResponse != expectedJSON {
			t.Errorf("JSON response doesn't match the expected for test number %d with sort=%s, order=%s\nExpected response %s\nActual response = %s\n",
				i+1, test.SortBy, test.OrderBy, expectedJSON, actualJSONResponse)
		}
	}
}


text:
package org.apache.ignite.internal.util.nio;

import org.apache.ignite.*;
import org.apache.ignite.internal.util.lang.*;
import org.apache.ignite.internal.util.typedef.internal.*;
import org.apache.ignite.plugin.extensions.communication.*;
import org.jetbrains.annotations.*;

import java.io.*;
import java.net.*;
import java.nio.*;
import java.util.*;
import java.util.concurrent.locks.*;

/**
 * Grid client for NIO server.
 */
public class GridTcpCommunicationClient extends GridAbstractCommunicationClient {
    /** Socket. */
    private final Socket sock;

    /** Output stream. */
    private final UnsafeBufferedOutputStream out;

    /** Minimum buffered message count. */
    private final int minBufferedMsgCnt;

    /** Communication buffer size ratio. */
    private final double bufSizeRatio;

    /** */
    private final ByteBuffer writeBuf;

    /** */
    private final MessageFormatter formatter;

    /**
     * @param metricsLsnr Metrics listener.
     * @param addr Address.
     * @param locHost Local address.
     * @param connTimeout Connect timeout.
     * @param tcpNoDelay Value for {@code TCP_NODELAY} socket option.
     * @param sockRcvBuf Socket receive buffer.
     * @param sockSndBuf Socket send buffer.
     * @param bufSize Buffer size (or {@code 0} to disable buffer).
     * @param minBufferedMsgCnt Minimum buffered message count.
     * @param bufSizeRatio Communication buffer size ratio.
     * @param formatter Message formatter.
     * @throws IgniteCheckedException If failed.
     */
    public GridTcpCommunicationClient(
        GridNioMetricsListener metricsLsnr,
        InetSocketAddress addr,
        InetAddress locHost,
        long connTimeout,
        boolean tcpNoDelay,
        int sockRcvBuf,
        int sockSndBuf,
        int bufSize,
        int minBufferedMsgCnt,
        double bufSizeRatio,
        MessageFormatter formatter
    ) throws IgniteCheckedException {
        super(metricsLsnr);

        assert metricsLsnr != null;
        assert addr != null;
        assert locHost != null;
        assert connTimeout >= 0;
        assert bufSize >= 0;

        A.ensure(minBufferedMsgCnt >= 0,
            "Value of minBufferedMessageCount property cannot be less than zero.");
        A.ensure(bufSizeRatio > 0 && bufSizeRatio < 1,
            "Value of bufSizeRatio property must be between 0 and 1 (exclusive).");

        this.minBufferedMsgCnt = minBufferedMsgCnt;
        this.bufSizeRatio = bufSizeRatio;
        this.formatter = formatter;

        writeBuf = ByteBuffer.allocate(8 << 10);

        writeBuf.order(ByteOrder.nativeOrder());

        sock = new Socket();

        boolean success = false;

        try {
            sock.bind(new InetSocketAddress(locHost, 0));

            sock.setTcpNoDelay(tcpNoDelay);

            if (sockRcvBuf > 0)
                sock.setReceiveBufferSize(sockRcvBuf);

            if (sockSndBuf > 0)
                sock.setSendBufferSize(sockSndBuf);

            sock.connect(addr, (int)connTimeout);

            out = new UnsafeBufferedOutputStream(sock.getOutputStream(), bufSize);

            success = true;
        }
        catch (IOException e) {
            throw new IgniteCheckedException("Failed to connect to remote host " +
                "[addr=" + addr + ", localHost=" + locHost + ']', e);
        }
        finally {
            if (!success)
                U.closeQuiet(sock);
        }
    }

    /** {@inheritDoc} */
    @Override public void doHandshake(IgniteInClosure2X<InputStream, OutputStream> handshakeC) throws IgniteCheckedException {
        try {
            handshakeC.applyx(sock.getInputStream(), sock.getOutputStream());
        }
        catch (IOException e) {
            throw new IgniteCheckedException("Failed to access IO streams when executing handshake with remote node: " +
                sock.getRemoteSocketAddress(), e);
        }
    }

    /** {@inheritDoc} */
    @Override public boolean close() {
        boolean res = super.close();

        if (res) {
            U.closeQuiet(out);
            U.closeQuiet(sock);
        }

        return res;
    }

    /** {@inheritDoc} */
    @Override public void forceClose() {
        super.forceClose();

        try {
            out.flush();
        }
        catch (IOException ignored) {
            // No-op.
        }

        // Do not call (directly or indirectly) out.close() here
        // since it may cause a deadlock.
        out.forceClose();

        U.closeQuiet(sock);
    }

    /** {@inheritDoc} */
    @Override public void sendMessage(byte[] data, int len) throws IgniteCheckedException {
        if (closed())
            throw new IgniteCheckedException("Client was closed: " + this);

        try {
            out.write(data, 0, len);

            metricsLsnr.onBytesSent(len);
        }
        catch (IOException e) {
            throw new IgniteCheckedException("Failed to send message to remote node: " + sock.getRemoteSocketAddress(), e);
        }

        markUsed();
    }

    /** {@inheritDoc} */
    @Override public boolean sendMessage(@Nullable UUID nodeId, Message msg)
        throws IgniteCheckedException {
        if (closed())
            throw new IgniteCheckedException("Client was closed: " + this);

        assert writeBuf.hasArray();

        try {
            int cnt = U.writeMessageFully(msg, out, writeBuf, formatter.writer());

            metricsLsnr.onBytesSent(cnt);
        }
        catch (IOException e) {
            throw new IgniteCheckedException("Failed to send message to remote node: " + sock.getRemoteSocketAddress(), e);
        }

        markUsed();

        return false;
    }

    /**
     * @param timeout Timeout.
     * @throws IOException If failed.
     */
    @Override public void flushIfNeeded(long timeout) throws IOException {
        assert timeout > 0;

        out.flushOnTimeout(timeout);
    }

    /** {@inheritDoc} */
    @Override public void sendMessage(ByteBuffer data) throws IgniteCheckedException {
        throw new UnsupportedOperationException();
    }

    /** {@inheritDoc} */
    @Override public String toString() {
        return S.toString(GridTcpCommunicationClient.class, this, super.toString());
    }

    /**
     *
     */
    private class UnsafeBufferedOutputStream extends FilterOutputStream {
        /** The internal buffer where data is stored. */
        private final byte buf[];

        /** Current size. */
        private int size;

        /** Count. */
        private int cnt;

        /** Message count. */
        private int msgCnt;

        /** Total messages size. */
        private int totalCnt;

        /** Lock. */
        private final ReentrantLock lock = new ReentrantLock();

        /** Last flushed timestamp. */
        private volatile long lastFlushed = U.currentTimeMillis();

        /** Cached flush timeout. */
        private volatile long flushTimeout;

        /** Buffer adjusted timestamp. */
        private long lastAdjusted = U.currentTimeMillis();

        /**
         * Creates a new buffered output stream to write data to the
         * specified underlying output stream.
         *
         * @param out The underlying output stream.
         */
        UnsafeBufferedOutputStream(OutputStream out) {
            this(out, 8192);
        }

        /**
         * Creates a new buffered output stream to write data to the
         * specified underlying output stream with the specified buffer
         * size.
         *
         * @param out The underlying output stream.
         * @param size The buffer size.
         */
        UnsafeBufferedOutputStream(OutputStream out, int size) {
            super(out);

            assert size >= 0;

            this.size = size;
            buf = size > 0 ? new byte[size] : null;
        }

        /** {@inheritDoc} */
        @Override public void write(int b) throws IOException {
            throw new UnsupportedOperationException();
        }

        /** {@inheritDoc} */
        @Override public void write(byte[] b, int off, int len) throws IOException {
            assert b != null;
            assert off == 0;

            // No buffering.
            if (buf == null) {
                lock.lock();

                try {
                    out.write(b, 0, len);
                }
                finally {
                    lock.unlock();
                }

                return;
            }

            // Buffering is enabled.
            lock.lock();

            try {
                msgCnt++;
                totalCnt += len;

                if (len >= size) {
                    flushLocked();

                    out.write(b, 0, len);

                    lastFlushed = U.currentTimeMillis();

                    adjustBufferIfNeeded();

                    return;
                }

                if (cnt + len > size) {
                    flushLocked();

                    messageToBuffer0(b, off, len, buf, 0);

                    cnt = len;

                    assert cnt < size;

                    adjustBufferIfNeeded();

                    return;
                }

                messageToBuffer0(b, 0, len, buf, cnt);

                cnt += len;

                if (cnt == size)
                    flushLocked();
                else
                    flushIfNeeded();
            }
            finally {
                lock.unlock();
            }
        }

        /**
         * @throws IOException If failed.
         */
        private void flushIfNeeded() throws IOException {
            assert lock.isHeldByCurrentThread();
            assert buf != null;

            long flushTimeout0 = flushTimeout;

            if (flushTimeout0 > 0)
                flushOnTimeoutLocked(flushTimeout0);
        }

        /**
         *
         */
        private void adjustBufferIfNeeded() {
            assert lock.isHeldByCurrentThread();
            assert buf != null;

            long flushTimeout0 = flushTimeout;

            if (flushTimeout0 > 0)
                adjustBufferLocked(flushTimeout0);
        }

        /** {@inheritDoc} */
        @Override public void flush() throws IOException {
            lock.lock();

            try {
                flushLocked();
            }
            finally {
                lock.unlock();
            }
        }

        /**
         * @param timeout Timeout.
         * @throws IOException If failed.
         */
        public void flushOnTimeout(long timeout) throws IOException {
            assert buf != null;
            assert timeout > 0;

            // Overwrite cached value.
            flushTimeout = timeout;

            if (lastFlushed + timeout > U.currentTimeMillis() || !lock.tryLock())
                return;

            try {
                flushOnTimeoutLocked(timeout);
            }
            finally {
                lock.unlock();
            }
        }

        /**
         * @param timeout Timeout.
         * @throws IOException If failed.
         */
        private void flushOnTimeoutLocked(long timeout) throws IOException {
            assert lock.isHeldByCurrentThread();
            assert timeout > 0;

            // Double check.
            if (cnt == 0 || lastFlushed + timeout > U.currentTimeMillis())
                return;

            flushLocked();

            adjustBufferLocked(timeout);
        }

        /**
         * @param timeout Timeout.
         */
        private void adjustBufferLocked(long timeout) {
            assert lock.isHeldByCurrentThread();
            assert timeout > 0;

            long time = U.currentTimeMillis();

            if (lastAdjusted + timeout < time) {
                if (msgCnt <= minBufferedMsgCnt)
                    size = 0;
                else {
                    size = (int)(totalCnt * bufSizeRatio);

                    if (size > buf.length)
                        size = buf.length;
                }

                msgCnt = 0;
                totalCnt = 0;

                lastAdjusted = time;
            }
        }

        /**
         * @throws IOException If failed.
         */
        private void flushLocked() throws IOException {
            assert lock.isHeldByCurrentThread();

            if (buf != null && cnt > 0) {
                out.write(buf, 0, cnt);

                cnt = 0;
            }

            out.flush();

            lastFlushed = U.currentTimeMillis();
        }

        /** {@inheritDoc} */
        @Override public void close() throws IOException {
            lock.lock();

            try {
                flushLocked();
            }
            finally {
                try {
                    out.close();
                }
                finally {
                    lock.unlock();
                }
            }
        }

        /**
         * Forcibly closes underlying stream ignoring any possible exception.
         */
        public void forceClose() {
            try {
                out.close();
            }
            catch (IOException ignored) {
                // No-op.
            }
        }

        /**
         * @param b Buffer to copy from.
         * @param off Offset in source buffer.
         * @param len Length.
         * @param resBuf Result buffer.
         * @param resOff Result offset.
         */
        private void messageToBuffer(byte[] b, int off, int len, byte[] resBuf, int resOff) {
            assert b.length == len;
            assert off == 0;
            assert resBuf.length >= resOff + len + 4;

            U.intToBytes(len, resBuf, resOff);

            U.arrayCopy(b, off, resBuf, resOff + 4, len);
        }

        /**
         * @param b Buffer to copy from (length included).
         * @param off Offset in source buffer.
         * @param len Length.
         * @param resBuf Result buffer.
         * @param resOff Result offset.
         */
        private void messageToBuffer0(byte[] b, int off, int len, byte[] resBuf, int resOff) {
            assert off == 0;
            assert resBuf.length >= resOff + len;

            U.arrayCopy(b, off, resBuf, resOff, len);
        }

        /** {@inheritDoc} */
        @Override public String toString() {
            lock.lock();

            try {
                return S.toString(UnsafeBufferedOutputStream.class, this);
            }
            finally {
                lock.unlock();
            }
        }
    }
}


text:
import { PolymerElement } from '@polymer/polymer/polymer-element.js';
import { html, htmlLiteral } from '@polymer/polymer/lib/utils/html-tag.js';
import { dedupingMixin } from '@polymer/polymer/lib/utils/mixin.js';
import { InputPickerPattern } from '@fooloomanzoo/input-picker-pattern/input-picker-pattern.js';
import { SwitchMixin } from '@fooloomanzoo/input-picker-pattern/switch-mixin.js';
import { DatetimeFormMixin, DatetimeInputMixin } from '@fooloomanzoo/datetime-input/datetime-input-mixin.js';
import { TimeInputPattern } from '@fooloomanzoo/datetime-input/time-input.js';
import { DatetimeMixin } from '@fooloomanzoo/property-mixins/datetime-mixin.js';
import { TimeElementPattern } from './time-element.js';
import { DatetimePickerMixin } from './datetime-picker-mixin.js';
import { style as dropdownStyle } from '@fooloomanzoo/input-picker-pattern/dropdown-style.js';

/**
 * Mixin for time-picker
 *
 * @appliesMixin TimeInputPattern
 * @appliesMixin TimeElementPattern
 * @appliesMixin DatetimePickerMixin
 *
 * @mixinFunction
 * @polymer
 */
export const TimePickerPattern = dedupingMixin( superClass => {
  return class extends superClass {

    static get expectedNativeInputType() {
      return htmlLiteral`time`;
    }

    static get pickerTemplate() {
      return html`

          ${this.timeTemplate}

            ${this.buttonTemplate}

      `;
    }

    _computeNativeInput(date, time) {
      if (!(date && time)) {
        if (!(date || time)) {
          this._nativeInput = '';
        }
        return;
      }
      this._nativeInput = time;
    }

    _reflectNativeInput(nativeInput) {
      if (!this._computeShouldNative(this.native) || !nativeInput) {
        return;
      }
      this._dateTimeChanged(this.date, nativeInput);
    }
  }
});

/**
 *  `<time-picker>` is a picker for time for **[Polymer](https://github.com/Polymer/@polymer)** that can use the **native** input, too. If the **native** picker is choosen and is not supported, this element uses the **polyfill** time-picker. The `<time-element>` will come in place if the native picker is not available or is not explicitly wanted. A range picker is provided by combining the `min`- and `max`-attributes.
 *
 *  ```html
 *    <time-picker value="{{value}}"></time-picker>
 *  ```
 *
 *  If you need an **overlay** then use `overlay-time-picker`, that creates the element in an `overlay-element`, that extends *IronOverlayBehavior* and will create some of its attribute-bindings.
 *
 * Custom property | Description | Default
 * ----------------|-------------|----------
 * `--time-element`                   | Mixin applied to the time-element              | {}
 *
 *  Have a look at [input-picker-pattern#input-picker-shared-style](https://github.com/fooloomanzoo/input-picker-pattern#input-picker-shared-style) and [input-picker-pattern#input-shared-style](https://github.com/fooloomanzoo/input-picker-pattern#input-shared-style) to see how to style the element.
 *
 *  @polymer
 *  @customElement
 *
 *  @appliesMixin DatetimePickerMixin
 *  @appliesMixin DatetimeInputMixin
 *  @appliesMixin TimePickerPattern
 *  @appliesMixin TimeInputPattern
 *  @appliesMixin TimeElementPattern
 *  @appliesMixin SwitchMixin
 *  @appliesMixin InputPickerPattern
 *  @appliesMixin DatetimeFormMixin
 *  @appliesMixin DatetimeMixin
 *
 *  @demo demo/index.html
 *  @demo demo/time-elements.html time elements
 *  @demo demo/form.html in a form
 *  @demo demo/music-album.html music album demo
 **/
export class TimePicker extends TimePickerPattern(DatetimePickerMixin(TimeElementPattern(SwitchMixin(TimeInputPattern(DatetimeInputMixin(DatetimeFormMixin(InputPickerPattern(DatetimeMixin(PolymerElement))))))))) {

  static get is() {
    return 'time-picker';
  }

  static get styleTemplate() {
    return html`
      ${dropdownStyle}
      ${super.styleTemplate}
    `
  }

  get _hasNative() {
    return TimePicker._hasNative;
  }
}

if (!customElements.get(TimePicker.is)) {
  customElements.define(TimePicker.is, TimePicker);
}


text:
"""Python part of the warnings subsystem."""

import sys

__all__ = ["warn", "warn_explicit", "showwarning",
           "formatwarning", "filterwarnings", "simplefilter",
           "resetwarnings", "catch_warnings"]

def showwarning(message, category, filename, lineno, file=None, line=None):
    """Hook to write a warning to a file; replace if you like."""
    if file is None:
        file = sys.stderr
        if file is None:
            # sys.stderr is None when run with pythonw.exe - warnings get lost
            return
    try:
        file.write(formatwarning(message, category, filename, lineno, line))
    except OSError:
        pass # the file (probably stderr) is invalid - this warning gets lost.

def formatwarning(message, category, filename, lineno, line=None):
    """Function to format a warning the standard way."""
    import linecache
    s =  "%s:%s: %s: %s\n" % (filename, lineno, category.__name__, message)
    line = linecache.getline(filename, lineno) if line is None else line
    if line:
        line = line.strip()
        s += "  %s\n" % line
    return s

def filterwarnings(action, message="", category=Warning, module="", lineno=0,
                   append=False):
    """Insert an entry into the list of warnings filters (at the front).

    'action' -- one of "error", "ignore", "always", "default", "module",
                or "once"
    'message' -- a regex that the warning message must match
    'category' -- a class that the warning must be a subclass of
    'module' -- a regex that the module name must match
    'lineno' -- an integer line number, 0 matches all warnings
    'append' -- if true, append to the list of filters
    """
    import re
    assert action in ("error", "ignore", "always", "default", "module",
                      "once"), "invalid action: %r" % (action,)
    assert isinstance(message, str), "message must be a string"
    assert isinstance(category, type), "category must be a class"
    assert issubclass(category, Warning), "category must be a Warning subclass"
    assert isinstance(module, str), "module must be a string"
    assert isinstance(lineno, int) and lineno >= 0, \
           "lineno must be an int >= 0"
    item = (action, re.compile(message, re.I), category,
            re.compile(module), lineno)
    if append:
        filters.append(item)
    else:
        filters.insert(0, item)
    _filters_mutated()

def simplefilter(action, category=Warning, lineno=0, append=False):
    """Insert a simple entry into the list of warnings filters (at the front).

    A simple filter matches all modules and messages.
    'action' -- one of "error", "ignore", "always", "default", "module",
                or "once"
    'category' -- a class that the warning must be a subclass of
    'lineno' -- an integer line number, 0 matches all warnings
    'append' -- if true, append to the list of filters
    """
    assert action in ("error", "ignore", "always", "default", "module",
                      "once"), "invalid action: %r" % (action,)
    assert isinstance(lineno, int) and lineno >= 0, \
           "lineno must be an int >= 0"
    item = (action, None, category, None, lineno)
    if append:
        filters.append(item)
    else:
        filters.insert(0, item)
    _filters_mutated()

def resetwarnings():
    """Clear the list of warning filters, so that no filters are active."""
    filters[:] = []
    _filters_mutated()

class _OptionError(Exception):
    """Exception used by option processing helpers."""
    pass

# Helper to process -W options passed via sys.warnoptions
def _processoptions(args):
    for arg in args:
        try:
            _setoption(arg)
        except _OptionError as msg:
            print("Invalid -W option ignored:", msg, file=sys.stderr)

# Helper for _processoptions()
def _setoption(arg):
    import re
    parts = arg.split(':')
    if len(parts) > 5:
        raise _OptionError("too many fields (max 5): %r" % (arg,))
    while len(parts) < 5:
        parts.append('')
    action, message, category, module, lineno = [s.strip()
                                                 for s in parts]
    action = _getaction(action)
    message = re.escape(message)
    category = _getcategory(category)
    module = re.escape(module)
    if module:
        module = module + '$'
    if lineno:
        try:
            lineno = int(lineno)
            if lineno < 0:
                raise ValueError
        except (ValueError, OverflowError):
            raise _OptionError("invalid lineno %r" % (lineno,))
    else:
        lineno = 0
    filterwarnings(action, message, category, module, lineno)

# Helper for _setoption()
def _getaction(action):
    if not action:
        return "default"
    if action == "all": return "always" # Alias
    for a in ('default', 'always', 'ignore', 'module', 'once', 'error'):
        if a.startswith(action):
            return a
    raise _OptionError("invalid action: %r" % (action,))

# Helper for _setoption()
def _getcategory(category):
    import re
    if not category:
        return Warning
    if re.match("^[a-zA-Z0-9_]+$", category):
        try:
            cat = eval(category)
        except NameError:
            raise _OptionError("unknown warning category: %r" % (category,))
    else:
        i = category.rfind(".")
        module = category[:i]
        klass = category[i+1:]
        try:
            m = __import__(module, None, None, [klass])
        except ImportError:
            raise _OptionError("invalid module name: %r" % (module,))
        try:
            cat = getattr(m, klass)
        except AttributeError:
            raise _OptionError("unknown warning category: %r" % (category,))
    if not issubclass(cat, Warning):
        raise _OptionError("invalid warning category: %r" % (category,))
    return cat

def _is_internal_frame(frame):
    """Signal whether the frame is an internal CPython implementation detail."""
    filename = frame.f_code.co_filename
    return 'importlib' in filename and '_bootstrap' in filename

def _next_external_frame(frame):
    """Find the next frame that doesn't involve CPython internals."""
    frame = frame.f_back
    while frame is not None and _is_internal_frame(frame):
        frame = frame.f_back
    return frame

# Code typically replaced by _warnings
def warn(message, category=None, stacklevel=1):
    """Issue a warning, or maybe ignore it or raise an exception."""
    # Check if message is already a Warning object
    if isinstance(message, Warning):
        category = message.__class__
    # Check category argument
    if category is None:
        category = UserWarning
    if not (isinstance(category, type) and issubclass(category, Warning)):
        raise TypeError("category must be a Warning subclass, "
                        "not '{:s}'".format(type(category).__name__))
    # Get context information
    try:
        if stacklevel <= 1 or _is_internal_frame(sys._getframe(1)):
            # If frame is too small to care or if the warning originated in
            # internal code, then do not try to hide any frames.
            frame = sys._getframe(stacklevel)
        else:
            frame = sys._getframe(1)
            # Look for one frame less since the above line starts us off.
            for x in range(stacklevel-1):
                frame = _next_external_frame(frame)
                if frame is None:
                    raise ValueError
    except ValueError:
        globals = sys.__dict__
        lineno = 1
    else:
        globals = frame.f_globals
        lineno = frame.f_lineno
    if '__name__' in globals:
        module = globals['__name__']
    else:
        module = "<string>"
    filename = globals.get('__file__')
    if filename:
        fnl = filename.lower()
        if fnl.endswith(".pyc"):
            filename = filename[:-1]
    else:
        if module == "__main__":
            try:
                filename = sys.argv[0]
            except AttributeError:
                # embedded interpreters don't have sys.argv, see bug #839151
                filename = '__main__'
        if not filename:
            filename = module
    registry = globals.setdefault("__warningregistry__", {})
    warn_explicit(message, category, filename, lineno, module, registry,
                  globals)

def warn_explicit(message, category, filename, lineno,
                  module=None, registry=None, module_globals=None):
    lineno = int(lineno)
    if module is None:
        module = filename or "<unknown>"
        if module[-3:].lower() == ".py":
            module = module[:-3] # XXX What about leading pathname?
    if registry is None:
        registry = {}
    if registry.get('version', 0) != _filters_version:
        registry.clear()
        registry['version'] = _filters_version
    if isinstance(message, Warning):
        text = str(message)
        category = message.__class__
    else:
        text = message
        message = category(message)
    key = (text, category, lineno)
    # Quick test for common case
    if registry.get(key):
        return
    # Search the filters
    for item in filters:
        action, msg, cat, mod, ln = item
        if ((msg is None or msg.match(text)) and
            issubclass(category, cat) and
            (mod is None or mod.match(module)) and
            (ln == 0 or lineno == ln)):
            break
    else:
        action = defaultaction
    # Early exit actions
    if action == "ignore":
        registry[key] = 1
        return

    # Prime the linecache for formatting, in case the
    # "file" is actually in a zipfile or something.
    import linecache
    linecache.getlines(filename, module_globals)

    if action == "error":
        raise message
    # Other actions
    if action == "once":
        registry[key] = 1
        oncekey = (text, category)
        if onceregistry.get(oncekey):
            return
        onceregistry[oncekey] = 1
    elif action == "always":
        pass
    elif action == "module":
        registry[key] = 1
        altkey = (text, category, 0)
        if registry.get(altkey):
            return
        registry[altkey] = 1
    elif action == "default":
        registry[key] = 1
    else:
        # Unrecognized actions are errors
        raise RuntimeError(
              "Unrecognized action (%r) in warnings.filters:\n %s" %
              (action, item))
    if not callable(showwarning):
        raise TypeError("warnings.showwarning() must be set to a "
                        "function or method")
    # Print message and context
    showwarning(message, category, filename, lineno)

class WarningMessage(object):

    """Holds the result of a single showwarning() call."""

    _WARNING_DETAILS = ("message", "category", "filename", "lineno", "file",
                        "line")

    def __init__(self, message, category, filename, lineno, file=None,
                    line=None):
        local_values = locals()
        for attr in self._WARNING_DETAILS:
            setattr(self, attr, local_values[attr])
        self._category_name = category.__name__ if category else None

    def __str__(self):
        return ("{message : %r, category : %r, filename : %r, lineno : %s, "
                    "line : %r}" % (self.message, self._category_name,
                                    self.filename, self.lineno, self.line))

class catch_warnings(object):

    """A context manager that copies and restores the warnings filter upon
    exiting the context.

    The 'record' argument specifies whether warnings should be captured by a
    custom implementation of warnings.showwarning() and be appended to a list
    returned by the context manager. Otherwise None is returned by the context
    manager. The objects appended to the list are arguments whose attributes
    mirror the arguments to showwarning().

    The 'module' argument is to specify an alternative module to the module
    named 'warnings' and imported under that name. This argument is only useful
    when testing the warnings module itself.

    """

    def __init__(self, *, record=False, module=None):
        """Specify whether to record warnings and if an alternative module
        should be used other than sys.modules['warnings'].

        For compatibility with Python 3.0, please consider all arguments to be
        keyword-only.

        """
        self._record = record
        self._module = sys.modules['warnings'] if module is None else module
        self._entered = False

    def __repr__(self):
        args = []
        if self._record:
            args.append("record=True")
        if self._module is not sys.modules['warnings']:
            args.append("module=%r" % self._module)
        name = type(self).__name__
        return "%s(%s)" % (name, ", ".join(args))

    def __enter__(self):
        if self._entered:
            raise RuntimeError("Cannot enter %r twice" % self)
        self._entered = True
        self._filters = self._module.filters
        self._module.filters = self._filters[:]
        self._module._filters_mutated()
        self._showwarning = self._module.showwarning
        if self._record:
            log = []
            def showwarning(*args, **kwargs):
                log.append(WarningMessage(*args, **kwargs))
            self._module.showwarning = showwarning
            return log
        else:
            return None

    def __exit__(self, *exc_info):
        if not self._entered:
            raise RuntimeError("Cannot exit %r without entering first" % self)
        self._module.filters = self._filters
        self._module._filters_mutated()
        self._module.showwarning = self._showwarning

# filters contains a sequence of filter 5-tuples
# The components of the 5-tuple are:
# - an action: error, ignore, always, default, module, or once
# - a compiled regex that must match the warning message
# - a class representing the warning category
# - a compiled regex that must match the module that is being warned
# - a line number for the line being warning, or 0 to mean any line
# If either if the compiled regexs are None, match anything.
_warnings_defaults = False
try:
    from _warnings import (filters, _defaultaction, _onceregistry,
                           warn, warn_explicit, _filters_mutated)
    defaultaction = _defaultaction
    onceregistry = _onceregistry
    _warnings_defaults = True
except ImportError:
    filters = []
    defaultaction = "default"
    onceregistry = {}

    _filters_version = 1

    def _filters_mutated():
        global _filters_version
        _filters_version += 1

# Module initialization
_processoptions(sys.warnoptions)
if not _warnings_defaults:
    silence = [ImportWarning, PendingDeprecationWarning]
    silence.append(DeprecationWarning)
    for cls in silence:
        simplefilter("ignore", category=cls)
    bytes_warning = sys.flags.bytes_warning
    if bytes_warning > 1:
        bytes_action = "error"
    elif bytes_warning:
        bytes_action = "default"
    else:
        bytes_action = "ignore"
    simplefilter(bytes_action, category=BytesWarning, append=1)
    # resource usage warnings are enabled by default in pydebug mode
    if hasattr(sys, 'gettotalrefcount'):
        resource_action = "always"
    else:
        resource_action = "ignore"
    simplefilter(resource_action, category=ResourceWarning, append=1)

del _warnings_defaults


text:
package org.jboss.as.quickstart.cdi.extension.test;

import static org.junit.Assert.assertTrue;

import javax.enterprise.inject.spi.Extension;
import javax.inject.Inject;

import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.quickstart.cdi.parameterlogger.ParameterLoggerExtension;
import org.jboss.as.quickstart.cdi.parameterlogger.model.MyBean;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.jboss.shrinkwrap.resolver.api.DependencyResolvers;
import org.jboss.shrinkwrap.resolver.api.maven.MavenDependencyResolver;
import org.junit.Test;
import org.junit.runner.RunWith;

/**
 * Verification test.
 */
@RunWith(Arquillian.class)
public class ParameterLoggerTest {
    @Deployment
    public static Archive<?> getDeployment() {

        MavenDependencyResolver resolver = DependencyResolvers.use(MavenDependencyResolver.class).loadMetadataFromPom("pom.xml");

        Archive<?> archive = ShrinkWrap.create(WebArchive.class, "parameter-logger.war")
                .addPackages(true, ParameterLoggerExtension.class.getPackage())
                .addClass(TestableParameterLog.class)
                .addAsWebInfResource("beans.xml")
                .addAsServiceProvider(Extension.class, ParameterLoggerExtension.class)
                .addAsLibraries(resolver.artifacts(
                        "org.apache.deltaspike.core:deltaspike-core-api",
                        "org.apache.deltaspike.core:deltaspike-core-impl").resolveAsFiles());
        return archive;
    }

    @Inject MyBean myBean;

    @Inject TestableParameterLog testableParameterLog;

    @Test
    public void assertFilledMonster() {
        myBean.sayHello("Pete", "Hardy");
        assertTrue(testableParameterLog.contains("Logging parameter value for parameter 1 of method sayHello: Hardy"));
    }
}


text:
'use strict'

const tap = require('tap')
const semver = require('semver')

if (semver.lt(process.versions.node, '13.3.0')) {
  tap.pass('Skip because Node version <= 13.3.0')
  tap.end()
} else {
  // Import is not allowed syntax in Node 8
  // eslint-disable-next-line
  new Function('module', 'return import(module)')('./esm.mjs').catch((err) => {
    process.nextTick(() => {
      throw err
    })
  })
}


text:
'use strict';
const nodemailer = require('nodemailer');

// create reusable transporter object using the default SMTP transport
let transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: {
        user: '71mb4.noreply@gmail.com',
        pass: 'Opus9no2'
    }
});

function sendMail(to, subject,body){
	let mailOptions = {
		from: '"71mb4" <71mb4.noreply@gmail.com>', // sender address
		to: to, // list of receivers
		subject: '71mb4 - ' + subject, // Subject line
		text: '', // plain text body
		html: `
 71mb4

` + body + `

	`
	};
	// send mail with defined transport object
	transporter.sendMail(mailOptions, (error, info) => {
		if (error)
			return console.log(error);
		console.log('Message %s sent: %s', info.messageId, info.response);
	});
}

exports.send=sendMail;


text:
include(CheckCXXSourceCompiles)

check_cxx_source_compiles("int main() { auto lambda = [](auto x, auto y) { return x + y; };  }" USE_GENERIC_LAMBDAS)

if (USE_GENERIC_LAMBDAS)
	message("-- Generic lambdas (C++14) are supported by the compiler.")
	add_definitions(-DUSE_GENERIC_LAMBDAS)
else ()
	message("-- Generic lambdas (C++14) are not supported by the compiler.")
endif()


text:
export enum EOperation {
    CREATE, DELETE, UPDATE, INIT
}


text:
FROM alpine

MAINTAINER paganini@paganini.net

ENV SUBSONIC_VERSION 6.1.6

# Desired UID & GID
ENV SUBSONIC_UID=10000
ENV SUBSONIC_GID=10000

# This is where subsonic will write its state. Should be mapped to a docker
# volume or a location outside the container. The unfortunate name comes from
# the upstream subsonic.sh, which uses SUBSONIC_HOME for a data directory.
ENV SUBSONIC_HOME=/var/subsonic

# Internal home directory for the "subsonic" user (internal to the container).
# and main location for subsonic binaries.
ENV SUBSONIC_BIN=/home/subsonic

# Add subsonic tar.gz
ADD https://sourceforge.net/projects/subsonic/files/subsonic/${SUBSONIC_VERSION}/subsonic-${SUBSONIC_VERSION}-standalone.tar.gz/download /tmp/subsonic.tar.gz

# - Create a new group 'subsonic' with SUBSONIC_GID, home $SUBSONIC_BIN
# - Create the $SUBSONIC_BIN
# - Create user 'subsonic' with SUBSONIC_UID, add to that group.
# - Set permissions of $SUBSONIC_BIN
RUN addgroup -g $SUBSONIC_GID subsonic && \
    adduser -D -H -h $SUBSONIC_BIN -u $SUBSONIC_UID -G subsonic -g "Subsonic User" subsonic && \
    mkdir -p $SUBSONIC_BIN && \
    tar zxvf /tmp/subsonic.tar.gz -C $SUBSONIC_BIN && \
    rm -f /tmp/*.tar.gz && \
    chown subsonic $SUBSONIC_BIN && \
    chmod 0770 $SUBSONIC_BIN

# Create subsonic data directory ($SUBSONIC_HOME). This is where subsonic stores
# its state information. This is normally overriden with --volume, but we create
# it here in case the user prefers to save state in the container itself.
RUN mkdir -p $SUBSONIC_HOME && \
    chown subsonic $SUBSONIC_HOME && \
    chmod 0770 $SUBSONIC_HOME

# Install java8, ffmpeg, lame & friends.
RUN apk --update add openjdk8-jre ffmpeg

# Create hardlinks to the transcoding binaries so we can mount a volume
# over $SUBSONIC_HOME. If you mount a volume over $SUBSONIC_HOME, create
# symlinks on the host.
#
# TODO: Investigate a better way to do this.
RUN mkdir -p $SUBSONIC_HOME/transcode && \
    ln /usr/bin/ffmpeg /usr/bin/lame $SUBSONIC_HOME/transcode

VOLUME $SUBSONIC_HOME

EXPOSE 4040

USER subsonic

COPY startup.sh /startup.sh

CMD []
ENTRYPOINT ["/startup.sh"]


text:
#pragma once
#include <aws/iot/IoT_EXPORTS.h>
#include <aws/iot/IoTRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/iot/model/TargetSelection.h>
#include <aws/iot/model/AwsJobExecutionsRolloutConfig.h>
#include <aws/core/utils/memory/stl/AWSMap.h>
#include <aws/iot/model/OTAUpdateFile.h>
#include <utility>

namespace Aws
{
namespace IoT
{
namespace Model
{

  /**
   */
  class AWS_IOT_API CreateOTAUpdateRequest : public IoTRequest
  {
  public:
    CreateOTAUpdateRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "CreateOTAUpdate"; }

    Aws::String SerializePayload() const override;

    /**
     *
The ID of the OTA update to be created.

     */
    inline const Aws::String& GetOtaUpdateId() const{ return m_otaUpdateId; }

    /**
     *
The ID of the OTA update to be created.

     */
    inline void SetOtaUpdateId(const Aws::String& value) { m_otaUpdateIdHasBeenSet = true; m_otaUpdateId = value; }

    /**
     *
The ID of the OTA update to be created.

     */
    inline void SetOtaUpdateId(Aws::String&& value) { m_otaUpdateIdHasBeenSet = true; m_otaUpdateId = std::move(value); }

    /**
     *
The ID of the OTA update to be created.

     */
    inline void SetOtaUpdateId(const char* value) { m_otaUpdateIdHasBeenSet = true; m_otaUpdateId.assign(value); }

    /**
     *
The ID of the OTA update to be created.

     */
    inline CreateOTAUpdateRequest& WithOtaUpdateId(const Aws::String& value) { SetOtaUpdateId(value); return *this;}

    /**
     *
The ID of the OTA update to be created.

     */
    inline CreateOTAUpdateRequest& WithOtaUpdateId(Aws::String&& value) { SetOtaUpdateId(std::move(value)); return *this;}

    /**
     *
The ID of the OTA update to be created.

     */
    inline CreateOTAUpdateRequest& WithOtaUpdateId(const char* value) { SetOtaUpdateId(value); return *this;}

    /**
     *
The description of the OTA update.

     */
    inline const Aws::String& GetDescription() const{ return m_description; }

    /**
     *
The description of the OTA update.

     */
    inline void SetDescription(const Aws::String& value) { m_descriptionHasBeenSet = true; m_description = value; }

    /**
     *
The description of the OTA update.

     */
    inline void SetDescription(Aws::String&& value) { m_descriptionHasBeenSet = true; m_description = std::move(value); }

    /**
     *
The description of the OTA update.

     */
    inline void SetDescription(const char* value) { m_descriptionHasBeenSet = true; m_description.assign(value); }

    /**
     *
The description of the OTA update.

     */
    inline CreateOTAUpdateRequest& WithDescription(const Aws::String& value) { SetDescription(value); return *this;}

    /**
     *
The description of the OTA update.

     */
    inline CreateOTAUpdateRequest& WithDescription(Aws::String&& value) { SetDescription(std::move(value)); return *this;}

    /**
     *
The description of the OTA update.

     */
    inline CreateOTAUpdateRequest& WithDescription(const char* value) { SetDescription(value); return *this;}

    /**
     *
The targeted devices to receive OTA updates.

     */
    inline const Aws::Vector<Aws::String>& GetTargets() const{ return m_targets; }

    /**
     *
The targeted devices to receive OTA updates.

     */
    inline void SetTargets(const Aws::Vector<Aws::String>& value) { m_targetsHasBeenSet = true; m_targets = value; }

    /**
     *
The targeted devices to receive OTA updates.

     */
    inline void SetTargets(Aws::Vector<Aws::String>&& value) { m_targetsHasBeenSet = true; m_targets = std::move(value); }

    /**
     *
The targeted devices to receive OTA updates.

     */
    inline CreateOTAUpdateRequest& WithTargets(const Aws::Vector<Aws::String>& value) { SetTargets(value); return *this;}

    /**
     *
The targeted devices to receive OTA updates.

     */
    inline CreateOTAUpdateRequest& WithTargets(Aws::Vector<Aws::String>&& value) { SetTargets(std::move(value)); return *this;}

    /**
     *
The targeted devices to receive OTA updates.

     */
    inline CreateOTAUpdateRequest& AddTargets(const Aws::String& value) { m_targetsHasBeenSet = true; m_targets.push_back(value); return *this; }

    /**
     *
The targeted devices to receive OTA updates.

     */
    inline CreateOTAUpdateRequest& AddTargets(Aws::String&& value) { m_targetsHasBeenSet = true; m_targets.push_back(std::move(value)); return *this; }

    /**
     *
The targeted devices to receive OTA updates.

     */
    inline CreateOTAUpdateRequest& AddTargets(const char* value) { m_targetsHasBeenSet = true; m_targets.push_back(value); return *this; }

    /**
     *
Specifies whether the update will continue to run (CONTINUOUS), or will be
     * complete after all the things specified as targets have completed the update
     * (SNAPSHOT). If continuous, the update may also be run on a thing when a change
     * is detected in a target. For example, an update will run on a thing when the
     * thing is added to a target group, even after the update was completed by all
     * things originally in the group. Valid values: CONTINUOUS | SNAPSHOT.

     */
    inline const TargetSelection& GetTargetSelection() const{ return m_targetSelection; }

    /**
     *
Specifies whether the update will continue to run (CONTINUOUS), or will be
     * complete after all the things specified as targets have completed the update
     * (SNAPSHOT). If continuous, the update may also be run on a thing when a change
     * is detected in a target. For example, an update will run on a thing when the
     * thing is added to a target group, even after the update was completed by all
     * things originally in the group. Valid values: CONTINUOUS | SNAPSHOT.

     */
    inline void SetTargetSelection(const TargetSelection& value) { m_targetSelectionHasBeenSet = true; m_targetSelection = value; }

    /**
     *
Specifies whether the update will continue to run (CONTINUOUS), or will be
     * complete after all the things specified as targets have completed the update
     * (SNAPSHOT). If continuous, the update may also be run on a thing when a change
     * is detected in a target. For example, an update will run on a thing when the
     * thing is added to a target group, even after the update was completed by all
     * things originally in the group. Valid values: CONTINUOUS | SNAPSHOT.

     */
    inline void SetTargetSelection(TargetSelection&& value) { m_targetSelectionHasBeenSet = true; m_targetSelection = std::move(value); }

    /**
     *
Specifies whether the update will continue to run (CONTINUOUS), or will be
     * complete after all the things specified as targets have completed the update
     * (SNAPSHOT). If continuous, the update may also be run on a thing when a change
     * is detected in a target. For example, an update will run on a thing when the
     * thing is added to a target group, even after the update was completed by all
     * things originally in the group. Valid values: CONTINUOUS | SNAPSHOT.

     */
    inline CreateOTAUpdateRequest& WithTargetSelection(const TargetSelection& value) { SetTargetSelection(value); return *this;}

    /**
     *
Specifies whether the update will continue to run (CONTINUOUS), or will be
     * complete after all the things specified as targets have completed the update
     * (SNAPSHOT). If continuous, the update may also be run on a thing when a change
     * is detected in a target. For example, an update will run on a thing when the
     * thing is added to a target group, even after the update was completed by all
     * things originally in the group. Valid values: CONTINUOUS | SNAPSHOT.

     */
    inline CreateOTAUpdateRequest& WithTargetSelection(TargetSelection&& value) { SetTargetSelection(std::move(value)); return *this;}

    /**
     *
Configuration for the rollout of OTA updates.

     */
    inline const AwsJobExecutionsRolloutConfig& GetAwsJobExecutionsRolloutConfig() const{ return m_awsJobExecutionsRolloutConfig; }

    /**
     *
Configuration for the rollout of OTA updates.

     */
    inline void SetAwsJobExecutionsRolloutConfig(const AwsJobExecutionsRolloutConfig& value) { m_awsJobExecutionsRolloutConfigHasBeenSet = true; m_awsJobExecutionsRolloutConfig = value; }

    /**
     *
Configuration for the rollout of OTA updates.

     */
    inline void SetAwsJobExecutionsRolloutConfig(AwsJobExecutionsRolloutConfig&& value) { m_awsJobExecutionsRolloutConfigHasBeenSet = true; m_awsJobExecutionsRolloutConfig = std::move(value); }

    /**
     *
Configuration for the rollout of OTA updates.

     */
    inline CreateOTAUpdateRequest& WithAwsJobExecutionsRolloutConfig(const AwsJobExecutionsRolloutConfig& value) { SetAwsJobExecutionsRolloutConfig(value); return *this;}

    /**
     *
Configuration for the rollout of OTA updates.

     */
    inline CreateOTAUpdateRequest& WithAwsJobExecutionsRolloutConfig(AwsJobExecutionsRolloutConfig&& value) { SetAwsJobExecutionsRolloutConfig(std::move(value)); return *this;}

    /**
     *
The files to be streamed by the OTA update.

     */
    inline const Aws::Vector<OTAUpdateFile>& GetFiles() const{ return m_files; }

    /**
     *
The files to be streamed by the OTA update.

     */
    inline void SetFiles(const Aws::Vector<OTAUpdateFile>& value) { m_filesHasBeenSet = true; m_files = value; }

    /**
     *
The files to be streamed by the OTA update.

     */
    inline void SetFiles(Aws::Vector<OTAUpdateFile>&& value) { m_filesHasBeenSet = true; m_files = std::move(value); }

    /**
     *
The files to be streamed by the OTA update.

     */
    inline CreateOTAUpdateRequest& WithFiles(const Aws::Vector<OTAUpdateFile>& value) { SetFiles(value); return *this;}

    /**
     *
The files to be streamed by the OTA update.

     */
    inline CreateOTAUpdateRequest& WithFiles(Aws::Vector<OTAUpdateFile>&& value) { SetFiles(std::move(value)); return *this;}

    /**
     *
The files to be streamed by the OTA update.

     */
    inline CreateOTAUpdateRequest& AddFiles(const OTAUpdateFile& value) { m_filesHasBeenSet = true; m_files.push_back(value); return *this; }

    /**
     *
The files to be streamed by the OTA update.

     */
    inline CreateOTAUpdateRequest& AddFiles(OTAUpdateFile&& value) { m_filesHasBeenSet = true; m_files.push_back(std::move(value)); return *this; }

    /**
     *
The IAM role that allows access to the AWS IoT Jobs service.

     */
    inline const Aws::String& GetRoleArn() const{ return m_roleArn; }

    /**
     *
The IAM role that allows access to the AWS IoT Jobs service.

     */
    inline void SetRoleArn(const Aws::String& value) { m_roleArnHasBeenSet = true; m_roleArn = value; }

    /**
     *
The IAM role that allows access to the AWS IoT Jobs service.

     */
    inline void SetRoleArn(Aws::String&& value) { m_roleArnHasBeenSet = true; m_roleArn = std::move(value); }

    /**
     *
The IAM role that allows access to the AWS IoT Jobs service.

     */
    inline void SetRoleArn(const char* value) { m_roleArnHasBeenSet = true; m_roleArn.assign(value); }

    /**
     *
The IAM role that allows access to the AWS IoT Jobs service.

     */
    inline CreateOTAUpdateRequest& WithRoleArn(const Aws::String& value) { SetRoleArn(value); return *this;}

    /**
     *
The IAM role that allows access to the AWS IoT Jobs service.

     */
    inline CreateOTAUpdateRequest& WithRoleArn(Aws::String&& value) { SetRoleArn(std::move(value)); return *this;}

    /**
     *
The IAM role that allows access to the AWS IoT Jobs service.

     */
    inline CreateOTAUpdateRequest& WithRoleArn(const char* value) { SetRoleArn(value); return *this;}

    /**
     *
A list of additional OTA update parameters which are name-value pairs.

     */
    inline const Aws::Map<Aws::String, Aws::String>& GetAdditionalParameters() const{ return m_additionalParameters; }

    /**
     *
A list of additional OTA update parameters which are name-value pairs.

     */
    inline void SetAdditionalParameters(const Aws::Map<Aws::String, Aws::String>& value) { m_additionalParametersHasBeenSet = true; m_additionalParameters = value; }

    /**
     *
A list of additional OTA update parameters which are name-value pairs.

     */
    inline void SetAdditionalParameters(Aws::Map<Aws::String, Aws::String>&& value) { m_additionalParametersHasBeenSet = true; m_additionalParameters = std::move(value); }

    /**
     *
A list of additional OTA update parameters which are name-value pairs.

     */
    inline CreateOTAUpdateRequest& WithAdditionalParameters(const Aws::Map<Aws::String, Aws::String>& value) { SetAdditionalParameters(value); return *this;}

    /**
     *
A list of additional OTA update parameters which are name-value pairs.

     */
    inline CreateOTAUpdateRequest& WithAdditionalParameters(Aws::Map<Aws::String, Aws::String>&& value) { SetAdditionalParameters(std::move(value)); return *this;}

    /**
     *
A list of additional OTA update parameters which are name-value pairs.

     */
    inline CreateOTAUpdateRequest& AddAdditionalParameters(const Aws::String& key, const Aws::String& value) { m_additionalParametersHasBeenSet = true; m_additionalParameters.emplace(key, value); return *this; }

    /**
     *
A list of additional OTA update parameters which are name-value pairs.

     */
    inline CreateOTAUpdateRequest& AddAdditionalParameters(Aws::String&& key, const Aws::String& value) { m_additionalParametersHasBeenSet = true; m_additionalParameters.emplace(std::move(key), value); return *this; }

    /**
     *
A list of additional OTA update parameters which are name-value pairs.

     */
    inline CreateOTAUpdateRequest& AddAdditionalParameters(const Aws::String& key, Aws::String&& value) { m_additionalParametersHasBeenSet = true; m_additionalParameters.emplace(key, std::move(value)); return *this; }

    /**
     *
A list of additional OTA update parameters which are name-value pairs.

     */
    inline CreateOTAUpdateRequest& AddAdditionalParameters(Aws::String&& key, Aws::String&& value) { m_additionalParametersHasBeenSet = true; m_additionalParameters.emplace(std::move(key), std::move(value)); return *this; }

    /**
     *
A list of additional OTA update parameters which are name-value pairs.

     */
    inline CreateOTAUpdateRequest& AddAdditionalParameters(const char* key, Aws::String&& value) { m_additionalParametersHasBeenSet = true; m_additionalParameters.emplace(key, std::move(value)); return *this; }

    /**
     *
A list of additional OTA update parameters which are name-value pairs.

     */
    inline CreateOTAUpdateRequest& AddAdditionalParameters(Aws::String&& key, const char* value) { m_additionalParametersHasBeenSet = true; m_additionalParameters.emplace(std::move(key), value); return *this; }

    /**
     *
A list of additional OTA update parameters which are name-value pairs.

     */
    inline CreateOTAUpdateRequest& AddAdditionalParameters(const char* key, const char* value) { m_additionalParametersHasBeenSet = true; m_additionalParameters.emplace(key, value); return *this; }

  private:

    Aws::String m_otaUpdateId;
    bool m_otaUpdateIdHasBeenSet;

    Aws::String m_description;
    bool m_descriptionHasBeenSet;

    Aws::Vector<Aws::String> m_targets;
    bool m_targetsHasBeenSet;

    TargetSelection m_targetSelection;
    bool m_targetSelectionHasBeenSet;

    AwsJobExecutionsRolloutConfig m_awsJobExecutionsRolloutConfig;
    bool m_awsJobExecutionsRolloutConfigHasBeenSet;

    Aws::Vector<OTAUpdateFile> m_files;
    bool m_filesHasBeenSet;

    Aws::String m_roleArn;
    bool m_roleArnHasBeenSet;

    Aws::Map<Aws::String, Aws::String> m_additionalParameters;
    bool m_additionalParametersHasBeenSet;
  };

} // namespace Model
} // namespace IoT
} // namespace Aws


text:
InternalGapLength::~InternalGapLength() {

}

InternalGapLength::InternalGapLength(int limit) : limit_(limit) {
  assert(limit >= 0);
}

bool InternalGapLength::Check(Seq *seq, Seq *cons) {
  assert(seq != nullptr && cons != nullptr);
  std::list<Node *> nodes;

  seq->GetNodes(&nodes);
  int largest_gap = 0;
  int temp_cons_gap = 0;
  int temp_seq_gap = 0;
  Node *match = nullptr;
  for (Node *node: nodes) {
    if (!node->HasSeq(cons) && !match) {
      // preskoci sve dok nema nekog zajednickog
      continue;
    }
    if (!node->HasSeq(cons) && match) {
      ++temp_seq_gap;
      continue;
    }
    if (node->HasSeq(cons)) {
      match = node;
      if (temp_cons_gap > largest_gap || temp_seq_gap > largest_gap) {
        largest_gap =
            temp_cons_gap > temp_seq_gap ? temp_cons_gap : temp_seq_gap;
        if (largest_gap > limit_) {
          return false;
        }
      }
      temp_seq_gap = 0;
      temp_cons_gap = 0;
    }

    if (node->LinkTo(seq) != node->LinkTo(cons) && match) {

      // u ovom cvoru se racvaju putevi
      // pronadi duljinu rupe u konsenzusu
      if (!node->LinkTo(cons)) {
        continue;
      }
      Node *cons_node = node->LinkTo(cons)->next_node();
      while (cons_node && !cons_node->HasSeq(seq)) {
        ++temp_cons_gap;
        if (cons_node->LinkTo(cons)) {
          cons_node = cons_node->LinkTo(cons)->next_node();
        } else {
          break;
        }
      }
    }

  }
  return largest_gap <= limit_;
}


text:
<?php
class Controller_reports extends Controller
{
	public function action_reports()
	{
		return Response::forge(View::forge('reports'));
	}

}


text:
require 'compass/import-once/activate'
sass_dir = "sass"
css_dir = "src/css"
images_dir = "src/img"
javascripts_dir = "src/js"
output_style = :compressed
relative_assets = true
line_comments = false