text:
cask "pynsource" do
  version "1.76"
  sha256 "d7ffd213b5fd033ab1561d9684b1322b99e9b0e3baa2d48e3a04c6d94fe75935"

  # github.com/abulka/pynsource/ was verified as official when first introduced to the cask
  url "https://github.com/abulka/pynsource/releases/download/version-#{version}/pynsource-#{version}-macosx.zip"
  appcast "https://github.com/abulka/pynsource/releases.atom"
  name "Pynsource"
  homepage "https://www.pynsource.com/"

  app "pynsource.app"

  zap trash: [
    "~/Library/Application Support/PyNsource",
    "~/Library/Logs/pynsource",
    "~/Library/Preferences/PyNSource",
    "~/Library/Saved Application State/Pynsource.savedState",
  ]
end


text:
package com.github.vmbenchmarks;

import org.openjdk.jmh.annotations.Benchmark;

public class GeneratePrimeNumbersWithForLoop {

    @Benchmark
    public void generatePrime() {

        int max = 100;

        //System.out.println("Generate Prime numbers between 1 and " + max);

        // loop through the numbers one by one
        for (int i = 1; i < max; i++) {

            boolean isPrimeNumber = true;

            // check to see if the number is prime
            for (int j = 2; j < i; j++) {
                if (i % j == 0) {
                    isPrimeNumber = false;
                    break; // exit the inner for loop
                }
            }

            // print the number if prime
            if (isPrimeNumber) {
                //System.out.print(i + " ");
            }
        }
    }

}

redpajama_set_name: RedPajamaGithub


text:
package cmd

import (
	"fmt"
	"os"
	"path/filepath"
	"strings"

	"github.com/spf13/cobra"

	homedir "github.com/mitchellh/go-homedir"
	"github.com/spf13/viper"
)

var cfgFile string

// rootCmd represents the base command when called without any subcommands
var rootCmd *cobra.Command = newRootCmd()

func newRootCmd() *cobra.Command {
	r := &cobra.Command{
		Use:   "git-monitor",
		Short: "git-monitor keeps track of changes in monitored git repositories",
		Long: `
git-monitor manages a list of git repositories and can check them for new
commits or changes on branches. It works against local and remote repositories.

git-monitor is a CLI application which can tell you if a repository has changes
since the last time you checked it. Think of it as "apt-get update" which tells
you that repository X on branch Y has new commits.`,
		Run: runRoot,
	}

	r.AddCommand(addCmd)
	r.AddCommand(checkCmd)
	r.AddCommand(listCmd)
	r.AddCommand(removeCmd)

	return r
}

// Execute of the root command is our main entry point.
func Execute(version string) {
	rootCmd.Version = version
	if err := rootCmd.Execute(); err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}

func init() {
	cobra.OnInitialize(initConfig)

	rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.git-monitor.yaml)")

	rootCmd.PersistentFlags().BoolP("verbose", "v", false, "enable verbose output")
	viper.BindPFlag("verbose", rootCmd.PersistentFlags().Lookup("verbose"))

	rootCmd.PersistentFlags().BoolP("open_in_browser", "b", false, "open the URL of each repository change in your browser")
	viper.BindPFlag("open_in_browser", rootCmd.PersistentFlags().Lookup("open_in_browser"))

	rootCmd.PersistentFlags().String("repo_dir", "", "directory where to store local repositories")
	viper.BindPFlag("repo_dir", rootCmd.PersistentFlags().Lookup("repo_dir"))
	viper.SetDefault("repo_dir", "~/.git-monitor")
}

// initConfig reads in config file and ENV variables if set.
func initConfig() {
	if cfgFile != "" {
		// Use config file from the flag.
		viper.SetConfigFile(cfgFile)
	} else {
		// Find home directory.
		home, err := homedir.Dir()
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}

		// Search config in home directory with name ".git-monitor" (without extension).
		viper.AddConfigPath(home)
		viper.SetConfigName(".git-monitor")
	}

	viper.AutomaticEnv() // read in environment variables that match

	// If a config file is found, read it in.
	if err := viper.ReadInConfig(); err == nil {
		if viper.GetBool("verbose") {
			fmt.Println("Using config file:", viper.ConfigFileUsed())
		}
	}

	repoDir := viper.GetString("repo_dir")
	if len(repoDir) == 0 {
		fmt.Fprintln(os.Stderr, "ERROR: repo_dir not set")
		os.Exit(1)
	}

	repoDir, err := homedir.Expand(repoDir)
	if err != nil {
		fmt.Fprintf(os.Stderr, "ERROR: homedir expand failed for repo_dir %s: %v\n", repoDir, err)
		os.Exit(1)
	}
	repoDir, err = filepath.Abs(repoDir)
	if err != nil {
		fmt.Fprintf(os.Stderr, "ERROR: absolute path failed for repo_dir %s: %v\n", repoDir, err)
		os.Exit(1)
	}
	repoDir, err = filepath.EvalSymlinks(repoDir)
	if err != nil {
		fmt.Fprintf(os.Stderr, "ERROR: eval-symlink failed for repo_dir %s: %v\n", repoDir, err)
		os.Exit(1)
	}
	viper.Set("repo_dir", repoDir)

	if _, err := os.Stat(repoDir); os.IsNotExist(err) {
		err := os.MkdirAll(repoDir, 0755)
		if err != nil {
			fmt.Fprintf(os.Stderr, "ERROR: could not create missing repo_dir under %s: %v\n", repoDir, err)
			os.Exit(1)
		}

		if viper.GetBool("verbose") {
			fmt.Println("Created empty repo_dir:", repoDir)
		}
	}
	if viper.GetBool("verbose") {
		fmt.Println("Using repo_dir:", repoDir)
	}

	if viper.GetBool("verbose") {
		ignoredBranches := viper.GetStringSlice("ignored_branches")
		if len(ignoredBranches) > 0 {
			fmt.Println("Ignoring all changes on branches:", strings.Join(ignoredBranches, ", "))
		}
	}
}

func runRoot(cmd *cobra.Command, args []string) {
	checkCmd.Run(cmd, args)
}


text:
# m2njs

[Mongrel2](http://mongrel2.org/wiki/quick_start.html) has handlers, which take HTTP requests, and turns them into nicely packed and processed [ZeroMQ](http://www.zeromq.org/intro:get-the-software) messages for your asynchronous handlers. m2njs is a [Mongrel2](http://mongrel2.org/wiki/quick_start.html) handler for [Node.js](http://nodejs.org/).

# How To

This assumes you have [ZeroMQ](http://www.zeromq.org/intro:get-the-software) and [Mongrel2](http://mongrel2.org/wiki/quick_start.html) installed.

Navigate to your mongrel2 installation `bin` directory. Add the following to the mongrel2 configuration file:

```config
nodejs = Handler(
  send_spec = 'tcp://127.0.0.1:9997',
  send_ident = '81b7114c-534c-4107-9f17-b317cfd59f62',
  recv_spec = 'tcp://127.0.0.1:9996',
  recv_ident = '81b7114c-534c-4107-9f17-b317cfd59f62'
)
```
You can change the address and port to whatever fits your need, then load your config using the following:

```bash
m2sh load -config YOUR_MONGREL2_CONF_FILE
```

Once configuration is loaded, start mongrel2 by issuing the following:

```bash
m2sh start -host localhost
```

Install m2njs using npm:

```bash
npm install m2njs
```

Use it in your code:

```javascript
...
  var mongrel2 = require('m2njs');

  /*
    This should match the equivalent in your mongrel2
    configuration file.
    example/nodejshandler.conf is an sample mongrel2 configuration file.
  */
  var config = {
    recv_spec: 'tcp://127.0.0.1:9996',
    send_spec: 'tcp://127.0.0.1:9997',
    identity: '81b7114c-534c-4107-9f17-b317cfd59f62'
  }

  mongrel2.connect(config.recv_spec, config.send_spec, config.identity, function(msg, reply) {

    //Perform some logic

    reply(200, headers, JSON.stringify(msg));
  });
....
```

# Copyright

Copyright (c) 2014 Wardell Bellanger. See LICENSE for details.


text:
import pointDistanceSquared from "./pointDistanceSquared";

/**
    @function pointDistance
    @desc Calculates the pixel distance between two points.
    @param {Array} p1 The first point, which should always be an `[x, y]` formatted Array.
    @param {Array} p2 The second point, which should always be an `[x, y]` formatted Array.
    @returns {Number}
*/
export default (p1, p2) => Math.sqrt(pointDistanceSquared(p1, p2));


text:
class Exo
  class PagesController < ExoController
    before_filter :fix_lookup_context
    include RequestRestriction
    helper Exo::BlockHelper

    def serve_page
      if exo_router.route.redirection?
        redirect_to exo_router.route.to_url
      else
        render exo_router.route.view_path, layout: exo_router.route.layout_path
      end
    end

    protected
    def fix_lookup_context
      lookup_context.prefixes = [
        exo_site.theme_path,
        exo_site.nest_path('application')
      ]
    end
  end
end


text:
package main

import (
	"encoding/gob"
	"fmt"
	"net"
	"os"
	"os/exec"
	"path/filepath"
	debugPkg "runtime/debug"
	"strconv"
	"sync"
	"syscall"
	"time"

	"io"

	linkpkg "github.com/cloudfoundry-incubator/garden-linux/iodaemon/link"
	"github.com/kr/pty"
)

// spawn listens on a unix socket at the given socketPath and when the first connection
// is received, starts a child process.
func spawn(
	socketPath string,
	argv []string,
	timeout time.Duration,
	withTty bool,
	windowColumns int,
	windowRows int,
	debug bool,
	terminate chan int,
	notifyStream io.WriteCloser,
	errStream io.WriteCloser,
) {
	var listener net.Listener

	fatal := func(err error) {
		if debug {
			debugPkg.PrintStack()
		}
		fmt.Fprintln(errStream, "fatal: "+err.Error())
		if listener != nil {
			listener.Close()
		}
		terminate <- 1
	}

	if debug {
		enableTracing(socketPath, fatal)
	}

	listener, err := listen(socketPath)
	if err != nil {
		fatal(err)
		return
	}

	executablePath, err := exec.LookPath(argv[0])
	if err != nil {
		fatal(err)
		return
	}

	cmd := child(executablePath, argv)

	var stdinW, stdoutR, stderrR *os.File
	if withTty {
		cmd.Stdin, stdinW, stdoutR, cmd.Stdout, stderrR, cmd.Stderr, err = createTtyPty(windowColumns, windowRows)
		cmd.SysProcAttr.Setctty = true
		cmd.SysProcAttr.Setsid = true
	} else {
		cmd.Stdin, stdinW, stdoutR, cmd.Stdout, stderrR, cmd.Stderr, err = createPipes()
	}

	if err != nil {
		fatal(err)
		return
	}

	statusR, statusW, err := os.Pipe()
	if err != nil {
		fatal(err)
		return
	}

	acceptConn := func(stopAccepting chan bool) (net.Conn, error) {
		notify(notifyStream, "ready")
		conn, err := acceptConnection(listener, stdoutR, stderrR, statusR)
		if err != nil {
			select {
			case <-stopAccepting:
				return nil, err
			default:
				fatal(err)
				return nil, err
			}
		}
		return conn, nil
	}

	processConn := func(conn net.Conn) {
		processLinkRequests(conn, stdinW, cmd, withTty)
	}

	startChild := func() error {
		err := cmd.Start()
		if err != nil {
			fatal(err)
			return err
		}

		notify(notifyStream, "active")
		notifyStream.Close()
		return nil
	}

	waitForChild := func() {
		cmd.Wait()
		if cmd.ProcessState != nil {
			fmt.Fprintf(statusW, "%d\n", cmd.ProcessState.Sys().(syscall.WaitStatus).ExitStatus())
		}
	}

	initChild, childStarted, childEnded, stopAccepting, connected := make(chan bool), make(chan bool), make(chan bool), make(chan bool), make(chan bool)

	onFirstConn := func() {
		connected <- true
		initChild <- true
		<-childStarted
	}

	exitCode := 1
	go acceptConnections(acceptConn, onFirstConn, stopAccepting, processConn)

	select {
	case <-connected:
		<-initChild
		go runChildProcess(startChild, waitForChild, childStarted, childEnded)
		<-childEnded
		exitCode = 0
	case <-time.After(timeout):
		exitCode = 2
		break
	}

	errStream.Close()
	close(stopAccepting)
	listener.Close()
	terminate <- exitCode
}

func acceptConnections(acceptConn func(chan bool) (net.Conn, error), onFirstConn func(), stopAccepting chan bool,
	processConn func(net.Conn)) {
	var once sync.Once

	for {
		conn, err := acceptConn(stopAccepting)
		if err != nil {
			return
		}

		once.Do(onFirstConn)

		processConn(conn)
	}
}

func runChildProcess(startChild func() error, waitForChild func(), childStarted, childEnded chan bool) {
	err := startChild()
	if err != nil {
		return
	}
	childStarted <- true

	waitForChild()
	childEnded <- true
}

func notify(notifyStream io.Writer, message string) {
	fmt.Fprintln(notifyStream, message)
}

func enableTracing(socketPath string, fatal func(error)) {
	ownPid := os.Getpid()

	traceOut, err := os.Create(socketPath + ".trace")
	if err != nil {
		fatal(err)
	}

	strace := exec.Command("strace", "-f", "-s", "10240", "-p", strconv.Itoa(ownPid))
	strace.Stdout = traceOut
	strace.Stderr = traceOut

	err = strace.Start()
	if err != nil {
		fatal(err)
	}
}

func listen(socketPath string) (net.Listener, error) {
	// Delete socketPath if it exists to avoid bind failures.
	err := os.Remove(socketPath)
	if err != nil && !os.IsNotExist(err) {
		return nil, err
	}

	err = os.MkdirAll(filepath.Dir(socketPath), 0755)
	if err != nil {
		return nil, err
	}

	return net.Listen("unix", socketPath)
}

func acceptConnection(listener net.Listener, stdoutR, stderrR, statusR *os.File) (net.Conn, error) {
	conn, err := listener.Accept()
	if err != nil {
		return nil, err
	}

	rights := syscall.UnixRights(
		int(stdoutR.Fd()),
		int(stderrR.Fd()),
		int(statusR.Fd()),
	)

	_, _, err = conn.(*net.UnixConn).WriteMsgUnix([]byte{}, rights, nil)
	if err != nil {
		return nil, err
	}

	return conn, nil
}

// Loop receiving and processing link requests on the given connection.
// The loop terminates when the connection is closed or an error occurs.
func processLinkRequests(conn net.Conn, stdinW *os.File, cmd *exec.Cmd, withTty bool) {
	decoder := gob.NewDecoder(conn)

	for {
		var input linkpkg.Input
		err := decoder.Decode(&input)
		if err != nil {
			break
		}

		if input.WindowSize != nil {
			setWinSize(stdinW, input.WindowSize.Columns, input.WindowSize.Rows)
			cmd.Process.Signal(syscall.SIGWINCH)
		} else if input.EOF {
			stdinW.Sync()
			err := stdinW.Close()
			if withTty {
				cmd.Process.Signal(syscall.SIGHUP)
			}
			if err != nil {
				conn.Close()
				break
			}
		} else {
			_, err := stdinW.Write(input.Data)
			if err != nil {
				conn.Close()
				break
			}
		}
	}
}

func createPipes() (stdinR, stdinW, stdoutR, stdoutW, stderrR, stderrW *os.File, err error) {
	// stderr will not be assigned in the case of a tty, so make
	// a dummy pipe to send across instead
	stderrR, stderrW, err = os.Pipe()
	if err != nil {
		return nil, nil, nil, nil, nil, nil, err
	}

	stdinR, stdinW, err = os.Pipe()
	if err != nil {
		return nil, nil, nil, nil, nil, nil, err
	}

	stdoutR, stdoutW, err = os.Pipe()
	if err != nil {
		return nil, nil, nil, nil, nil, nil, err
	}

	return
}

func createTtyPty(windowColumns int, windowRows int) (stdinR, stdinW, stdoutR, stdoutW, stderrR, stderrW *os.File, err error) {
	// stderr will not be assigned in the case of a tty, so ensure it will return EOF on read
	stderrR, err = os.Open("/dev/null")
	if err != nil {
		return nil, nil, nil, nil, nil, nil, err
	}

	pty, tty, err := pty.Open()
	if err != nil {
		return nil, nil, nil, nil, nil, nil, err
	}

	// do NOT assign stderrR to pty; the receiving end should only receive one
	// pty output stream, as they're both the same fd

	stdinW = pty
	stdoutR = pty

	stdinR = tty
	stdoutW = tty
	stderrW = tty

	setWinSize(stdinW, windowColumns, windowRows)

	return
}


text:
namespace AutoMapper
{
    using System;
    using System.ComponentModel;
    using System.Linq.Expressions;

    /// <summary>
    /// Mapping configuration options for non-generic maps
    /// </summary>
    public interface IMappingExpression
    {
        /// <summary>
        /// Skip normal member mapping and convert using a <see cref="ITypeConverter{TSource,TDestination}"/> instantiated during mapping
        /// </summary>
        /// <typeparam name="TTypeConverter">Type converter type</typeparam>
        void ConvertUsing<TTypeConverter>();

        /// <summary>
        /// Skip normal member mapping and convert using a <see cref="ITypeConverter{TSource,TDestination}"/> instantiated during mapping
        /// Use this method if you need to specify the converter type at runtime
        /// </summary>
        /// <param name="typeConverterType">Type converter type</param>
        void ConvertUsing(Type typeConverterType);

        /// <summary>
        /// Override the destination type mapping for looking up configuration and instantiation
        /// </summary>
        /// <param name="typeOverride"></param>
        void As(Type typeOverride);

        /// <summary>
        /// Assign a profile to the current type map
        /// </summary>
        /// <param name="profileName">Profile name</param>
        /// <returns>Itself</returns>
        IMappingExpression WithProfile(string profileName);

        /// <summary>
        /// Customize individual members
        /// </summary>
        /// <param name="name">Name of the member</param>
        /// <param name="memberOptions">Callback for configuring member</param>
        /// <returns>Itself</returns>
        IMappingExpression ForMember(string name, Action<IMemberConfigurationExpression> memberOptions);

        /// <summary>
        /// Customize configuration for an individual source member
        /// </summary>
        /// <param name="sourceMemberName">Source member name</param>
        /// <param name="memberOptions">Callback for member configuration options</param>
        /// <returns>Itself</returns>
        IMappingExpression ForSourceMember(string sourceMemberName,
            Action<ISourceMemberConfigurationExpression> memberOptions);
    }

    /// <summary>
    /// Mapping configuration options
    /// </summary>
    /// <typeparam name="TSource">Source type</typeparam>
    /// <typeparam name="TDestination">Destination type</typeparam>
    public interface IMappingExpression<TSource, TDestination>
    {
        /// <summary>
        /// Customize configuration for individual member
        /// </summary>
        /// <param name="destinationMember">Expression to the top-level destination member. This must be a member on the <typeparamref name="TDestination"/>TDestination</param> type
        /// <param name="memberOptions">Callback for member options</param>
        /// <returns>Itself</returns>
        IMappingExpression<TSource, TDestination> ForMember(Expression<Func<TDestination, object>> destinationMember,
            Action<IMemberConfigurationExpression<TSource>> memberOptions);

        /// <summary>
        /// Customize configuration for individual member. Used when the name isn't known at compile-time
        /// </summary>
        /// <param name="name">Destination member name</param>
        /// <param name="memberOptions">Callback for member options</param>
        /// <returns></returns>
        IMappingExpression<TSource, TDestination> ForMember(string name,
            Action<IMemberConfigurationExpression<TSource>> memberOptions);

        /// <summary>
        /// Customize configuration for all members
        /// </summary>
        /// <param name="memberOptions">Callback for member options</param>
        void ForAllMembers(Action<IMemberConfigurationExpression<TSource>> memberOptions);

        /// <summary>
        /// Ignores all <typeparamref name="TDestination"/> properties that have either a private or protected setter, forcing the mapper to respect encapsulation (note: order matters, so place this before explicit configuration of any properties with an inaccessible setter)
        /// </summary>
        /// <returns>Itself</returns>
        IMappingExpression<TSource, TDestination> IgnoreAllPropertiesWithAnInaccessibleSetter();

        /// <summary>
        /// When using ReverseMap, ignores all <typeparamref name="TSource"/> properties that have either a private or protected setter, keeping the reverse mapping consistent with the forward mapping (note: <typeparamref name="TDestination"/> properties with an inaccessible setter may still be mapped unless IgnoreAllPropertiesWithAnInaccessibleSetter is also used)
        /// </summary>
        /// <returns>Itself</returns>
        IMappingExpression<TSource, TDestination> IgnoreAllSourcePropertiesWithAnInaccessibleSetter();

        /// <summary>
        /// Include this configuration in derived types' maps
        /// </summary>
        /// <typeparam name="TOtherSource">Derived source type</typeparam>
        /// <typeparam name="TOtherDestination">Derived destination type</typeparam>
        /// <returns>Itself</returns>
        IMappingExpression<TSource, TDestination> Include<TOtherSource, TOtherDestination>()
            where TOtherSource : TSource
            where TOtherDestination : TDestination;

        /// <summary>
        /// Include the base type map's configuration in this map
        /// </summary>
        /// <typeparam name="TSourceBase">Base source type</typeparam>
        /// <typeparam name="TDestinationBase">Base destination type</typeparam>
        /// <returns>Itself</returns>
        IMappingExpression<TSource, TDestination> IncludeBase<TSourceBase, TDestinationBase>();

        /// <summary>
        /// Include this configuration in derived types' maps
        /// </summary>
        /// <param name="derivedSourceType">Derived source type</param>
        /// <param name="derivedDestinationType">Derived destination type</param>
        /// <returns>Itself</returns>
        IMappingExpression<TSource, TDestination> Include(Type derivedSourceType, Type derivedDestinationType);

        /// <summary>
        /// Assign a profile to the current type map
        /// </summary>
        /// <param name="profileName">Name of the profile</param>
        /// <returns>Itself</returns>
        IMappingExpression<TSource, TDestination> WithProfile(string profileName);

        /// <summary>
        /// Skip member mapping and use a custom expression during LINQ projection
        /// </summary>
        /// <param name="projectionExpression">Projection expression</param>
        void ProjectUsing(Expression<Func<TSource, TDestination>> projectionExpression);

        /// <summary>
        /// Skip member mapping and use a custom function to convert to the destination type
        /// </summary>
        /// <param name="mappingFunction">Callback to convert from source type to destination type</param>
        void ConvertUsing(Func<TSource, TDestination> mappingFunction);

        /// <summary>
        /// Skip member mapping and use a custom type converter instance to convert to the destination type
        /// </summary>
        /// <param name="converter">Type converter instance</param>
        void ConvertUsing(ITypeConverter<TSource, TDestination> converter);

        /// <summary>
        /// Skip member mapping and use a custom type converter instance to convert to the destination type
        /// </summary>
        /// <typeparam name="TTypeConverter">Type converter type</typeparam>
        void ConvertUsing<TTypeConverter>() where TTypeConverter : ITypeConverter<TSource, TDestination>;

        /// <summary>
        /// Execute a custom function to the source and/or destination types before member mapping
        /// </summary>
        /// <param name="beforeFunction">Callback for the source/destination types</param>
        /// <returns>Itself</returns>
        IMappingExpression<TSource, TDestination> BeforeMap(Action<TSource, TDestination> beforeFunction);

        /// <summary>
        /// Execute a custom mapping action before member mapping
        /// </summary>
        /// <typeparam name="TMappingAction">Mapping action type instantiated during mapping</typeparam>
        /// <returns>Itself</returns>
        IMappingExpression<TSource, TDestination> BeforeMap<TMappingAction>()
            where TMappingAction : IMappingAction<TSource, TDestination>;

        /// <summary>
        /// Execute a custom function to the source and/or destination types after member mapping
        /// </summary>
        /// <param name="afterFunction">Callback for the source/destination types</param>
        /// <returns>Itself</returns>
        IMappingExpression<TSource, TDestination> AfterMap(Action<TSource, TDestination> afterFunction);

        /// <summary>
        /// Execute a custom mapping action after member mapping
        /// </summary>
        /// <typeparam name="TMappingAction">Mapping action type instantiated during mapping</typeparam>
        /// <returns>Itself</returns>
        IMappingExpression<TSource, TDestination> AfterMap<TMappingAction>()
            where TMappingAction : IMappingAction<TSource, TDestination>;

        /// <summary>
        /// Supply a custom instantiation function for the destination type
        /// </summary>
        /// <param name="ctor">Callback to create the destination type given the source object</param>
        /// <returns>Itself</returns>
        IMappingExpression<TSource, TDestination> ConstructUsing(Func<TSource, TDestination> ctor);

        /// <summary>
        /// Supply a custom instantiation expression for the destination type for LINQ projection
        /// </summary>
        /// <param name="ctor">Callback to create the destination type given the source object</param>
        /// <returns>Itself</returns>
        IMappingExpression<TSource, TDestination> ConstructProjectionUsing(Expression<Func<TSource, TDestination>> ctor);

        /// <summary>
        /// Supply a custom instantiation function for the destination type, based on the entire resolution context
        /// </summary>
        /// <param name="ctor">Callback to create the destination type given the current resolution context</param>
        /// <returns>Itself</returns>
        IMappingExpression<TSource, TDestination> ConstructUsing(Func<ResolutionContext, TDestination> ctor);

        /// <summary>
        /// Override the destination type mapping for looking up configuration and instantiation
        /// </summary>
        /// <typeparam name="T">Destination type to use</typeparam>
        void As<T>();

        /// <summary>
        /// For self-referential types, limit recurse depth
        /// </summary>
        /// <param name="depth">Number of levels to limit to</param>
        /// <returns>Itself</returns>
        IMappingExpression<TSource, TDestination> MaxDepth(int depth);

        /// <summary>
        /// Construct the destination object using the service locator
        /// </summary>
        /// <returns>Itself</returns>
        IMappingExpression<TSource, TDestination> ConstructUsingServiceLocator();

        /// <summary>
        /// Create a type mapping from the destination to the source type, using the <typeparamref name="TDestination"/> members as validation
        /// </summary>
        /// <returns>Itself</returns>
        IMappingExpression<TDestination, TSource> ReverseMap();

        /// <summary>
        /// Customize configuration for an individual source member
        /// </summary>
        /// <param name="sourceMember">Expression to source member. Must be a member of the <typeparamref name="TSource"/> type</param>
        /// <param name="memberOptions">Callback for member configuration options</param>
        /// <returns>Itself</returns>
        IMappingExpression<TSource, TDestination> ForSourceMember(Expression<Func<TSource, object>> sourceMember,
            Action<ISourceMemberConfigurationExpression<TSource>> memberOptions);

        /// <summary>
        /// Customize configuration for an individual source member. Member name not known until runtime
        /// </summary>
        /// <param name="sourceMemberName">Expression to source member. Must be a member of the <typeparamref name="TSource"/> type</param>
        /// <param name="memberOptions">Callback for member configuration options</param>
        /// <returns>Itself</returns>
        IMappingExpression<TSource, TDestination> ForSourceMember(string sourceMemberName,
            Action<ISourceMemberConfigurationExpression<TSource>> memberOptions);

        /// <summary>
        /// Replace the original runtime instance with a new source instance. Useful when ORMs return proxy types with no relationships to runtime types.
        /// The returned source object will be mapped instead of what was supplied in the original source object.
        /// </summary>
        /// <param name="substituteFunc">Substitution function</param>
        /// <returns>New source object to map.</returns>
        IMappingExpression<TSource, TDestination> Substitute(Func<TSource, object> substituteFunc);

        /// <summary>
        /// The current TypeMap being configured
        /// </summary>
        [EditorBrowsable(EditorBrowsableState.Never)]
        TypeMap TypeMap { get; }
    }
}


text:
package com.intellij.refactoring.changeSignature;

import com.intellij.psi.PsiElement;
import org.jetbrains.annotations.NotNull;

/**
 * @author Konstantin Bulenkov
 */
public interface ParameterIndexer {
  void setIndex(@NotNull PsiElement element, int index);

  int getIndex(@NotNull PsiElement element);
}


text:
import collections
import math

import os

WORD_SIZE = 3 # i.e. triplets

class ReadFeature (object):
  '''features of a read'''

  def __init__( self, content, word_size = WORD_SIZE ):
    self.content = content
    self.word_size = word_size
    self.alphabet = min( 4 ** word_size, len(self.content) - word_size)

  def entropy( self ):
    if self.alphabet <= 1:
      return 0

    counts = collections.defaultdict(int)
    words = len(self.content) - self.word_size
    for i in xrange( words ):
      counts[ self.content[i:i+self.word_size] ] += 1 # count how many of each (overlapping) word is in content

    result = 0.
    max_count = max( self.alphabet, words )
    for word in counts:
      p = 1. * counts[word] / max_count
      result -= p * math.log( p, self.alphabet )
      #print "word", word, "result", result, "counts", counts[word], "alphabet", self.alphabet

    return result

  def complexity( self ):
    '''based on dust TODO'''
    pass

  def gc( self ):
    denom = self.content.count('G') + self.content.count('C') + self.content.count('A') + self.content.count('T')
    if denom == 0:
      return None
    else:
      return 1. * ( self.content.count('G') + self.content.count('C') ) / denom

class MapFeature (object):
  '''features of a mapped location'''

  def __init__( self, fasta ):
    '''
      @fasta: ProbabilisticFasta
    '''
    self.fasta = fasta

  def depth( self, position ):
    '''
      number of reads covering the position
      @position: int
    '''
    counts =  self.fasta.count( position )
    return sum( counts.values() )


text:
package org.hisp.dhis.analytics.event.data;

import static java.util.stream.Collectors.joining;
import static org.apache.commons.lang3.StringUtils.EMPTY;
import static org.hisp.dhis.analytics.DataType.BOOLEAN;
import static org.hisp.dhis.analytics.event.data.OrgUnitTableJoiner.joinOrgUnitTables;
import static org.hisp.dhis.analytics.util.AnalyticsSqlUtils.ANALYTICS_TBL_ALIAS;
import static org.hisp.dhis.analytics.util.AnalyticsSqlUtils.encode;
import static org.hisp.dhis.analytics.util.AnalyticsSqlUtils.getCoalesce;
import static org.hisp.dhis.analytics.util.AnalyticsSqlUtils.quote;
import static org.hisp.dhis.analytics.util.AnalyticsSqlUtils.quoteAlias;
import static org.hisp.dhis.common.DimensionItemType.DATA_ELEMENT;
import static org.hisp.dhis.common.DimensionalObject.ORGUNIT_DIM_ID;
import static org.hisp.dhis.common.IdentifiableObjectUtils.getUids;
import static org.hisp.dhis.commons.util.TextUtils.getQuotedCommaDelimitedString;
import static org.hisp.dhis.commons.util.TextUtils.removeLastOr;

import java.util.Date;
import java.util.List;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;
import org.hisp.dhis.analytics.analyze.ExecutionPlanStore;
import org.hisp.dhis.analytics.event.EnrollmentAnalyticsManager;
import org.hisp.dhis.analytics.event.EventQueryParams;
import org.hisp.dhis.analytics.event.ProgramIndicatorSubqueryBuilder;
import org.hisp.dhis.analytics.util.AnalyticsUtils;
import org.hisp.dhis.common.DimensionType;
import org.hisp.dhis.common.DimensionalItemObject;
import org.hisp.dhis.common.DimensionalObject;
import org.hisp.dhis.common.Grid;
import org.hisp.dhis.common.OrganisationUnitSelectionMode;
import org.hisp.dhis.common.QueryItem;
import org.hisp.dhis.common.QueryRuntimeException;
import org.hisp.dhis.common.ValueType;
import org.hisp.dhis.commons.collection.ListUtils;
import org.hisp.dhis.commons.util.ExpressionUtils;
import org.hisp.dhis.commons.util.SqlHelper;
import org.hisp.dhis.feedback.ErrorCode;
import org.hisp.dhis.jdbc.StatementBuilder;
import org.hisp.dhis.organisationunit.OrganisationUnit;
import org.hisp.dhis.program.AnalyticsType;
import org.hisp.dhis.program.ProgramIndicatorService;
import org.hisp.dhis.system.util.SqlUtils;
import org.hisp.dhis.util.DateUtils;
import org.locationtech.jts.util.Assert;
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.rowset.SqlRowSet;
import org.springframework.stereotype.Component;

import com.google.common.collect.Lists;
import com.google.common.collect.Sets;

/**
 * @author Markus Bekken
 */
@Slf4j
@Component( "org.hisp.dhis.analytics.event.EnrollmentAnalyticsManager" )
public class JdbcEnrollmentAnalyticsManager
    extends AbstractJdbcEventAnalyticsManager
    implements EnrollmentAnalyticsManager
{
    private final EnrollmentTimeFieldSqlRenderer timeFieldSqlRenderer;

    private static final String ANALYTICS_EVENT = "analytics_event_";

    private static final String ORDER_BY_EXECUTION_DATE = "order by executiondate ";

    private static final String LIMIT_1 = "limit 1";

    private static final String IS_NOT_NULL = " is not null ";

    private List<String> COLUMNS = Lists.newArrayList( "pi", "tei", "enrollmentdate", "incidentdate",
        "storedby", "createdbydisplayname", "lastupdatedbydisplayname", "lastupdated",
        "ST_AsGeoJSON(pigeometry)", "longitude", "latitude",
        "ouname", "oucode", "enrollmentstatus" );

    public JdbcEnrollmentAnalyticsManager( JdbcTemplate jdbcTemplate, StatementBuilder statementBuilder,
        ProgramIndicatorService programIndicatorService,
        ProgramIndicatorSubqueryBuilder programIndicatorSubqueryBuilder,
        EnrollmentTimeFieldSqlRenderer timeFieldSqlRenderer, ExecutionPlanStore executionPlanStore )
    {
        super( jdbcTemplate, statementBuilder, programIndicatorService,
            programIndicatorSubqueryBuilder, executionPlanStore );
        this.timeFieldSqlRenderer = timeFieldSqlRenderer;
    }

    @Override
    public void getEnrollments( EventQueryParams params, Grid grid, int maxLimit )
    {
        String sql = getEventsOrEnrollmentsSql( params, maxLimit );

        if ( params.analyzeOnly() )
        {
            executionPlanStore.addExecutionPlan( params.getExplainOrderId(), sql );
        }
        else
        {
            withExceptionHandling( () -> getEnrollments( params, grid, sql ) );
        }
    }

    /**
     * Adds enrollments to the given grid based on the given parameters and SQL
     * statement.
     *
     * @param params the {@link EventQueryParams}.
     * @param grid the {@link Grid}.
     * @param sql the SQL statement used to retrieve events.
     */
    private void getEnrollments( EventQueryParams params, Grid grid, String sql )
    {
        log.debug( String.format( "Analytics enrollment query SQL: %s", sql ) );

        SqlRowSet rowSet = jdbcTemplate.queryForRowSet( sql );

        int rowsRed = 0;

        grid.setLastDataRow( true );

        while ( rowSet.next() )
        {
            if ( ++rowsRed > params.getPageSizeWithDefault() && !params.isTotalPages() )
            {
                grid.setLastDataRow( false );

                continue;
            }

            grid.addRow();

            for ( int i = 0; i < grid.getHeaders().size(); ++i )
            {
                addGridValue( grid, grid.getHeaders().get( i ), i + 1, rowSet, params );
            }
        }
    }

    @Override
    public long getEnrollmentCount( EventQueryParams params )
    {
        String sql = "select count(pi) ";

        sql += getFromClause( params );

        sql += getWhereClause( params );

        long count = 0;

        try
        {
            log.debug( "Analytics enrollment count SQL: " + sql );

            if ( params.analyzeOnly() )
            {
                executionPlanStore.addExecutionPlan( params.getExplainOrderId(), sql );
            }
            else
            {
                count = jdbcTemplate.queryForObject( sql, Long.class );
            }
        }
        catch ( BadSqlGrammarException ex )
        {
            log.info( AnalyticsUtils.ERR_MSG_TABLE_NOT_EXISTING, ex );
        }
        catch ( DataAccessResourceFailureException ex )
        {
            log.warn( ErrorCode.E7131.getMessage(), ex );
            throw new QueryRuntimeException( ErrorCode.E7131 );
        }

        return count;
    }

    /**
     * Returns a from SQL clause for the given analytics table partition.
     *
     * @param params the {@link EventQueryParams}.
     */
    @Override
    protected String getFromClause( EventQueryParams params )
    {
        return " from " + params.getTableName() + " as " + ANALYTICS_TBL_ALIAS + " " +
            joinOrgUnitTables( params, getAnalyticsType() );
    }

    /**
     * Returns a from and where SQL clause. If this is a program indicator with
     * non-default boundaries, the relationship with the reporting period is
     * specified with where conditions on the enrollment or incident dates. If
     * the default boundaries is used, or the params does not include program
     * indicators, the periods are joined in from the analytics tables the
     * normal way. A where clause can never have a mix of indicators with
     * non-default boundaries and regular analytics table periods.
     *
     * @param params the {@link EventQueryParams}.
     */
    @Override
    protected String getWhereClause( EventQueryParams params )
    {
        String sql = "";
        SqlHelper hlp = new SqlHelper();

        // ---------------------------------------------------------------------
        // Periods
        // ---------------------------------------------------------------------

        sql += hlp.whereAnd() + " " + timeFieldSqlRenderer.renderTimeFieldSql( params );

        // ---------------------------------------------------------------------
        // Organisation units
        // ---------------------------------------------------------------------

        if ( params.isOrganisationUnitMode( OrganisationUnitSelectionMode.SELECTED ) )
        {
            sql += hlp.whereAnd() + " ou in ("
                + getQuotedCommaDelimitedString( getUids( params.getDimensionOrFilterItems( ORGUNIT_DIM_ID ) ) ) + ") ";
        }
        else if ( params.isOrganisationUnitMode( OrganisationUnitSelectionMode.CHILDREN ) )
        {
            sql += hlp.whereAnd() + " ou in ("
                + getQuotedCommaDelimitedString( getUids( params.getOrganisationUnitChildren() ) ) + ") ";
        }
        else // Descendants
        {
            sql += hlp.whereAnd() + " (";

            for ( DimensionalItemObject object : params.getDimensionOrFilterItems( ORGUNIT_DIM_ID ) )
            {
                OrganisationUnit unit = (OrganisationUnit) object;
                sql += params.getOrgUnitField().getOrgUnitLevelCol( unit.getLevel(), getAnalyticsType() )
                    + " = '" + unit.getUid() + "' or ";
            }

            sql = removeLastOr( sql ) + ") ";
        }

        // ---------------------------------------------------------------------
        // Organisation unit group sets
        // ---------------------------------------------------------------------

        List<DimensionalObject> dynamicDimensions = params.getDimensionsAndFilters(
            Sets.newHashSet( DimensionType.CATEGORY ) );

        for ( DimensionalObject dim : dynamicDimensions )
        {
            String col = quoteAlias( dim.getDimensionName() );

            sql += "and " + col + " in (" + getQuotedCommaDelimitedString( getUids( dim.getItems() ) ) + ") ";
        }

        dynamicDimensions = params
            .getDimensionsAndFilters( Sets.newHashSet( DimensionType.ORGANISATION_UNIT_GROUP_SET ) );

        for ( DimensionalObject dim : dynamicDimensions )
        {
            if ( !dim.isAllItems() )
            {
                String col = quoteAlias( dim.getDimensionName() );

                sql += "and " + col + " in (" + getQuotedCommaDelimitedString( getUids( dim.getItems() ) ) + ") ";
            }
        }

        // ---------------------------------------------------------------------
        // Program stage
        // ---------------------------------------------------------------------

        if ( params.hasProgramStage() )
        {
            sql += "and ps = '" + params.getProgramStage().getUid() + "' ";
        }

        // ---------------------------------------------------------------------
        // Query items and filters
        // ---------------------------------------------------------------------

        sql += getStatementForDimensionsAndFilters( params, hlp );

        // ---------------------------------------------------------------------
        // Filter expression
        // ---------------------------------------------------------------------

        if ( params.hasProgramIndicatorDimension() && params.getProgramIndicator().hasFilter() )
        {
            String filter = programIndicatorService.getAnalyticsSql( params.getProgramIndicator().getFilter(),
                BOOLEAN, params.getProgramIndicator(), params.getEarliestStartDate(), params.getLatestEndDate() );

            String sqlFilter = ExpressionUtils.asSql( filter );

            sql += "and (" + sqlFilter + ") ";
        }

        // ---------------------------------------------------------------------
        // Various filters
        // ---------------------------------------------------------------------

        if ( params.hasProgramStatus() )
        {
            sql += "and enrollmentstatus in ("
                + params.getProgramStatus().stream().map( p -> encode( p.name(), true ) )
                    .collect( joining( "," ) )
                + ") ";
        }

        if ( params.isCoordinatesOnly() )
        {
            sql += "and (longitude is not null and latitude is not null) ";
        }

        if ( params.isGeometryOnly() )
        {
            sql += "and " + getCoalesce( params.getCoordinateFields() ) + IS_NOT_NULL;
        }

        if ( params.isCompletedOnly() )
        {
            sql += "and completeddate is not null ";
        }

        if ( params.hasBbox() )
        {
            sql += "and " + getCoalesce( params.getCoordinateFields() ) + " && ST_MakeEnvelope(" + params.getBbox()
                + ",4326) ";
        }

        return sql;
    }

    @Override
    protected String getSelectClause( EventQueryParams params )
    {
        List<String> selectCols = ListUtils.distinctUnion( COLUMNS, getSelectColumns( params, false ) );

        return "select " + StringUtils.join( selectCols, "," ) + " ";
    }

    /**
     * Returns an encoded column name respecting the geometry/coordinate format.
     * The given QueryItem must be of type COORDINATE.
     *
     * @param item the {@link QueryItem}
     * @return the column selector (SQL query) or EMPTY if the item valueType is
     *         not COORDINATE.
     *
     * @throws NullPointerException if item is null
     */
    @Override
    protected ColumnAndAlias getCoordinateColumn( QueryItem item )
    {
        return getCoordinateColumn( item, null );
    }

    /**
     * Returns an encoded column name respecting the geometry/coordinate format.
     * The given QueryItem can be of type COORDINATE or ORGANISATION_UNIT.
     *
     * @param suffix is currently ignored. Not currently used for enrollments
     * @param item the {@link QueryItem}
     * @return the column selector (SQL query) or EMPTY if the item valueType is
     *         not COORDINATE.
     *
     * @throws NullPointerException if item is null
     */
    @Override
    protected ColumnAndAlias getCoordinateColumn( QueryItem item, String suffix )
    {
        if ( item.getProgram() != null )
        {
            String eventTableName = ANALYTICS_EVENT + item.getProgram().getUid();
            String colName = quote( item.getItemId() );

            String psCondition = "";

            if ( item.hasProgramStage() )
            {
                assertProgram( item );

                psCondition = "and ps = '" + item.getProgramStage().getUid() + "' ";
            }

            String stCentroidFunction = "";

            if ( ValueType.ORGANISATION_UNIT == item.getValueType() )
            {
                stCentroidFunction = "ST_Centroid";

            }

            String alias = getAlias( item ).orElse( null );

            return ColumnAndAlias.ofColumnAndAlias( "(select '[' || round(ST_X(" + stCentroidFunction + "(" + colName
                + "))::numeric, 6) || ',' || round(ST_Y("
                + stCentroidFunction + "(" + colName + "))::numeric, 6) || ']' as " + colName
                + " from " + eventTableName
                + " where " + eventTableName + ".pi = " + ANALYTICS_TBL_ALIAS + ".pi " +
                "and " + colName + IS_NOT_NULL + psCondition + ORDER_BY_EXECUTION_DATE +
                createOrderTypeAndOffset( item.getProgramStageOffset() ) + " " + LIMIT_1 + " )",
                alias );
        }

        return ColumnAndAlias.EMPTY;
    }

    /**
     * Creates a column "selector" for the given item name. The suffix will be
     * appended as part of the item name. The column selection is based on
     * events analytics tables.
     *
     * @param item the {@link QueryItem}
     * @param suffix to be appended to the item name (column)
     * @return when there is a program stage: returns the column select
     *         statement for the given item and suffix, otherwise returns the
     *         item name quoted and prefixed with the table prefix. ie.:
     *         ax."enrollmentdate"
     */
    @Override
    protected String getColumn( QueryItem item, String suffix )
    {
        String colName = item.getItemName();
        String alias = EMPTY;

        if ( item.hasProgramStage() )
        {
            assertProgram( item );

            colName = quote( colName + suffix );

            String eventTableName = ANALYTICS_EVENT + item.getProgram().getUid();

            if ( item.getProgramStage().getRepeatable() &&
                item.hasRepeatableStageParams() && !item.getRepeatableStageParams().simpleStageValueExpected() )
            {
                return "(select json_agg(t1) from (select " + colName + ", incidentdate, duedate, executiondate "
                    + " from " + eventTableName
                    + " where " + eventTableName + ".pi = " + ANALYTICS_TBL_ALIAS + ".pi "
                    + "and ps = '" + item.getProgramStage().getUid() + "'"
                    + getExecutionDateFilter( item.getRepeatableStageParams().getStartDate(),
                        item.getRepeatableStageParams().getEndDate() )
                    + ORDER_BY_EXECUTION_DATE + createOrderTypeAndOffset( item.getProgramStageOffset() )
                    + getLimit( item.getRepeatableStageParams().getCount() ) + " ) as t1)";

            }

            if ( item.getProgramStage().getRepeatable() && item.hasRepeatableStageParams() )
            {
                return "(select " + colName
                    + " from " + eventTableName
                    + " where " + eventTableName + ".pi = " + ANALYTICS_TBL_ALIAS + ".pi "
                    + "and ps = '" + item.getProgramStage().getUid() + "' "
                    + getExecutionDateFilter( item.getRepeatableStageParams().getStartDate(),
                        item.getRepeatableStageParams().getEndDate() )
                    + ORDER_BY_EXECUTION_DATE + createOrderTypeAndOffset( item.getProgramStageOffset() )
                    + " " + LIMIT_1 + " )";
            }

            if ( item.getItem().getDimensionItemType() == DATA_ELEMENT && item.getProgramStage() != null )
            {
                alias = " as " + quote( item.getProgramStage().getUid() + "." + item.getItem().getUid() );
            }

            return "(select " + colName + alias
                + " from " + eventTableName
                + " where " + eventTableName + ".pi = " + ANALYTICS_TBL_ALIAS + ".pi "
                + "and " + colName + IS_NOT_NULL + "and ps = '" + item.getProgramStage().getUid() + "' "
                + ORDER_BY_EXECUTION_DATE + createOrderTypeAndOffset( item.getProgramStageOffset() )
                + " " + LIMIT_1 + " )";
        }
        else
        {
            return quoteAlias( colName );
        }
    }

    /**
     * Returns an encoded column name wrapped in lower directive if not numeric
     * or boolean.
     *
     * @param item the {@link QueryItem}.
     */
    @Override
    protected String getColumn( QueryItem item )
    {
        return getColumn( item, "" );
    }

    private static String getExecutionDateFilter( Date startDate, Date endDate )
    {
        StringBuilder sb = new StringBuilder();

        if ( startDate != null )
        {
            sb.append( " and executiondate >= " );

            sb.append( String.format( "%s ", SqlUtils.singleQuote( DateUtils.getMediumDateString( startDate ) ) ) );
        }

        if ( endDate != null )
        {
            sb.append( " and executiondate <= " );

            sb.append( String.format( "%s ", SqlUtils.singleQuote( DateUtils.getMediumDateString( endDate ) ) ) );
        }

        return sb.toString();
    }

    private static String getLimit( int count )
    {
        if ( count == Integer.MAX_VALUE )
        {
            return "";
        }

        return " LIMIT " + count;
    }

    private void assertProgram( QueryItem item )
    {
        Assert.isTrue( item.hasProgram(),
            "Can not query item with program stage but no program:" + item.getItemName() );
    }

    @Override
    protected AnalyticsType getAnalyticsType()
    {
        return AnalyticsType.ENROLLMENT;
    }

    private String createOrderTypeAndOffset( int offset )
    {
        if ( offset == 0 )
        {
            return "desc";
        }
        if ( offset < 0 )
        {
            return "desc offset " + (-1 * offset);
        }
        else
        {
            return "asc offset " + (offset - 1);
        }
    }
}


text:
{% extends "base.html" %}
{% block title %}Search | Results{% endblock %}
{% block content %}
{% if pagination.count == 0 %}

😿  can not find anything matching <q class="hey-look">{{ query|e }}</q>

{% else %}

{% if pagination.total == 1 %}
There is one place matching <q class="hey-look">{{ query.decode('utf-8') |e }}</q>
{% else %}
There are {{ pagination.total|e }} places matching <q class="hey-look">{{ query.decode('utf-8') |e }}</q>
{% if pagination.pages > 1 %}
and this page {{ pagination.page|e }} of {{ pagination.pages|e }}
{% endif %}
{% endif %}

{% include "inc_docs.html" %}

{% endif %}

{% endblock %}


text:
package org.sfm.jdbc;

import org.junit.Test;
import org.sfm.beans.Bar;
import org.sfm.beans.Foo;
import org.sfm.beans.Pair;
import org.sfm.reflect.TypeReference;
import org.sfm.test.jdbc.DbHelper;
import org.sfm.test.jdbc.TestRowHandler;

import java.sql.PreparedStatement;
import java.sql.ResultSet;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

public class JdbcMapperPairObjectTest {

	private static final String QUERY = "select "
			+ "'first_bar' as first_bar, "
			+ "'second_bar' as second_bar, "
			+ "'second_foo' as second_foo "
			+ "from TEST_DB_OBJECT where id = 1 ";

	@Test
	public void testMapGenericObjectWithStaticMapper() throws Exception {
		JdbcMapperBuilder<Pair<Bar, Foo>> builder = JdbcMapperFactoryHelper.asm().newBuilder(new TypeReference<Pair<Bar, Foo>>() {
        })
                .addMapping("first_bar")
                .addMapping("second_bar")
                .addMapping("second_foo");

		final JdbcMapper<Pair<Bar, Foo>> mapper = builder.mapper();

		DbHelper.testQuery(new TestRowHandler<PreparedStatement>() {
			@Override
			public void handle(PreparedStatement t) throws Exception {
				ResultSet rs = t.executeQuery();
				rs.next();
				Pair<Bar, Foo> object = mapper.map(rs);
				assertNotNull(object);
				assertNotNull(object.getFirst());
				assertEquals("first_bar", object.getFirst().getBar());
				assertNotNull(object.getSecond());
				assertEquals("second_bar", object.getSecond().getBar());
				assertEquals("second_foo", object.getSecond().getFoo());
			}
		}, QUERY);
	}
}


text:
const { send } = require("micro");
const Boom = require("@hapi/boom");
const Raven = require("raven");

module.exports = exports = url => fn => {
  if (!url) throw Error("micro-sentry must be initialized with a Sentry DSN.");

  if (!fn || typeof fn !== "function")
    throw Error("micro-sentry must be passed a function.");

  Raven.config(url).install();
  return async function(request, response) {
    try {
      return await fn(request, response);
    } catch (error) {
      Raven.captureException(error);
      let status = response.statusCode;
      if (status < 400) status = 500;
      const err = Boom.boomify(error, { statusCode: status });
      send(
        response,
        status,
        Object.assign({}, err.output.payload, err.data && { data: err.data })
      );
    }
  };
};


text:
xbuild Common/Common.csproj
xbuild Production/Production.csproj


text:
package akka.japi.pf

import scala.runtime.BoxedUnit
import akka.actor.AbstractActor
import akka.actor.AbstractActor.Receive

object ReceiveBuilder {

  def create() : ReceiveBuilder = new ReceiveBuilder()

}

class ReceiveBuilder {

  private var statements: PartialFunction[Any, BoxedUnit] = null

  protected def addStatement(statement : PartialFunction[Any, BoxedUnit]): Unit = {
    if (statements == null)
      statements = statement
    else
      statements = statements.orElse(statement)
  }

  def build() : Receive = {
    val empty = CaseStatement.empty()

    if (statements == null)
      new Receive(empty)
    else
      new Receive(statements.orElse(empty)) // FIXME why no new Receive(statements)?
  }

}


text:
package main

import (
	"flag"
	"fmt"
	"os"

	"text/template"

	"github.com/kyokomi/gogen"
)

var (
	// command line flags
	out  string // output file
	file string // input file (or directory)
	pkg  string // output package name

)

var (
	baseTemplateText = `
// Sample sample code
func ({{.Varname}} *{{.Value.Struct.Name}}) Sample() {
	{{range .Value.Struct.Fields}}
	fmt.Println({{.FieldElem.Varname}})
	{{end}}
}
`
	sampleTemplate = template.Must(template.New("base").Parse(baseTemplateText))
)

func init() {
	flag.StringVar(&out, "o", "", "output file")
	flag.StringVar(&file, "file", os.Getenv("GOFILE"), "input file")
	flag.StringVar(&pkg, "pkg", os.Getenv("GOPACKAGE"), "output package")
}

func main() {
	flag.Parse()

	if file == "" {
		fmt.Println("No file to parse.")
		os.Exit(1)
	}

	g := gogen.NewGenerator(file, out, pkg, "fmt")

	err := g.DoAllTemplate(sampleTemplate)

	if err != nil {
		fmt.Println(err.Error())
		os.Exit(1)
	}
}


text:
/**
 * @fileoverview NetworkClient - Broadcast/listen on network
 *
 * @author Tony Parisi
 */
goog.provide('SB.NetworkClient');
goog.require('SB.Component');

SB.NetworkClient = function(param)
{
	this.param = param || {};

    SB.Component.call(this);
    this.running = false;
}

goog.inherits(SB.NetworkClient, SB.Component);

SB.NetworkClient.prototype.realize = function()
{
	SB.Component.prototype.realize.call(this);
}

SB.NetworkClient.prototype.start = function()
{
    this.running = true;
}

SB.NetworkClient.prototype.stop = function(x, y)
{
    this.running = false;
}

SB.NetworkClient.prototype.update = function()
{
    if (!this.running)
    {
        return;
    }
}


text:
<title>Inserting Code</title>
<link rel="stylesheet" href="theme/style.css" type="text/css">
<link rel="prev" href="adding_new_methods.html">

      Inserting Code

You can insert arbitrary code in the generated cpps, just use the functions
<tt>declaration_code</tt> and <tt>module_code</tt>. This will insert the given string in the
respective sections. Example:

    ##file A.pyste
    Class("A", "A.h")
    declaration_code("/* declaration_code() comes here */\n")
    module_code("/* module_code() comes here */\n")

Will generate:

    // Includes ====================================================================
    #include <boost/python.hpp>

    // Using =======================================================================
    using namespace boost::python;

    // Declarations ================================================================

    /* declaration_code() comes here */

    // Module ======================================================================
    BOOST_PYTHON_MODULE(A)
    {
        class_< A >("A", init<  >())
            .def(init< const A& >())
        ;

    /* module_code() comes here */
    }

Copyright © 2003 Bruno da Silva de Oliveira
Copyright © 2002-2003 Joel de Guzman

Distributed under
  the Boost Software License, Version 1.0. (See accompanying file
  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="generator" content="rustdoc">
    <meta name="description" content="API documentation for the Rust `MsQueue` struct in crate `crossbeam`.">
    <meta name="keywords" content="rust, rustlang, rust-lang, MsQueue">

    <title>crossbeam::sync::MsQueue - Rust</title>

    <link rel="stylesheet" type="text/css" href="../../normalize.css">
    <link rel="stylesheet" type="text/css" href="../../rustdoc.css">
    <link rel="stylesheet" type="text/css" href="../../main.css">

crossbeam::<wbr>sync

        <form class="search-form js-only">

                <input class="search-input" name="search"
                       autocomplete="off"
                       placeholder="Click or press 'S' to search, '?' for more options…"
                       type="search">

        </form>

Struct crossbeam::<wbr>sync::<wbr>MsQueue

                       [−]

               [src]

pub struct MsQueue<T> { /* fields omitted */ }

A Michael-Scott lock-free queue, with support for blocking pops.

Usable with any number of producers and consumers.

Methods

impl<T> MsQueue<T>

[src]

fn new() -> MsQueue<T>

Create a new, empty queue.

fn push(&self, t: T)

Add t to the back of the queue, possibly waking up threads
blocked on pop.

fn is_empty(&self) -> bool

Check if this queue is empty.

fn try_pop(&self) -> Option<T>

Attempt to dequeue from the front.

Returns None if the queue is observed to be empty.

fn pop(&self) -> T

Dequeue an element from the front of the queue, blocking if the queue is
empty.

Trait Implementations

impl<T: Debug> Debug for MsQueue<T>

[src]

fn fmt(&self, __arg_0: &mut Formatter) -> Result

Formats the value using the given formatter.

impl<T: Send> Sync for MsQueue<T>

[src]

impl<T: Send> Send for MsQueue<T>

[src]

Help

Keyboard Shortcuts

?

Show this help dialog

S

Focus the search field

⇤

Move up in search results

⇥

Move down in search results

⏎

Go to active search result

+

Collapse/expand all sections

Search Tricks

                    Prefix searches with a type followed by a colon (e.g.
                    fn:) to restrict the search to a given type.

                    Accepted types are: fn, mod,
                    struct, enum,
                    trait, type, macro,
                    and const.

                    Search functions by type signature (e.g.
                    vec -> usize or * -> vec)


text:
<!--
Copyright (c) 2014 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE
The complete set of authors may be found at http://polymer.github.io/AUTHORS
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS
--><!--
/**
 * core-input is an unstyled single- or multi-line text field where user can
 * enter input.
 *
 * Example:
 *
 *     <core-input placeholder="Placeholder text here"></core-input>
 *
 *     <core-input multiline placeholder="Enter multiple lines here"></core-input>
 *
 * The text input's value is considered "committed" if the user hits the "enter"
 * key or blurs the input after changing the value. The `change` event is fired
 * when the value becomes committed, and the committed value is stored in the
 * `value` property. The current value of the input is stored in the `inputValue`
 * property.
 *
 * Validation
 * ----------
 *
 * core-input can optionally validate the value using the HTML5 constraints API,
 * similar to native inputs. There are two methods to enable input validation:
 *
 * 1. By setting the `type` attribute. For example, setting it to `email` will
 *    check the value is a valid email, and setting it to `number` will check
 *    the input is a number.
 *
 * 2. By setting attributes related to validation. The attributes are `pattern`,
 *    `min`, `max`, `step` and `required`.
 *
 * Only `required` is supported for multiline inputs currently.
 *
 * Example:
 *
 *     <core-input type="email" placeholder="enter your email"></core-input>
 *
 *     <core-input type="number" min="5" placeholder="enter a number greater than or equal to 5"></core-input>
 *
 *     <core-input pattern=".*abc.*" placeholder="enter something containing 'abc'"></core-input>
 *
 * See https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/HTML5/Constraint_validation
 * for more info on validation.
 *
 * @group Polymer Core Elements
 * @element core-input
 * @homepage github.io
 */
--><!--
Fired when the inputValue of is changed. This is the same event as the DOM
"input" event.

@event input
--><!--
Fired when the user commits the value of the input, either by the hitting the
`enter` key or blurring the input after the changing the inputValue. Also see the
DOM "change" event.

@event change
--><!--
Fired when the inputValue of this text input changes and fails validation.

@event input-invalid
@param {Object} detail
@param {string} value The text input's inputValue.
--><!--
Fired when the inputValue of this text input changes and passes validation.

@event input-valid
@param {Object} detail
@param {string} value The text input's inputValue.
--><html><head><link href="../polymer/polymer.html" rel="import">

</head><body><polymer-element name="core-input" on-focus="{{focusAction}}">

  <template>

    <link href="core-input.css" rel="stylesheet">

    <template if="{{multiline}}">
      <textarea id="input" value="{{inputValue}}" rows="{{rows}}" fit?="{{rows === 'fit'}}" disabled?="{{disabled}}" placeholder="{{placeholder}}" autofocus?="{{autofocus}}" required?="{{required}}" readonly?="{{readonly}}" aria-label="{{label || placeholder}}" aria-invalid="{{invalid}}" on-change="{{inputChangeAction}}" on-focus="{{inputFocusAction}}" on-blur="{{inputBlurAction}}"></textarea>
    </template>

    <template if="{{!multiline}}">
      <input id="input" value="{{inputValue}}" disabled?="{{disabled}}" type="{{type}}" placeholder="{{placeholder}}" autofocus?="{{autofocus}}" required?="{{required}}" readonly?="{{readonly}}" pattern="{{pattern}}" min="{{min}}" max="{{max}}" step="{{step}}" maxlength="{{maxlength}}" aria-label="{{label || placeholder}}" aria-invalid="{{invalid}}" on-keydown="{{keydownAction}}" on-change="{{inputChangeAction}}" on-focus="{{inputFocusAction}}" on-blur="{{inputBlurAction}}">
    </template>

  </template>

  <script src="core-input.html.0.js"></script>

</polymer-element>
</body></html>


text:
package com.playfab;

import java.util.HashMap;
import java.util.Date;

public class ItemPuchaseRequest
{

	/// <summary>
	/// unique ItemId of the item to purchase
	/// </summary>

	public String ItemId;

	/// <summary>
	/// how many of this item to purchase
	/// </summary>

	public Integer Quantity;

	/// <summary>
	/// title-specific text concerning this purchase
	/// </summary>

	public String Annotation;

	/// <summary>
	/// items to be upgraded as a result of this purchase (upgraded items are hidden, as they are "replaced" by the new items)
	/// </summary>

	public String[] UpgradeFromItems;
}


text:
package utils

import (
	"fmt"
	"os"

	"github.com/astaxie/beego/logs"
	"github.com/zhangjunfang/softwareScaffolding/codeGenerator/vender/lib"
)

func Write() {
	f1, err := os.OpenFile(lib.Src()+lib.HeadToUpper(lib.GetDBName())+"/utils/log.go", os.O_RDWR, 0766)
	if err != nil {
		logs.Error(err.Error())
	}
	_, err = f1.WriteString(fmt.Sprintf(`
	package utils

	import (
		"fmt"

		"github.com/astaxie/beego/logs"
	)

	/**
	*@param status string ["Success","Error","Warn","Info"]
	*@param msg
	*@param level []
	*@SaveFile /logs/[status].log
	*/

	func ToLog(status string, msg string, level int) {
		logs.SetLogger(logs.AdapterFile, fmt.Sprintf("{\"filename\":\"logs/%s.log\",\"level\":%d}", status, level))
		switch status {
		case "Error":
			logs.Error(msg)
		case "Success":
			logs.Notice(msg)
		case "Warn":
			logs.Warning(msg)
		case "Info":
			logs.Informational(msg)
		default:
			logs.Debug(msg)
		}
	}
	`))
	f1.Close()
	lib.GoFmt(lib.Src() + lib.HeadToUpper(lib.GetDBName()) + "/utils/tpl.go")

	f2, err := os.OpenFile(lib.Src()+lib.HeadToUpper(lib.GetDBName())+"/utils/tpl.go", os.O_RDWR, 0766)
	if err != nil {
		logs.Error(err.Error())
	}
	_, err = f2.WriteString(fmt.Sprintf(`
	package utils

	type Tpl struct {
		Attributes map[string]string
		Action     string
		Danger     interface{}
		Model      interface{}
		Success    interface{}
		Title      string
	}
	`))
	f2.Close()
	lib.GoFmt(lib.Src() + lib.HeadToUpper(lib.GetDBName()) + "/utils/tpl.go")
}


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

import java.io.Reader;
import java.io.Writer;

import org.activiti.engine.impl.util.json.JSONObject;

/**
 * @author Tom Baeyens
 */
public abstract class JsonObjectConverter <T> {

  public void toJson(T object, Writer writer) {
    toJsonObject(object).write(writer);
  }

  public String toJson(T object) {
    return toJsonObject(object).toString();
  }

  public String toJson(T object, int indentFactor) {
    return toJsonObject(object).toString(indentFactor);
  }

  public abstract JSONObject toJsonObject(T object);
  public abstract T toObject(Reader reader);
}


text:
define(['mithril', 'lodash', 'string-plus', 'models/validatable_mixin', 'models/model_mixins'], function (m, _, s, Validatable, Mixins) {
  describe('Validatable', function () {
    describe('errors', function () {
      var Material = function (data) {
        Validatable.call(this, data);
      };

      it('should map errors', function () {
        var material = new Material({errors: {url: ["Cannot be blank"]}});

        expect(material.errors()._isEmpty()).toBe(false);
        expect(material.errors().errors('url')).toEqual(["Cannot be blank"]);
      });
    });

    describe('validatePresenceOf', function () {
      var Material = function (data) {
        Validatable.call(this, data);
        this.name = m.prop('');

        this.validatePresenceOf('name');
      };

      it('should validate the presence of a given field', function () {
        var material = new Material({});

        material.validate();

        expect(material.errors()._isEmpty()).toBe(false);
        expect(material.errors().errors('name')).toEqual(['Name must be present']);
      });

      it('should be conditional', function () {
        var EnvVariable = function (data) {
          Validatable.call(this, data);
          this.name = m.prop('');
          this.value = m.prop('');

          this.validatePresenceOf('value', {condition: function (variable) {return !s.isBlank(variable.name());}});
        };

        var variable = new EnvVariable({});

        variable.validate();

        expect(variable.errors()._isEmpty()).toBe(true);
      });
    });

    describe('validateUniquenessOf', function () {
      var Variables = function (data) {
        Mixins.HasMany.call(this, {
          factory: Variables.Variable.create,
          as: 'Variable',
          collection: data,
          uniqueOn: 'name'
        });
      };

      Variables.Variable = function (data) {
        Validatable.call(this, data);

        this.key = m.prop(data.key);
        this.parent = Mixins.GetterSetter();

        this.validateUniquenessOf('key');
      };

      it('should validate uniqueness of a given field', function () {
        var var1 = new Variables.Variable({key: 'name'});
        var var2 = new Variables.Variable({key: 'name'});
        var variables = new Variables([var1, var2]);
        var1.parent(variables);
        var1.parent(variables);

        var1.validate();

        expect(var1.errors()._isEmpty()).toBe(false);
        expect(var1.errors().errors('key')).toEqual(["Key is a duplicate"]);
      });

      it('should skip validation in absence of parent', function () {
        var variable = new Variables.Variable({key: 'name'});

        variable.validate();

        expect(variable.errors()._isEmpty()).toBe(true);
      });

      it('should skip validation if attribute is empty', function () {
        var var1 = new Variables.Variable({key: ''});
        var var2 = new Variables.Variable({key: ''});
        var variables = new Variables([var1, var2]);
        var1.parent(variables);
        var1.parent(variables);

        var1.validate();

        expect(var1.errors()._isEmpty()).toBe(true);
      });
    });

    describe('validateUrlPattern', function () {
      var Material = function (data) {
        Validatable.call(this, data);
        this.url = m.prop(data.url);

        this.validateUrlPattern('url');
      };

      it('should validate url pattern', function () {
        var material = new Material({url: 'ftp://some.com'});

        material.validate();

        expect(material.errors()._isEmpty()).toBe(false);
        expect(material.errors().errors('url')).toEqual(['Url must be a valid http(s) url']);
      });

      it('should skip validation for empty attribute', function () {
        var material = new Material({url: ''});

        material.validate();

        expect(material.errors()._isEmpty()).toBe(true);
      });
    });

    describe('validateFormatOf', function () {
      var Material = function (data) {
        Validatable.call(this, data);
        this.url = m.prop(data.url);

        this.validateFormatOf('url', {format: /^http(s)?:\/\/.+/, message: 'Url format is invalid'});
      };

      it('should validate the format of field', function () {
        var material = new Material({url: 'ftp://some.com'});

        material.validate();

        expect(material.errors()._isEmpty()).toBe(false);
        expect(material.errors().errors('url')).toEqual(['Url format is invalid']);
      });

      it('should skip validation for empty attribute', function () {
        var material = new Material({url: ''});

        material.validate();

        expect(material.errors()._isEmpty()).toBe(true);
      });
    });

    describe('validateWith', function () {
      var Material = function (data) {
        Validatable.call(this, data);
        this.name = m.prop(data.name);
        this.url = m.prop(data.url);

        var UrlValidator = function () {
          this.validate = function (entity) {
            if (_.isEmpty(entity.url())) {
              entity.errors().add('url', 'Url cannot be blank');
            }
          };
        };

        var NameValidator = function () {
          this.validate = function (entity) {
            if (_.isEmpty(entity.url())) {
              entity.errors().add('name', 'Name cannot be blank');
            }
          };
        };

        this.validateWith('url', UrlValidator);
        this.validateWith('name', NameValidator);
      };

      it('should validate with custom validator', function () {
        var material = new Material({});

        material.validate();

        expect(material.errors()._isEmpty()).toBe(false);
        expect(material.errors().errors('url')).toEqual(['Url cannot be blank']);
        expect(material.errors().errors('name')).toEqual(['Name cannot be blank']);
      });
    });

    describe('validateAssociated', function () {
      var Material = function (data) {
        Validatable.call(this, data);
        this.url = m.prop(data.url);

        this.validatePresenceOf('url');
      };

      var Pipeline = function (data) {
        Validatable.call(this, data);
        this.material = m.prop(new Material(data.material));

        this.validateAssociated('material');
      };

      it('should validate associated attributes', function () {
        var pipeline = new Pipeline({material: {}});

        pipeline.isValid();

        expect(pipeline.errors()._isEmpty()).toBe(true);
        expect(pipeline.material().errors()._isEmpty()).toBe(false);
        expect(pipeline.material().errors().errors('url')).toEqual(['URL must be present']);
      });

    });

    describe('validate', function () {
      var Material = function (data) {
        Validatable.call(this, data);
        this.username = m.prop('');
        this.password = m.prop('');

        this.validatePresenceOf('username');
        this.validatePresenceOf('password');
      };

      it('should validate the model', function () {
        var material = new Material({});

        material.validate();

        expect(material.errors()._isEmpty()).toBe(false);
        expect(material.errors().errors('username')).toEqual(['Username must be present']);
        expect(material.errors().errors('password')).toEqual(['Password must be present']);
      });

      it('should be able validate a single attribute', function () {
        var material = new Material({});

        material.validate('username');

        expect(material.errors()._isEmpty()).toBe(false);
        expect(material.errors().errors('username')).toEqual(['Username must be present']);
        expect(material.errors().hasErrors('password')).toBe(false);
      });

      it('should clear existing errors before validating', function () {
        var material = new Material({});

        material.validate();

        expect(material.errors()._isEmpty()).toBe(false);
        expect(material.errors().errors('username')).toEqual(['Username must be present']);
        expect(material.errors().errors('password')).toEqual(['Password must be present']);

        material.validate();

        expect(material.errors().errors('username')).toEqual(['Username must be present']);
        expect(material.errors().errors('password')).toEqual(['Password must be present']);
      });

      it('should clear existing errors for a given attribute before validating', function () {
        var material = new Material({});

        material.validate();

        expect(material.errors()._isEmpty()).toBe(false);
        expect(material.errors().errors('username')).toEqual(['Username must be present']);
        expect(material.errors().errors('password')).toEqual(['Password must be present']);

        material.username('somename');
        material.validate('username');

        expect(material.errors().hasErrors('username')).toBe(false);
        expect(material.errors().errors('password')).toEqual(['Password must be present']);
      });
    });

    describe('isValid', function () {
      var Variables = function (data) {
        Mixins.HasMany.call(this, {
          factory: Variables.Variable.create,
          as: 'Variable',
          collection: data,
          uniqueOn: 'name'
        });
      };

      Variables.Variable = function (data) {
        Validatable.call(this, data);

        this.key  = m.prop(data.key);
        this.name = m.prop();
        this.parent = Mixins.GetterSetter();

        this.validatePresenceOf('name');
        this.validateUniquenessOf('key');
      };

      it('should validate the model', function () {
        var var1 = new Variables.Variable({key: 'name'});
        var var2 = new Variables.Variable({key: 'name'});
        var variables = new Variables([var1, var2]);
        var1.parent(variables);
        var1.parent(variables);

        var1.isValid();

        expect(var1.errors()._isEmpty()).toBe(false);
        expect(var1.errors().errors('key')).toEqual(['Key is a duplicate']);
        expect(var1.errors().errors('name')).toEqual(['Name must be present']);
      });

      it('should be invalid if associated attributes are invalid', function () {
        var Material = function (data) {
          Validatable.call(this, data);
          this.url = m.prop(data.url);

          this.validatePresenceOf('url');
        };

        var Task = function (data) {
          Validatable.call(this, data);
          this.command = m.prop(data.command);

          this.validatePresenceOf('command');
        };

        var Pipeline = function (data) {
          Validatable.call(this, data);
          this.material = m.prop(new Material(data.material));
          this.task     = m.prop(new Task(data.task));

          this.validateAssociated('material');
          this.validateAssociated('task');
        };

        var pipeline = new Pipeline({material: {}, task: {command: 'some_command'}});

        expect(pipeline.isValid()).toBe(false);
        expect(pipeline.errors()._isEmpty()).toBe(true);
        expect(pipeline.material().errors()._isEmpty()).toBe(false);
        expect(pipeline.task().errors()._isEmpty()).toBe(true);
      });
    });
  });
});


text:
<?php

namespace Sellsy\Tests\Api\Catalogue;

use Sellsy\Api\Catalogue;
use Sellsy\Criteria\Catalogue\GetItemCriteria;
use Sellsy\Criteria\Catalogue\SearchItemsCriteria;
use Sellsy\Tests\Fixtures\Components;
use Sellsy\Models\Catalogue\ItemInterface;
use Sellsy\Tests\Fixtures\NewItem;

class ReadTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @return Catalogue
     */
    public function testCatalogueApi()
    {
        $catalogue = Components::getApi()->catalogue();

        $this->assertInstanceOf('Sellsy\Api\Catalogue', $catalogue);

        return $catalogue;
    }

    /**
     * @param Catalogue $catalogue
     * @return ItemInterface
     * @depends testCatalogueApi
     */
    public function testGetItem(Catalogue $catalogue)
    {
        $item = $catalogue->getItem(new GetItemCriteria(CATALOGUE_ITEM_ID));

        $this->assertInstanceOf('Sellsy\Models\Catalogue\ItemInterface', $item);

        return $item;
    }

    /**
     * @param ItemInterface $item
     * @depends testGetItem
     */
    public function testItemMappings(ItemInterface $item)
    {
        $this->assertInternalType('integer', $item->getId());
        $this->assertInternalType('float', $item->getSaleUnitAmountWithoutTax());
        $this->assertInternalType('float', $item->getSaleUnitTaxAmount());
        $this->assertInternalType('float', $item->getPurchaseUnitAmountWithoutTax());
        $this->assertInternalType('float', $item->getPurchaseUnitTaxAmount());
        $this->assertInternalType('float', $item->getQuantity());
        $this->assertInternalType('bool', $item->isActive());

        $this->assertInstanceOf('\DateTime', $item->getCreateAt());
        $this->assertInstanceOf('\DateTime', $item->getUpdateAt());

        $this->assertEquals('analyticsCode_value', $item->getAnalyticsCode());
        $this->assertEquals('notes_value', $item->getDescription());
        $this->assertStringStartsWith('https://www.sellsy.fr/?_f', $item->getImage());
        $this->assertEquals('name_value', $item->getName());
        $this->assertEquals('tradename_value', $item->getTradename());
        $this->assertEquals('slug_value', $item->getSlug());
        $this->assertEquals('unit_value', $item->getUnit());

        $this->assertInstanceOf('\Sellsy\Models\Catalogue\Item\Packaging', $item->getPackaging());

        $this->assertInstanceOf('Sellsy\Models\SmartTags\TagInterface', $item->getTag(function() { return true; }));
        $this->assertInternalType('array', $item->getTags());
        $this->assertGreaterThan(0, count($item->getTags()));

        $this->assertInstanceOf('Sellsy\Models\CustomFields\CustomFieldInterface', $item->getCustomField(function() { return true; }));
        $this->assertInternalType('array', $item->getCustomFields());
        $this->assertGreaterThan(0, count($item->getCustomFields()));
    }

    /**
     * @param Catalogue $catalogue
     * @return ItemInterface
     * @depends testCatalogueApi
     */
    public function testSearchItems(Catalogue $catalogue)
    {
        Components::getMapper()->setInterfaceMapping(ItemInterface::class, NewItem::class);

        $items = $catalogue->searchItems(new SearchItemsCriteria());

        $this->assertInstanceOf('Sellsy\Collections\Collection', $items);
        $this->assertInstanceOf('Sellsy\Models\Catalogue\ItemInterface', $items->current());

        return $items->current();
    }

    /**
     * @param ItemInterface $item
     * @depends testSearchItems
     */
    public function testInterfacesMappings(ItemInterface $item)
    {
        $this->assertInstanceOf('Sellsy\Tests\Fixtures\NewItem', $item);
    }
}


text:
package org.formix.btb;

import static junit.framework.Assert.*;

import java.io.File;
import java.sql.SQLException;
import java.sql.SQLNonTransientConnectionException;
import java.util.HashSet;
import java.util.SortedSet;
import java.util.TreeSet;

import org.formix.btb.Bridge;
import org.formix.btb.ConnectionManager;
import org.formix.btb.SqlDescriptor;
import org.formix.btb.Util;
import org.formix.btb.types.Employee;
import org.formix.btb.types.EmployeeEntity;
import org.formix.btb.types.EmployeeTable;
import org.formix.btb.types.EmployeeWithState;
import org.formix.btb.utils.DatabaseManager;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

public class BasicDataTableTest {

	private SqlDescriptor sqlDescriptor;
	private SortedSet<String> columns;
	private static DatabaseManager dbm;
	private static String dbName = "data/testdb";

	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
		File testDB = new File(dbName);
		boolean testDBExists = testDB.exists();

		if (!testDBExists) {
			dbm = new DatabaseManager();
			dbm.createDatabase(new File("TestDB.sql"));
		}
	}

	@AfterClass
	public static void tearDownAfterClass() throws Exception {
		try {
			ConnectionManager mgr = new ConnectionManager();
			mgr.createConnection("derbyShutdown");
		} catch (SQLNonTransientConnectionException e) {
			System.out.println("Connection closed.");
		}
		Util.delete(new File("data"));
	}

	public BasicDataTableTest() throws Exception {
		Bridge<Employee> bridge = new Bridge<Employee>(Employee.class);
		sqlDescriptor = bridge.getDescriptor();

		columns = new TreeSet<String>();
		columns.add("birthDate");
		columns.add("departmentId");
		columns.add("id");
		columns.add("name");
		columns.add("sin");
		columns.add("wages");
	}

	@Test
	public void testTestAlternativeTypes() throws SQLException {
		Bridge<EmployeeTable> bridgeTable = new Bridge<EmployeeTable>(
				EmployeeTable.class);
		SqlDescriptor descTable = bridgeTable.getDescriptor();
		assertEquals(
				"The tableName from the sqlDescriptor should be Employee " +
				"when a classe named EmployeeTable is used.",
				"Employee", descTable.getTableName());

		Bridge<EmployeeEntity> bridgeEntity = new Bridge<EmployeeEntity>(
				EmployeeEntity.class);
		SqlDescriptor descEntity = bridgeEntity.getDescriptor();
		assertEquals(
				"The tableName from the sqlDescriptor should be Employee " +
				"when a classe named EmployeeTable is used.",
				"Employee", descEntity.getTableName());

	}

	@Test
	public void testGetTableName() {
		String name = sqlDescriptor.getTableName();
		assertEquals("name should be Employee instead of " + name, "Employee",
				name);
	}

	@Test
	public void testGetPrimaryKey() {
		String expected = "id";
		String primKey = sqlDescriptor.getPrimaryKey();
		assertEquals("primKey should be id instead of " + primKey, expected,
				primKey);
	}

	@Test
	public void testGetSetValue() throws Exception {
		Employee e1 = new Employee();
		e1.setName("Robert Walsh");
		e1.setSin("123 345 567");
		e1.setWages(14.35);

		Employee e2 = new Employee();
		for (String property : columns) {
			if (sqlDescriptor.isAccessible(property)) {
				Object value = sqlDescriptor.getValue(e1, property);
				sqlDescriptor.setValue(e2, property, value);
			} else {
				System.out.println("INACCESSIBLE: " + property);
			}

		}

		assertEquals("e2 should be equal to e1.", e1, e2);
	}

	@Test
	public void testGetColumns() {
		assertEquals(
				"The columns set and descriptor.getColumns should be equal.",
				new HashSet<String>(columns),
				new HashSet<String>(sqlDescriptor.getColumns()));
	}

	@Test
	public void testGetSelectQuery() {

		String expectedQuery = "SELECT ";
		int i = 0;
		for (String property : columns) {
			if (i > 0) {
				expectedQuery += ", ";
			}
			expectedQuery += "Employee." + property;
			i++;
		}
		expectedQuery += " FROM Employee";

		String actualQuery = sqlDescriptor.getSelectQuery();

		assertEquals("the actual query should be " + expectedQuery
				+ " instead of " + actualQuery, expectedQuery, actualQuery);
	}

	@Test
	public void testGetInsertQuery() {
		String expectedQuery = "INSERT INTO Employee ";
		String cols = "(";
		int i = 0;

		String values = " VALUES (";

		for (String column : columns) {

			if (sqlDescriptor.isReadOnly(column)) {
				continue;
			}

			if (i > 0) {
				cols += ", ";
				values += ", ";
			}

			values += "?";
			cols += column;
			i++;
		}

		values += ")";
		cols += ")";
		expectedQuery += cols + values;

		String actualQuery = sqlDescriptor.getInsertQuery();

		assertEquals("the actual query should be " + expectedQuery
				+ " instead of " + actualQuery, expectedQuery, actualQuery);
	}

	@Test
	public void testGetUpdateQuery() {
		String expectedQuery = "UPDATE Employee SET ";
		int i = 0;

		for (String column : columns) {

			if (sqlDescriptor.getPrimaryKey().equals(column)) {
				continue;
			}

			if (i > 0) {
				expectedQuery += ", ";
			}

			expectedQuery += column + " = ?";
			i++;
		}

		expectedQuery += " WHERE id = ?";

		String actualQuery = sqlDescriptor.getUpdateQuery();

		assertEquals("the actual query should be " + expectedQuery
				+ " instead of " + actualQuery, expectedQuery, actualQuery);
	}

	@Test
	public void testGetDeleteQuery() {
		String expectedQuery = "DELETE FROM Employee WHERE id = ?";
		String actualQuery = sqlDescriptor.getDeleteQuery();
		assertEquals("the actual query should be " + expectedQuery
				+ " instead of " + actualQuery, expectedQuery, actualQuery);
	}

	@Test
	public void testToString() {
		System.out.println(sqlDescriptor);
	}

	@Test
	public void testIgnoredProperties() throws Exception {
		Bridge<EmployeeWithState> bridge = new Bridge<EmployeeWithState>(
				EmployeeWithState.class, "state");
		SqlDescriptor sqlDescriptor = bridge.getDescriptor();

		assertEquals(
				"The columns set and descriptor.getColumns should be equal.",
				new HashSet<String>(columns),
				new HashSet<String>(sqlDescriptor.getColumns()));
	}
}