text:
module SingularIntegralEquations
    using Base, BandedMatrices, ApproxFun, DualNumbers, DomainSets,
            LinearAlgebra, SpecialFunctions, LowRankApprox, HypergeometricFunctions

export cauchy, cauchyintegral, stieltjes, logkernel,
       stieltjesintegral, hilbert, pseudohilbert, pseudocauchy,
       stieltjesjacobimoment, logjacobimoment, singularintegral

import Base: values, getindex, setindex!, *, +, -, ==, <, <=, >,
                >=, /, ^, \, ∪, transpose, convert, Array, Vector, Matrix,
                AbstractVector, AbstractMatrix, AbstractArray, in

import Base.Broadcast: broadcasted, DefaultArrayStyle

import LinearAlgebra: ldiv!, mul!, rank, cond, qr

import DomainSets: UnionDomain, TypedEndpointsInterval

import ApproxFunBase: bandwidths, blockbandwidths, SpaceOperator, bilinearform, linebilinearform,dotu, blocklengths,
                  plan_transform,plan_itransform,transform,itransform,transform!,itransform!,
                  rangespace, domainspace, promotespaces, InterlaceOperator, coefficientmatrix,
                  canonicalspace, domain, space, Space, promotedomainspace, promoterangespace, AnyDomain, CalculusOperator,
                  ConcreteDefiniteIntegral, ConcreteDefiniteLineIntegral,
                  SumSpace,PiecewiseSpace, interlace,Multiplication, VectorSpace, ArraySpace,
                  BandedMatrix,  AbstractProductSpace,evaluate,
                  UnsetSpace, MultivariateFun, BivariateFun,linesum,complexlength,
                  Fun, ProductFun, LowRankFun, mappoint, prectype,
                  real, UnivariateSpace, RealUnivariateSpace, setdomain, eps, choosedomainspace, isapproxinteger,
                  ConstantSpace, DirectSumSpace, ArraySpace, ZeroSpace,
                  LowRankPertOperator,  setcanonicaldomain, SubSpace,
                  reverseorientation, @wrapper, mobius,
                  defaultgetindex, WeightSpace, spacescompatible, ∞, LowRankMatrix, SubOperator,
                  DFunction,
                  component, ncomponents, factor, nfactors, components, factors, rangetype,
                  VFun, Point, dynamic, pieces, npieces, piece, cfstype, isreal, IntervalOrSegmentDomain,
                  IntervalOrSegment, canonicaldomain,
                  testbandedoperator,
                  columnspace,
                  DefiniteLineIntegralWrapper, DefiniteIntegral, DefiniteLineIntegral, @calculus_operator,
                  checkpoints, SumSpace

import ApproxFunOrthogonalPolynomials: ChebyshevDirichlet, PolynomialSpace, IntervalCurve,
                                        recA, recB, recC, recα, recβ, recγ,
                                        jacobirecA, jacobirecB, jacobirecC, jacobirecα, jacobirecβ, jacobirecγ,
                                        order, JacobiZ

import ApproxFunFourier: LaurentDirichlet, PeriodicCurve

import DualNumbers: dual

import LowRankApprox: refactorsvd!

export ⁺, ⁻

"""
`Directed` represents a number that is a limit from either left (s=true) or right (s=false)
For functions with branch cuts, it is assumed that the value is on the branch cut,
Therefore not requiring tolerances.  This will naturally give the analytic continuation.
"""
struct Directed{s,T} <: Number
    x::T
    Directed{s,T}(x::T) where {s,T} = new{s,T}(x)
    Directed{s,T}(x::Number) where {s,T} = new{s,T}(T(x))
end

Directed{s}(x) where {s} = Directed{s,eltype(x)}(x)

convert(::Type{Directed{s,T}},x::Directed{s}) where {s,T} = Directed{s,T}(T(x.x))
convert(::Type{Directed{s,T}},x::T) where {s,T} = Directed{s,T}(x)
convert(::Type{Directed{s,T}},x::Real) where {s,T} = Directed{s,T}(T(x))
convert(::Type{Directed{s,T}},x::Complex) where {s,T} = Directed{s,T}(T(x))

const ⁺ = Directed{true}(true)
const ⁻ = Directed{false}(true)

orientationsign(::Type{Directed{true}}) = 1
orientationsign(::Type{Directed{false}}) = -1
orientation(::Type{Directed{s}}) where {s} = s
orientation(::Directed{s}) where {s} = s

# removes direction from a number
undirected(x::Number) = x
undirected(x::Fun) = x
undirected(x::Directed) = undirected(x.x)  # x might also have directeion
reverseorientation(x::Number) = x
reverseorientation(x::Directed{s}) where {s} = Directed{!s}(reverseorientation(x.x))

for OP in (:*,:+,:-,:/)
    @eval begin
        $OP(a::Directed{s}) where {s} = Directed{s}($OP(a.x))
        $OP(a::Directed{s},b::Directed{s}) where {s} = Directed{s}($OP(a.x,b.x))
        $OP(a::Directed{s},b::Number) where {s} = Directed{s}($OP(a.x,b))
        $OP(a::Number,b::Directed{s}) where {s} = Directed{s}($OP(a,b.x))
    end
end

real(::Type{Directed{s,T}}) where {s,T} = real(T)

# abs, real and imag delete orientation.
for OP in (:(Base.isfinite),:(Base.isinf),:(Base.abs),:(Base.real),:(Base.imag),:(Base.angle))
    @eval $OP(a::Directed) = $OP(a.x)
end

# branchcuts of log, sqrt, etc. are oriented from (0,-∞)
Base.log(x::Directed{true}) = log(-x.x) - π*im
Base.log(x::Directed{false}) = log(-x.x) + π*im
Base.log1p(x::Directed) = log(1+x)
Base.sqrt(x::Directed{true}) = real(x.x) ≥ 0 ? sqrt(complex(x.x)) : -im*sqrt(-x.x)
Base.sqrt(x::Directed{false}) = real(x.x) ≥ 0 ? sqrt(complex(x.x)) : im*sqrt(-x.x)
^(x::Directed{true},a::Integer) = x.x^a
^(x::Directed{false},a::Integer) = x.x^a
^(x::Directed{true},a::Number) = exp(-a*π*im)*(-x.x)^a
^(x::Directed{false},a::Number) = exp(a*π*im)*(-x.x)^a

dual(a::Directed{s},b) where {s} = Directed{s}(dual(undirected(a),b))

# Support for _2F1
import HypergeometricFunctions: log1pover, logandpoly, mxa_₂F₁, _₂F₁general, abeqcd, log1p, _₂F₁maclaurin, _₂F₁Inf, _₂F₁one, _₂F₁taylor, speciallog

speciallog(x::Directed) = (s = sqrt(-x); 3(s-atan(s))/s^3)
log1pover(s::Directed) = log1p(s)/undirected(s)
logandpoly(x::Directed) = undirected(x) == 0 ? one(x) : 6*(-2undirected(x)+(undirected(x)-2)*log1p(-x))/undirected(x)^3

function directed_mxa_₂F₁(a,b,c,z)
    if isequal(c,2)
        if abeqcd(a,b,1) # 6. 15.4.1
            return log1p(-z)
        end
    elseif isequal(c,4)
        if abeqcd(a,b,2)
            return 6*(-2 + (1-2/undirected(z))*log1p(-z))
        end
    end
    undirected(-z)^a*_₂F₁(a,b,c,z)
end

function directed_₂F₁general(a::Number,b::Number,c::Number,z)
    T = promote_type(typeof(a),typeof(b),typeof(c),typeof(undirected(z)))

    real(b) < real(a) && (return _₂F₁general(b,a,c,z))
    real(c) < real(a)+real(b) && (return exp((c-a-b)*log1p(-z))*_₂F₁general(c-a,c-b,c,z))

    if abs(z) ≤ ρ || -a ∈ ℕ₀ || -b ∈ ℕ₀
        _₂F₁maclaurin(a,b,c,undirected(z))
    elseif abs(z/(z-1)) ≤ ρ
        exp(-a*log1p(-z))_₂F₁maclaurin(a,c-b,c,undirected(z/(z-1)))
    elseif abs(inv(z)) ≤ ρ
        _₂F₁Inf(a,b,c,z)
    elseif abs(1-inv(z)) ≤ ρ
        exp(-a*log1p(-z))*_₂F₁Inf(a,c-b,c,reverseorientation(z/(z-1)))
    elseif abs(1-z) ≤ ρ
        _₂F₁one(a,b,c,z)
    elseif abs(inv(1-z)) ≤ ρ
        exp(-a*log1p(-z))*_₂F₁one(a,c-b,c,reverseorientation(z/(z-1)))
    else
        _₂F₁taylor(a,b,c,undirected(z))
    end
end

mxa_₂F₁(a,b,c,z::Directed) = directed_mxa_₂F₁(a,b,c,z)
_₂F₁general(a::Number,b::Number,c::Number,z::Directed) = directed_₂F₁general(a,b,c,z)

### Stieltjes

for OP in (:stieltjes,:stieltjesintegral,:pseudostieltjes)
    @eval $OP(f::Fun) = $OP(space(f),coefficients(f))
    @eval $OP(f::Fun,z) = $OP(space(f),coefficients(f),z)
end

stieltjes(s::SumSpace, c::AbstractVector, z::Number) =
    sum(stieltjes.(components(Fun(s,c)), z))

hilbert(f) = Hilbert()*f
hilbert(S,f,z) = hilbert(Fun(S,f))(z)
hilbert(f::Fun,z) = hilbert(space(f),coefficients(f),z)

logkernel(f::Fun,z) = logkernel(space(f),coefficients(f),z)
in(x::Directed, d::Domain) = x.x ∈ d
in(x::Directed, d::TypedEndpointsInterval{:closed,:closed}) = x.x ∈ d

cauchy(f...) = stieltjes(f...)*(im/(2π))
pseudocauchy(f...) = pseudostieltjes(f...)*(im/(2π))
cauchyintegral(u...) = stieltjesintegral(u...)*(im/(2π))

function singularintegral(k::Integer,s::Space,f,z)
    k == 0 && return logkernel(s,f,z)
    k == 1 && isreal(domain(s)) && return stieltjes(s,f,z)/π
    k == 1 && domain(s) isa Segment && return stieltjes(s,f/sign(domain(s)),z)/π
    error("Not implemented")
end

singularintegral(k::Integer,s::PiecewiseSpace,f,z) =
    mapreduce(g -> singularintegral(k, g, z), +, pieces(Fun(s,f)))

function csingularintegral(k::Integer,s::Space,f,z)
    k == 0 && error("Not defined")
    k == 1 && return stieltjes(s,f,z)/π
    return epsilon(csingularintegral(k-1,s,f,dual(z,1)))
end

singularintegral(k::Integer,f::Fun,z) = singularintegral(k,space(f),coefficients(f),z)
csingularintegral(k::Integer,f::Fun,z) = csingularintegral(k,space(f),coefficients(f),z)

# Modifier spaces

stieltjes(sp::SubSpace,v,z) = stieltjes(sp.space,coefficients(v,sp,sp.space),z)

include("Operators/Operators.jl")
include("FundamentalSolutions/FundamentalSolutions.jl")

include("JacobiQWeight.jl")
include("JacobiQ.jl")
include("stieltjesmoment.jl")

include("circlecauchy.jl")
include("intervalcauchy.jl")
include("singfuncauchy.jl")

include("vectorcauchy.jl")

include("GreensFun/GreensFun.jl")

include("periodicline.jl")
include("arc.jl")
include("curve.jl")
include("asymptotics.jl")

include("Extras/Extras.jl")

using Test

function testsieoperators(S::Space)
    testbandedoperator(SingularIntegral(S,0))
    testbandedoperator(SingularIntegral(S,1))
    testbandedoperator(Hilbert(S))
    p=checkpoints(S)[1] # random point on contour
    x=Fun(domain(S))
    z=2.12312231+1.433453443534im # random point not on contour

    for k=1:5
        f=Fun(S,[zeros(k-1);1])
        @test (SingularIntegral(S,0)*f)(p) ≈ logkernel(f,p)
        @test (Hilbert(S,1)*f)(p) ≈ hilbert(f,p)
    end
end

function testsieeval(S::Space;posdirection=im)
    p=checkpoints(S)[1] # random point on contour
    x=Fun(domain(S))
    z=2.12312231+1.433453443534im # random point not on contour

    for k=1:5
        f=Fun(S,[zeros(k-1);1])
        @test abs(sum(f/(z-x))-stieltjes(f,z)) ≤ 100eps()
        @test stieltjes(f,(p)⁺) ≈ stieltjes(f,p+eps()*posdirection)
        @test stieltjes(f,(p)⁻) ≈ stieltjes(f,p-eps()*posdirection)
        @test cauchy(f,(p)⁺)-cauchy(f,(p)⁻) ≈ f(p)
        @test im*(cauchy(f,(p)⁺)+cauchy(f,(p)⁻)) ≈ hilbert(f,p)

        @test abs(linesum(f*logabs(x-z))/π-logkernel(f,z)) ≤ 100eps()
        @test logkernel(f,p) ≈ logkernel(f,p+eps()*posdirection)
    end
end

function testsies(S::Space;posdirection=im)
    testsieoperators(S)
    testsieeval(S;posdirection=posdirection)
end

function testsies(d::IntervalOrSegmentDomain; posdirection=im)
    testsies(JacobiWeight(-0.5,-0.5,Chebyshev(d)))
    testsies(JacobiWeight(0.5,0.5,Ultraspherical(1,d)))
    testsies(JacobiWeight(-0.5,-0.5,ChebyshevDirichlet{1,1}(d)))
    testsieeval(Legendre(d);posdirection=posdirection)
end

end #module


text:
import { IModuleContainer, IModuleInternal } from "./angularInterfaces";
import { IModule, Injectable } from "angular";

"use strict";

export function setupModuleLoader(w: Window) {
    var ensure = function (obj, name, factory) {
        return obj[name] || (obj[name] = factory());
    }
    var angular = ensure(w, "angular", Object);

    var createModule = function (name: string, requires: string[], modules: IModuleContainer, configFn: Function): IModule {
        if (name === "hasOwnProperty") {
            throw "hasOwnProperty is not a valid module name";
        }
        var invokeQueue = [];
        var configBlocks = [];

        var invokeLater = function (service: string, method: string, arrayMethod: string, queue: any[]) {
            return function () {
                var item = [service, method, arguments];
                queue[arrayMethod](item);
                return moduleInstance;
            };
        };
        var moduleInstance = <IModuleInternal>{
            name: name,
            requires: requires,
            constant: invokeLater("$provide", "constant", "unshift", invokeQueue),
            provider: invokeLater("$provide", "provider", "push", invokeQueue),
            factory: invokeLater("$provide", "factory", "push", invokeQueue),
            value: invokeLater("$provide", "value", "push", invokeQueue),
            service: invokeLater("$provide", "service", "push", invokeQueue),
            decorator: invokeLater("$provide", "decorator", "push", invokeQueue),
            filter: invokeLater("$filterProvider", "register", "push", invokeQueue),
            directive: invokeLater("$compileProvider", "directive", "push", invokeQueue),
            controller: invokeLater("$controllerProvider", "register", "push", invokeQueue),
            component: invokeLater("$compileProvider", "component", "push", invokeQueue),
            config: invokeLater("$injector", "invoke", "push", configBlocks),
            run(fn: Injectable<Function>) {
                moduleInstance._runBlocks.push(fn);
                return moduleInstance;
            },
            _invokeQueue: invokeQueue,
            _configBlocks: configBlocks,
            _runBlocks: []
        };
        if (configFn) {
            moduleInstance.config(configFn);
        }
        modules[name] = moduleInstance;
        return moduleInstance;
    }
    var getModule = function (name: string, modules: IModuleContainer): IModuleInternal {
        if (modules.hasOwnProperty(name)) {
            var moduleInstance = modules[name];
            return moduleInstance;
        } else {
            throw "Module " + name + "is not available!";
        }
    }
    ensure(angular, "module", function () {
        var modules: IModuleContainer = {};
        return function (name: string, requires?: string[], configFn?: Function) {
            if (requires) {
                return createModule(name, requires, modules, configFn);
            } else {
                return getModule(name, modules);
            }
        };
    });
}

redpajama_set_name: RedPajamaGithub


text:
namespace pp {
namespace proxy {

// Represents a PP_Resource sent over the wire. This just wraps a PP_Resource.
// The point is to prevent mistakes where the wrong resource value is sent.
// Resource values are remapped in the plugin so that it can talk to multiple
// hosts. If all values were PP_Resource, it would be easy to forget to do
// this tranformation.
//
// All HostResources respresent IDs valid in the host.
class HostResource {
 public:
  HostResource() : instance_(0), host_resource_(0) {
  }

  bool is_null() const {
    return !host_resource_;
  }

  // Sets and retrieves the internal PP_Resource which is valid for the host
  // (a.k.a. renderer, as opposed to the plugin) process.
  //
  // DO NOT CALL THESE FUNCTIONS IN THE PLUGIN SIDE OF THE PROXY. The values
  // will be invalid. See the class comment above.
  void SetHostResource(PP_Instance instance, PP_Resource resource) {
    instance_ = instance;
    host_resource_ = resource;
  }
  PP_Resource host_resource() const {
    return host_resource_;
  }

  PP_Instance instance() const { return instance_; }

  // This object is used in maps so we need to provide this sorting operator.
  bool operator<(const HostResource& other) const {
    if (instance_ != other.instance_)
      return instance_ < other.instance_;
    return host_resource_ < other.host_resource_;
  }

 private:
  PP_Instance instance_;
  PP_Resource host_resource_;
};

}  // namespace proxy
}  // namespace pp

#endif  // PPAPI_PROXY_HOST_RESOURCE_H_


text:
/**
 * This software is released as part of the Pumpernickel project.
 *
 * All com.pump resources in the Pumpernickel project are distributed under the
 * MIT License:
 * https://github.com/mickleness/pumpernickel/raw/master/License.txt
 *
 * More information about the Pumpernickel project is available here:
 * https://mickleness.github.io/pumpernickel/
 */
package com.pump.swing.popover;

import java.awt.Component;
import java.awt.KeyboardFocusManager;
import java.awt.Window;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.HierarchyBoundsListener;
import java.awt.event.HierarchyEvent;
import java.awt.event.HierarchyListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.HashMap;
import java.util.Map;

import javax.swing.JComponent;
import javax.swing.SwingUtilities;

/**
 * This PopoverVisibility will refresh the popover and/or its visibility when
 * the owner's hierarchy or bounds change.
 */
public abstract class AbstractComponentVisibility<T extends JComponent>
		implements PopoverVisibility<T> {

	private static final String PROPERTY_ACTIVE_WINDOW = "activeWindow";

	static class PopoverHierarchyBoundsListener
			implements HierarchyBoundsListener {
		JPopover<?> popover;

		PopoverHierarchyBoundsListener(JPopover<?> popover) {
			this.popover = popover;
		}

		@Override
		public void ancestorMoved(HierarchyEvent e) {
			popover.refreshPopup();
		}

		@Override
		public void ancestorResized(HierarchyEvent e) {
			popover.refreshPopup();
		}
	}

	static class PopoverHierarchyListener implements HierarchyListener {
		JPopover<?> popover;

		PopoverHierarchyListener(JPopover<?> popover) {
			this.popover = popover;
		}

		@Override
		public void hierarchyChanged(HierarchyEvent e) {
			popover.refreshVisibility(false);
			popover.refreshPopup();
		}
	}

	static class PopoverComponentListener implements ComponentListener {
		JPopover<?> popover;

		PopoverComponentListener(JPopover<?> popover) {
			this.popover = popover;
		}

		@Override
		public void componentResized(ComponentEvent e) {
			popover.refreshPopup();
		}

		@Override
		public void componentMoved(ComponentEvent e) {
			popover.refreshPopup();
		}

		@Override
		public void componentShown(ComponentEvent e) {
			popover.refreshVisibility(false);
		}

		@Override
		public void componentHidden(ComponentEvent e) {
			popover.refreshVisibility(false);
		}
	}

	static class PopoverPropertyChangeListener
			implements PropertyChangeListener {
		JPopover<?> popover;

		public PopoverPropertyChangeListener(JPopover<?> popover) {
			this.popover = popover;
		}

		@Override
		public void propertyChange(PropertyChangeEvent evt) {
			popover.refreshVisibility(false);

		}

	}

	Map<JPopover<T>, PopoverHierarchyListener> hierarchyListenerMap = new HashMap<>();
	Map<JPopover<T>, PopoverHierarchyBoundsListener> hierarchyBoundsListenerMap = new HashMap<>();
	Map<JPopover<T>, PopoverComponentListener> componentListenerMap = new HashMap<>();
	Map<JPopover<T>, PopoverPropertyChangeListener> propertyListenerMap = new HashMap<>();

	@Override
	public void install(JPopover<T> popover) {
		PopoverHierarchyBoundsListener l1 = hierarchyBoundsListenerMap
				.get(popover);
		if (l1 == null) {
			l1 = new PopoverHierarchyBoundsListener(popover);
			hierarchyBoundsListenerMap.put(popover, l1);
			popover.getOwner().addHierarchyBoundsListener(l1);
		}

		PopoverHierarchyListener l2 = hierarchyListenerMap.get(popover);
		if (l2 == null) {
			l2 = new PopoverHierarchyListener(popover);
			hierarchyListenerMap.put(popover, l2);
			popover.getOwner().addHierarchyListener(l2);
		}

		PopoverComponentListener l3 = componentListenerMap.get(popover);
		if (l3 == null) {
			l3 = new PopoverComponentListener(popover);
			componentListenerMap.put(popover, l3);
			popover.getOwner().addComponentListener(l3);
		}

		PopoverPropertyChangeListener l4 = propertyListenerMap.get(popover);
		if (l4 == null) {
			l4 = new PopoverPropertyChangeListener(popover);
			propertyListenerMap.put(popover, l4);
			KeyboardFocusManager.getCurrentKeyboardFocusManager()
					.addPropertyChangeListener(PROPERTY_ACTIVE_WINDOW, l4);
		}
	}

	@Override
	public void uninstall(JPopover<T> popover) {
		PopoverHierarchyBoundsListener l1 = hierarchyBoundsListenerMap
				.remove(popover);
		if (l1 != null) {
			popover.getOwner().removeHierarchyBoundsListener(l1);
		}

		PopoverHierarchyListener l2 = hierarchyListenerMap.remove(popover);
		if (l2 != null) {
			popover.getOwner().removeHierarchyListener(l2);
		}

		PopoverComponentListener l3 = componentListenerMap.remove(popover);
		if (l3 != null) {
			popover.getOwner().removeComponentListener(l3);
		}

		PopoverPropertyChangeListener l4 = propertyListenerMap.remove(popover);
		if (l4 != null) {
			KeyboardFocusManager.getCurrentKeyboardFocusManager()
					.removePropertyChangeListener(PROPERTY_ACTIVE_WINDOW, l4);
		}
	}

	public static boolean isActiveWindow(JPopover<?> popover) {
		return isInsideActiveWindow(popover.getOwner())
				|| isInsideActiveWindow(popover.getContents());
	}

	public static boolean isInsideActiveWindow(Component comp) {
		Window activeWindow = KeyboardFocusManager
				.getCurrentKeyboardFocusManager().getActiveWindow();
		if (activeWindow == null)
			return false;
		return activeWindow == comp
				|| SwingUtilities.isDescendingFrom(comp, activeWindow);
	}
}


text:
package thedemitrius.androidif.glk;

import android.view.View;
import android.content.Context;

class PairWindow extends Window
{
	PairWindow(Context context,int id, int method, int size, int rock, boolean key)
	{
		super(context,id, method, size, rock, key);

		setWillNotDraw(true);
	}

	void clear(boolean helpActive)
	{
	}

	void setArrangement(int method,int size,int keyWin)
	{
		final Window child=(Window)getChildAt(keyWin);

		if (!child.keyWin()){
			child.setKey(true);
			if (keyWin==0)
				((Window)getChildAt(1)).setKey(false);
			else
				((Window)getChildAt(0)).setKey(false);
		}

		child.setMethod(method);
		child.setSize(size);

		requestLayout();
	}

	public void onMeasure(int widthMeasureSpec,int heightMeasureSpec)
	{
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);

		if (getChildCount()==2){
			Window key,nonkey;
			if (((Window)getChildAt(0)).keyWin()){
				key=(Window)getChildAt(0);
				nonkey=(Window)getChildAt(1);}
			else{
				key=(Window)getChildAt(1);
				nonkey=(Window)getChildAt(0);}
			int totalWidth=View.MeasureSpec.getSize(widthMeasureSpec);
			int totalHeight=View.MeasureSpec.getSize(heightMeasureSpec);
			int keyWidth,keyHeight;
			int nonkeyWidth,nonkeyHeight;
			if ((key.getMethod()&2)==2){
				if ((key.getMethod()&WINMETHOD_FIXED)==WINMETHOD_FIXED){
					keyHeight=key.getSizeSetting();}
				else{
					keyHeight=(totalHeight/100)*key.getSizeSetting();}
				keyWidth=totalWidth;
				nonkeyHeight=totalHeight-keyHeight;
				nonkeyWidth=totalWidth;}
			else{
				if ((key.getMethod()&WINMETHOD_FIXED)==WINMETHOD_FIXED){
					keyWidth=key.getSizeSetting();}
				else{
					keyWidth=(totalWidth/100)*key.getSizeSetting();}
				keyHeight=totalHeight;
				nonkeyWidth=totalWidth-keyWidth;
				nonkeyHeight=totalHeight;}
			key.measure(View.MeasureSpec.makeMeasureSpec(keyWidth, View.MeasureSpec.EXACTLY),
					View.MeasureSpec.makeMeasureSpec(keyHeight,View.MeasureSpec.EXACTLY));
			nonkey.measure(View.MeasureSpec.makeMeasureSpec(nonkeyWidth, View.MeasureSpec.EXACTLY),
					View.MeasureSpec.makeMeasureSpec(nonkeyHeight,View.MeasureSpec.EXACTLY));}
	}

	public void onLayout(boolean changed, int l, int t, int r, int b)
	{
		if (getChildCount()==2){
			Window key,nonkey;
			if (((Window)getChildAt(0)).keyWin()){
				key=(Window)getChildAt(0);
				nonkey=(Window)getChildAt(1);}
			else{
				key=(Window)getChildAt(1);
				nonkey=(Window)getChildAt(0);}
			int keyL=0; int keyT=0; int keyR=0; int keyB=0;
			int nonkeyL=0; int nonkeyT=0; int nonkeyR=0; int nonkeyB=0;
			switch (key.getMethod()&3){
			case WINMETHOD_LEFT:
				keyL=0; keyT=0; keyR=key.getMeasuredWidth(); keyB=b;
				nonkeyL=key.getMeasuredWidth(); nonkeyT=0; nonkeyR=r; nonkeyB=b;
				break;
			case WINMETHOD_RIGHT:
				keyL=nonkey.getMeasuredWidth(); keyT=0; keyR=r; keyB=b;
				nonkeyL=0; nonkeyT=0; nonkeyR=nonkey.getMeasuredWidth(); nonkeyB=b;
				break;
			case WINMETHOD_ABOVE:
				keyL=0; keyT=0; keyR=r; keyB=key.getMeasuredHeight();
				nonkeyL=0; nonkeyT=key.getMeasuredHeight(); nonkeyR=r; nonkeyB=b;
				break;
			case WINMETHOD_BELOW:
				keyL=0; keyT=nonkey.getMeasuredHeight(); keyR=r; keyB=b;
				nonkeyL=0; nonkeyT=0; nonkeyR=r; nonkeyB=nonkey.getMeasuredHeight();
				break;}
			key.layout(keyL, keyT, keyR, keyB);
			nonkey.layout(nonkeyL, nonkeyT, nonkeyR, nonkeyB);}
	}
}


text:
namespace Algebra.QL.Core.Factory
{
    public interface IFactory<S, E, T> : IStmntFactory<S, E, T>, IExprFactory<E, T>, ITypeFactory<T>, Algebra.Core.Factory.IFactory<S, E, T>
    {

    }
}


text:
import users from './users'
import players from './players'

/* creates the service layer */
const userService = users()
const playerService = players()

export default {
	userService,
	playerService
}


text:
require "google/cloud/video/live_stream/v1"

##
# Example demonstrating basic usage of
# Google::Cloud::Video::LiveStream::V1::LivestreamService::Client#stop_channel
#
def stop_channel
  # Create a client object. The client can be reused for multiple calls.
  client = Google::Cloud::Video::LiveStream::V1::LivestreamService::Client.new

  # Create a request. To set request fields, pass in keyword arguments.
  request = Google::Cloud::Video::LiveStream::V1::StopChannelRequest.new

  # Call the stop_channel method.
  result = client.stop_channel request

  # The returned object is of type Gapic::Operation. You can use this
  # object to check the status of an operation, cancel it, or wait
  # for results. Here is how to block until completion:
  result.wait_until_done! timeout: 60
  if result.response?
    p result.response
  else
    puts "Error!"
  end
end
# [END livestream_v1_generated_LivestreamService_StopChannel_sync]


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ImageView
        android:id="@+id/iv_splash"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@drawable/splash"
        android:scaleType="fitXY"
        android:visibility="gone"/>
    <com.facebook.drawee.view.SimpleDraweeView
        android:id="@+id/sdv_splash"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</FrameLayout>


text:
package org.openengsb.openticket.model;

import static org.junit.Assert.assertTrue;

import java.util.Date;

import org.junit.Before;
import org.junit.Test;

public class TicketTest {
    private Ticket ticket;
    private DeveloperTicket devTicket;
    private ReviewerTicket revTicket;
    private InformationTicket infTicket;

    @Before
    public void init() throws Exception {
        ticket = new Ticket();
        ticket.setPriority(TicketPriority.Medium);
        ticket.setContactEmailAddress("test@domain.at");
        devTicket = new DeveloperTicket();
        devTicket.setWorkingHours(27);
        revTicket = new ReviewerTicket();
        revTicket.setTicketResolved(true);
        revTicket.setFeedback("some feedback");
        infTicket = new InformationTicket();
        infTicket.setInformation("42");
    }

    @Test
    public void initTicket_shouldInitializeProperties() throws Exception {
        assertTrue(ticket.getTaskId().length() > 0);
        assertTrue(ticket.getTaskCreationTimestamp().before(new Date(System.currentTimeMillis() + 10)));
        assertTrue(ticket.getPriority().equals(new String(TicketPriority.Medium.toString())));
        assertTrue(ticket.getContactEmailAddress().equals(new String("test@domain.at")));
    }

    @Test
    public void initDeveloperTicket_shouldInitializeProperties() throws Exception {
        assertTrue(devTicket.getTaskId().length() > 0);
        assertTrue(devTicket.getTaskCreationTimestamp().before(new Date(System.currentTimeMillis() + 10)));
        assertTrue(devTicket.getWorkingHours().equals(new Integer(27)));
    }

    @Test
    public void initReviewerTicket_shouldInitializeProperties() throws Exception {
        assertTrue(revTicket.getTaskId().length() > 0);
        assertTrue(revTicket.getTaskCreationTimestamp().before(new Date(System.currentTimeMillis() + 10)));
        assertTrue(revTicket.getTicketResolved());
        assertTrue(revTicket.getFeedback().equals(new String("some feedback")));
    }

    @Test
    public void initInformationTicket_shouldInitializeProperties() throws Exception {
        assertTrue(infTicket.getTaskId().length() > 0);
        assertTrue(infTicket.getTaskCreationTimestamp().before(new Date(System.currentTimeMillis() + 10)));
        assertTrue(infTicket.getInformation().equals(new String("42")));
    }
}


text:
title: Centralize Cowrie Honeypot Logs with Graylog in AWS
date: 2018-05-16 00:00:00 Z
layout: post
---

This summer I want to do more botnet analysis. I've done some before with my [rootonyour.webcam](https://rootonyour.webcam) SSH log analysis [sensor](https://github.com/becksteadn/Log-Sensor) and [server](https://github.com/becksteadn/Mapper-Server) projects. This really only included geolocation and linked to Shodan information on running services. Cowrie is a medium interaction honeypot that can log login credentials and command execution and also capture downloaded files. I don't prioritize availability with my self-hosted servers, so I'd rather put everything in the cloud.

## Graylog in AWS

### AMI

Graylog, Inc. maintains a full-stack installation AMI for every version of Graylog. Search for it in the public AMIs page of the EC2 section.

![AMI](https://lambda.sx/ffM.png)

Launch with `t2.medium` at least. Edit the EBS storage for however big you want. Cost is roughly $1 per 10Gb.

### Security Group

The Graylog web interface uses ports 80 (HTTP), 443 (HTTPS), and 9000 (TCP). The default Cowrie syslog configuration uses port 8514 (UDP).

### Initial Configuration

Launch and connect to the box via SSH.

#### Graylog-Reconfigure

To start complete the Graylog installation, you'll need to configure a few settings using the `graylog-ctl` command.

```
sudo graylog-ctl set-external-ip https://<public ip>:443/api
sudo graylog-ctl enforce-ssl
sudo graylog-ctl set-admin-password <password>
sudo graylog-ctl set-timezone <zone acronym>
sudo graylog-ctl reconfigure
```

After the configuration completes, log in as admin at `https://<public ip>`.

#### Input

Once logged in, navigate to `System -> Inputs`. At the top of the page select `Syslog UDP` and launch the new input then configure it. Use Port 8514.

## Honeypot Setup

We'll assume a Cowrie honeypot is already running. First, add the following lines to `cowrie.cfg`.

```
[output_localsyslog]
enabled = true
facility = USER
format = text
```

Then create the file `/etc/rsyslog.d/85-graylog.conf` with the following:

```
$template GRAYLOGRFC5424,"<%pri%>%protocol-version% %timestamp:::date-rfc3339% %HOSTNAME% %app-name% %procid% %msg%\n"
*.* @<graylog-server-ip>:8514;GRAYLOGRFC5424
```

Finally, restart cowrie and rsyslog.

```
bin/cowrie restart

service rsyslog restart
```

## Graylog Configuration

After messages start flowing, we can customize Graylog for honeypot logs.

### Extractors

Extractors can pick out additional information from a message. For this case, we'll be pulling IP addresses, usernames, and passwords. Hit `Manage extractors` to go to the extractors menu.

#### IP Addresses

Hit `Get started` and paste a Message ID from a message with an attacker's IP address and use the default index `graylog_0` then load the message. Next to the `message` field select `Select extractor type` and choose `Regular Expression`.

Feel free to use your own IP regex, but I use `(\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b)`. Set it to always try to extract or choose to only extract when `New Connection` appears. Store the field as `ip`. Set the `Extraction strategy` to copy.

#### Login Credentials

Select a message with a login attempt containing the username and password. Here I'll just give you the field I use and the regex to match it.

 ```
field : regex

attempt_username : login attempt \[(.*)\/
attempt_password : \/(.*)\]

 ```

These fields can now be used in searches.

![Login Regex Extractor](https://lambda.sx/nYM.png)

### Streams

Messages can be routed into streams based on a set of rules. This is done is realtime so it can be used for alerting or forwarding to another system.

I have one stream called `Honeypot Data` with rules that it matches a hostname of one of my sensors. The other is called `SSH Login Attempts` and matches when a message contains the phrase `login attempt`.

### Dashboards

Create a new dashboard then go back to the search page. Search for `login attempt` in the last 1 day. On the left under **Search result**  select `Add count to dashboard`. This will show the number of login attempts in the last 24 hours. You can also use the time filter keyword `today midnight` to show the attempts in the current day. Finally, add the histogram to the dashboard as well.

#### Extra Credit

Also from the left-hand side, you can select any field and choose `Quick Values` to get a chart of values found in the search. Try it for `attempt_username`.

![Attempt Username Chart](https://lambda.sx/ulM.png)

## Conclusion

I'm just getting started with Cowrie and Graylog. I hope to automate honeypot setup with Ansible soon and get more valuable analytics from Graylog.

## Additional Notes

- Configuration files are located in `/opt/graylog/` for the AMI images.
- Set up dynamic DNS for the server to be used in honeypot syslog configuration.

## Resources

[Graylog AWS Documentation](http://docs.graylog.org/en/2.4/pages/installation/aws.html)

[cyberdefense.pl Tutorial](https://cyberdefense.pl/2016/10/30/graylog-and-aws-quick-start/)

[Cowrie Graylog Documentation](https://github.com/micheloosterhof/cowrie/tree/master/doc/graylog)

[Drools - Something to look into](http://docs.graylog.org/en/2.4/pages/drools.html)


text:
package joe.testlib;

import java.util.List;

import joe.testlib.testers.AddTester;
import joe.testlib.testers.MultiplyTester;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.testing.AbstractTester;
import com.google.common.collect.testing.FeatureSpecificTestSuiteBuilder;

public class CalculatorTestSuiteBuilder extends FeatureSpecificTestSuiteBuilder<CalculatorTestSuiteBuilder, CalculatorTestSubjectGenerator> {
	@SuppressWarnings("rawtypes")
	@Override protected List<Class<? extends AbstractTester>> getTesters() {
		return ImmutableList.of(AddTester.class, MultiplyTester.class);
	}
	public static CalculatorTestSuiteBuilder using(CalculatorTestSubjectGenerator generator) {
		return new CalculatorTestSuiteBuilder().usingGenerator(generator).named(generator.getName());
	}
}


text:
#include "ion/remote/portutils.h"

#include <initializer_list>

#include "base/integral_types.h"

#if defined(ION_PLATFORM_WINDOWS)
#include "ws2tcpip.h"  // NOLINT(build/include)
#define inet_pton InetPtonA
#endif

namespace ion {
namespace remote {

namespace {

enum SocketAddress {
  kAddress,
  kAny,
  kLoopback
};

sockaddr_storage MakeSockaddr(int family, int port, SocketAddress address,
                              const char* address_string) {
  sockaddr_storage addr = {};
  if (family == AF_INET6) {
    sockaddr_in6* paddr = reinterpret_cast<sockaddr_in6*>(&addr);
    paddr->sin6_family = AF_INET6;
    if (address == kAny) {
      paddr->sin6_addr = in6addr_any;
    } else if (address == kLoopback) {
      paddr->sin6_addr = in6addr_loopback;
    } else {
      inet_pton(family, address_string, &paddr->sin6_addr);
    }
    paddr->sin6_port = static_cast<uint16>(htons(static_cast<uint16>(port)));
  } else {
    sockaddr_in* paddr = reinterpret_cast<sockaddr_in*>(&addr);
    paddr->sin_family = AF_INET;
    if (address == kAny) {
      paddr->sin_addr.s_addr = htonl(INADDR_ANY);
    } else if (address == kLoopback) {
      paddr->sin_addr.s_addr = htonl(INADDR_LOOPBACK);
    } else {
      inet_pton(family, address_string, &paddr->sin_addr.s_addr);
    }
    paddr->sin_port = htons(static_cast<uint16>(port));
  }
  return addr;
}

}  // anonymous namespace

sockaddr_storage MakeWildcard(int family, int port) {
  return MakeSockaddr(family, port, kAny, nullptr);
}

sockaddr_storage MakeLoopback(int family, int port) {
  return MakeSockaddr(family, port, kLoopback, nullptr);
}

sockaddr_storage MakeAddress(int family, int port, const char* address) {
  return MakeSockaddr(family, port, kAddress, address);
}

int GetSocket(int protocol, sockaddr_storage* addr) {
  // Try IPV6 first.
  for (int family : {AF_INET6, AF_INET}) {
    const ion_socket_t fd = socket(family, protocol, 0);
#if defined(ION_PLATFORM_WINDOWS)
    const bool socket_is_valid = fd != INVALID_SOCKET;
#else
    const bool socket_is_valid = fd >= 0;
#endif
    if (socket_is_valid) {
      *addr = MakeWildcard(family, 0);
      return static_cast<int>(fd);
    }
  }
  return -1;
}

int GetPort(const sockaddr_storage& addr) {
  if (addr.ss_family == AF_INET6) {
    return ntohs(reinterpret_cast<const sockaddr_in6*>(&addr)->sin6_port);
  } else {
    return ntohs(reinterpret_cast<const sockaddr_in*>(&addr)->sin_port);
  }
}

socklen_t GetSockaddrLength(const sockaddr_storage& addr) {
  if (addr.ss_family == AF_INET6) {
    return sizeof(sockaddr_in6);
  } else {
    return sizeof(sockaddr_in);
  }
}

}  // namespace remote
}  // namespace ion


text:
package main

import (
	"testing"

	"github.com/jonboulle/clockwork"
	"github.com/spf13/viper"
)

func TestSuperceded(t *testing.T) {
	xml := []byte(`<?xml version='1.0' encoding='UTF-8'?>
<eveapi version="2">
  <result>
    <rowset name="jobs" key="jobID" columns="jobID,installerName,blueprintTypeName,endDate">
      <row jobID="1" installerName="Fake Character" blueprintTypeName="Test Item I Blueprint" endDate="2020-01-01 01:01:01" />
      <row jobID="2" installerName="Fake Character" blueprintTypeName="Test Item I Blueprint" endDate="2020-01-01 01:01:02" />
      <row jobID="3" installerName="Fake Character" blueprintTypeName="Test Item I Blueprint" endDate="2020-01-01 01:02:03" />
      <row jobID="4" installerName="Fake Character" blueprintTypeName="Test Item I Blueprint" endDate="2020-01-01 02:02:03" />
      <row jobID="5" installerName="Fake Character" blueprintTypeName="Test Item I Blueprint" endDate="2020-01-01 02:02:03" />
    </rowset>
  </result>
</eveapi>`)
	jobs, err := ParseXmlApiResponse(xml)
	if err != nil {
		t.Fatal(err)
	}

	jobList := NewJobList(NewTestCharacterConfig(), clockwork.NewFakeClock(), NewFakeAlerter())
	jobList.SetJobs(jobs)

	expected := true
	result := jobList.IsSuperceded(jobs[0])
	if expected != result {
		t.Fatal("Unexpected result", result)
	}

	expected = false
	result = jobList.IsSuperceded(jobs[1])
	if expected != result {
		t.Fatal("Unexpected result", result)
	}

	expected = false
	result = jobList.IsSuperceded(jobs[2])
	if expected != result {
		t.Fatal("Unexpected result", result)
	}

	expected = true
	result = jobList.IsSuperceded(jobs[3])
	if expected != result {
		t.Fatal("Unexpected result", result)
	}

	expected = false
	result = jobList.IsSuperceded(jobs[4])
	if expected != result {
		t.Fatal("Unexpected result", result)
	}
}

// Jobs which are removed from the feed are forgotten about.
func TestJobsAreRemoved(t *testing.T) {
	xml := []byte(`<?xml version='1.0' encoding='UTF-8'?>
<eveapi version="2">
  <result>
    <rowset name="jobs" key="jobID" columns="jobID,installerName,blueprintTypeName,endDate">
      <row jobID="1" installerName="Fake Character" blueprintTypeName="Test Item I Blueprint" endDate="2020-01-01 01:01:01" />
      <row jobID="2" installerName="Fake Character" blueprintTypeName="Test Item I Blueprint" endDate="2020-01-01 01:01:02" />
    </rowset>
  </result>
</eveapi>`)
	jobs, err := ParseXmlApiResponse(xml)
	if err != nil {
		t.Fatal(err)
	}

	jobList := NewJobList(NewTestCharacterConfig(), clockwork.NewFakeClock(), NewFakeAlerter())
	jobList.SetJobs(jobs)

	jobs = jobs[1:]
	jobList.SetJobs(jobs)

	if jobList.Count() != 1 {
		t.Fatal("Unexpected elements in job list.")
	}
}

func TestJobEquality(t *testing.T) {
	j1 := Job{
		ID:            1,
		Blueprint:     "Test Item Blueprint I",
		Installer:     "Fake Character",
		EndDateString: "2020-01-01 01:01:01",
	}
	j2 := Job{
		ID:            1,
		Blueprint:     "Test Item Blueprint I",
		Installer:     "Fake Character",
		EndDateString: "2020-01-01 01:01:01",
	}
	if j1 != j2 {
		t.Fatal("Jobs are not equal")
	}
}

// This will actualy post a message to "agrakari" on Slack.
func TestSlackAlert(t *testing.T) {
	viper.SetEnvPrefix("ijns")
	viper.BindEnv("slack_token")
	token := viper.GetString("slack_token")

	if token == "" {
		t.Skip("Token not specified")
	}

	alerter := NewSlackAlerter(token)
	j1 := &Job{
		ID:            1,
		Blueprint:     "Test Item Blueprint I",
		Installer:     "Fake Character",
		EndDateString: "2020-01-01 01:01:01",
	}
	alerter.Alert(j1, "agrakari")
}


text:
package com.axonivy.ivy.process.element.rest.start.ui;

import java.util.List;

import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.forms.widgets.ExpandableComposite;
import org.eclipse.ui.forms.widgets.SharedScrolledComposite;

import ch.ivyteam.ivy.awtGuiComponents.ivvScriptTrees.IvyClassIconProvider.Mode;
import ch.ivyteam.ivy.guiComponents.swt.restricted.mapping.MappingTreeTable;
import ch.ivyteam.ivy.guiComponents.swt.tables.MappingTable;
import ch.ivyteam.swt.table.ExpandableCompositeUtil;
import ch.ivyteam.swt.table.Row;
import ch.ivyteam.ui.model.swt.UiChangeListener;

public class RestStartComposite extends SharedScrolledComposite implements Listener, UiChangeListener
{
  final ExpandableComposite propertySelector;
  final MappingTable inputParamsTable;
  final MappingTreeTable parameterMapping;
  final Text signatureText;
  final Text nameText;

  public RestStartComposite(Composite parent)
  {
    super(parent, SWT.H_SCROLL | SWT.V_SCROLL);
    setExpandHorizontal(true);
    setExpandVertical(true);

    Composite scrollContent = new Composite(this, SWT.NONE);
    scrollContent.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
    scrollContent.setLayout(new GridLayout(1, true));
    setContent(scrollContent);

    Group signatureComposite = new Group(scrollContent, SWT.NONE);
    signatureComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1));
    signatureComposite.setText("Start Signature");
    signatureComposite.setLayout(new GridLayout(2, false));

    Label signatureLabel = new Label(signatureComposite, SWT.NONE);
    signatureLabel.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1));
    signatureLabel.setText("Signature");
    signatureText = new Text(signatureComposite, SWT.NONE);
    signatureText.setEnabled(false);
    signatureText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));

    Label nameLabel = new Label(signatureComposite, SWT.NONE);
    nameLabel.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1));
    nameLabel.setText("Name");
    nameText = new Text(signatureComposite, SWT.NONE);
    nameText.addListener(SWT.Modify, this);
    nameText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));

    propertySelector = new ExpandableComposite(signatureComposite, SWT.NONE);
    propertySelector.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1));
    propertySelector.setText("Input Parameters");
    inputParamsTable = new MappingTable(propertySelector, SWT.DROP_DOWN);
    propertySelector.setClient(inputParamsTable);
    ExpandableCompositeUtil.wireSizeUpdates(this, propertySelector, inputParamsTable);
    inputParamsTable.addChangeListener(this);

    Group parameterComposite = new Group(scrollContent, SWT.NONE);
    parameterComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
    parameterComposite.setText("Input Parameters to Process Data Mapping");
    parameterComposite.setLayout(new GridLayout(1, false));
    parameterMapping = new MappingTreeTable(parameterComposite, SWT.NONE);
    parameterMapping.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
    parameterMapping.setMode(Mode.PANEL);
  }

  @Override
  public void handleEvent(Event event)
  {
    uiChanged();
  }

  private static String getMethodParams(List<Row> rows)
  {
    if(rows == null || rows.size() == 0)
    {
      return "";
    }
    StringBuilder builder = new StringBuilder();
    for (int i = 0; i < rows.size(); i++)
    {
      Row row = rows.get(i);
      builder.append(row.value);
      if (i+1 < rows.size())
      {
        builder.append(",");
      }
    }
    return builder.toString();
  }

  @Override
  public void uiChanged()
  {
    signatureText.setText(nameText.getText() + "(" + getMethodParams(inputParamsTable.getItems()) + ")");
  }

  @SuppressWarnings("unused")
  public static void main(String[] args)
  {
    Display display = Display.getDefault();
    Shell shell = new Shell();

    new RestStartComposite(shell);

    shell.setLayout(new FillLayout());
    shell.setSize(600,600);
    shell.setText("Test Rest Service Start UI");
    shell.layout();
    shell.open();
    while(!shell.isDisposed())
    {
      if (!display.readAndDispatch())
      {
        display.sleep();
      }
    }
  }
}


text:
package Lucy::Build::Binding::Misc;
use strict;
use warnings;

our $VERSION = '0.004000';
$VERSION = eval $VERSION;

sub bind_all {
    my ($class, $hierarchy) = @_;

    require Clownfish;
    $hierarchy->inherit_metadata;

    $class->bind_lucy;
    $class->bind_simple;
    $class->bind_test;
}

sub bind_lucy {
    my $xs_code = <<'END_XS_CODE';
MODULE = Lucy    PACKAGE = Lucy

IV
_dummy_function()
CODE:
    RETVAL = 1;
OUTPUT:
    RETVAL

void
STORABLE_freeze(self, ...)
    cfish_Obj *self;
PPCODE:
{
    CFISH_UNUSED_VAR(self);
    if (items < 2 || !SvTRUE(ST(1))) {
        SV *retval;
        cfish_ByteBuf *serialized_bb;
        lucy_RAMFileHandle *file_handle
            = lucy_RAMFH_open(NULL, LUCY_FH_WRITE_ONLY | LUCY_FH_CREATE, NULL);
        lucy_OutStream *target = lucy_OutStream_open((cfish_Obj*)file_handle);

        lucy_Freezer_serialize(self, target);

        LUCY_OutStream_Close(target);
        serialized_bb
            = LUCY_RAMFile_Get_Contents(LUCY_RAMFH_Get_File(file_handle));
        retval = (SV*)CFISH_BB_To_Host(serialized_bb);
        CFISH_DECREF(file_handle);
        CFISH_DECREF(target);

        if (SvCUR(retval) == 0) { // Thwart Storable bug
            THROW(CFISH_ERR, "Calling serialize produced an empty string");
        }
        ST(0) = sv_2mortal(retval);
        XSRETURN(1);
    }
}

=begin comment

Calls deserialize(), and copies the object pointer.  Since deserialize is an
abstract method, it will confess() unless implemented.

=end comment

=cut

void
STORABLE_thaw(blank_obj, cloning, serialized_sv)
    SV *blank_obj;
    SV *cloning;
    SV *serialized_sv;
PPCODE:
{
    char *class_name = HvNAME(SvSTASH(SvRV(blank_obj)));
    cfish_String *class_name_str
        = CFISH_SSTR_WRAP_UTF8(class_name, strlen(class_name));
    cfish_Class *klass = cfish_Class_singleton(class_name_str, NULL);
    STRLEN len;
    char *ptr = SvPV(serialized_sv, len);
    cfish_ByteBuf *contents = cfish_BB_new_bytes(ptr, len);
    lucy_RAMFile *ram_file = lucy_RAMFile_new(contents, true);
    lucy_RAMFileHandle *file_handle
        = lucy_RAMFH_open(NULL, LUCY_FH_READ_ONLY, ram_file);
    lucy_InStream *instream = lucy_InStream_open((cfish_Obj*)file_handle);
    cfish_Obj *self = CFISH_Class_Foster_Obj(klass, blank_obj);
    cfish_Obj *deserialized = lucy_Freezer_deserialize(self, instream);

    CFISH_UNUSED_VAR(cloning);
    CFISH_DECREF(contents);
    CFISH_DECREF(ram_file);
    CFISH_DECREF(file_handle);
    CFISH_DECREF(instream);

    // Catch bad deserialize() override.
    if (deserialized != self) {
        THROW(CFISH_ERR, "Error when deserializing obj of class %o", klass);
    }
}
END_XS_CODE

    my $binding = Clownfish::CFC::Binding::Perl::Class->new(
        parcel     => "Lucy",
        class_name => "Lucy",
    );
    $binding->append_xs($xs_code);

    Clownfish::CFC::Binding::Perl::Class->register($binding);
}

sub bind_simple {
    my @hand_rolled = qw( Add_Doc );

    my $pod_spec = Clownfish::CFC::Binding::Perl::Pod->new;
    my $synopsis = <<'END_SYNOPSIS';
First, build an index of your documents.

    my $index = Lucy::Simple->new(
        path     => '/path/to/index/'
        language => 'en',
    );

    while ( my ( $title, $content ) = each %source_docs ) {
        $index->add_doc({
            title    => $title,
            content  => $content,
        });
    }

Later, search the index.

    my $total_hits = $index->search(
        query      => $query_string,
        offset     => 0,
        num_wanted => 10,
    );

    print "Total hits: $total_hits\n";
    while ( my $hit = $index->next ) {
        print "$hit->{title}\n",
    }
END_SYNOPSIS
    my $add_doc_pod = <<'END_ADD_DOC_POD';
=head2 add_doc

    $lucy->add_doc({
        location => $url,
        title    => $title,
        content  => $content,
    });

Add a document to the index. The document must be supplied as a hashref,
with field names as keys and content as values.

END_ADD_DOC_POD
    $pod_spec->set_synopsis($synopsis);

    # Override is necessary because there's no standard way to explain
    # hash/hashref across multiple host languages.
    $pod_spec->add_method(
        method => 'Add_Doc',
        alias  => 'add_doc',
        pod    => $add_doc_pod,
    );

    my $xs_code = <<'END_XS_CODE';
MODULE = Lucy  PACKAGE = Lucy::Simple

void
add_doc(self, doc_sv)
    lucy_Simple *self;
    SV *doc_sv;
PPCODE:
{
    lucy_Doc *doc = NULL;

    // Either get a Doc or use the stock doc.
    if (sv_isobject(doc_sv)
        && sv_derived_from(doc_sv, "Lucy::Document::Doc")
       ) {
        IV tmp = SvIV(SvRV(doc_sv));
        doc = INT2PTR(lucy_Doc*, tmp);
    }
    else if (XSBind_sv_defined(aTHX_ doc_sv) && SvROK(doc_sv)) {
        HV *maybe_fields = (HV*)SvRV(doc_sv);
        if (SvTYPE((SV*)maybe_fields) == SVt_PVHV) {
            lucy_Indexer *indexer = LUCY_Simple_Get_Indexer(self);
            doc = LUCY_Indexer_Get_Stock_Doc(indexer);
            LUCY_Doc_Set_Fields(doc, maybe_fields);
        }
    }
    if (!doc) {
        THROW(CFISH_ERR, "Need either a hashref or a %o",
              CFISH_Class_Get_Name(LUCY_DOC));
    }

    LUCY_Simple_Add_Doc(self, doc);
}
END_XS_CODE

    my $binding = Clownfish::CFC::Binding::Perl::Class->new(
        parcel     => "Lucy",
        class_name => "Lucy::Simple",
    );
    $binding->exclude_method($_) for @hand_rolled;
    $binding->append_xs($xs_code);
    $binding->set_pod_spec($pod_spec);

    Clownfish::CFC::Binding::Perl::Class->register($binding);
}

sub bind_test {
    my $xs_code = <<'END_XS_CODE';
MODULE = Lucy   PACKAGE = Lucy::Test

#include "Clownfish/TestHarness/TestFormatter.h"
#include "Clownfish/TestHarness/TestSuite.h"

bool
run_tests(package)
    char *package;
CODE:
    cfish_String *class_name = cfish_Str_newf("%s", package);
    cfish_TestFormatter *formatter
        = (cfish_TestFormatter*)cfish_TestFormatterTAP_new();
    cfish_TestSuite *suite = testlucy_Test_create_test_suite();
    bool result = CFISH_TestSuite_Run_Batch(suite, class_name, formatter);
    CFISH_DECREF(class_name);
    CFISH_DECREF(formatter);
    CFISH_DECREF(suite);

    RETVAL = result;
OUTPUT: RETVAL
END_XS_CODE

    my $binding = Clownfish::CFC::Binding::Perl::Class->new(
        parcel     => "TestLucy",
        class_name => "Lucy::Test",
    );
    $binding->append_xs($xs_code);

    Clownfish::CFC::Binding::Perl::Class->register($binding);
}

1;


text:
function createError(message, statusCode = null, innerError = null) {
  const error = new Error(message || (innerError && innerError.message) || 'Unknown error');

  return Object.assign(error, {
    code: parseInt(statusCode),
    innerError
  });
}

function throwError(...args) {
  throw createError.apply(null, args);
}

export {
  createError,
  throwError
}


text:
module Api
  module V1
    module Data
      class NdcSdgController < Api::V1::Data::ApiController
        include Streamable
        before_action :parametrise_filter, only: [:index, :download]

        def index
          @records = paginate @filter.call
          render json: @records,
                 adapter: :json,
                 each_serializer: Api::V1::Data::NdcSdg::NdcSdgSerializer,
                 params: params,
                 root: :data,
                 meta: @filter.meta
        end

        def meta
          set_links_header(
            [:goals, :targets, :sectors].map do |resource|
              {
                link: "/api/v1/data/ndc_sdg/#{resource}",
                rel: "meta #{resource}"
              }
            end + [{link: '/api/v1/locations/countries', rel: 'meta locations'}]
          )
        end

        def download
          zipped_download = Api::V1::Data::NdcSdg::ZippedDownload.new(@filter)
          stream_file(zipped_download.filename) { zipped_download.call }
        end

        private

        def parametrise_filter
          @filter = Data::NdcSdg::Filter.new(params)
        end
      end
    end
  end
end


text:
#include "rdkafka_int.h"
#include "rdkafka_assignor.h"

#include <ctype.h>

/**
 * Clear out and free any memory used by the member, but not the rkgm itself.
 */
void rd_kafka_group_member_clear (rd_kafka_group_member_t *rkgm) {
        if (rkgm->rkgm_subscription)
                rd_kafka_topic_partition_list_destroy(rkgm->rkgm_subscription);

        if (rkgm->rkgm_assignment)
                rd_kafka_topic_partition_list_destroy(rkgm->rkgm_assignment);

        rd_list_destroy(&rkgm->rkgm_eligible, NULL);

        if (rkgm->rkgm_member_id)
                rd_kafkap_str_destroy(rkgm->rkgm_member_id);

        if (rkgm->rkgm_userdata)
                rd_kafkap_bytes_destroy(rkgm->rkgm_userdata);

        if (rkgm->rkgm_member_metadata)
                rd_kafkap_bytes_destroy(rkgm->rkgm_member_metadata);

        memset(rkgm, 0, sizeof(*rkgm));
}

/**
 * Member id string comparator (takes rd_kafka_group_member_t *)
 */
int rd_kafka_group_member_cmp (const void *_a, const void *_b) {
        const rd_kafka_group_member_t *a =
                (const rd_kafka_group_member_t *)_a;
        const rd_kafka_group_member_t *b =
                (const rd_kafka_group_member_t *)_b;

        return rd_kafkap_str_cmp(a->rkgm_member_id, b->rkgm_member_id);
}

/**
 * Member id string comparator (takes rd_kafka_group_member_t **)
 */
int rd_kafka_group_member_cmp_pp (const void *_a, const void *_b) {
        const rd_kafka_group_member_t *a =
                *(const rd_kafka_group_member_t * const *)_a;
        const rd_kafka_group_member_t *b =
                *(const rd_kafka_group_member_t * const *)_b;

        return rd_kafkap_str_cmp(a->rkgm_member_id, b->rkgm_member_id);
}

/**
 * Returns true if member subscribes to topic, else false.
 */
int
rd_kafka_group_member_find_subscription (rd_kafka_t *rk,
					 const rd_kafka_group_member_t *rkgm,
					 const char *topic) {
	int i;

	/* Match against member's subscription. */
        for (i = 0 ; i < rkgm->rkgm_subscription->cnt ; i++) {
                const rd_kafka_topic_partition_t *rktpar =
                        &rkgm->rkgm_subscription->elems[i];

		if (rd_kafka_topic_partition_match(rk, rkgm, rktpar,
						   topic, NULL))
			return 1;
	}

	return 0;
}

static rd_kafkap_bytes_t *
rd_kafka_consumer_protocol_member_metadata_new (
        const rd_kafka_topic_partition_list_t *subscription,
        const void *userdata, size_t userdata_size) {
        rd_kafka_buf_t *rkbuf;
        rd_kafkap_bytes_t *kbytes;
        int i;

        /*
         * MemberMetadata => Version Subscription AssignmentStrategies
         *   Version      => int16
         *   Subscription => Topics UserData
         *     Topics     => [String]
         *     UserData     => Bytes
         */

        rkbuf = rd_kafka_buf_new_growable(NULL, 1,
                                          100 +
                                          (subscription->cnt * 100) +
                                          userdata_size);

        rd_kafka_buf_write_i16(rkbuf, 0);
        rd_kafka_buf_write_i32(rkbuf, subscription->cnt);
        for (i = 0 ; i < subscription->cnt ; i++)
                rd_kafka_buf_write_str(rkbuf, subscription->elems[i].topic,-1);
        rd_kafka_buf_write_bytes(rkbuf, userdata, userdata_size);

        rd_kafka_buf_autopush(rkbuf);

        kbytes = rd_kafkap_bytes_from_buf(rkbuf);

        rd_kafka_buf_destroy(rkbuf);

        return kbytes;

}

rd_kafkap_bytes_t *
rd_kafka_assignor_get_metadata (rd_kafka_assignor_t *rkas,
                                const rd_kafka_topic_partition_list_t
                                *subscription) {
        return rd_kafka_consumer_protocol_member_metadata_new(
                subscription, rkas->rkas_userdata,
                rkas->rkas_userdata_size);
}

/**
 * Returns 1 if all subscriptions are satifised for this member, else 0.
 */
static int rd_kafka_member_subscription_match (
        rd_kafka_cgrp_t *rkcg,
        rd_kafka_group_member_t *rkgm,
        const rd_kafka_metadata_topic_t *topic_metadata,
        rd_kafka_assignor_topic_t *eligible_topic) {
        int i;
        int has_regex = 0;
        int matched = 0;

        /* Match against member's subscription. */
        for (i = 0 ; i < rkgm->rkgm_subscription->cnt ; i++) {
                const rd_kafka_topic_partition_t *rktpar =
                        &rkgm->rkgm_subscription->elems[i];
		int matched_by_regex = 0;

		if (rd_kafka_topic_partition_match(rkcg->rkcg_rk, rkgm, rktpar,
						   topic_metadata->topic,
						   &matched_by_regex)) {
			rd_list_add(&rkgm->rkgm_eligible,
				    (void *)topic_metadata);
			matched++;
			has_regex += matched_by_regex;
		}
	}

        if (matched)
                rd_list_add(&eligible_topic->members, rkgm);

        if (!has_regex &&
            rd_list_cnt(&rkgm->rkgm_eligible) == rkgm->rkgm_subscription->cnt)
                return 1; /* All subscriptions matched */
        else
                return 0;
}

/**
 * Maps the available topics to the group members' subscriptions
 * and updates the `member` map with the proper list of eligible topics,
 * the latter are returned in `eligible_topics`.
 */
static void
rd_kafka_member_subscriptions_map (rd_kafka_cgrp_t *rkcg,
                                   rd_list_t *eligible_topics,
                                   const rd_kafka_metadata_t *metadata,
                                   rd_kafka_group_member_t *members,
                                   int member_cnt) {
        int ti;
        rd_kafka_assignor_topic_t *eligible_topic = NULL;

        rd_list_init(eligible_topics, RD_MIN(metadata->topic_cnt, 10));

        /* For each topic in the cluster, scan through the member list
         * to find matching subscriptions. */
        for (ti = 0 ; ti < metadata->topic_cnt ; ti++) {
                int complete_cnt = 0;
                int i;

                /* Ignore topics in blacklist */
                if (rd_kafka_pattern_match(&rkcg->rkcg_rk->rk_conf.
                                           topic_blacklist,
                                           metadata->topics[ti].topic)) {
                        rd_kafka_dbg(rkcg->rkcg_rk, TOPIC, "BLACKLIST",
                                   "Assignor ignoring blacklisted "
                                     "topic \"%s\"",
                                     metadata->topics[ti].topic);
                        continue;
                }

                if (!eligible_topic)
                        eligible_topic = rd_calloc(1, sizeof(*eligible_topic));

                rd_list_init(&eligible_topic->members, member_cnt);

                /* For each member: scan through its topic subscription */
                for (i = 0 ; i < member_cnt ; i++) {
                        /* Match topic against existing metadata,
                           incl regex matching. */
                        if (rd_kafka_member_subscription_match(
                                    rkcg, &members[i], &metadata->topics[ti],
                                    eligible_topic))
                                complete_cnt++;
                }

                if (rd_list_empty(&eligible_topic->members)) {
                        rd_list_destroy(&eligible_topic->members, NULL);
                        continue;
                }

                eligible_topic->metadata = &metadata->topics[ti];
                rd_list_add(eligible_topics, eligible_topic);
                eligible_topic = NULL;

                if (complete_cnt == (int)member_cnt)
                        break;
        }

        if (eligible_topic)
                rd_free(eligible_topic);
}

static void
rd_kafka_assignor_topic_destroy (rd_kafka_assignor_topic_t *at) {
        rd_list_destroy(&at->members, NULL);
        rd_free(at);
}

int rd_kafka_assignor_topic_cmp (const void *_a, const void *_b) {
	const rd_kafka_assignor_topic_t *a =
                *(const rd_kafka_assignor_topic_t * const *)_a;
        const rd_kafka_assignor_topic_t *b =
                *(const rd_kafka_assignor_topic_t * const *)_b;

	return !strcmp(a->metadata->topic, b->metadata->topic);
}

rd_kafka_resp_err_t
rd_kafka_assignor_run (rd_kafka_cgrp_t *rkcg,
                       const char *protocol_name,
                       rd_kafka_metadata_t *metadata,
                       rd_kafka_group_member_t *members,
                       int member_cnt,
                       char *errstr, size_t errstr_size) {
        rd_kafka_resp_err_t err;
        rd_kafka_assignor_t *rkas;
        rd_ts_t ts_start = rd_clock();
        int i;
        rd_list_t eligible_topics;
        int j;

	if (!(rkas = rd_kafka_assignor_find(rkcg->rkcg_rk, protocol_name)) ||
	    !rkas->rkas_enabled) {
		rd_snprintf(errstr, errstr_size,
			    "Unsupported assignor \"%s\"", protocol_name);
		return RD_KAFKA_RESP_ERR__UNKNOWN_PROTOCOL;
	}

        /* Map available topics to subscribing members */
        rd_kafka_member_subscriptions_map(rkcg, &eligible_topics, metadata,
                                          members, member_cnt);

        if (rkcg->rkcg_rk->rk_conf.debug & RD_KAFKA_DBG_CGRP) {
                rd_kafka_dbg(rkcg->rkcg_rk, CGRP, "ASSIGN",
                             "Group \"%s\" running %s assignment for "
                             "%d member(s):",
                             rkcg->rkcg_group_id->str, protocol_name,
                             member_cnt);

                for (i = 0 ; i < member_cnt ; i++) {
                        const rd_kafka_group_member_t *member = &members[i];

                        rd_kafka_dbg(rkcg->rkcg_rk, CGRP, "ASSIGN",
                                     " Member \"%.*s\"%s with "
                                     "%d subscription(s):",
                                     RD_KAFKAP_STR_PR(member->rkgm_member_id),
                                     !rd_kafkap_str_cmp(member->rkgm_member_id,
                                                        rkcg->rkcg_member_id) ?
                                     " (me)":"",
                                     member->rkgm_subscription->cnt);
                        for (j = 0 ; j < member->rkgm_subscription->cnt ; j++) {
                                const rd_kafka_topic_partition_t *p =
                                        &member->rkgm_subscription->elems[j];
                                rd_kafka_dbg(rkcg->rkcg_rk, CGRP, "ASSIGN",
                                             "  %s [%"PRId32"]",
                                             p->topic, p->partition);
                        }
                }

        }

        /* Call assignors assign callback */
        err = rkas->rkas_assign_cb(rkcg->rkcg_rk,
                                    rkcg->rkcg_member_id->str,
                                    protocol_name, metadata,
                                    members, member_cnt,
                                    (rd_kafka_assignor_topic_t **)
                                    eligible_topics.rl_elems,
                                    eligible_topics.rl_cnt,
                                    errstr, sizeof(errstr),
                                    rkas->rkas_opaque);

        if (err) {
                rd_kafka_dbg(rkcg->rkcg_rk, CGRP, "ASSIGN",
                             "Group \"%s\" %s assignment failed "
                             "for %d member(s): %s",
                             rkcg->rkcg_group_id->str, protocol_name,
                             (int)member_cnt, errstr);
        } else if (rkcg->rkcg_rk->rk_conf.debug & RD_KAFKA_DBG_CGRP) {
                rd_kafka_dbg(rkcg->rkcg_rk, CGRP, "ASSIGN",
                             "Group \"%s\" %s assignment for %d member(s) "
                             "finished in %.3fms:",
                             rkcg->rkcg_group_id->str, protocol_name,
                             (int)member_cnt,
                             (float)(rd_clock() - ts_start)/1000.0f);
                for (i = 0 ; i < member_cnt ; i++) {
                        const rd_kafka_group_member_t *member = &members[i];

                        rd_kafka_dbg(rkcg->rkcg_rk, CGRP, "ASSIGN",
                                     " Member \"%.*s\"%s assigned "
                                     "%d partition(s):",
                                     RD_KAFKAP_STR_PR(member->rkgm_member_id),
                                     !rd_kafkap_str_cmp(member->rkgm_member_id,
                                                        rkcg->rkcg_member_id) ?
                                     " (me)":"",
                                     member->rkgm_assignment->cnt);
                        for (j = 0 ; j < member->rkgm_assignment->cnt ; j++) {
                                const rd_kafka_topic_partition_t *p =
                                        &member->rkgm_assignment->elems[j];
                                rd_kafka_dbg(rkcg->rkcg_rk, CGRP, "ASSIGN",
                                             "  %s [%"PRId32"]",
                                             p->topic, p->partition);
                        }
                }
        }

        rd_list_destroy(&eligible_topics,
                        (void *)rd_kafka_assignor_topic_destroy);

        return err;
}

/**
 * Assignor protocol string comparator
 */
static int rd_kafka_assignor_cmp_str (const void *_a, const void *_b) {
        const char *a = _a;
        const rd_kafka_assignor_t *b = _b;

        return rd_kafkap_str_cmp_str(b->rkas_protocol_name, a);
}

/**
 * Find assignor by protocol name.
 *
 * Locality: any
 * Locks: none
 */
rd_kafka_assignor_t *
rd_kafka_assignor_find (rd_kafka_t *rk, const char *protocol) {
        return (rd_kafka_assignor_t *)
                rd_list_find(&rk->rk_conf.partition_assignors, protocol,
                             rd_kafka_assignor_cmp_str);
}

/**
 * Destroys an assignor (but does not unlink).
 */
static void rd_kafka_assignor_destroy (rd_kafka_assignor_t *rkas) {
        rd_kafkap_str_destroy(rkas->rkas_protocol_type);
        rd_kafkap_str_destroy(rkas->rkas_protocol_name);
        rd_free(rkas);
}

/**
 * Add an assignor, overwriting any previous one with the same protocol_name.
 */
rd_kafka_resp_err_t
rd_kafka_assignor_add (rd_kafka_t *rk,
                       const char *protocol_type,
                       const char *protocol_name,
                       rd_kafka_resp_err_t (*assign_cb) (
                               rd_kafka_t *rk,
                               const char *member_id,
                               const char *protocol_name,
                               const rd_kafka_metadata_t *metadata,
                               rd_kafka_group_member_t *members,
                               size_t member_cnt,
                               rd_kafka_assignor_topic_t **eligible_topics,
                               size_t eligible_topic_cnt,
                               char *errstr, size_t errstr_size, void *opaque),
                       void *opaque) {
        rd_kafka_assignor_t *rkas;

        if (rd_kafkap_str_cmp_str(rk->rk_conf.group_protocol_type,
                                  protocol_type))
                return RD_KAFKA_RESP_ERR__UNKNOWN_PROTOCOL;

        /* Dont overwrite application assignors */
        if ((rkas = rd_kafka_assignor_find(rk, protocol_name)))
		return RD_KAFKA_RESP_ERR__CONFLICT;

        rkas = rd_calloc(1, sizeof(*rkas));

        rkas->rkas_protocol_name    = rd_kafkap_str_new(protocol_name, -1);
        rkas->rkas_protocol_type    = rd_kafkap_str_new(protocol_type, -1);
        rkas->rkas_assign_cb        = assign_cb;
        rkas->rkas_get_metadata_cb  = rd_kafka_assignor_get_metadata;
        rkas->rkas_opaque = opaque;

        rd_list_add(&rk->rk_conf.partition_assignors, rkas);

        return RD_KAFKA_RESP_ERR_NO_ERROR;
}

/* Right trim string of whitespaces */
static void rtrim (char *s) {
	char *e = s + strlen(s);

	if (e == s)
		return;

	while (e >= s && isspace(*e))
		e--;

	*e = '\0';
}

/**
 * Initialize assignor list based on configuration.
 */
int rd_kafka_assignors_init (rd_kafka_t *rk, char *errstr, size_t errstr_size) {
	char *wanted;
	char *s;

	/* Add builtin assignors */
	rd_kafka_assignor_add(rk, "consumer", "range",
                              rd_kafka_range_assignor_assign_cb,
                              NULL);
        rd_kafka_assignor_add(rk, "consumer", "roundrobin",
                              rd_kafka_roundrobin_assignor_assign_cb,
                              NULL);

	rd_strdupa(&wanted, rk->rk_conf.partition_assignment_strategy);

	s = wanted;
	while (*s) {
		rd_kafka_assignor_t *rkas;
		char *t;

		/* Left trim */
		while (*s == ' ' || *s == ',')
			s++;

		if ((t = strchr(s, ','))) {
			*t = '\0';
			t++;
		} else {
			t = s + strlen(s);
		}

		/* Right trim */
		rtrim(s);

		if (!(rkas = rd_kafka_assignor_find(rk, s))) {
			rd_snprintf(errstr, errstr_size,
				    "Unsupported "
				    "partition.assignment.strategy \"%s\" "
				    "for group.protocol.type=\"%s\"",
				    s, rk->rk_conf.group_protocol_type->str);
			return -1;
		} else {
			if (!rkas->rkas_enabled) {
				rkas->rkas_enabled = 1;
				rk->rk_conf.enabled_assignor_cnt++;
			}
		}

		s = t;
	}

	return 0;
}

/**
 * Free assignors
 */
void rd_kafka_assignors_term (rd_kafka_t *rk) {
        rd_list_destroy(&rk->rk_conf.partition_assignors,
                        (void *)rd_kafka_assignor_destroy);
}


text:
require 'spec_helper'

describe ApplicationHelper do
  describe '#stars' do
    it 'adds some stars' do
      helper.stars(2).should include "icons/star.png"
    end

    it 'add some images' do
      helper.stars(2).should include "<img"
    end

    it 'takes a second parameter to specify the maximum available stars' do
      helper.stars(2, 2).should_not include "icons/star_inactive.png"
    end

    it 'second parameter defaults to 5' do
      helper.stars(5).should_not include "icons/star_inactive.png"
    end

    it 'fills up with inactive stars according to the total parameter' do
      helper.stars(2, 3).should include "icons/star_inactive.png"
    end

    it 'adds exactly as much images as the second paremeter specifies' do
      helper.stars(2, 3).should match /^<img.+?<img.+?<img.+?>[^<img]*$/
    end

    it 'should return html safe content' do
      helper.stars(2).html_safe?.should be_true
    end
  end

  describe '#acceptance_state' do
    it 'returns an image' do
      helper.acceptance_state(true).should include "<img"
    end

    it 'returns the right image for true' do
      helper.acceptance_state(true).should include 'icons/accepted.png'
    end

    it 'returns the right image for false' do
      helper.acceptance_state(false).should include 'icons/not_accepted.png'
    end

    it 'should return html safe content' do
      helper.acceptance_state(true).html_safe?.should be_true
    end
  end

  describe '#uptime' do
    it 'includes "Up since" when passed nil' do
      helper.uptime(nil).should include "Up since"
    end

    it 'includes "Up since when passed a time' do
      helper.uptime(3.days.from_now).should include "Up since"
    end

    it 'includes "never" if passed nil' do
      helper.uptime(nil).should include "never"
    end

    it 'includes not "never" if passed in a time' do
      helper.uptime(3.days.from_now).should_not include "never"
    end

    it 'should call time_ago_in_words when passed in a time' do
      time = 3.days.from_now
      helper.should_receive(:time_ago_in_words).with(time).exactly(1).times.and_return("foo")

      helper.uptime(time)
    end

    it 'should include the return value of time_ago_in_words in the return value when passed in a time' do
      helper.stub!(:time_ago_in_words).and_return("test")

      helper.uptime(3.days.from_now).should include "test"
    end

    it 'should return html safe content when passed in nil' do
      helper.uptime(nil).html_safe?.should be_true
    end

    it 'should return html safe content when passed in a time' do
      helper.uptime(3.days.from_now).html_safe?.should be_true
    end
  end
end


text:
package mcjty.deepresonance.compat.computers;

import li.cil.oc.api.machine.Arguments;
import li.cil.oc.api.machine.Callback;
import li.cil.oc.api.machine.Context;
import li.cil.oc.api.prefab.AbstractManagedEnvironment;
import mcjty.deepresonance.blocks.pedestal.PedestalTileEntity;
import mcjty.lib.integration.computers.AbstractOCDriver;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;

import java.util.Optional;

public class PedestalDriver {
    public static class OCDriver extends AbstractOCDriver {
        public OCDriver() {
            super("deepresonance_pedastal", PedestalTileEntity.class);
        }

        public static class InternalManagedEnvironment extends AbstractOCDriver.InternalManagedEnvironment<PedestalTileEntity> {
            public InternalManagedEnvironment(PedestalTileEntity tile) {
                super(tile, "deepresonance_pedastal");
            }

            @Callback(doc="function():boolean; Returns whether there is a crystal on the pedestal.")
            public Object[] crystalPresent(Context c, Arguments a) {
                return new Object[]{tile.crystalPresent()};
            }

            @Callback(doc="function(); Drops the crystal on the pedestal.")
            public Object[] dropCrystal(Context c, Arguments a) {
                tile.dropCrystal();
                return new Object[]{};
            }

            @Callback(doc="function():number; Returns the purity of the crystal on the pedestal.")
            public Object[] getPurity(Context c, Arguments a) {
                Optional<Float> purity = tile.getCrystal().map(cr -> cr.getPurity());
                if (purity.isPresent()) {
                    return new Object[]{purity.get().floatValue()};
                } else {
                    return new Object[]{null, "No crystal present"};
                }
            }

            @Callback(doc="function():number; Returns the strength of the crystal on the pedestal.")
            public Object[] getStrength(Context c, Arguments a) {
                Optional<Float> strength = tile.getCrystal().map(cr -> cr.getStrength());
                if (strength.isPresent()) {
                    return new Object[]{strength.get().floatValue()};
                } else {
                    return new Object[]{null, "No crystal present"};
                }
            }

            @Callback(doc="function():number; Returns the efficiency of the crystal on the pedestal.")
            public Object[] getEfficiency(Context c, Arguments a) {
                Optional<Float> efficiency = tile.getCrystal().map(cr -> cr.getEfficiency());
                if (efficiency.isPresent()) {
                    return new Object[]{efficiency.get().floatValue()};
                } else {
                    return new Object[]{null, "No crystal present"};
                }
            }

            @Callback(doc="function():number; Returns the power left in the crystal on the pedestal.")
            public Object[] getPower(Context c, Arguments a) {
                Optional<Float> power = tile.getCrystal().map(cr -> cr.getPower());
                if (power.isPresent()) {
                    return new Object[]{power.get().floatValue()};
                } else {
                    return new Object[]{null, "No crystal present"};
                }
            }

            @Callback(doc="function():number; Returns the RF output of the crystal on the pedestal in RF/tick.")
            public Object[] getOutput(Context c, Arguments a) {
                Optional<Integer> output = tile.getCrystal().map(cr -> cr.getRfPerTick());
                if (output.isPresent()) {
                    return new Object[]{output.get().intValue()};
                } else {
                    return new Object[]{null, "No crystal present"};
                }
            }

            @Callback(doc="function():number; Returns whether the crystal on the pedestal is currently in use.")
            public Object[] isInUse(Context c, Arguments a) {
                Optional<Boolean> inUse = tile.getCrystal().map(cr -> cr.isGlowing());
                if (inUse.isPresent()) {
                    return new Object[]{inUse.get().booleanValue()};
                } else {
                    return new Object[]{null, "No crystal present"};
                }
            }

            @Override
            public int priority() {
                return 4;
            }
        }

        @Override
        public AbstractManagedEnvironment createEnvironment(World world, BlockPos pos, EnumFacing side, TileEntity tile) {
            return new InternalManagedEnvironment((PedestalTileEntity)tile);
        }
    }
}


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 com.facebook.presto.bytecode;

import com.facebook.presto.bytecode.control.DoWhileLoop;
import com.facebook.presto.bytecode.control.FlowControl;
import com.facebook.presto.bytecode.control.ForLoop;
import com.facebook.presto.bytecode.control.IfStatement;
import com.facebook.presto.bytecode.control.SwitchStatement;
import com.facebook.presto.bytecode.control.TryCatch;
import com.facebook.presto.bytecode.control.WhileLoop;
import com.facebook.presto.bytecode.debug.DebugNode;
import com.facebook.presto.bytecode.debug.LineNumberNode;
import com.facebook.presto.bytecode.debug.LocalVariableNode;
import com.facebook.presto.bytecode.expression.BytecodeExpression;
import com.facebook.presto.bytecode.instruction.Constant;
import com.facebook.presto.bytecode.instruction.Constant.BooleanConstant;
import com.facebook.presto.bytecode.instruction.Constant.BoxedBooleanConstant;
import com.facebook.presto.bytecode.instruction.Constant.BoxedDoubleConstant;
import com.facebook.presto.bytecode.instruction.Constant.BoxedFloatConstant;
import com.facebook.presto.bytecode.instruction.Constant.BoxedIntegerConstant;
import com.facebook.presto.bytecode.instruction.Constant.BoxedLongConstant;
import com.facebook.presto.bytecode.instruction.Constant.ClassConstant;
import com.facebook.presto.bytecode.instruction.Constant.DoubleConstant;
import com.facebook.presto.bytecode.instruction.Constant.FloatConstant;
import com.facebook.presto.bytecode.instruction.Constant.IntConstant;
import com.facebook.presto.bytecode.instruction.Constant.LongConstant;
import com.facebook.presto.bytecode.instruction.Constant.StringConstant;
import com.facebook.presto.bytecode.instruction.FieldInstruction;
import com.facebook.presto.bytecode.instruction.FieldInstruction.GetFieldInstruction;
import com.facebook.presto.bytecode.instruction.FieldInstruction.PutFieldInstruction;
import com.facebook.presto.bytecode.instruction.InstructionNode;
import com.facebook.presto.bytecode.instruction.InvokeInstruction;
import com.facebook.presto.bytecode.instruction.InvokeInstruction.InvokeDynamicInstruction;
import com.facebook.presto.bytecode.instruction.JumpInstruction;
import com.facebook.presto.bytecode.instruction.LabelNode;
import com.facebook.presto.bytecode.instruction.VariableInstruction;
import com.facebook.presto.bytecode.instruction.VariableInstruction.IncrementVariableInstruction;
import com.facebook.presto.bytecode.instruction.VariableInstruction.LoadVariableInstruction;
import com.facebook.presto.bytecode.instruction.VariableInstruction.StoreVariableInstruction;

public class BytecodeVisitor<T>
{
    public T visitClass(ClassDefinition classDefinition)
    {
        for (AnnotationDefinition annotationDefinition : classDefinition.getAnnotations()) {
            visitAnnotation(classDefinition, annotationDefinition);
        }
        for (FieldDefinition fieldDefinition : classDefinition.getFields()) {
            visitField(classDefinition, fieldDefinition);
        }
        for (MethodDefinition methodDefinition : classDefinition.getMethods()) {
            visitMethod(classDefinition, methodDefinition);
        }
        return null;
    }

    public T visitAnnotation(Object parent, AnnotationDefinition annotationDefinition)
    {
        return null;
    }

    public T visitField(ClassDefinition classDefinition, FieldDefinition fieldDefinition)
    {
        for (AnnotationDefinition annotationDefinition : fieldDefinition.getAnnotations()) {
            visitAnnotation(fieldDefinition, annotationDefinition);
        }
        return null;
    }

    public T visitMethod(ClassDefinition classDefinition, MethodDefinition methodDefinition)
    {
        for (AnnotationDefinition annotationDefinition : methodDefinition.getAnnotations()) {
            visitAnnotation(methodDefinition, annotationDefinition);
        }
        methodDefinition.getBody().accept(null, this);
        return null;
    }

    public T visitNode(BytecodeNode parent, BytecodeNode node)
    {
        for (BytecodeNode child : node.getChildNodes()) {
            child.accept(node, this);
        }
        return null;
    }

    //
    // Comment
    //

    public T visitComment(BytecodeNode parent, Comment node)
    {
        return visitNode(parent, node);
    }

    //
    // Block
    //

    public T visitBlock(BytecodeNode parent, BytecodeBlock block)
    {
        return visitNode(parent, block);
    }

    //
    // Bytecode Expression
    //
    public T visitBytecodeExpression(BytecodeNode parent, BytecodeExpression expression)
    {
        return visitNode(parent, expression);
    }

    //
    // Flow Control
    //

    public T visitFlowControl(BytecodeNode parent, FlowControl flowControl)
    {
        return visitNode(parent, flowControl);
    }

    public T visitTryCatch(BytecodeNode parent, TryCatch tryCatch)
    {
        return visitFlowControl(parent, tryCatch);
    }

    public T visitIf(BytecodeNode parent, IfStatement ifStatement)
    {
        return visitFlowControl(parent, ifStatement);
    }

    public T visitFor(BytecodeNode parent, ForLoop forLoop)
    {
        return visitFlowControl(parent, forLoop);
    }

    public T visitWhile(BytecodeNode parent, WhileLoop whileLoop)
    {
        return visitFlowControl(parent, whileLoop);
    }

    public T visitDoWhile(BytecodeNode parent, DoWhileLoop doWhileLoop)
    {
        return visitFlowControl(parent, doWhileLoop);
    }

    public T visitSwitch(BytecodeNode parent, SwitchStatement switchStatement)
    {
        return visitFlowControl(parent, switchStatement);
    }

    //
    // Instructions
    //

    public T visitInstruction(BytecodeNode parent, InstructionNode node)
    {
        return visitNode(parent, node);
    }

    public T visitLabel(BytecodeNode parent, LabelNode labelNode)
    {
        return visitInstruction(parent, labelNode);
    }

    public T visitJumpInstruction(BytecodeNode parent, JumpInstruction jumpInstruction)
    {
        return visitInstruction(parent, jumpInstruction);
    }

    //
    // Constants
    //

    public T visitConstant(BytecodeNode parent, Constant constant)
    {
        return visitInstruction(parent, constant);
    }

    public T visitBoxedBooleanConstant(BytecodeNode parent, BoxedBooleanConstant boxedBooleanConstant)
    {
        return visitConstant(parent, boxedBooleanConstant);
    }

    public T visitBooleanConstant(BytecodeNode parent, BooleanConstant booleanConstant)
    {
        return visitConstant(parent, booleanConstant);
    }

    public T visitIntConstant(BytecodeNode parent, IntConstant intConstant)
    {
        return visitConstant(parent, intConstant);
    }

    public T visitBoxedIntegerConstant(BytecodeNode parent, BoxedIntegerConstant boxedIntegerConstant)
    {
        return visitConstant(parent, boxedIntegerConstant);
    }

    public T visitFloatConstant(BytecodeNode parent, FloatConstant floatConstant)
    {
        return visitConstant(parent, floatConstant);
    }

    public T visitBoxedFloatConstant(BytecodeNode parent, BoxedFloatConstant boxedFloatConstant)
    {
        return visitConstant(parent, boxedFloatConstant);
    }

    public T visitLongConstant(BytecodeNode parent, LongConstant longConstant)
    {
        return visitConstant(parent, longConstant);
    }

    public T visitBoxedLongConstant(BytecodeNode parent, BoxedLongConstant boxedLongConstant)
    {
        return visitConstant(parent, boxedLongConstant);
    }

    public T visitDoubleConstant(BytecodeNode parent, DoubleConstant doubleConstant)
    {
        return visitConstant(parent, doubleConstant);
    }

    public T visitBoxedDoubleConstant(BytecodeNode parent, BoxedDoubleConstant boxedDoubleConstant)
    {
        return visitConstant(parent, boxedDoubleConstant);
    }

    public T visitStringConstant(BytecodeNode parent, StringConstant stringConstant)
    {
        return visitConstant(parent, stringConstant);
    }

    public T visitClassConstant(BytecodeNode parent, ClassConstant classConstant)
    {
        return visitConstant(parent, classConstant);
    }

    //
    // Local Variable Instructions
    //

    public T visitVariableInstruction(BytecodeNode parent, VariableInstruction variableInstruction)
    {
        return visitInstruction(parent, variableInstruction);
    }

    public T visitLoadVariable(BytecodeNode parent, LoadVariableInstruction loadVariableInstruction)
    {
        return visitVariableInstruction(parent, loadVariableInstruction);
    }

    public T visitStoreVariable(BytecodeNode parent, StoreVariableInstruction storeVariableInstruction)
    {
        return visitVariableInstruction(parent, storeVariableInstruction);
    }

    public T visitIncrementVariable(BytecodeNode parent, IncrementVariableInstruction incrementVariableInstruction)
    {
        return visitVariableInstruction(parent, incrementVariableInstruction);
    }

    //
    // Field Instructions
    //

    public T visitFieldInstruction(BytecodeNode parent, FieldInstruction fieldInstruction)
    {
        return visitInstruction(parent, fieldInstruction);
    }

    public T visitGetField(BytecodeNode parent, GetFieldInstruction getFieldInstruction)
    {
        return visitFieldInstruction(parent, getFieldInstruction);
    }

    public T visitPutField(BytecodeNode parent, PutFieldInstruction putFieldInstruction)
    {
        return visitFieldInstruction(parent, putFieldInstruction);
    }

    //
    // Invoke
    //

    public T visitInvoke(BytecodeNode parent, InvokeInstruction invokeInstruction)
    {
        return visitInstruction(parent, invokeInstruction);
    }

    public T visitInvokeDynamic(BytecodeNode parent, InvokeDynamicInstruction invokeDynamicInstruction)
    {
        return visitInvoke(parent, invokeDynamicInstruction);
    }

    //
    // Debug
    //

    public T visitDebug(BytecodeNode parent, DebugNode debugNode)
    {
        return visitNode(parent, debugNode);
    }

    public T visitLineNumber(BytecodeNode parent, LineNumberNode lineNumberNode)
    {
        return visitDebug(parent, lineNumberNode);
    }

    public T visitLocalVariable(BytecodeNode parent, LocalVariableNode localVariableNode)
    {
        return visitDebug(parent, localVariableNode);
    }
}


text:
"""WavPack reading and writing.

WavPack is a lossless format that uses APEv2 tags. Read

* http://www.wavpack.com/
* http://www.wavpack.com/file_format.txt

for more information.
"""

__all__ = ["WavPack", "Open", "delete"]

from mutagen import StreamInfo
from mutagen.apev2 import APEv2File, error, delete
from mutagen._util import cdata

class WavPackHeaderError(error):
    pass

RATES = [6000, 8000, 9600, 11025, 12000, 16000, 22050, 24000, 32000, 44100,
         48000, 64000, 88200, 96000, 192000]

class _WavPackHeader(object):

    def __init__(self, block_size, version, track_no, index_no, total_samples,
                 block_index, block_samples, flags, crc):

        self.block_size = block_size
        self.version = version
        self.track_no = track_no
        self.index_no = index_no
        self.total_samples = total_samples
        self.block_index = block_index
        self.block_samples = block_samples
        self.flags = flags
        self.crc = crc

    @classmethod
    def from_fileobj(cls, fileobj):
        """A new _WavPackHeader or raises WavPackHeaderError"""

        header = fileobj.read(32)
        if len(header) != 32 or not header.startswith(b"wvpk"):
            raise WavPackHeaderError("not a WavPack header: %r" % header)

        block_size = cdata.uint_le(header[4:8])
        version = cdata.ushort_le(header[8:10])
        track_no = ord(header[10:11])
        index_no = ord(header[11:12])
        samples = cdata.uint_le(header[12:16])
        if samples == 2**32 - 1:
            samples = -1
        block_index = cdata.uint_le(header[16:20])
        block_samples = cdata.uint_le(header[20:24])
        flags = cdata.uint_le(header[24:28])
        crc = cdata.uint_le(header[28:32])

        return _WavPackHeader(block_size, version, track_no, index_no,
                              samples, block_index, block_samples, flags, crc)

class WavPackInfo(StreamInfo):
    """WavPack stream information.

    Attributes:

    * channels - number of audio channels (1 or 2)
    * length - file length in seconds, as a float
    * sample_rate - audio sampling rate in Hz
    * version - WavPack stream version
    """

    def __init__(self, fileobj):
        try:
            header = _WavPackHeader.from_fileobj(fileobj)
        except WavPackHeaderError:
            raise WavPackHeaderError("not a WavPack file")

        self.version = header.version
        self.channels = bool(header.flags & 4) or 2
        self.sample_rate = RATES[(header.flags >> 23) & 0xF]

        if header.total_samples == -1 or header.block_index != 0:
            # TODO: we could make this faster by using the tag size
            # and search backwards for the last block, then do
            # last.block_index + last.block_samples - initial.block_index
            samples = header.block_samples
            while 1:
                fileobj.seek(header.block_size - 32 + 8, 1)
                try:
                    header = _WavPackHeader.from_fileobj(fileobj)
                except WavPackHeaderError:
                    break
                samples += header.block_samples
        else:
            samples = header.total_samples

        self.length = float(samples) / self.sample_rate

    def pprint(self):
        return "WavPack, %.2f seconds, %d Hz" % (self.length, self.sample_rate)

class WavPack(APEv2File):
    _Info = WavPackInfo
    _mimes = ["audio/x-wavpack"]

    @staticmethod
    def score(filename, fileobj, header):
        return header.startswith(b"wvpk") * 2

Open = WavPack