text:
using System;

namespace NCron.Service
{
    /// <summary>
    /// Defines a job scheduled for execution.
    /// </summary>
    public class ScheduledJob : IComparable<ScheduledJob>
    {
        private readonly Func<DateTime, DateTime> _schedule;

        /// <summary>
        /// Gets the execution wrapper method to be invoked on each occurence of the job.
        /// </summary>
        public JobExecutionWrapper ExecutionWrapper { get; private set; }

        /// <summary>
        /// Gets the date and time of the next occurence of the job.
        /// </summary>
        public DateTime NextOccurence { get; private set; }

        internal ScheduledJob(Func<DateTime, DateTime> schedule, JobExecutionWrapper executionWrapper, DateTime baseTime)
        {
            _schedule = schedule;
            ExecutionWrapper = executionWrapper;
            NextOccurence = schedule(baseTime);
        }

        internal void Advance()
        {
            NextOccurence = _schedule(NextOccurence);
        }

        public int CompareTo(ScheduledJob other)
        {
            return NextOccurence.CompareTo(other.NextOccurence);
        }
    }
}


text:
				<button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Confirm Delete

One fine body…

				{!! Form::button(' Cancel', array('class' => 'btn btn-default pull-left', 'type' => 'button', 'data-dismiss' => 'modal' )) !!}
				{!! Form::button(' Confirm Delete', array('class' => 'btn btn-danger pull-right', 'type' => 'button', 'id' => 'confirm' )) !!}

redpajama_set_name: RedPajamaGithub


text:
<?php
  session_start();
  if(!isset($_SESSION['studentok']))
  header("location: login.php");
  date_default_timezone_set('America/Chicago');
  include "../medooconnect.php";
  include "../versionInfo.php";

?>

    <title>Passport-Student</title>
    <? include "../personalCode.php";
	     trackerGA(); ?>
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <link href="/passport/css/materialize.css" type="text/css" rel="stylesheet" media="screen,projection" />
    <link href="/passport/css/passport.css" type="text/css" rel="stylesheet" media="screen,projection" />
    <link href="/passport/css/passr.css" type="text/css" rel="stylesheet" media="screen,projection" />
    <link href="/passport/css/animate.css" type="text/css" rel="stylesheet" media="screen,projection" />
    <link rel="manifest" href="/passport/manifest.json">

    <link rel="shortcut icon" type="image/png" href="image/favicon.png"/>

    <meta name="theme-color" content="#D32F2F">

    <meta name="msapplication-navbutton-color" content="#D32F2F">

    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">

    <link rel="shortcut icon" type="image/png" href="/passport/image/favicon.png"/>

    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

             account_circle
             <?php echo $_SESSION['sFN'] . " " . $_SESSION['sLN']; ?>
             <?php echo $_SESSION['email']; ?>

Home

Your Account

Logoutlock_outline

          menu
            Passport
            <?echo $CurrentVersionOfPassport;?>

Your Account

              Change Your Default Study Hall

                <select name="stYear" required onchange="stYearTall();">
                  <option value="" disabled selected>Choose a Class</option>
                  <option value="9">Freshman</option>
                  <option value="10">Sophomore</option>
                  <option value="11">Junior</option>
                  <option value="12">Senior</option>
                </select>
                Your Class

                <select name="shPeriod" required onchange="periodToTeacher(this.value)">
                  <option value="" disabled selected>Choose a Period</option>
                  <option value="A">A Period</option>
                  <option value="B">B Period</option>
                  <option value="C">C Period</option>
                  <option value="D">D Period</option>
                  <option value="E1">E Period (You Have First Lunch)</option>
                  <option value="E2">E Period (You Have Second Lunch)</option>
                  <option value="F">F Period</option>
                  <option value="G">G Period</option>
                  <option value="H">H Period</option>
                </select>
                Study Hall Period

              fast_forwardUpdate Studdy Hall Details

Update Your Account

You must update your Study Hall before you can continue.

This won't take long

        Got It!

  <?php
  if (isset($_GET['updateWelcome'])) {
    echo "";
  }
   ?>


text:
package com.orientechnologies.orient.test.database.auto;

import java.text.ParseException;
import java.util.Date;
import java.util.List;

import org.testng.Assert;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;

import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
import com.orientechnologies.orient.core.metadata.schema.OType;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery;

@Test(groups = "sql-select")
public class DateTest {
	private ODatabaseDocument	database;

	@Parameters(value = "url")
	public DateTest(String iURL) {
		database = new ODatabaseDocumentTx(iURL);
	}

	@Test
	public void testDateConversion() throws ParseException {
		database.open("admin", "admin");

		final long begin = System.currentTimeMillis();

		ODocument doc1 = new ODocument(database, "Order");
		doc1.field("context", "test");
		doc1.field("date", new Date());
		doc1.save();

		ODocument doc2 = new ODocument(database, "Order");
		doc2.field("context", "test");
		doc2.field("date", System.currentTimeMillis());
		doc2.save();

		doc2.reload();
		Assert.assertTrue(doc2.field("date", OType.DATE) instanceof Date);

		doc2.reload();
		Assert.assertTrue(doc2.field("date", Date.class) instanceof Date);

		List<ODocument> result = database.command(
				new OSQLSynchQuery<ODocument>("select * from Order where date >= ? and context = 'test'")).execute(begin);

		Assert.assertEquals(result.size(), 2);
		database.close();
	}

	@Test
	public void testDatePrecision() throws ParseException {
		database.open("admin", "admin");

		final long begin = System.currentTimeMillis();

		String dateAsString = database.getStorage().getConfiguration().getDateFormatInstance().format(begin);

		ODocument doc = new ODocument(database, "Order");
		doc.field("context", "testPrecision");
		doc.field("date", new Date(), OType.DATE);
		doc.save();

		List<ODocument> result = database.command(
				new OSQLSynchQuery<ODocument>("select * from Order where date >= ? and context = 'testPrecision'")).execute(dateAsString);

		Assert.assertEquals(result.size(), 1);
		database.close();
	}

	@Test
	public void testDateTypes() throws ParseException {
		ODocument doc = new ODocument();
		doc.field("context", "test");
		doc.field("date", System.currentTimeMillis(), OType.DATE);

		Assert.assertTrue(doc.field("date") instanceof Date);

	}
}


text:
package http

import (
	"log"
	"net/http"

	"github.com/upframe/shopy"
	"github.com/gorilla/mux"
)

// Serve ...
// TODO: definately move this function to CMD
func Serve(c *shopy.Config) {
	r := mux.NewRouter()

	r.NotFoundHandler = &notFoundHandler{Config: c}

	r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir(c.Assets+"static/"))))

	r.HandleFunc("/", Inject(StaticHandler("index"), c)).Methods("GET")
	r.HandleFunc("/login", Inject(LoginGet, c)).Methods("GET")
	r.HandleFunc("/login", Inject(LoginPost, c)).Methods("POST")

	r.HandleFunc("/register", Inject(RegisterGet, c)).Methods("GET")
	r.HandleFunc("/register", Inject(RegisterPost, c)).Methods("POST")

	r.HandleFunc("/reset", Inject(ResetGet, c)).Methods("GET")
	r.HandleFunc("/reset", Inject(ResetPost, c)).Methods("POST")

	r.HandleFunc("/settings", Inject(MustLogin(SettingsGet), c)).Methods("GET")

	r.HandleFunc("/settings/deactivate", Inject(MustLogin(DeactivateGet), c)).Methods("GET")
	r.HandleFunc("/settings/deactivate", Inject(MustLogin(DeactivatePost), c)).Methods("POST")

	r.HandleFunc("/store", Inject(StoreGet, c)).Methods("GET")

	// If you can Register without having an invite, you will be able to start adding
	// items to the cart without being logged in. Then, you log in or create an account
	// and finish the checkout.
	// TODO: this should be checked directly on the functions...
	if c.InviteOnly {
		r.HandleFunc("/cart", Inject(MustLogin(CartGet), c)).Methods("GET")
		r.HandleFunc("/cart/{id:[0-9]+}", Inject(MustLogin(CartItemPost), c)).Methods("POST")
		r.HandleFunc("/cart/{id:[0-9]+}", Inject(MustLogin(CartItemDelete), c)).Methods("DELETE")
	} else {
		r.HandleFunc("/cart", Inject(CartGet, c)).Methods("GET")
		r.HandleFunc("/cart/{id:[0-9]+}", Inject(CartItemPost, c)).Methods("POST")
		r.HandleFunc("/cart/{id:[0-9]+}", Inject(CartItemDelete, c)).Methods("DELETE")
	}

	r.HandleFunc("/orders", Inject(MustLogin(OrdersGet), c)).Methods("GET")
	r.HandleFunc("/orders/{id:[0-9]+}/cancel", Inject(MustLogin(OrderCancel), c)).Methods("GET")

	r.HandleFunc("/checkout", Inject(MustLogin(CheckoutGet), c)).Methods("GET")
	r.HandleFunc("/checkout", Inject(MustLogin(CheckoutPost), c)).Methods("POST")
	r.HandleFunc("/checkout/confirm", Inject(MustLogin(CheckoutConfirmGet), c)).Methods("GET")

	r.HandleFunc("/logout", Inject(logout, c))

	// Users can only access their own orders and their own user information. Admins
	// can access everything.
	api := r.PathPrefix("/api").Subrouter()

	api.HandleFunc("/orders/{id:[0-9]+}", Inject(MustLogin(APIOrderGet), c)).Methods("GET")
	api.HandleFunc("/products/{id:[0-9]+}", Inject(MustAdmin(APIProductGet), c)).Methods("GET")
	api.HandleFunc("/promocodes/{id}", Inject(MustLogin(APIPromocodeGet), c)).Methods("GET")
	api.HandleFunc("/users/{id:[0-9]+}", Inject(MustLogin(APIUserGet), c)).Methods("GET")

	api.HandleFunc("/orders", Inject(MustAdmin(APIOrderPost), c)).Methods("POST")
	api.HandleFunc("/products", Inject(MustAdmin(APIProductPost), c)).Methods("POST")
	api.HandleFunc("/promocodes", Inject(MustAdmin(APIPromocodePost), c)).Methods("POST")
	api.HandleFunc("/users", Inject(MustAdmin(APIUserPost), c)).Methods("POST")

	api.HandleFunc("/orders/{id:[0-9]+}", Inject(MustAdmin(APIOrderPatch), c)).Methods("PATCH")
	api.HandleFunc("/products/{id:[0-9]+}", Inject(MustAdmin(APIProductPatch), c)).Methods("PATCH")
	api.HandleFunc("/promocodes/{id:[0-9]+}", Inject(MustAdmin(APIPromocodePatch), c)).Methods("PATCH")
	api.HandleFunc("/users/{id:[0-9]+}", Inject(MustLogin(APIUserPatch), c)).Methods("PATCH")

	api.HandleFunc("/orders/{id:[0-9]+}", Inject(MustAdmin(APIOrderDelete), c)).Methods("DELETE")
	api.HandleFunc("/products/{id:[0-9]+}", Inject(MustAdmin(APIProductDelete), c)).Methods("DELETE")
	api.HandleFunc("/promocodes/{id:[0-9]+}", Inject(MustAdmin(APIPromocodeDelete), c)).Methods("DELETE")
	api.HandleFunc("/users/{id:[0-9]+}", Inject(MustAdmin(APIUserDelete), c)).Methods("DELETE")
	api.HandleFunc("/users/current", Inject(MustLogin(APICurrentUser), c))

	r.HandleFunc("/admin", Inject(MustAdmin(AdminGet), c)).Methods("GET")

	admin := r.PathPrefix("/admin").Methods("GET").Subrouter()

	admin.HandleFunc("/{category:(?:products|promocodes|orders|users)}", Inject(MustAdmin(AdminRedirect), c))
	admin.HandleFunc("/{category:(?:products|promocodes|orders|users)}/new", Inject(MustAdmin(AdminNew), c))
	admin.HandleFunc("/{category:(?:products|promocodes|orders|users)}/last", Inject(MustAdmin(AdminListingLast), c))
	admin.HandleFunc("/{category:(?:products|promocodes|orders|users)}/{page:[0-9]+}", Inject(MustAdmin(AdminListing), c))

	// TODO :check CSRF
	log.Fatal(http.ListenAndServe(":"+c.Port, r))
}

type notFoundHandler struct {
	Config *shopy.Config
}

func (h *notFoundHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	Inject(func(w http.ResponseWriter, r *http.Request, c *shopy.Config) (int, error) {
		return http.StatusNotFound, nil
	}, h.Config)(w, r)
}

// logout resets the session values and saves the cookie
func logout(w http.ResponseWriter, r *http.Request, c *shopy.Config) (int, error) {
	err := c.Services.Session.Reset(w)
	if err != nil {
		return http.StatusInternalServerError, err
	}

	return Redirect(w, r, "/")
}


text:
"""
    Server API

    Reference for Server API (REST/Json)

    OpenAPI spec version: 2.0.21

    Generated by: https://github.com/swagger-api/swagger-codegen.git
"""

from __future__ import absolute_import

import os
import sys
import unittest

import kinow_client
from kinow_client.rest import ApiException
from kinow_client.models.tax_price import TaxPrice

class TestTaxPrice(unittest.TestCase):
    """ TaxPrice unit test stubs """

    def setUp(self):
        pass

    def tearDown(self):
        pass

    def testTaxPrice(self):
        """
        Test TaxPrice
        """
        model = kinow_client.models.tax_price.TaxPrice()

if __name__ == '__main__':
    unittest.main()


text:
Quickly upload csv files to customer.io.

## Usage

The first row of the csv file must contain headers. A minimal valid csv file would be:

    id,email
    1,chris@untrod.com

The order of columns does not matter. Fields must be separated by commas (or comma-space) and *lines separated with either \n or \r\n*. Any fields beyond email and id are treated as additional properties to be sent to customer.io. If the id is already present in customer.io, the record will be updated. Otherwise it will be created.

Run with leiningrad, with the following arguments:

    $ lein run -f <csv file path> -u <site id> -p <api key>

## License

MIT. See LICENSE file.


text:
The [Hel](http://en.wikipedia.org/wiki/Hel_%28being%29) library allows
bypassing technical complications in common patterns.

The motivation behind the library is to abstract away lot of the boilerplate
by packaging patterns into easy to use functions.

```sh
npm install hel
```

For `package.json` projects install with `npm i -D hel` and uninstall
with `npm rm -D hel`

#### Simplefied Webpack

The following helper functions will help you configure the boilerplate with
minimal effort. Note that the tasks are biased towards `gulp`

```js
var gulp = require('gulp');
// ----------------------------------------------------------------------------

// Javascript
// ==========

var hel = {
	webpack: require('hel/webpack')
};

var entryPath = './src/client/node_modules/Client/frontend';

var webpackConf = {

	entry: {
		home: entryPath + '/home.js',
	},

	output: {
		path: 'public/web',  // where to place files
		publicPath: '/web/', // url prefix when loading
	}

};

gulp.task('js', function (resolve) {
	hel.webpack
		.instance(webpackConf)
		.build(resolve);
});

gulp.task('watch:js', function (resolve) {
	hel.webpack
		.instance(webpackConf)
		.watch(resolve);
});

gulp.task('debug:js', function (resolve) {
	hel.webpack
		.instance(webpackConf)
		.debug(resolve, {
			'/src/client/node_modules/': ''
		});
});
```

`js` and `watch:js` do exactly what you would think. If you execute in a
development environment (ie. `NODE_ENV=development gulp`) optimizations will
happen so you get the fastest re-compilation possible. If no `NODE_ENV` is
provided "production" will be assumed.

`debug:js` requires you to first build in production so as to generate source
maps. Once you have them it will analyse them and tell you what each module
uses, with your modules split from your 3rd party modules.

If you're interested in more analysis you may wish to check out,
http://webpack.github.io/analyse/ and
https://www.npmjs.com/package/stats-webpack-plugin


text:
ssh_chk=`systemsetup -getremotelogin`
ssh_conf="/etc/sshd_config"

if [[ "$ssh_chk" == *On ]] && [[ -f "$ssh_conf" ]]; then

   result="Enabled"
else
   result="Disabled"
fi

echo "<result>$result</result>"


text:
using System.Collections.Generic;
using System.Text;

namespace WebIDLCollector.IDLTypes
{
    public class Argument
    {
        public Argument(string name)
        {
            Name = name;
        }

        private string Name { get; }
        public string Type { get; set; }
        public bool Optional { get; set; }
        public string ExtendedAttribute { get; set; }
        public bool Clamp { get; set; }
        public bool EnforceRange { get; set; }
        public string TreatNullAs { get; set; }
        public bool Ellipsis { get; set; }
        public string Value { get; set; }

        private string Reconstruct()
        {
            var sb = new StringBuilder();
            var comma = string.Empty;

            if (Clamp ||
                EnforceRange ||
                !string.IsNullOrWhiteSpace(TreatNullAs))
            {
                sb.Append("[");

                if (Clamp)
                {
                    sb.Append("Clamp");
                    comma = ", ";
                }
                if (EnforceRange)
                {
                    sb.Append(comma).Append("EnforceRange");
                    comma = ", ";
                }
                if (!string.IsNullOrWhiteSpace(TreatNullAs))
                {
                    sb.Append(comma).Append("TreatNullAs=").Append(TreatNullAs);
                }

                sb.Append("] ");
            }

            if (Optional)
            {
                sb.Append("optional ");
            }
            sb.Append(Type);
            if (Ellipsis)
            {
                sb.Append("...");
            }
            sb.Append(" ");
            sb.Append(Name);
            if (!string.IsNullOrWhiteSpace(Value))
            {
                sb.Append(" = ");
                sb.Append(Value);
            }

            return sb.ToString().Trim();
        }

        public static string ReconstructArgs(IEnumerable<Argument> argTypes)
        {
            var sb = new StringBuilder();

            var comma = string.Empty;
            foreach (var argument in argTypes)
            {
                sb.Append(comma).Append(argument.Reconstruct());
                comma = ", ";
            }

            return sb.ToString();
        }
    }

    public class ArgumentTypeCompare : IEqualityComparer<Argument>
    {
        public bool Equals(Argument x, Argument y)
        {
            return x.Type.Equals(y.Type) &&
                    x.Optional.Equals(y.Optional) &&
                    x.Clamp.Equals(y.Clamp) &&
                    x.EnforceRange.Equals(y.EnforceRange) &&
                    (x.TreatNullAs == null || x.TreatNullAs.Equals(y.TreatNullAs)) &&
                    x.Ellipsis.Equals(y.Ellipsis) &&
                    (x.Value == null || x.Value.Equals(y.Value));
        }

        public int GetHashCode(Argument obj)
        {
            return ((((((((((((obj.Type.GetHashCode() << 5)
                                ^ obj.Optional.GetHashCode()) << 5)
                              ^ obj.Clamp.GetHashCode()) << 5)
                            ^ obj.EnforceRange.GetHashCode()) << 5)
                          ^ obj.TreatNullAs.GetHashCode()) << 5)
                        ^ obj.Ellipsis.GetHashCode()) << 5)
                      ^ obj.Value.GetHashCode()) << 5;
        }
    }
}


text:
package org.hswebframework.web.oauth2.server.impl;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.hswebframework.web.authorization.Authentication;
import org.hswebframework.web.oauth2.server.AccessToken;

import java.io.Serializable;

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class RedisAccessToken implements Serializable {

    private String clientId;

    private String accessToken;

    private String refreshToken;

    private long createTime;

    private Authentication authentication;

    private boolean singleton;

    public AccessToken toAccessToken(int expiresIn){
        AccessToken token=new AccessToken();
        token.setAccessToken(accessToken);
        token.setRefreshToken(refreshToken);
        token.setExpiresIn(expiresIn);
        return token;
    }
}


text:
#import "NSObject.h"

@interface FTRegUtilities : NSObject
{
}

+ (void)authorizationController:(id)arg1 authorizedAccount:(_Bool)arg2;
+ (void)changePasswordControllerDidFinish:(id)arg1 withAppleID:(id)arg2 authID:(id)arg3 authToken:(id)arg4;
+ (void)changePasswordControllerDidCancel:(id)arg1;
+ (id)standaloneNewPasswordControllerWithRegController:(id)arg1 appleID:(id)arg2;
+ (id)standaloneAuthorizationControllerWithRegController:(id)arg1 authID:(id)arg2 token:(id)arg3;
+ (id)serviceWithType:(long long)arg1;

@end


text:
<?php
/**
 * Template part for displaying posts.
 *
 * @link https://codex.wordpress.org/Template_Hierarchy
 *
 * @package Bemmy
 */

require_once dirname( dirname( __FILE__ ) ) . '/components/Article/Article.php';

?>

<?php Article(); ?>


text:
package equus.webstack.command;

import java.util.HashSet;
import java.util.Set;

import lombok.val;
import lombok.extern.slf4j.Slf4j;

import org.slf4j.Logger;

import com.google.inject.Injector;

import equus.webstack.model.Course;
import equus.webstack.model.Customer;
import equus.webstack.model.Student;
import equus.webstack.service.CourseService;
import equus.webstack.service.CustomerService;
import equus.webstack.service.StudentService;

@Slf4j
public class DBInitializeWithTestDataCommand implements Command {

  @Override
  public Logger getLogger() {
    return log;
  }

  public static void main(String[] args) {
    new DBInitializeWithTestDataCommand().executeCommand(args);
  }

  @Override
  public void execute(String... args) {
    new DBInitializeCommand().execute(injector -> {
      initCustomer(injector);
      initStudent(injector);
      // setup test data
      });
  }

  private void initCustomer(Injector injector) {
    val service = injector.getInstance(CustomerService.class);
    val customer = new Customer();
    customer.setId(0);
    customer.setName("Hiro");
    service.save(customer);

  }

  private void initStudent(Injector injector) {
    Set<Course> courseList = initCourse(injector);
    Set<Student> list = new HashSet<>();
    {
      val entity = new Student();
      entity.setName("student_A");
      entity.setCourseList(courseList);
      list.add(entity);
    }
    {
      val entity = new Student();
      entity.setName("student_B");
      entity.setCourseList(courseList);
      list.add(entity);
    }
    val service = injector.getInstance(StudentService.class);
    for (val entity : list) {
      service.save(entity);
    }
    val list2 = service.findAll();
    for (val entity : list2) {
      for (val c : entity.getCourseList()) {
        System.out.println();
      }
    }
  }

  private Set<Course> initCourse(Injector injector) {
    Set<Course> list = new HashSet<>();
    {
      val entity = new Course();
      entity.setName("course_A");
      list.add(entity);
    }
    {
      val entity = new Course();
      entity.setName("course_B");
      list.add(entity);
    }
    val service = injector.getInstance(CourseService.class);
    for (val entity : list) {
      service.save(entity);
    }
    return list;
  }
}


text:
import { combineReducers } from 'redux';

export function error(state = null, action) {
  switch (action.type) {
    case 'INGREDIENT_LIST_ERROR':
      return action.error;

    case 'INGREDIENT_LIST_MERCURE_DELETED':
      return `${action.retrieved['@id']} has been deleted by another user.`;

    case 'INGREDIENT_LIST_RESET':
      return null;

    default:
      return state;
  }
}

export function loading(state = false, action) {
  switch (action.type) {
    case 'INGREDIENT_LIST_LOADING':
      return action.loading;

    case 'INGREDIENT_LIST_RESET':
      return false;

    default:
      return state;
  }
}

export function retrieved(state = null, action) {
  switch (action.type) {
    case 'INGREDIENT_LIST_SUCCESS':
      return action.retrieved;

    case 'INGREDIENT_LIST_RESET':
      return null;

    case 'INGREDIENT_LIST_MERCURE_MESSAGE':
      return {
        ...state,
        'hydra:member': state['hydra:member'].map(item =>
          item['@id'] === action.retrieved['@id'] ? action.retrieved : item
        )
      };

    case 'INGREDIENT_LIST_MERCURE_DELETED':
      return {
        ...state,
        'hydra:member': state['hydra:member'].filter(
          item => item['@id'] !== action.retrieved['@id']
        )
      };

    default:
      return state;
  }
}

export function eventSource(state = null, action) {
  switch (action.type) {
    case 'INGREDIENT_LIST_MERCURE_OPEN':
      return action.eventSource;

    case 'INGREDIENT_LIST_RESET':
      return null;

    default:
      return state;
  }
}

export default combineReducers({ error, loading, retrieved, eventSource });


text:
using System;
using System.Linq;
using System.Reflection;

namespace Refit
{
    struct CloseGenericMethodKey : IEquatable<CloseGenericMethodKey>
    {
        internal CloseGenericMethodKey(MethodInfo openMethodInfo, Type[] types)
        {
            OpenMethodInfo = openMethodInfo;
            Types = types;
        }

        public MethodInfo OpenMethodInfo { get; }
        public Type[] Types { get; }

        public bool Equals(CloseGenericMethodKey other) => OpenMethodInfo == other.OpenMethodInfo && Types.SequenceEqual(other.Types);

        public override bool Equals(object obj)
        {
            if (obj is CloseGenericMethodKey closeGenericMethodKey)
            {
                return Equals(closeGenericMethodKey);
            }
            return false;
        }

        public override int GetHashCode()
        {
            unchecked
            {
                int hash = 17;
                hash = hash * 23 + OpenMethodInfo.GetHashCode();
                foreach (Type type in Types)
                {
                    hash = hash * 23 + type.GetHashCode();
                }
                return hash;
            }
        }
    }
}


text:
import { PersonalizesPage } from './app.po';

describe('personalizes App', function() {
  let page: PersonalizesPage;

  beforeEach(() => {
    page = new PersonalizesPage();
  });

  it('should display message saying app works', () => {
    page.navigateTo();
    expect(page.getParagraphText()).toEqual('app works!');
  });
});


text:
A project which will, eventually, provide lots of useful
[expvar.Vars](http://localhost:6060/pkg/expvar/) types.

[Docs](http://go.pkgdoc.org/github.com/brianm/variant)

To use:

    go get github.com/brianm/variant


text:
[![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat-square)](https://github.com/karma-runner/karma-browserstack-launcher)
 [![npm version](https://img.shields.io/npm/v/karma-browserstack-launcher.svg?style=flat-square)](https://www.npmjs.com/package/karma-browserstack-launcher) [![npm downloads](https://img.shields.io/npm/dm/karma-browserstack-launcher.svg?style=flat-square)](https://www.npmjs.com/package/karma-browserstack-launcher)

[![Build Status](https://img.shields.io/travis/karma-runner/karma-browserstack-launcher/master.svg?style=flat-square)](https://travis-ci.org/karma-runner/karma-browserstack-launcher) [![Dependency Status](https://img.shields.io/david/karma-runner/karma-browserstack-launcher.svg?style=flat-square)](https://david-dm.org/karma-runner/karma-browserstack-launcher) [![devDependency Status](https://img.shields.io/david/dev/karma-runner/karma-browserstack-launcher.svg?style=flat-square)](https://david-dm.org/karma-runner/karma-browserstack-launcher#info=devDependencies)

> Use any browser on [BrowserStack](https://www.browserstack.com/)!

## Installation

The easiest way is to keep `karma-browserstack-launcher` as a devDependency in your `package.json`. Just run,

```bash
$ npm install karma-browserstack-launcher --save-dev
```

and it will be added automatically.

## Configuration

```js
// karma.conf.js
module.exports = function(config) {
  config.set({
    // global config of your BrowserStack account
    browserStack: {
      username: 'jamesbond',
      accessKey: '007'
    },

    // define browsers
    customLaunchers: {
      bs_firefox_mac: {
        base: 'BrowserStack',
        browser: 'firefox',
        browser_version: '21.0',
        os: 'OS X',
        os_version: 'Mountain Lion'
      },
      bs_iphone5: {
        base: 'BrowserStack',
        device: 'iPhone 5',
        os: 'ios',
        os_version: '6.0'
      }
    },

    browsers: ['bs_firefox_mac', 'bs_iphone5']
  })
}
```

### Global options

- `username` your BS username, you can also use `BROWSERSTACK_USERNAME` env variable.
- `accessKey` your BS access key, you can also use `BROWSERSTACK_ACCESS_KEY` env variable.
- `startTunnel` do you wanna establish the BrowserStack tunnel ? (defaults to `true`)
- `tunnelIdentifier`/`localIdentifier` in case you want to start the BrowserStack tunnel outside `karma` by setting `startTunnel` to `false`, set the identifier passed to the `-localIdentifier` option here (optional)
- `retryLimit` how many times do you want to retry to capture the browser ? (defaults to `3`)
- `captureTimeout` the browser capture timeout (defaults to `120`)
- `timeout` the BS worker timeout (defaults to `300`
- `build` the BS worker build name (optional)
- `name` the BS worker name (optional)
- `project` the BS worker project name (optional)
- `proxyHost` the host of your proxy for communicating with BrowserStack REST API and BrowserStackLocal (optional)
- `proxyPort` the port of your proxy (optional)
- `proxyUser` the username used for authentication with your proxy (optional)
- `proxyPass` the password used for authentication with your proxy (optional)
- `proxyProtocol` the protocol of your proxy (optional. default: `http`. valid: `http` or `https`)
- `forcelocal` force traffic through the local BrowserStack tunnel, passes flag through to BrowserStackTunnel
- `video` enable video recording of session on BrowserStack (defaults to `true`)

### Per browser options

- `device` name of the device
- `real_mobile` or `realMobile` allows the session to run on a real mobile device instead of an emulator / simulator (optional, defaults to `false`)
- `browser` name of the browser
- `browser_version` version of the browser
- `os` which platform ?
- `os_version` version of the platform
- `build` the BS worker build name (optional, defaults to global)
- `name` the BS worker name (optional, defaults to global)
- `project` the BS worker project name (optional, defaults to global)

> **Note:** you can also pass through any additional options supported by browserstack. (EG. `url`, `resolution`, etc.)
See https://www.browserstack.com/automate/capabilities for a full list of supported options.

### BrowserStack reporter

To report session results back to BrowserStack for display on your BrowserStack dashboard, use the following additional configuration:

```js
// karma.conf.js
module.exports = function(config) {
  config.set({
    // The rest of your karma config is here
    // ...
    reporters: ['dots', 'BrowserStack']
  })
}
```

### Browserstack iOS simulators

By default, your Selenium and JS tests will run on real iOS devices on BrowserStack. Since we are in the implementation phase, we are still working on a few things, such as adding more devices, ability to test on local URLs, etc.

In case your tests are facing any issues on real iOS devices, we also provide iOS simulators where you can run your automated tests smoothly.

To access our iOS simulators, use the following capabilities:

```js
customLaunchers: {
  iPad_3: {
    real_mobile: false,
    device: 'iPad 3rd (6.0)',
    os: 'ios',
    'os_version': '6.0',
    'browser_version': null,
    browser: 'Mobile Safari'
  }
}
```

List of iOS simulators you can test on:

- `device: 'iPad 3rd', 'os_version': '5.1'`
- `device: 'iPad 3rd (6.0)', 'os_version': '6.0'`
- `device: 'iPad Mini', 'os_version': '7.0'`
- `device: 'iPad 4th', 'os_version': '7.0'`
- `device: 'iPhone 4S', 'os_version': '5.1'`
- `device: 'iPhone 4S (6.0)', 'os_version': '6.0'`
- `device: 'iPhone 5', 'os_version': '6.0'`
- `device: 'iPhone 5S', 'os_version': '7.0'`

### CI/CD Build Environment Variables

Many CI/CD systems will make the name or ID of the currently running build available via an environment variable. The follow environment variables below are supported by default:

* `process.env.BUILD_NUMBER`
* `process.env.BUILD_TAG`
* `process.env.CI_BUILD_NUMBER`
* `process.env.CI_BUILD_TAG`
* `process.env.TRAVIS_BUILD_NUMBER`
* `process.env.CIRCLE_BUILD_NUM`
* `process.env.DRONE_BUILD_NUMBER`

---

[BrowserStack's REST API documentation](https://www.browserstack.com/automate/rest-api#rest-api-browsers)
explains how to retrieve a list of desired capabilities for browsers.

----

For more information on Karma see the [homepage](http://karma-runner.github.io).

----

Check out sample code working with karma-browserstack-launcher [here](https://github.com/browserstack/karma-browserstack-example).


text:
package ua.stqa.pft.addressbook.tests;

import org.testng.Assert;
import org.testng.annotations.Test;
import ua.stqa.pft.addressbook.model.GroupData;

import java.util.ArrayList;
import java.util.List;

public class GroupCreationTests extends TestBase{

  @Test
  public void testGroupCreation() {
    app.getNavigationHelper().goToGroupPage();
    List<GroupData> before = app.getGroupHelper().getGroupList();
    app.getGroupHelper().createGroup(new GroupData("test1", null, null));
    List<GroupData> after = app.getGroupHelper().getGroupList();
    Assert.assertEquals(after.size(), before.size() + 1);
  }

}


text:
package client

import "github.com/NebulousLabs/Sia/node/api"

// DaemonVersionGet requests the /daemon/version resource
func (c *Client) DaemonVersionGet() (dvg api.DaemonVersionGet, err error) {
	err = c.get("/daemon/version", &dvg)
	return
}

// DaemonStopGet stops the daemon using the /daemon/stop endpoint.
func (c *Client) DaemonStopGet() (err error) {
	err = c.get("/daemon/stop", nil)
	return
}

// DaemonUpdateGet checks for an available daemon update.
func (c *Client) DaemonUpdateGet() (dig api.DaemonUpdateGet, err error) {
	err = c.get("/daemon/update", nil)
	return
}

// DaemonUpdatePost updates the daemon.
func (c *Client) DaemonUpdatePost() (err error) {
	err = c.post("/daemon/update", "", nil)
	return
}


text:
package multibuf

import (
	"bytes"
	"crypto/md5"
	"encoding/hex"
	"io"
	"io/ioutil"
	"os"
	"testing"

	"github.com/stretchr/testify/assert"
)

func createReaderOfSize(size int64) (reader io.Reader, hash string) {
	f, err := os.Open("/dev/urandom")
	if err != nil {
		panic(err)
	}

	b := make([]byte, int(size))

	_, err = io.ReadFull(f, b)

	if err != nil {
		panic(err)
	}

	h := md5.New()
	h.Write(b)
	return bytes.NewReader(b), hex.EncodeToString(h.Sum(nil))
}

func hashOfReader(r io.Reader) string {
	h := md5.New()
	tr := io.TeeReader(r, h)
	_, _ = io.Copy(ioutil.Discard, tr)
	return hex.EncodeToString(h.Sum(nil))
}

func TestSmallBuffer(t *testing.T) {
	r, hash := createReaderOfSize(1)
	bb, err := New(r)
	assert.NoError(t, err)
	assert.Equal(t, hash, hashOfReader(bb))
	bb.Close()
}

func TestBigBuffer(t *testing.T) {
	r, hash := createReaderOfSize(13631488)
	bb, err := New(r)
	assert.NoError(t, err)
	assert.Equal(t, hash, hashOfReader(bb))
}

func TestSeek(t *testing.T) {
	tlen := int64(1057576)
	r, hash := createReaderOfSize(tlen)
	bb, err := New(r)

	assert.NoError(t, err)
	assert.Equal(t, hash, hashOfReader(bb))
	l, err := bb.Size()
	assert.NoError(t, err)
	assert.Equal(t, tlen, l)

	bb.Seek(0, 0)
	assert.Equal(t, hash, hashOfReader(bb))
	l, err = bb.Size()
	assert.NoError(t, err)
	assert.Equal(t, tlen, l)
}

func TestSeekWithFile(t *testing.T) {
	tlen := int64(DefaultMemBytes)
	r, hash := createReaderOfSize(tlen)
	bb, err := New(r, MemBytes(1))

	assert.NoError(t, err)
	assert.Equal(t, hash, hashOfReader(bb))
	l, err := bb.Size()
	assert.NoError(t, err)
	assert.Equal(t, tlen, l)

	bb.Seek(0, 0)
	assert.Equal(t, hash, hashOfReader(bb))
	l, err = bb.Size()
	assert.NoError(t, err)
	assert.Equal(t, tlen, l)
}

func TestSeekFirst(t *testing.T) {
	tlen := int64(1057576)
	r, hash := createReaderOfSize(tlen)
	bb, err := New(r)
	assert.NoError(t, err)

	l, err := bb.Size()
	assert.NoError(t, err)
	assert.Equal(t, tlen, l)

	assert.NoError(t, err)
	assert.Equal(t, hash, hashOfReader(bb))

	bb.Seek(0, 0)

	assert.Equal(t, hash, hashOfReader(bb))
	l, err = bb.Size()
	assert.NoError(t, err)
	assert.Equal(t, tlen, l)
}

func TestLimitDoesNotExceed(t *testing.T) {
	requestSize := int64(1057576)
	r, hash := createReaderOfSize(requestSize)
	bb, err := New(r, MemBytes(1024), MaxBytes(requestSize+1))
	assert.NoError(t, err)
	assert.Equal(t, hash, hashOfReader(bb))
	size, err := bb.Size()
	assert.NoError(t, err)
	assert.Equal(t, requestSize, size)
	bb.Close()
}

func TestLimitExceeds(t *testing.T) {
	requestSize := int64(1057576)
	r, _ := createReaderOfSize(requestSize)
	bb, err := New(r, MemBytes(1024), MaxBytes(requestSize-1))
	assert.IsType(t, &MaxSizeReachedError{}, err)
	assert.Nil(t, bb)
}

func TestLimitExceedsMemBytes(t *testing.T) {
	requestSize := int64(1057576)
	r, _ := createReaderOfSize(requestSize)
	bb, err := New(r, MemBytes(requestSize+1), MaxBytes(requestSize-1))
	assert.IsType(t, &MaxSizeReachedError{}, err)
	assert.Nil(t, bb)
}

func TestWriteToBigBuffer(t *testing.T) {
	l := int64(13631488)
	r, hash := createReaderOfSize(l)
	bb, err := New(r)
	assert.NoError(t, err)

	other := &bytes.Buffer{}
	wrote, err := bb.WriteTo(other)
	assert.NoError(t, err)
	assert.Equal(t, l, wrote)
	assert.Equal(t, hash, hashOfReader(other))
}

func TestWriteToSmallBuffer(t *testing.T) {
	l := int64(1)
	r, hash := createReaderOfSize(l)
	bb, err := New(r)
	assert.NoError(t, err)

	other := &bytes.Buffer{}
	wrote, err := bb.WriteTo(other)
	assert.NoError(t, err)
	assert.Equal(t, l, wrote)
	assert.Equal(t, hash, hashOfReader(other))
}

func TestWriterOnceMemBytesDefault(t *testing.T) {
	w, err := NewWriterOnce(MemBytes(0))
	assert.NoError(t, err)

	wo, ok := w.(*writerOnce)
	assert.True(t, ok)

	assert.Equal(t, DefaultMemBytes, int(wo.o.memBytes))
}

func TestWriterOnceSmallBuffer(t *testing.T) {
	r, hash := createReaderOfSize(1)

	w, err := NewWriterOnce()
	assert.NoError(t, err)

	total, err := io.Copy(w, r)
	assert.Equal(t, nil, err)
	assert.Equal(t, int64(1), total)

	bb, err := w.Reader()
	assert.NoError(t, err)

	assert.Equal(t, hash, hashOfReader(bb))
	bb.Close()
}

func TestWriterOnceBigBuffer(t *testing.T) {
	size := int64(13631488)
	r, hash := createReaderOfSize(size)

	w, err := NewWriterOnce()
	assert.NoError(t, err)

	total, err := io.Copy(w, r)
	assert.Equal(t, nil, err)
	assert.Equal(t, size, total)

	bb, err := w.Reader()
	assert.NoError(t, err)

	assert.Equal(t, hash, hashOfReader(bb))
	bb.Close()
}

func TestWriterOncePartialWrites(t *testing.T) {
	size := int64(13631488)
	r, hash := createReaderOfSize(size)

	w, err := NewWriterOnce()
	assert.NoError(t, err)

	total, err := io.CopyN(w, r, DefaultMemBytes+1)
	assert.Equal(t, nil, err)
	assert.Equal(t, int64(DefaultMemBytes+1), total)

	remained := size - DefaultMemBytes - 1
	total, err = io.CopyN(w, r, remained)
	assert.Equal(t, nil, err)
	assert.Equal(t, remained, total)

	bb, err := w.Reader()
	assert.NoError(t, err)
	assert.Nil(t, w.(*writerOnce).mem)
	assert.Nil(t, w.(*writerOnce).file)

	assert.Equal(t, hash, hashOfReader(bb))
	bb.Close()
}

func TestWriterOnceMaxSizeExceeded(t *testing.T) {
	size := int64(1000)
	r, _ := createReaderOfSize(size)

	w, err := NewWriterOnce(MemBytes(10), MaxBytes(100))
	assert.NoError(t, err)

	_, err = io.Copy(w, r)
	assert.Error(t, err)
	assert.NoError(t, w.Close())
}

func TestWriterReaderCalled(t *testing.T) {
	size := int64(1000)
	r, hash := createReaderOfSize(size)

	w, err := NewWriterOnce()
	assert.NoError(t, err)

	_, err = io.Copy(w, r)
	assert.NoError(t, err)
	assert.NoError(t, w.Close())

	bb, err := w.Reader()
	assert.NoError(t, err)

	assert.Equal(t, hash, hashOfReader(bb))

	// Subsequent calls to write and get reader will fail
	_, err = w.Reader()
	assert.Error(t, err)

	_, err = w.Write([]byte{1})
	assert.Error(t, err)
}

func TestWriterNoData(t *testing.T) {
	w, err := NewWriterOnce()
	assert.NoError(t, err)

	_, err = w.Reader()
	assert.Error(t, err)
}


text:
<!DOCTYPE html>

<meta charset="iso-8859-1">

<link href="css" rel="stylesheet">

Resizable

Resizable


text:
package versionserver

import (
	"encoding/json"
	"fmt"
	"net/http"
	"strconv"

	"code.cloudfoundry.org/lager"

	"github.com/concourse/concourse/atc"
	"github.com/concourse/concourse/atc/db"
)

func (s *Server) GetDownstreamResourceCausality(pipeline db.Pipeline) http.Handler {
	return s.getResourceCausality(db.CausalityDownstream, pipeline)
}

func (s *Server) GetUpstreamResourceCausality(pipeline db.Pipeline) http.Handler {
	return s.getResourceCausality(db.CausalityUpstream, pipeline)
}

func (s *Server) getResourceCausality(direction db.CausalityDirection, pipeline db.Pipeline) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		logger := s.logger.Session(fmt.Sprintf("%v-causality", direction))

		if !atc.EnableResourceCausality {
			logger.Info("causality-disabled")
			w.WriteHeader(http.StatusForbidden)
			return
		}

		versionIDString := r.FormValue(":resource_config_version_id")
		resourceName := r.FormValue(":resource_name")
		versionID, _ := strconv.Atoi(versionIDString)

		resource, found, err := pipeline.Resource(resourceName)
		if err != nil {
			logger.Error("failed-to-get-resource", err, lager.Data{"resource-name": resourceName})
			w.WriteHeader(http.StatusInternalServerError)
			return
		}

		if !found {
			logger.Info("resource-not-found", lager.Data{"resource-name": resourceName})
			w.WriteHeader(http.StatusNotFound)
			return
		}

		causality, found, err := resource.Causality(versionID, direction)
		if err != nil {
			if err == db.ErrTooManyBuilds || err == db.ErrTooManyResourceVersions {
				logger.Error("too-many-nodes", err, lager.Data{"resource-name": resourceName, "resource-config-version": versionID})
				w.WriteHeader(http.StatusUnprocessableEntity)
				return
			} else {
				logger.Error("failed-to-fetch", err, lager.Data{"resource-name": resourceName, "resource-config-version": versionID})
				w.WriteHeader(http.StatusInternalServerError)
				return
			}
		}

		if !found {
			logger.Info("resource-version-not-found", lager.Data{"resource-name": resourceName, "resource-config-version": versionID})
			w.WriteHeader(http.StatusNotFound)
			return
		}

		w.Header().Set("Content-Type", "application/json")
		err = json.NewEncoder(w).Encode(causality)
		if err != nil {
			logger.Error("failed-to-encode", err, lager.Data{"resource-name": resourceName, "resource-config-version": versionID})
			w.WriteHeader(http.StatusInternalServerError)
			return
		}
		w.WriteHeader(http.StatusOK)
	})
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping"
                  xmlns:gedmo="http://gediminasm.org/schemas/orm/doctrine-extensions-mapping"
                  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                  xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping
                  http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd">

    <entity name="Kitpages\FileBundle\Entity\File" repository-class="Kitpages\FileBundle\Entity\FileRepository" table="kit_file">
        <one-to-many
            field="children"
            target-entity="Kitpages\FileBundle\Entity\File"
            mapped-by="parent"
        >
            <cascade>
                <cascade-persist />
            </cascade>
        </one-to-many>

        <many-to-one field="parent" target-entity="Kitpages\FileBundle\Entity\File" inversed-by="children" nullable="true" >
            <join-columns>
                <join-column name="parent_id" referenced-column-name="id" nullable="true" on-delete="SET NULL" on-update="CASCADE" />
            </join-columns>
        </many-to-one>
    </entity>

</doctrine-mapping>


text:
@class NSString;

@interface DVTOpenQuicklyPattern : NSObject
{
    NSString *_pattern;
    BOOL _patternHasSeparators;
    char *_charactersInPattern;
    unsigned short *_patternCharacters;
    unsigned short *_lowerCasePatternCharacters;
    unsigned long long _patternLength;
}

+ (id)patternWithInput:(id)arg1;
@property(readonly) NSString *pattern; // @synthesize pattern=_pattern;
- (double)scoreCandidate:(id)arg1 matchedRanges:(id *)arg2;
- (double)scoreCandidate:(id)arg1;
- (BOOL)matchesCandidate:(id)arg1;
- (BOOL)matchesEverythingMatchedBy:(id)arg1;
- (BOOL)rejectsEverything;
- (id)description;
- (BOOL)isEqual:(id)arg1;
- (BOOL)isEqualToPattern:(id)arg1;
- (void)dealloc;
- (id)initWithPattern:(id)arg1;
- (id)matchedRanges:(id)arg1;

@end


text:
<!DOCTYPE html>

		<title>JsUnit testing page</title>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

XPath.js JsUnit unit page


text:
module Hanami
  module Action
    module Rack
      module Callable
        # Callable module for actions. With this module, actions with middlewares
        # will be able to work with rack builder.
        #
        # @param env [Hash] the full Rack env or the params. This value may vary,
        #   see the examples below.
        #
        # @since 0.4.0
        #
        # @see Hanami::Action::Rack::ClassMethods#rack_builder
        # @see Hanami::Action::Rack::ClassMethods#use
        #
        # @example
        #   require 'hanami/controller'
        #
        #    class MyMiddleware
        #      def initialize(app)
        #        @app = app
        #      end
        #
        #      def call(env)
        #        #...
        #      end
        #    end
        #
        #    class Show
        #      include Hanami::Action
        #      use MyMiddleware
        #
        #      def call(params)
        #        # ...
        #        puts params # => { id: 23 } extracted from Rack env
        #      end
        #    end
        #
        #    Show.respond_to?(:call) # => true
        def call(env)
          rack_builder.call(env)
        end
      end
    end
  end
end


text:
package org.openstack.atlas.api.validation.validator;

import org.openstack.atlas.api.validation.Validator;
import org.openstack.atlas.api.validation.result.ValidatorResult;
import org.openstack.atlas.api.validation.validator.builder.VirtualIpValidatorBuilder;
import org.openstack.atlas.core.api.v1.VirtualIp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import static org.openstack.atlas.api.validation.ValidatorBuilder.build;

@Component
@Scope("request")
public class VirtualIpValidator implements ResourceValidator<VirtualIp> {
    protected Validator<VirtualIp> validator;
    protected VirtualIpValidatorBuilder ruleBuilder;

    @Autowired
    public VirtualIpValidator(VirtualIpValidatorBuilder ruleBuilder) {
        this.ruleBuilder = ruleBuilder;
        validator = build(ruleBuilder);
    }

    @Override
    public ValidatorResult validate(VirtualIp virtualIp, Object context) {
        ValidatorResult result = validator.validate(virtualIp, context);
        return ValidatorUtilities.removeEmptyMessages(result);
    }

    @Override
    public Validator<VirtualIp> getValidator() {
        return validator;
    }
}


text:
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true" ng-hide="CreationFolder">×</button>

${Create folder}

        <form class="form-horizontal">

            ${Folder name}:

              <input type="text" class="form-control" ng-model="NewFolderName" autocomplete="off" ng-disabled="CreationFolder" />

                <input type="checkbox" ng-model="NewFolderCreateParents" /> ${create all parents}

            ${Owner}:

              <input type="text" class="form-control" ng-model="NewFolderOwnerName" autocomplete="off" placeholder="${Owner name or empty for root}" ng-disabled="CreationFolder" />

            ${Group}:

              <input type="text" class="form-control" ng-model="NewFolderGroupName" autocomplete="off" placeholder="${Group name or empty for owner group}" ng-disabled="CreationFolder" />

        </form>

        <button class="btn btn-primary" ng-click="CreateFolder()" ng-disabled="NewFolderName == '' || CreationFolder">${Create}</button>
        <button class="btn btn-default" data-dismiss="modal" aria-hidden="true" ng-disabled="CreationFolder">${Cancel}</button>


text:
Metabolism : The Enzyme class
=============================

.. autoclass:: PyFBA.metabolism.Enzyme
    :members:


text:
<?xml version="1.0" encoding="UTF-8"?>
<mstns:OpenSearchDescription xmlns:oseo="http://www.opengis.net/oseo/1.0" xmlns:roseo="http://www.opengis.net/roseo/1.0" xmlns:swe="http://www.opengis.net/swe/2.0" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:mstns="http://a9.com/-/spec/opensearch/1.1/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	<mstns:ShortName>Order Options</mstns:ShortName>
	<mstns:Description>OSDD for Order Options</mstns:Description>
	<mstns:Url type="application/atom+xml" template="http://some.roseo.server/ROSEO/1.0.0/product/ESA:EECF:ENVISAT_ASA_IMx_xS:EN1-05121921114570-3322.XI?prclv={roseo:ProcessingLevel}&prdt={roseo:ProductType}&qos={roseo:QualityOfService}"/>
	<mstns:SyndicationRight>open</mstns:SyndicationRight>
	<mstns:AdultContent>false</mstns:AdultContent>
	<mstns:Language>*</mstns:Language>
	<mstns:InputEncoding>UTF-8</mstns:InputEncoding>
	<mstns:OutputEncoding>UTF-8</mstns:OutputEncoding>
	<roseo:OrderOptions xsi:schemaLocation="http://www.opengis.net/roseo/1.0 ../roseo.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
		<roseo:OrderOptionGroup>
			<oseo:productOrderOptionsId>Level 1,Product PRI (ASA_IMP)</oseo:productOrderOptionsId>
			<oseo:identifier>ESA:EECF:ENVISAT_ASA_IMx_xS:EN1-05121921114570-3322.XI</oseo:identifier>
			<oseo:description>Order Options for producing ASAR IMP 1P product</oseo:description>
			<oseo:orderType>PRODUCT_ORDER</oseo:orderType>
			<oseo:option>
				<swe:DataRecord>
					<swe:field name="processingLevel">
						<swe:Category updatable="false" optional="true" definition="http://www.opengis.net/def/parameter/ESA/1.0/processingLevel">
							<swe:identifier>processing Level</swe:identifier>
							<swe:constraint>
								<swe:AllowedTokens>
									<swe:value>1B</swe:value>
								</swe:AllowedTokens>
							</swe:constraint>
						</swe:Category>
					</swe:field>
				</swe:DataRecord>
				<oseo:grouping>Processing Option</oseo:grouping>
			</oseo:option>
			<oseo:option>
				<swe:DataRecord>
					<swe:field name="productType">
						<swe:Category updatable="false" optional="true" definition="http://www.opengis.net/def/parameter/ESA/1.0/productType">
							<swe:identifier>Product Type</swe:identifier>
							<swe:constraint>
								<swe:AllowedTokens>
									<swe:value>ASA_IMP_1P</swe:value>
								</swe:AllowedTokens>
							</swe:constraint>
						</swe:Category>
					</swe:field>
				</swe:DataRecord>
				<oseo:grouping>Processing Option</oseo:grouping>
			</oseo:option>
			<oseo:option>
				<swe:DataRecord>
					<swe:field name="qualityOfService">
						<swe:Category updatable="false" optional="true" definition="http://www.opengis.net/def/parameter/ESA/1.0/qualityOfService">
							<swe:identifier>qualityOfService</swe:identifier>
							<swe:constraint>
								<swe:AllowedTokens>
									<swe:value>STANDARD</swe:value>
									<swe:value>NRT</swe:value>
									<swe:value>RUSH</swe:value>
								</swe:AllowedTokens>
							</swe:constraint>
						</swe:Category>
					</swe:field>
				</swe:DataRecord>
				<oseo:grouping>Processing Option</oseo:grouping>
			</oseo:option>
			<oseo:productDeliveryOptions>
				<oseo:onlineDataAccess>
					<oseo:protocol>https</oseo:protocol>
				</oseo:onlineDataAccess>
			</oseo:productDeliveryOptions>
			<roseo:downloadURL>http://some.roseo.server/ROSEO/1.0.0/product/ESA:EECF:ENVISAT_ASA_IMx_xS:EN1-05121921114570-3322.XI?prclv={roseo:ProcessingLevel}&prdt={roseo:ProductType}&qos={roseo:QualityOfService}</roseo:downloadURL>
		</roseo:OrderOptionGroup>
		<roseo:OrderOptionGroup>
			<oseo:productOrderOptionsId>Level 1,Product GEC (ASA_IMG)</oseo:productOrderOptionsId>
			<oseo:identifier>ESA:EECF:ENVISAT_ASA_IMx_xS:EN1-05121921114570-3322.XI</oseo:identifier>
			<oseo:description>Order Options for producing ASAR IMG 1P product</oseo:description>
			<oseo:orderType>PRODUCT_ORDER</oseo:orderType>
			<oseo:option>
				<swe:DataRecord>
					<swe:field name="processingLevel">
						<swe:Category updatable="false" optional="true" definition="http://www.opengis.net/def/parameter/ESA/1.0/processingLevel">
							<swe:identifier>processingLevel</swe:identifier>
							<swe:constraint>
								<swe:AllowedTokens>
									<swe:value>1B</swe:value>
								</swe:AllowedTokens>
							</swe:constraint>
						</swe:Category>
					</swe:field>
				</swe:DataRecord>
				<oseo:grouping>Processing Option</oseo:grouping>
			</oseo:option>
			<oseo:option>
				<swe:DataRecord>
					<swe:field name="productType">
						<swe:Category updatable="false" optional="true" definition="http://www.opengis.net/def/parameter/ESA/1.0/productType">
							<swe:identifier>productType</swe:identifier>
							<swe:constraint>
								<swe:AllowedTokens>
									<swe:value>ASA_IMG_1P</swe:value>
								</swe:AllowedTokens>
							</swe:constraint>
						</swe:Category>
					</swe:field>
				</swe:DataRecord>
				<oseo:grouping>Processing Option</oseo:grouping>
			</oseo:option>
			<oseo:option>
				<swe:DataRecord>
					<swe:field name="qualityOfService">
						<swe:Category updatable="false" optional="true" definition="http://www.opengis.net/def/parameter/ESA/1.0/qualityOfService">
							<swe:identifier>qualityOfService</swe:identifier>
							<swe:constraint>
								<swe:AllowedTokens>
									<swe:value>STANDARD</swe:value>
									<swe:value>NRT</swe:value>
									<swe:value>RUSH</swe:value>
								</swe:AllowedTokens>
							</swe:constraint>
						</swe:Category>
					</swe:field>
				</swe:DataRecord>
				<oseo:grouping>Processing Option</oseo:grouping>
			</oseo:option>
			<oseo:productDeliveryOptions>
				<oseo:onlineDataAccess>
					<oseo:protocol>https</oseo:protocol>
				</oseo:onlineDataAccess>
			</oseo:productDeliveryOptions>
			<roseo:downloadURL>http://some.roseo.server/ROSEO/1.0.0/product/ESA:EECF:ENVISAT_ASA_IMx_xS:EN1-05121921114570-3322.XI?prclv={roseo:ProcessingLevel}&prdt={roseo:ProductType}&qos={roseo:QualityOfService}</roseo:downloadURL>
		</roseo:OrderOptionGroup>
		<roseo:OrderOptionGroup>
			<oseo:productOrderOptionsId>Level 1,Product SLC (ASA_IMS)</oseo:productOrderOptionsId>
			<oseo:identifier>ESA:EECF:ENVISAT_ASA_IMx_xS:EN1-05121921114570-3322.XI</oseo:identifier>
			<oseo:description>Order Options for producing ASAR IMS 1P product</oseo:description>
			<oseo:orderType>PRODUCT_ORDER</oseo:orderType>
			<oseo:option>
				<swe:DataRecord>
					<swe:field name="processingLevel">
						<swe:Category updatable="false" optional="true" definition="http://www.opengis.net/def/parameter/ESA/1.0/processingLevel">
							<swe:identifier>processingLevel</swe:identifier>
							<swe:constraint>
								<swe:AllowedTokens>
									<swe:value>1B</swe:value>
								</swe:AllowedTokens>
							</swe:constraint>
						</swe:Category>
					</swe:field>
				</swe:DataRecord>
				<oseo:grouping>Processing Option</oseo:grouping>
			</oseo:option>
			<oseo:option>
				<swe:DataRecord>
					<swe:field name="productType">
						<swe:Category updatable="false" optional="true" definition="http://www.opengis.net/def/parameter/ESA/1.0/productType">
							<swe:identifier>productType</swe:identifier>
							<swe:constraint>
								<swe:AllowedTokens>
									<swe:value>ASA_IMS_1P</swe:value>
								</swe:AllowedTokens>
							</swe:constraint>
						</swe:Category>
					</swe:field>
				</swe:DataRecord>
				<oseo:grouping>Processing Option</oseo:grouping>
			</oseo:option>
			<oseo:option>
				<swe:DataRecord>
					<swe:field name="qualityOfService">
						<swe:Category updatable="false" optional="true" definition="http://www.opengis.net/def/parameter/ESA/1.0/qualityOfService">
							<swe:identifier>qualityOfService</swe:identifier>
							<swe:constraint>
								<swe:AllowedTokens>
									<swe:value>STANDARD</swe:value>
									<swe:value>NRT</swe:value>
									<swe:value>RUSH</swe:value>
								</swe:AllowedTokens>
							</swe:constraint>
						</swe:Category>
					</swe:field>
				</swe:DataRecord>
				<oseo:grouping>Processing Option</oseo:grouping>
			</oseo:option>
			<oseo:productDeliveryOptions>
				<oseo:onlineDataAccess>
					<oseo:protocol>https</oseo:protocol>
				</oseo:onlineDataAccess>
			</oseo:productDeliveryOptions>
			<roseo:downloadURL>http://some.roseo.server/ROSEO/1.0.0/product/ESA:EECF:ENVISAT_ASA_IMx_xS:EN1-05121921114570-3322.XI?prclv={roseo:ProcessingLevel}&prdt={roseo:ProductType}&qos={roseo:QualityOfService}</roseo:downloadURL>
		</roseo:OrderOptionGroup>
	</roseo:OrderOptions>
</mstns:OpenSearchDescription>


text:
'use strict'

export function preferButtons (session, choiceCnt, rePrompt) {
  switch (getChannelId(session)) {
    case 'facebook':
      return (choiceCnt <= 3)
    case 'telegram':
    case 'kik':
      return true
    default:
      return false
  }
}

export function getChannelId (session) {
  const account = session.message.from || session.message.to
  return account.channelId.toLowerCase()
}


text:
package com.jayqqaa12.jbase.spring.util;

import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class ProfileHelper implements ApplicationContextAware {

    private static ApplicationContext context = null;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext)
            throws BeansException {
        this.context = applicationContext;
    }

    // 获取当前环境参数  exp: dev,prod,test
    public static String getActiveProfile() {
        String []profiles = context.getEnvironment().getActiveProfiles();
        if(ArrayUtils.isEmpty(profiles)){
            return profiles[0];
        }
        return "";
    }
}


text:
package uk.gov.hmrc.ct.accounts.frs102.boxes

import uk.gov.hmrc.ct.accounts.frs102.calculations.IntangibleAssetsCalculator
import uk.gov.hmrc.ct.accounts.frs102.retriever.{Frs102AccountsBoxRetriever, FullAccountsBoxRetriever}
import uk.gov.hmrc.ct.box._

case class AC117A(value: Option[Int]) extends CtBoxIdentifier(name = "Intangible assets - Goodwill - Cost - Cost at [POA END]")
  with CtOptionalInteger
  with Input
  with ValidatableBox[Frs102AccountsBoxRetriever]
  with Validators {

  override def validate(boxRetriever: Frs102AccountsBoxRetriever): Set[CtValidation] = {
    collectErrors(
      validateMoney(value, min = 0)
    )
  }
}

object AC117A extends Calculated[AC117A, FullAccountsBoxRetriever]
  with IntangibleAssetsCalculator {

  override def calculate(boxRetriever: FullAccountsBoxRetriever): AC117A = {
    import boxRetriever._
    calculateAC117A(ac114A(), ac115A(), ac116A(), ac209A(), ac210A())
  }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<library xmlns="urn:hl7-org:elm:r1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:quick="http://org.hl7.fhir" xmlns:a="urn:hl7-org:cql-annotations:r1">
    <identifier id="PropertyTest"/>
    <schemaIdentifier id="urn:hl7-org:elm" version="r1"/>
    <usings>
        <def localIdentifier="QUICK" uri="http://org.hl7.fhir"/>
    </usings>
    <valueSets>
        <def name="Female Administrative Sex" id="2.16.840.1.113883.3.560.100.2"/>
    </valueSets>
    <statements>
        <def name="Patient" context="Patient">
            <expression xsi:type="ElementOf">
                <operand dataType="quick:Patient" xsi:type="Retrieve"/>
            </expression>
        </def>
        <def name="InDemographic" context="Patient">
            <expression xsi:type="And">
                <operand xsi:type="GreaterOrEqual">
                    <operand name="CalculateAgeInYears" xsi:type="FunctionRef">
                        <operand path="birthDate" xsi:type="Property">
                            <source name="Patient" xsi:type="ExpressionRef"/>
                        </operand>
                    </operand>
                    <operand valueType="xsd:int" value="18" xsi:type="Literal"/>
                </operand>
                <operand xsi:type="In">
                    <operand path="gender" xsi:type="Property">
                        <source name="Patient" xsi:type="ExpressionRef"/>
                    </operand>
                    <operand name="Female Administrative Sex" xsi:type="ValueSetRef"/>
                </operand>
            </expression>
        </def>
    </statements>
</library>


text:
'use strict';

var $ = require('jquery');
var cardTmpl = require('hgn!./templates/card');
var util = require('streamhub-sdk/util');
var StreamhubShareButton = require('streamhub-share');

// Get user link based on content type
function getUserLink(content) {
    if (content.source === 'instagram') {
        return content.author.profileUrl;
    }

    if (content.source === 'twitter') {
        var base = 'http://twitter.com/intent/user?user_id=';
        var userId = content.author.twitterUserId;
        return base + userId;
    }

    if (content.source === 'facebook') {
        return content.author.profileUrl;
    }
}

// Get source url based on content type
function getSourceUrl(source) {
    var protocol = 'https://';
    if (source === 'instagram') {
        return protocol + 'instagram.com';
    }

    if (source === 'twitter') {
        return protocol + 'twitter.com';
    }

    if (source === 'facebook') {
        return protocol + 'facebook.com';
    }
}

/**
 * SingleCardView
 * @class
 */
var SingleCardView = function (opts) {
    this.content = opts.content;
    this.el = document.createElement('div');
    this.$el = $(this.el);

    var self = this;

    var imageSrc = null;
    if (this.content.attachments.length) {
        if (this.content.attachments[0].url) {
            imageSrc = this.content.attachments[0].url;
        }
        else {
            imageSrc = this.content.attachments[0].thumbnail_url;
        }
    }

    // facebook does not have display user handle, but a profile link
    var userhandle = (this.content.source !== 'facebook') ?
                        '@' + this.content.author.profileUrl.split('.com/')[1] :
                        '';

    var userLink = {
        url: getUserLink(this.content),
        target: '_blank'
    };

    // Ensure that this.content.body has a p tag
    var isHtml = /^\s*<(p|div)/;
    if ( !isHtml.test(this.content.body)) {
        this.content.body = '<p>' + this.content.body + '</p>';
    }

    this.el.innerHTML = cardTmpl({
        imageSrc: imageSrc || 'http://placehold.it/200x200',
        body: this.content.body,
        source: this.content.source,
        sourceHomeUrl: getSourceUrl(this.content.source),
        useravatar: this.content.author.avatar,
        username: this.content.author.displayName,
        userhandle: userhandle,
        userLinkUrl: userLink.url,
        userLinkTarget: userLink.target,
        formattedCreatedAt: util.formatDate(this.content.createdAt)
    });

    this.$contentContainer = this.$el.find('.content-container');
    this.$shareControlsContainer = this.$el.find('.content-share-controls');

    // TODO: this part could probably be a partial
    if (this.content.source !== 'twitter') {
        // @comment disabled for now at the request of @bo
        // var sharebutton = new StreamhubShareButton({
        //     el: this.$shareControlsContainer,
        //     content: this.content
        // });
    }
    else {
        var actionButtons = [
            {
                className: 'content-action content-action-reply',
                buttonUrl: 'https://twitter.com/intent/tweet?in_reply_to=' + this.content.tweetId
            },
            {
                className: 'content-action content-action-retweet',
                buttonUrl: 'https://twitter.com/intent/retweet?tweet_id=' + this.content.tweetId
            },
            {
                className: 'content-action content-action-favorite',
                buttonUrl: 'https://twitter.com/intent/favorite?tweet_id=' + this.content.tweetId
            }
        ];

        actionButtons.forEach(function (elem) {
            var a = document.createElement('a');
            a.href = elem.buttonUrl;
            a.className = elem.className;
            a.target = '_blank';
            self.$shareControlsContainer.append(a);
        });
    }
};

SingleCardView.cardWidth = 200;
SingleCardView.cardHeight = 200;

/**
 * Show
 * @param  {number} delay Delay for animation, if any.
 */
SingleCardView.prototype.show = function (delay) {
    var self = this;
    delay = delay || 0;
    setTimeout( function () {
        self.$el.parents('.card-container').css("background-color","white");
        self.$contentContainer.animate({'opacity': 1}, 100);
    }, delay);
};

/**
 * Destroy
 * @public
 */
SingleCardView.prototype.destroy = function () {
    this.el = null;
    this.$el = null;
    this.fullImage = null;
    this.smallImage = null;
    this.$contentContainer = null;
};

/**
 * Render stub
 * @public
 */
SingleCardView.prototype.render = function () {};

module.exports = SingleCardView;


text:
![Jekyll site CI](https://github.com/ouyi/ouyi.github.io/workflows/jekyll/badge.svg)

![GitHub Pages build](https://github.com/ouyi/ouyi.github.io/workflows/main/badge.svg)

# Memory Spills

Memory Spills is [a blog based on Jeykll and hosted on GitHub](https://ouyi.github.io).

## Useful commands

### Set up local test envrionment

**TLDR**: run `docker-compose up` in a console and preview the blog at http://localhost:8000/ with a browser.

#### Docker-based environment

The easiest way to have a local test envrionment up and running is executing this command in a Linux or macOS console:

    docker-compose up

This will install all dependencies and bring up a test web server, all in a Docker container. If everything works, the following messages are displayed in the console:

    jekyll_1  |     Server address: http://0.0.0.0:8000/
    jekyll_1  |   Server running... press ctrl-c to stop.

The blog site is available for preview at http://localhost:8000/ .

If for whatever reason docker-compose is not wanted, the following manual steps can achieve the same effect.

Build the image:

    docker build . -t docker-github-pages

Start the container serving the static site:

    docker run -it -v "$PWD":/usr/src/app -p 8000:8000 docker-github-pages

Run a single command:

    docker run -it -v "$PWD":/usr/src/app -p 8000:8000 docker-github-pages bundle exec github-pages versions

#### Host-based environment

One-liner to set up the environment:

    curl -sSL https://rvm.io/mpapis.asc | gpg --import - \
    && curl -L get.rvm.io | bash -s stable \
    && bash -l -c 'source /etc/profile.d/rvm.sh \
    && rvm reload \
    && rvm requirements run \
    && rvm install 2.5.3 \
    && rvm use 2.5.3 --default \
    && gem install jekyll bundler sass'

Test locally:

    bundle exec jekyll serve --port 8000 --host 0.0.0.0 --drafts

### Misc

Show a bundle package content:

    bundle show minima

Update the last_modified_at field of a post using its file system modification time:

    ./lastmod.sh _posts/2015-12-14-ansible-downgrade-rpm.md


text:
package org.odlabs.wiquery.ui.button;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.apache.wicket.markup.head.IHeaderResponse;
import org.apache.wicket.markup.head.JavaScriptHeaderItem;
import org.apache.wicket.markup.head.OnDomReadyHeaderItem;
import org.apache.wicket.markup.html.form.Check;
import org.apache.wicket.markup.html.form.CheckGroup;
import org.apache.wicket.markup.html.form.SimpleFormComponentLabel;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.util.CollectionModel;
import org.odlabs.wiquery.core.javascript.JsQuery;
import org.odlabs.wiquery.core.javascript.JsStatement;
import org.odlabs.wiquery.ui.widget.WidgetJavaScriptResourceReference;

/**
 * $Id$
 *

 * Creates a set of button checkbox UI component from this {@link Panel}'s HTML markup.
 *

 *
 * @param <T>
 *            The model object type
 *
 * @author Julien Roche
 * @since 1.1
 */
public class ButtonCheckSet<T extends Serializable> extends Panel
{
	// Constants
	/** Constant of serialization */
	private static final long serialVersionUID = -7837076246968244110L;

	// Properties
	private final CheckGroup<T> checkGroup;

	/**
	 * Constructor
	 *
	 * @param id
	 *            Wicket identifier
	 * @param checks
	 *            List of checks
	 */
	public ButtonCheckSet(String id, IModel< ? extends List<ButtonElement<T>>> checks)
	{
		this(id, checks, new CollectionModel<T>(new ArrayList<T>()));
	}

	/**
	 * Constructor
	 *
	 * @param id
	 *            Wicket identifier
	 * @param checks
	 *            List of checks
	 * @param model
	 *            Model of the default object
	 */
	public ButtonCheckSet(String id, IModel< ? extends List<ButtonElement<T>>> checks,
			IModel< ? extends Collection<T>> model)
	{
		super(id);

		checkGroup = new CheckGroup<T>("buttonCheckSetGroup", model)
		{
			private static final long serialVersionUID = 8265281439115476364L;

			@Override
			protected void onSelectionChanged(final Collection<T> newSelection)
			{
				ButtonCheckSet.this.onSelectionChanged(newSelection);
			}

			/**
			 * This method should be overridden to return true if it is desirable to have
			 * on-selection-changed notification.
			 *
			 * @return true if component should receive on-selection-changed
			 *         notifications, false otherwise
			 */
			@Override
			protected boolean wantOnSelectionChangedNotifications()
			{
				return ButtonCheckSet.this.wantOnSelectionChangedNotifications();
			}
		};
		checkGroup.setOutputMarkupId(true);
		checkGroup.setRenderBodyOnly(false);
		add(checkGroup);

		ListView< ? extends ButtonElement<T>> view =
			new ListView<ButtonElement<T>>("buttonCheckSetView", checks)
			{
				private static final long serialVersionUID = 1L;

				@Override
				protected void populateItem(ListItem<ButtonElement<T>> item)
				{
					ButtonElement<T> buttonElement = item.getModelObject();

					Check<T> check = newCheck("buttonCheck", buttonElement.getModel(), checkGroup);
					check.setLabel(buttonElement.getLabel());
					check.setOutputMarkupId(true);

					SimpleFormComponentLabel label =
						new SimpleFormComponentLabel("buttonCheckLabel", check);

					item.add(check);
					item.add(label);
				}
			};
		checkGroup.add(view);
	}

	/**
	 * Constructor
	 *
	 * @param id
	 *            Wicket identifier
	 * @param checks
	 *            List of checks
	 */
	public ButtonCheckSet(String id, List<ButtonElement<T>> checks)
	{
		this(id, Model.ofList(checks));
	}

	/**
	 * Constructor
	 *
	 * @param id
	 *            Wicket identifier
	 * @param checks
	 *            List of checks
	 * @param model
	 *            Model of the default object
	 */
	public ButtonCheckSet(String id, List<ButtonElement<T>> checks,
			IModel< ? extends Collection<T>> model)
	{
		this(id, Model.ofList(checks), model);
	}

	@Override
	public void renderHead(IHeaderResponse response)
	{
		response.render(JavaScriptHeaderItem.forReference(WidgetJavaScriptResourceReference.get()));
		response.render(JavaScriptHeaderItem.forReference(ButtonJavaScriptResourceReference.get()));
		response.render(OnDomReadyHeaderItem.forScript(statement().render()));
	}

	/**
	 * @return the check group of this component
	 */
	public CheckGroup<T> getCheckGroup()
	{
		return checkGroup;
	}

	/**
	 * Method creating a new {@link Check}
	 *
	 * @param wicketId
	 *            Wicket identifier
	 * @param model
	 *            Model to use
	 * @param group
	 *            Group of the {@link Check}
	 * @return a {@link Check}
	 */
	protected Check<T> newCheck(String wicketId, IModel<T> model, CheckGroup<T> group)
	{
		Check<T> check = new Check<T>(wicketId, model, group);
		return check;
	}

	/**
	 * Template method that can be overridden by clients that implement IOnChangeListener
	 * to be notified by onChange events of a select element. This method does nothing by
	 * default.
	 *

	 * Called when a {@link Check} is clicked in a {@link CheckGroup} that wants to be
	 * notified of this event. This method is to be implemented by clients that want to be
	 * notified of selection events.
	 *
	 * @param newSelection
	 *            The new selection of the {@link CheckGroup}. NOTE this is the same as
	 *            you would get by calling getModelObject() if the new selection were
	 *            current
	 */
	protected void onSelectionChanged(final Collection< ? extends T> newSelection)
	{
	}

	/**
	 * This method should be overridden to return true if it is desirable to have
	 * on-selection-changed notification.
	 *
	 * @return true if component should receive on-selection-changed notifications, false
	 *         otherwise
	 */
	protected boolean wantOnSelectionChangedNotifications()
	{
		return false;
	}

	public JsStatement statement()
	{
		return new JsQuery(checkGroup).$().chain("buttonset");
	}
}


text:
package io.pebbletemplates.pebble.utils;

public class StringLengthComparator implements java.util.Comparator<String> {

  public static StringLengthComparator INSTANCE = new StringLengthComparator();

  private StringLengthComparator() {
  }

  public int compare(String s1, String s2) {
    return s2.length() - s1.length();
  }
}


text:
namespace AgileObjects.ReadableExpressions.UnitTests
{
    using System;
    using System.Linq;
#if !NET35
    using System.Collections.Generic;
#endif
    using Common;
    using NetStandardPolyfills;
#if !NET35
    using Xunit;
    using static System.Linq.Expressions.Expression;
    using static Issue22;
    using static Issue22.InheritanceTests;
#else
    using Fact = NUnit.Framework.TestAttribute;
    using static Microsoft.Scripting.Ast.Expression;

    [NUnit.Framework.TestFixture]
#endif
    public class WhenTranslatingConditionals : TestClassBase
    {
        [Fact]
        public void ShouldTranslateASingleLineIfStatement()
        {
            var intVariable = Variable(typeof(int), "i");
            var one = Constant(1);
            var intVariableLessThanOne = LessThan(intVariable, one);
            var writeLessThan = CreateLambda(() => Console.Write("Less than"));
            var ifLessThanOneThenWrite = IfThen(intVariableLessThanOne, writeLessThan.Body);

            var translated = ifLessThanOneThenWrite.ToReadableString();

            const string EXPECTED = @"
if (i < 1)
{
    Console.Write(""Less than"");
}";
            translated.ShouldBe(EXPECTED.TrimStart());
        }

        [Fact]
        public void ShouldTranslateAShortCircuitingIfStatement()
        {
            var oneCastToDouble = Convert(Constant(1), typeof(double?));

            var ifTrueOne = IfThen(Constant(true), oneCastToDouble);

            var nullDouble = Constant(null, typeof(double?));

            var block = Block(ifTrueOne, nullDouble);

            var translated = block.ToReadableString();

            const string EXPECTED = @"
if (true)
{
    return (double?)1;
}

return null;";

            translated.ShouldBe(EXPECTED.TrimStart());
        }

        [Fact]
        public void ShouldTranslateAnIfStatementWithAConditional()
        {
            var guidVariable = Variable(typeof(Guid), "guid");
            var defaultGuid = Default(typeof(Guid));
            var guidNotDefault = NotEqual(guidVariable, defaultGuid);
            var guidEmpty = Field(null, typeof(Guid), "Empty");
            var guidNotEmpty = NotEqual(guidVariable, guidEmpty);
            var falseConstant = Constant(false);
            var guidNotEmptyOrFalse = Condition(guidNotDefault, guidNotEmpty, falseConstant);
            var writeGuidFun = CreateLambda(() => Console.Write("GUID FUN!"));
            var ifNotEmptyThenWrite = IfThen(guidNotEmptyOrFalse, writeGuidFun.Body);

            var translated = ifNotEmptyThenWrite.ToReadableString();

            const string EXPECTED = @"
if ((guid != default(Guid)) ? guid != Guid.Empty : false)
{
    Console.Write(""GUID FUN!"");
}";
            translated.ShouldBe(EXPECTED.TrimStart());
        }

        [Fact]
        public void ShouldTranslateAMultipleLineIfStatement()
        {
            var intVariable = Variable(typeof(int), "i");
            var one = Constant(1);
            var intVariableLessThanOne = LessThan(intVariable, one);
            var writeHello = CreateLambda(() => Console.WriteLine("Hello"));
            var writeThere = CreateLambda(() => Console.WriteLine("There"));
            var writeBlock = Block(writeHello.Body, writeThere.Body);
            var ifLessThanOneThenWrite = IfThen(intVariableLessThanOne, writeBlock);

            var translated = ifLessThanOneThenWrite.ToReadableString();

            const string EXPECTED = @"
if (i < 1)
{
    Console.WriteLine(""Hello"");
    Console.WriteLine(""There"");
}";
            translated.ShouldBe(EXPECTED.TrimStart());
        }

        [Fact]
        public void ShouldTranslateAMultipleClauseIfStatement()
        {
            var intVariable = Variable(typeof(int), "i");
            var one = Constant(1);
            var intVariableLessThanOne = LessThan(intVariable, one);
            var intVariableMoreThanOne = GreaterThan(intVariable, one);
            var intVariableInRange = AndAlso(intVariableLessThanOne, intVariableMoreThanOne);
            var writeHello = CreateLambda(() => Console.WriteLine("Hello"));
            var ifLessThanOneThenWrite = IfThen(intVariableInRange, writeHello.Body);

            var translated = ifLessThanOneThenWrite.ToReadableString();

            const string EXPECTED = @"
if ((i < 1) && (i > 1))
{
    Console.WriteLine(""Hello"");
}";
            translated.ShouldBe(EXPECTED.TrimStart());
        }

        [Fact]
        public void ShouldTranslateAMultipleLineIfStatementTest()
        {
            var intVariable = Variable(typeof(int), "i");
            var one = Constant(1);
            var intVariableLessThanOne = LessThan(intVariable, one);
            var returnLabel = Label(typeof(bool), "Return");
            var returnTrue = Return(returnLabel, Constant(true));
            var ifLessThanOneReturnTrue = IfThen(intVariableLessThanOne, returnTrue);
            var five = Constant(5);
            var intVariableMoreThanFive = GreaterThan(intVariable, five);
            var returnMoreThanFive = Label(returnLabel, intVariableMoreThanFive);
            var testBlock = Block(ifLessThanOneReturnTrue, returnMoreThanFive);

            var writeHello = CreateLambda(() => Console.WriteLine("Hello"));
            var writeVariable = Variable(writeHello.Type, "write");
            var assignWrite = Assign(writeVariable, writeHello);
            var ifTestPassesThenWrite = IfThen(testBlock, assignWrite);

            var translated = ifTestPassesThenWrite.ToReadableString();

            const string EXPECTED = @"
if ({
        if (i < 1)
        {
            return true;
        }

        return i > 5;
    })
{
    write = () => Console.WriteLine(""Hello"");
}";
            translated.ShouldBe(EXPECTED.TrimStart());
        }

        [Fact]
        public void ShouldTranslateAnIfElseStatement()
        {
            var intVariable = Variable(typeof(int), "i");
            var one = Constant(1);
            var intVariableLessThanOne = LessThan(intVariable, one);
            var writeHello = CreateLambda(() => Console.WriteLine("Hello"));
            var writeGoodbye = CreateLambda(() => Console.WriteLine("Goodbye"));
            var writeHelloOrGoodbye = IfThenElse(intVariableLessThanOne, writeHello.Body, writeGoodbye.Body);

            var translated = writeHelloOrGoodbye.ToReadableString();

            const string EXPECTED = @"
if (i < 1)
{
    Console.WriteLine(""Hello"");
}
else
{
    Console.WriteLine(""Goodbye"");
}";
            translated.ShouldBe(EXPECTED.TrimStart());
        }

        [Fact]
        public void ShouldTranslateAnIfElseIfStatement()
        {
            var intVariable = Variable(typeof(int), "i");
            var intEqualsOne = Equal(intVariable, Constant(1));
            var intEqualsTwo = Equal(intVariable, Constant(2));
            var writeOne = CreateLambda(() => Console.WriteLine("One"));
            var writeTwo = CreateLambda(() => Console.WriteLine("Two"));
            var ifTwoWriteTwo = IfThen(intEqualsTwo, writeTwo.Body);
            var writeOneOrTwo = IfThenElse(intEqualsOne, writeOne.Body, ifTwoWriteTwo);

            var translated = writeOneOrTwo.ToReadableString();

            const string EXPECTED = @"
if (i == 1)
{
    Console.WriteLine(""One"");
}
else if (i == 2)
{
    Console.WriteLine(""Two"");
}";
            translated.ShouldBe(EXPECTED.TrimStart());
        }

        [Fact]
        public void ShouldTranslateMultipleLineVoidIfElseStatements()
        {
            var intVariable = Variable(typeof(int), "i");
            var zero = Constant(0);
            var intVariableEqualsZero = Equal(intVariable, zero);
            var writeHello = CreateLambda(() => Console.WriteLine("Hello"));
            var writeGoodbye = CreateLambda(() => Console.WriteLine("Goodbye"));
            var helloThenGoodbye = Block(writeHello.Body, writeGoodbye.Body);
            var goodbyeThenHello = Block(writeGoodbye.Body, writeHello.Body);
            var writeHelloAndGoodbye = IfThenElse(intVariableEqualsZero, helloThenGoodbye, goodbyeThenHello);

            var translated = writeHelloAndGoodbye.ToReadableString();

            const string EXPECTED = @"
if (i == 0)
{
    Console.WriteLine(""Hello"");
    Console.WriteLine(""Goodbye"");
}
else
{
    Console.WriteLine(""Goodbye"");
    Console.WriteLine(""Hello"");
}";
            translated.ShouldBe(EXPECTED.TrimStart());
        }

        [Fact]
        public void ShouldTranslateAMultipleLineNonVoidIfElseStatements()
        {
            var intVariable = Variable(typeof(int), "i");
            var zero = Constant(0);
            var intVariableEqualsZero = Equal(intVariable, zero);
            var writeHello = CreateLambda(() => Console.WriteLine("Hello"));
            var writeGoodbye = CreateLambda(() => Console.WriteLine("Goodbye"));
            var helloThenGoodbye = Block(writeHello.Body, writeGoodbye.Body, intVariable);
            var goodbyeThenHello = Block(writeGoodbye.Body, writeHello.Body, intVariable);
            var writeHelloAndGoodbye = IfThenElse(intVariableEqualsZero, helloThenGoodbye, goodbyeThenHello);

            var translated = writeHelloAndGoodbye.ToReadableString();

            const string EXPECTED = @"
if (i == 0)
{
    Console.WriteLine(""Hello"");
    Console.WriteLine(""Goodbye"");

    return i;
}

Console.WriteLine(""Goodbye"");
Console.WriteLine(""Hello"");

return i;
";
            translated.ShouldBe(EXPECTED.Trim());
        }

        [Fact]
        public void ShouldNotWrapSingleExpressionTernaryConditionsInParentheses()
        {
            var ternary = Condition(
                Constant(false),
                Constant(1),
                Constant(2));

            var translated = ternary.ToReadableString();

            translated.ShouldBe("false ? 1 : 2");
        }

        [Fact]
        public void ShouldNotWrapMethodCallTernaryConditionsInParentheses()
        {
            var method = typeof(MethodCallHelper).GetPublicInstanceMethod("MultipleParameterMethod");

            var methodCall = Call(
                Variable(typeof(MethodCallHelper), "helper"),
                method,
                Constant("hello"),
                Constant(123));

            var ternary = Condition(
                methodCall,
                Constant(1),
                Constant(2));

            var translated = ternary.ToReadableString();

            translated.ShouldBe("helper.MultipleParameterMethod(\"hello\", 123) ? 1 : 2");
        }

        [Fact]
        public void ShouldTranslateASwitchStatement()
        {
            var intVariable = Variable(typeof(int), "i");
            var writeOne = CreateLambda(() => Console.WriteLine("One"));
            var writeTwo = CreateLambda(() => Console.WriteLine("Two"));
            var writeThree = CreateLambda(() => Console.WriteLine("Three"));

            var switchStatement = Switch(
                intVariable,
                SwitchCase(writeOne.Body, Constant(1)),
                SwitchCase(writeTwo.Body, Constant(2)),
                SwitchCase(writeThree.Body, Constant(3)));

            var translated = switchStatement.ToReadableString();

            const string EXPECTED = @"
switch (i)
{
    case 1:
        Console.WriteLine(""One"");
        break;

    case 2:
        Console.WriteLine(""Two"");
        break;

    case 3:
        Console.WriteLine(""Three"");
        break;
}";
            translated.ShouldBe(EXPECTED.TrimStart());
        }

        [Fact]
        public void ShouldTranslateASwitchStatementWithMultipleCaseTestValues()
        {
            var intVariable = Variable(typeof(int), "i");

            var writeOneOrTwo = CreateLambda(() => Console.WriteLine("One or Two"));
            var writeOneOrTwoCase = SwitchCase(writeOneOrTwo.Body, Constant(1), Constant(2));

            var writeThree = CreateLambda(() => Console.WriteLine("Three"));
            var writeThreeCase = SwitchCase(writeThree.Body, Constant(3));

            var switchStatement = Switch(intVariable, writeOneOrTwoCase, writeThreeCase);

            var translated = switchStatement.ToReadableString();

            const string EXPECTED = @"
switch (i)
{
    case 1:
    case 2:
        Console.WriteLine(""One or Two"");
        break;

    case 3:
        Console.WriteLine(""Three"");
        break;
}";
            translated.ShouldBe(EXPECTED.TrimStart());
        }

        [Fact]
        public void ShouldTranslateASwitchStatementWithADefault()
        {
            var intVariable = Variable(typeof(int), "i");
            var writeOne = CreateLambda(() => Console.WriteLine("One"));
            var writeTwo = CreateLambda(() => Console.WriteLine("Two"));
            var writeThree = CreateLambda(() => Console.WriteLine("Three"));

            var writeOneTwoThree = Block(writeOne.Body, writeTwo.Body, writeThree.Body);

            var switchStatement = Switch(
                intVariable,
                writeOneTwoThree,
                SwitchCase(writeOne.Body, Constant(1)),
                SwitchCase(writeTwo.Body, Constant(2)),
                SwitchCase(writeThree.Body, Constant(3)));

            var translated = switchStatement.ToReadableString();

            const string EXPECTED = @"
switch (i)
{
    case 1:
        Console.WriteLine(""One"");
        break;

    case 2:
        Console.WriteLine(""Two"");
        break;

    case 3:
        Console.WriteLine(""Three"");
        break;

    default:
        Console.WriteLine(""One"");
        Console.WriteLine(""Two"");
        Console.WriteLine(""Three"");
        break;
}";
            translated.ShouldBe(EXPECTED.TrimStart());
        }

        [Fact]
        public void ShouldTranslateASwitchStatementWithMultiLineCases()
        {
            var intVariable = Variable(typeof(int), "i");
            var writeOne = CreateLambda(() => Console.WriteLine("One"));
            var writeTwo = CreateLambda(() => Console.WriteLine("Two"));
            var writeThree = CreateLambda(() => Console.WriteLine("Three"));

            var writeOneTwo = Block(writeOne.Body, writeTwo.Body);
            var writeTwoThree = Block(writeTwo.Body, writeThree.Body);

            var switchStatement = Switch(
                intVariable,
                SwitchCase(writeOneTwo, Constant(12)),
                SwitchCase(writeTwoThree, Constant(23)));

            var translated = switchStatement.ToReadableString();

            const string EXPECTED = @"
switch (i)
{
    case 12:
        Console.WriteLine(""One"");
        Console.WriteLine(""Two"");
        break;

    case 23:
        Console.WriteLine(""Two"");
        Console.WriteLine(""Three"");
        break;
}";
            translated.ShouldBe(EXPECTED.TrimStart());
        }

        [Fact]
        public void ShouldTranslateASwitchStatementWithReturns()
        {
            var returnTarget = Label(typeof(string), "Return");

            var switchCases = Enumerable.Range(0, 5).Select(i => SwitchCase(
                Return(returnTarget, Constant(i.ToString())),
                Constant(i))).ToArray();

            switchCases[1] = SwitchCase(
                Throw(New(typeof(NotSupportedException).GetPublicInstanceConstructor(Type.EmptyTypes))),
                Constant(1));

            var @switch = Switch(
                Constant(3),
                Return(returnTarget, Constant("Nope")),
                switchCases);

            var switchBlock = Block(@switch, Label(returnTarget, Constant(string.Empty)));

            var translated = switchBlock.ToReadableString();

            const string EXPECTED = @"
switch (3)
{
    case 0:
        return ""0"";

    case 1:
        throw new NotSupportedException();

    case 2:
        return ""2"";

    case 3:
        return ""3"";

    case 4:
        return ""4"";

    default:
        return ""Nope"";
}

return """";";
            translated.ShouldBe(EXPECTED.TrimStart());
        }

        [Fact]
        public void ShouldIncludeReturnKeywordsForConstantsAndCasts()
        {
            var nullLong = Constant(null, typeof(long?));

            var writeOne = CreateLambda(() => Console.WriteLine("One!"));
            var oneCastToLong = Convert(Constant(1), typeof(long?));
            var elseBlock = Block(writeOne.Body, writeOne.Body, oneCastToLong);

            var nullOrOne = IfThenElse(Constant(true), nullLong, elseBlock);

            var translated = nullOrOne.ToReadableString();

            const string EXPECTED = @"
if (true)
{
    return null;
}

Console.WriteLine(""One!"");
Console.WriteLine(""One!"");

return (long?)1;";

            translated.ShouldBe(EXPECTED.TrimStart());
        }

        [Fact]
        public void ShouldBreakLongMultipleConditionsOntoMultipleLines()
        {
            var intVariable1 = Variable(typeof(int), "thisVariableHasALongName");
            var intVariable2 = Variable(typeof(int), "thisOtherVariableHasALongNameToo");
            var int1IsGreaterThanInt2 = GreaterThan(intVariable1, intVariable2);
            var int1IsNotEqualToInt2 = NotEqual(intVariable1, intVariable2);

            var intIsInRange = AndAlso(int1IsGreaterThanInt2, int1IsNotEqualToInt2);
            var writeYo = CreateLambda(() => Console.WriteLine("Yo!"));
            var ifInRangeWriteYo = IfThen(intIsInRange, writeYo.Body);

            var translated = ifInRangeWriteYo.ToReadableString();

            const string EXPECTED = @"
if ((thisVariableHasALongName > thisOtherVariableHasALongNameToo) &&
    (thisVariableHasALongName != thisOtherVariableHasALongNameToo))
{
    Console.WriteLine(""Yo!"");
}";

            translated.ShouldBe(EXPECTED.TrimStart());
        }

        [Fact]
        public void ShouldTranslateAssignmentOutcomeTests()
        {
            var intVariable = Variable(typeof(int), "i");
            var intValue = Constant(123);
            var intAssignment = Assign(intVariable, intValue);
            var intDefault = Default(typeof(int));
            var assignmentResultNotDefault = NotEqual(intAssignment, intDefault);
            var doNothing = Default(typeof(void));
            var ifNotdefaultDoNothing = IfThen(assignmentResultNotDefault, doNothing);

            var translated = ifNotdefaultDoNothing.ToReadableString();

            const string EXPECTED = @"
if ((i = 123) != default(int))
{
}";

            translated.ShouldBe(EXPECTED.TrimStart());
        }

        // See https://github.com/agileobjects/ReadableExpressions/issues/22
        [Fact]
        public void ShouldTranslateEnumComparisonTests()
        {
            var flagParameter = Parameter(typeof(bool), "flag");
            var one = Constant(Test.One);
            var two = Constant(Test.Two);
            var oneOrTwo = Condition(flagParameter, one, two);
            var oneOrTwoEqualsTwo = Equal(oneOrTwo, two);
            var testLambda = Lambda<Func<bool, bool>>(oneOrTwoEqualsTwo, flagParameter);

            var translated = testLambda.ToReadableString();

            translated.ShouldBe("flag => (flag ? Test.One : Test.Two) == Test.Two");
        }

#if !NET35
        [Fact]
        public void ShouldTranslateConditionalWithConditionalTest()
        {
            var dataContext = Parameter(typeof(IDataContext), "dctx");
            var dataReader = Parameter(typeof(IDataReader), "rd");

            var ldr = Variable(typeof(SqLiteDataReader), "ldr");

            var onEntityCreatedMethod = typeof(TableContext)
                .GetPublicStaticMethod(nameof(TableContext.OnEntityCreated));

            var mapperBody = Block(
                new[] { ldr },
                Assign(ldr, Convert(dataReader, typeof(SqLiteDataReader))),
                Condition(
                    Equal(
                        Condition(
                            Call(ldr, nameof(SqLiteDataReader.IsDbNull), null, Constant(0)),
                            Constant(TypeCodeEnum.Base),
                            Convert(
                                Call(ldr, nameof(SqLiteDataReader.GetInt32), null, Constant(0)),
                                typeof(TypeCodeEnum))),
                        Constant(TypeCodeEnum.A1)),
                    Convert(
                        Convert(
                            Call(
                                onEntityCreatedMethod,
                                dataContext,
                                MemberInit(
                                    New(typeof(InheritanceA1)),
                                    Bind(
                                        typeof(InheritanceA1).GetPublicInstanceProperty(nameof(InheritanceBase.GuidValue)),
                                        Condition(
                                            Call(ldr, nameof(SqLiteDataReader.IsDbNull), null, Constant(1)),
                                            Constant(Guid.Empty),
                                            Call(ldr, nameof(SqLiteDataReader.GetGuid), null, Constant(1))))
                                )
                            ),
                            typeof(InheritanceA1)),
                        typeof(InheritanceA)),
                    Convert(
                        Convert(
                            Call(
                                onEntityCreatedMethod,
                                dataContext,
                                MemberInit(
                                    New(typeof(InheritanceA2)),
                                    Bind(
                                        typeof(InheritanceA2).GetPublicInstanceProperty(nameof(InheritanceBase.GuidValue)),
                                        Condition(
                                            Call(ldr, nameof(SqLiteDataReader.IsDbNull), null, Constant(1)),
                                            Constant(Guid.Empty),
                                            Call(ldr, nameof(SqLiteDataReader.GetGuid), null, Constant(1))))
                                )
                            ),
                            typeof(InheritanceA2)),
                        typeof(InheritanceA))));

            var mapper = Lambda<Func<IDataContext, IDataReader, InheritanceA>>(
                mapperBody,
                dataContext,
                dataReader);

            var body = Invoke(mapper, dataContext, dataReader);

            var lambda = Lambda<Func<IDataContext, IDataReader, InheritanceA>>(body, dataContext, dataReader);

            const string EXPECTED = @"
(dctx, rd) => ((dctx, rd) =>
{
    var ldr = (Issue22.SqLiteDataReader)rd;

    return ((ldr.IsDbNull(0)
        ? Issue22.InheritanceTests.TypeCodeEnum.Base
        : (Issue22.InheritanceTests.TypeCodeEnum)ldr.GetInt32(0)) == Issue22.InheritanceTests.TypeCodeEnum.A1)
        ? (Issue22.InheritanceTests.InheritanceA)((Issue22.InheritanceTests.InheritanceA1)Issue22.TableContext.OnEntityCreated(
            dctx,
            new Issue22.InheritanceTests.InheritanceA1
            {
                GuidValue = ldr.IsDbNull(1) ? default(Guid) : ldr.GetGuid(1)
            }))
        : (Issue22.InheritanceTests.InheritanceA)((Issue22.InheritanceTests.InheritanceA2)Issue22.TableContext.OnEntityCreated(
            dctx,
            new Issue22.InheritanceTests.InheritanceA2
            {
                GuidValue = ldr.IsDbNull(1) ? default(Guid) : ldr.GetGuid(1)
            }));
}).Invoke(dctx, rd)";

            var translated = lambda.ToReadableString();

            translated.ShouldBe(EXPECTED.TrimStart());
        }
#endif
    }

    #region Helpers

    internal class MethodCallHelper
    {
        public bool MultipleParameterMethod(string stringValue, int intValue)
        {
            return true;
        }
    }

    internal enum Test { One, Two };

#if !NET35
    internal static class Issue22
    {
        public interface IDataContext
        {
        }

        public interface IDataReader
        {
        }

        public class SqLiteDataReader : IDataReader
        {
            public bool IsDbNull(int idx) => default(bool);

            public int GetInt32(int idx) => default(int);

            public Guid GetGuid(int idx) => default(Guid);
        }

        public static class InheritanceTests
        {
            public enum TypeCodeEnum
            {
                Base,
                A,
                A1,
                A2,
            }

            public abstract class InheritanceBase
            {
                public Guid GuidValue { get; set; }
            }

            public abstract class InheritanceA : InheritanceBase
            {
                public List<InheritanceB> Bs { get; set; }
            }

            public class InheritanceB : InheritanceBase
            {
            }

            public class InheritanceA2 : InheritanceA
            {
            }

            public class InheritanceA1 : InheritanceA
            {
            }
        }

        public class TableContext
        {
            public static object OnEntityCreated(IDataContext context, object entity) => entity;
        }

        public enum Test
        {
            One,
            Two
        }
    }
#endif

    #endregion
}