text:
namespace ExpressionToCodeLib.Internal;

class ExpressionToCodeImpl : IExpressionTypeDispatch<StringifiedExpression>
{
    #region General Helpers
    public ExpressionToCodeImpl(ExpressionToCodeConfiguration config)
        => this.config = config;

    readonly ExpressionToCodeConfiguration config;

    string? PlainObjectToCode(object? val, Type? type)
        => ObjectToCodeImpl.PlainObjectToCode(config, val, type);

    string TypeNameToCode(Type type)
        => type.ToCSharpFriendlyTypeName(config, false);

    bool AlwaysUseExplicitTypeArguments => config.AlwaysUseExplicitTypeArguments;

    [Pure]
    IEnumerable<StringifiedExpression> NestExpression(ExpressionType? parentType, Expression child, bool parensIfEqualRank = false)
    {
        var parentRank = parentType == null ? 0 : ExpressionPrecedence.Rank(parentType.Value);
        var needsParens = parentRank > 0
            && (parensIfEqualRank ? parentRank - 1 : parentRank) < ExpressionPrecedence.Rank(child.NodeType);

        if (needsParens) {
            yield return StringifiedExpression.TextOnly("(");
        }

        yield return SingleChildDispatch(child);

        if (needsParens) {
            yield return StringifiedExpression.TextOnly(")");
        }
    }

    StringifiedExpression SingleChildDispatch(Expression child)
        => this.ExpressionDispatch(child).MarkAsConceptualChild();

    StringifiedExpression SingleChildDispatch(string? prefix, Expression child)
        => StringifiedExpression.WithChildren(new[] { StringifiedExpression.TextOnly(prefix), this.ExpressionDispatch(child), }).MarkAsConceptualChild();

    [Pure]
    static IEnumerable<StringifiedExpression> JoinDispatch(IEnumerable<StringifiedExpression> children, string joiner)
    {
        var isFirst = true;
        foreach (var child in children) {
            if (!isFirst) {
                yield return StringifiedExpression.TextOnly(joiner);
            }

            yield return child;

            isFirst = false;
        }
    }

    [Pure]
    static IEnumerable<StringifiedExpression> ArgListDispatch(
        IEnumerable<StringifiedExpression> arguments,
        Expression? value = null,
        string open = "(",
        string close = ")",
        string joiner = ", ")
    {
        yield return value != null ? StringifiedExpression.TextAndExpr(open, value) : StringifiedExpression.TextOnly(open);

        foreach (var o in JoinDispatch(arguments, joiner)) {
            yield return o;
        }

        yield return StringifiedExpression.TextOnly(close);
    }

    readonly struct KidsBuilder
    {
        readonly List<StringifiedExpression> kids;

        KidsBuilder(List<StringifiedExpression> init)
            => kids = init;

        [Pure]
        public static KidsBuilder Create()
            => new(new());

        public void Add(StringifiedExpression node)
            => kids.Add(node);

        public void Add(IEnumerable<StringifiedExpression> nodes)
            => kids.AddRange(nodes);

        public void Add(string text, Expression value)
            => kids.Add(StringifiedExpression.TextAndExpr(text, value));

        public void Add(string text)
            => kids.Add(StringifiedExpression.TextOnly(text));

        public StringifiedExpression Finish()
            => StringifiedExpression.WithChildren(kids.ToArray());
    }

    [Pure]
    StringifiedExpression BinaryDispatch(string op, Expression e)
    {
        var kids = KidsBuilder.Create();
        var be = (BinaryExpression)e;
        UnwrapEnumOp(be, out var left, out var right);
        kids.Add(NestExpression(be.NodeType, left));
        kids.Add(" " + op + " ", e);
        kids.Add(NestExpression(be.NodeType, right, true));
        return kids.Finish();
    }

    [Pure]
    static void UnwrapEnumOp(BinaryExpression be, out Expression left, out Expression right)
    {
        left = be.Left;
        right = be.Right;
        var uncastLeft = left.NodeType == ExpressionType.Convert ? ((UnaryExpression)left).Operand : null;
        var uncastRight = right.NodeType == ExpressionType.Convert ? ((UnaryExpression)right).Operand : null;
        if (uncastLeft != null) {
            if (uncastRight != null) {
                if (uncastRight.Type.EnsureNullability() == uncastLeft.Type.EnsureNullability()) {
                    left = uncastLeft;
                    right = uncastRight;
                }
            } else {
                UnwrapEnumBinOp(uncastLeft, ref left, ref right);
            }
        } else if (uncastRight != null) {
            //implies uleft == null
            UnwrapEnumBinOp(uncastRight, ref right, ref left);
        }
    }

    static void UnwrapEnumBinOp(Expression expr1uncast, ref Expression expr1, ref Expression expr2)
    {
        var expr1nonnullableType = expr1uncast.Type.AvoidNullability();
        var expr2nonnullableType = expr2.Type.AvoidNullability();
        if (expr1nonnullableType.GetTypeInfo().IsEnum
            && expr1nonnullableType.GetTypeInfo().GetEnumUnderlyingType() == expr2nonnullableType
            || expr1nonnullableType == typeof(char) && expr2nonnullableType == typeof(int)
        ) {
            expr1 = expr1uncast;

            expr2 = expr2 is not ConstantExpression { NodeType: ExpressionType.Constant, } constantExpression
                ? Expression.Convert(expr2, expr1uncast.Type)
                : constantExpression.Value == null
                    ? Expression.Default(expr1uncast.Type.EnsureNullability())
                    : expr1nonnullableType == typeof(char)
                        ? Expression.Constant((char)(int)constantExpression.Value)
                        : Expression.Constant(Enum.ToObject(expr1nonnullableType, constantExpression.Value));
        }
    }

    [Pure]
    StringifiedExpression UnaryDispatch(string op, Expression e)
    {
        var ue = (UnaryExpression)e;
        var needsSpace = ExpressionPrecedence.TokenizerConfusable(ue.NodeType, ue.Operand.NodeType);
        var kids = KidsBuilder.Create();
        kids.Add(op + (needsSpace ? " " : ""), e);
        kids.Add(NestExpression(ue.NodeType, ue.Operand));
        return kids.Finish();
    }

    [Pure]
    StringifiedExpression UnaryDispatchConvert(Expression e)
    {
        var kids = KidsBuilder.Create();
        var ue = (UnaryExpression)e;
        var operand = ue.Operand;
        if (!config.OmitImplicitCasts
            || !ReflectionHelpers.CanImplicitlyCast(operand.Type, e.Type)
            || typeof(Delegate).IsAssignableFrom(operand.Type) && operand.NodeType == ExpressionType.Lambda
            || typeof(Expression).IsAssignableFrom(operand.Type) && operand.NodeType == ExpressionType.Quote
        ) {
            if (e.Type.GetTypeInfo().IsAssignableFrom(operand.Type)) // base class, basically; don't re-print identical values.
            {
                kids.Add("(" + TypeNameToCode(e.Type) + ")");
            } else {
                kids.Add("(" + TypeNameToCode(e.Type) + ")", e);
            }

            if (operand.NodeType == ExpressionType.Convert) {
                var nestedConvert = (UnaryExpression)operand;
                kids.Add("(" + TypeNameToCode(operand.Type) + ")");
                kids.Add(NestExpression(nestedConvert.NodeType, nestedConvert.Operand));
            } else {
                kids.Add(NestExpression(ue.NodeType, operand));
            }
        } else {
            kids.Add(NestExpression(ue.NodeType, operand));
        }

        return kids.Finish();
    }

    [Pure]
    StringifiedExpression UnaryPostfixDispatch(string op, Expression e)
    {
        var kids = KidsBuilder.Create();
        var ue = (UnaryExpression)e;
        kids.Add(NestExpression(ue.NodeType, ue.Operand));
        kids.Add(op, e);
        return kids.Finish();
    }

    [Pure]
    StringifiedExpression TypeOpDispatch(string op, Expression e)
    {
        var kids = KidsBuilder.Create();
        kids.Add(NestExpression(e.NodeType, ((TypeBinaryExpression)e).Expression));
        kids.Add(" " + op + " ", e);
        kids.Add(TypeNameToCode(((TypeBinaryExpression)e).TypeOperand));
        return kids.Finish();
    }

    [Pure]
    StringifiedExpression StatementDispatch(Expression e, ExpressionType? parentType = null)
    {
        var kids = KidsBuilder.Create();
        kids.Add(NestExpression(parentType, e));
        kids.Add("; ");
        return kids.Finish();
    }

    [Pure]
    StringifiedExpression StatementDispatch(string prefix, Expression e, ExpressionType? parentType = null)
    {
        var kids = KidsBuilder.Create();
        kids.Add(prefix);
        kids.Add(" ");
        kids.Add(StatementDispatch(e, parentType));
        return kids.Finish();
    }
    #endregion

    #region Hard Cases
    [Pure]
    public StringifiedExpression DispatchLambda(Expression e)
    {
        var kids = KidsBuilder.Create();
        var le = (LambdaExpression)e;
        kids.Add(
            le.Parameters.Count == 1
                ? NestExpression(e.NodeType, le.Parameters.Single())
                : ArgListDispatch(le.Parameters.Select(SingleChildDispatch))
            //though delegate lambdas do support ref/out parameters, expression tree lambda's don't
        );
        kids.Add(" => ");
        kids.Add(NestExpression(le.NodeType, le.Body));
        return kids.Finish();
    }

    static bool IsThisRef(Expression e)
        => e is ConstantExpression { Value: not null, }
            && e.Type.GuessTypeClass() == ReflectionHelpers.TypeClass.NormalType;

    static bool IsClosureRef(Expression e)
        => e is ConstantExpression { Value: not null, } or { NodeType: ExpressionType.MemberAccess, }
            && e.Type.GuessTypeClass() is ReflectionHelpers.TypeClass.ClosureType or ReflectionHelpers.TypeClass.TopLevelProgramClosureType;

    [Pure]
    public StringifiedExpression DispatchMemberAccess(Expression e)
    {
        var kids = KidsBuilder.Create();
        var me = (MemberExpression)e;
        var memberOfExpr = me.Expression;
        if (memberOfExpr != null && !IsThisRef(memberOfExpr) && !IsClosureRef(memberOfExpr)) {
            kids.Add(NestExpression(e.NodeType, memberOfExpr));
            kids.Add(".");
        } else if (ReflectionHelpers.IsMemberInfoStatic(me.Member)) {
            kids.Add(TypeNameToCode(me.Member.DeclaringType ?? throw new("A static member must have a declaring type")) + ".");
        }

        kids.Add(me.Member.Name, e);
        return kids.Finish();
    }

    static readonly MethodInfo createDelegate = ((Func<Type, object, MethodInfo, Delegate>)Delegate.CreateDelegate).Method;

    [Pure]
    public StringifiedExpression DispatchCall(Expression e)
    {
        var kids = KidsBuilder.Create();

        var mce = (MethodCallExpression)e;

        var optPropertyInfo = ReflectionHelpers.GetPropertyIfGetter(mce.Method);
        if (optPropertyInfo != null
            && mce.Object != null
            && (optPropertyInfo.Name == "Item"
                || optPropertyInfo.Name == "Chars" && mce.Object.Type == typeof(string))) {
            kids.Add(NestExpression(mce.NodeType, mce.Object));
            //indexers don't support ref/out; so we can use unprefixed arguments
            kids.Add(ArgListDispatch(GetArgumentsForMethod(mce.Method, mce.Arguments), mce, "[", "]"));
        } else if (mce.Method.Equals(createDelegate)
            && mce.Arguments.Count == 3
            && mce.Arguments[2] is ConstantExpression { Value: MethodInfo implicitlyConstructedDelegateMethodTarget, }) {
            //.net 4.0
            //implicitly constructed delegate from method group.
            var targetExpr = mce.Arguments[1] is ConstantExpression { Value: null, } ? null : mce.Arguments[1];
            kids.Add(StringifyMethodName(mce, implicitlyConstructedDelegateMethodTarget, targetExpr));
        } else if (mce.Method.Name == "CreateDelegate"
            && mce.Arguments.Count == 2
            && mce.Object is ConstantExpression { NodeType : ExpressionType.Constant, Value: MethodInfo targetMethod, }
            && mce.Object.Type == typeof(MethodInfo)
            && mce.Method.GetParameters()[1].ParameterType == typeof(object)
        ) {
            //.net 4.5
            //implicitly constructed delegate from method group.
            var targetExpr = mce.Arguments[1] is ConstantExpression { NodeType: ExpressionType.Constant, Value: null, }
                ? null
                : mce.Arguments[1];
            kids.Add(StringifyMethodName(mce, targetMethod, targetExpr));
        } else if (mce.Object == null
            && mce.Type.FullName == "System.FormattableString"
            && mce.Method.DeclaringType?.FullName == "System.Runtime.CompilerServices.FormattableStringFactory"
            && mce.Method.Name == "Create"
            && mce.Arguments.Count == 2
            && mce.Arguments[0] is ConstantExpression { Value: string formattableStringFormatString, }
            && mce.Arguments[1] is NewArrayExpression { Expressions: { } formattableStringArguments, }
        ) {
            //.net 4.6
            //string-interpolations are compiled into FormattableStringFactory.Create
            kids = AddStringInterpolation(kids, formattableStringFormatString, formattableStringArguments);
        } else if (mce.Object == null
            && mce.Type == typeof(string)
            && mce.Method.DeclaringType == typeof(string)
            && mce.Method.Name == "Format"
            && mce.Arguments.Count == 2
            && mce.Arguments[0].Type == typeof(string)
            && mce.Arguments[0] is ConstantExpression { Value: string stringInterpolationFormatString, }
            && mce.Arguments[1].Type == typeof(object[])
            && mce.Arguments[1] is NewArrayExpression { Expressions: { } stringInterpolationArguments, }
        ) {
            //.net 4.6
            //string-interpolations are compiled into FormattableStringFactory.Create
            kids = AddStringInterpolation(kids, stringInterpolationFormatString, stringInterpolationArguments);
        } else if (mce.Object == null
            && mce.Type == typeof(string)
            && mce.Method.DeclaringType == typeof(string)
            && mce.Method.Name == "Format"
            && mce.Arguments.Count >= 2
            && mce.Arguments[0].Type == typeof(string)
            && mce.Arguments[0] is ConstantExpression { Value: string stringInterpolationFormatString2, }
            && mce.Method.GetParameters().Skip(1).All(pi => pi.ParameterType == typeof(object))
        ) {
            //.net 4.6
            //string-interpolations are compiled into FormattableStringFactory.Create
            kids = AddStringInterpolation(kids, stringInterpolationFormatString2, mce.Arguments.Skip(1));
        } else if (mce.Object != null && mce.Method.Attributes.HasFlag(MethodAttributes.SpecialName) && mce.Method.Name == "get_Item") {
            //.net 4.5.1 or older object indexer.

            kids.Add(NestExpression(mce.NodeType, mce.Object));
            kids.Add(ArgListDispatch(mce.Arguments.Select(SingleChildDispatch), mce, "[", "]"));
            return kids.Finish();
        } else {
            var isExtensionMethod = mce.Method.IsStatic
                && mce.Method.GetCustomAttributes(typeof(ExtensionAttribute), false).Any() && mce.Arguments.Any()
                && mce.Object == null;
            var objectExpr = isExtensionMethod ? mce.Arguments.First() : mce.Object;
            kids.Add(StringifyMethodName(mce, mce.Method, objectExpr));
            var args = GetArgumentsForMethod(mce.Method, mce.Arguments);

            kids.Add(ArgListDispatch(isExtensionMethod ? args.Skip(1) : args));
        }

        return kids.Finish();
    }

    KidsBuilder AddStringInterpolation(KidsBuilder kids, string formatString, IEnumerable<Expression> arguments)
    {
        var interpolationArgumentsStringified = arguments
            .Select(
                expr =>
                    expr.NodeType == ExpressionType.Convert
                    && expr.Type == typeof(object)
                    && expr is UnaryExpression unaryExpr
                        ? unaryExpr.Operand
                        : expr
            )
            .Select(
                child =>
                    child.NodeType == ExpressionType.Conditional
                        ? StringifiedExpression.WithChildren(new[] { StringifiedExpression.TextOnly("("), this.ExpressionDispatch(child), StringifiedExpression.TextOnly(")"), })
                        : this.ExpressionDispatch(child)
            ).ToArray();
        var useVerbatimSyntax = ObjectToCodeImpl.UseVerbatimSyntax(config, formatString)
                || StringifiedExpression.WithChildren(interpolationArgumentsStringified).ToString().Contains('\n') // no longer necessary after https://devblogs.microsoft.com/dotnet/early-peek-at-csharp-11-features/#c-11-preview-allow-newlines-in-the-holes-of-interpolated-strings
            ;

        var parsed = FormatStringParser.ParseFormatString(formatString, interpolationArgumentsStringified.Cast<object>().ToArray());

        if (useVerbatimSyntax) {
            kids.Add("$@\"");
            foreach (var segment in parsed.segments) {
                kids.Add(segment.InitialStringPart.Replace("\"", "\"\"").Replace("{", "{{").Replace("}", "}}") + "{");
                kids.Add(segment.FollowedByValue is StringifiedExpression expr ? expr : throw new InvalidOperationException("All arguments should have been StringifiedExpressions"));
                if (segment.WithFormatString != null) {
                    kids.Add(":" + segment.WithFormatString + "}");
                } else {
                    kids.Add("}");
                }
            }

            kids.Add(parsed.Tail.Replace("\"", "\"\"").Replace("{", "{{").Replace("}", "}}") + "\"");
        } else {
            kids.Add("$\"");
            foreach (var segment in parsed.segments) {
                kids.Add(ObjectToCodeImpl.EscapeStringChars(segment.InitialStringPart.Replace("{", "{{").Replace("}", "}}")) + "{");
                kids.Add(segment.FollowedByValue is StringifiedExpression expr ? expr : throw new InvalidOperationException("All arguments should have been StringifiedExpressions"));
                if (segment.WithFormatString != null) {
                    kids.Add(":" + segment.WithFormatString + "}");
                } else {
                    kids.Add("}");
                }
            }

            kids.Add(ObjectToCodeImpl.EscapeStringChars(parsed.Tail.Replace("{", "{{").Replace("}", "}}")) + "\"");
        }

        return kids;
    }

    IEnumerable<StringifiedExpression> GetArgumentsForMethod(MethodBase methodInfo, IEnumerable<Expression> argValueExprs)
        => GetArgumentsForMethod(methodInfo.GetParameters(), argValueExprs);

    IEnumerable<StringifiedExpression> GetArgumentsForMethod(ParameterInfo[] parameters, IEnumerable<Expression> argValueExprs)
    {
        var argPrefixes = parameters.Select(p => p.IsOut ? "out " : p.ParameterType.IsByRef ? "ref " : null).ToArray();
        return argValueExprs.Zip(argPrefixes, (expr, prefix) => SingleChildDispatch(prefix, expr));
    }

    [Pure]
    StringifiedExpression StringifyMethodName(MethodCallExpression mce, MethodInfo method, Expression? objExpr)
    {
        var kids = KidsBuilder.Create();

        if (objExpr != null) {
            if (!(IsThisRef(objExpr) || IsClosureRef(objExpr))) {
                kids.Add(NestExpression(mce.NodeType, objExpr));
                kids.Add(".");
            }
        } else if (method.IsStatic && method.DeclaringType is not null) {
            kids.Add(TypeNameToCode(method.DeclaringType) + "."); //TODO:better reference avoiding for this?
        }

        kids.Add(method.Name + CreateGenericArgumentsIfNecessary(method), mce);
        return kids.Finish();
    }

    string CreateGenericArgumentsIfNecessary(MethodInfo method)
    {
        if (!method.IsGenericMethod) {
            return "";
        }

        if (!AlwaysUseExplicitTypeArguments && method.DeclaringType != null) {
            var genericMethodDefinition = method.GetGenericMethodDefinition();
            var relevantBindingFlagsForOverloads =
                BindingFlags.Public
                | (!method.IsPublic ? BindingFlags.NonPublic : 0)
                | (method.IsStatic ? BindingFlags.Static : BindingFlags.Instance);

            var confusibleOverloads = method.DeclaringType.GetTypeInfo()
                .GetMethods(relevantBindingFlagsForOverloads)
                .Where(
                    otherMethod =>
                        otherMethod != genericMethodDefinition
                        && otherMethod.Name == method.Name
                        && otherMethod.GetParameters().Select(pi => pi.ParameterType).SequenceEqual(method.GetParameters().Select(pi => pi.ParameterType))
                );

            if (!confusibleOverloads.Any()
                && genericMethodDefinition.GetGenericArguments()
                    .All(typeParameter => genericMethodDefinition.GetParameters().Any(parameter => ContainsInferableType(parameter.ParameterType, typeParameter)))) {
                return "";
            }
        }

        var methodTypeArgs = method.GetGenericArguments().Select(type => TypeNameToCode(type)).ToArray();
        return string.Concat("<", string.Join(", ", methodTypeArgs), ">");
    }

    static bool ContainsInferableType(Type haystack, Type needle)
        => haystack == needle
            || (haystack.IsArray || haystack.IsByRef) && ContainsInferableType(haystack.GetElementType() ?? throw new InvalidOperationException("arrays have elements"), needle)
            || haystack.GetTypeInfo().IsGenericType
            && !(typeof(Delegate).IsAssignableFrom(haystack)
                    && (haystack.GetTypeInfo().GetMethod("Invoke") ?? throw new InvalidOperationException("delegates have Invoke")).GetParameters().Any(pi => pi.ParameterType == needle)
                )
            && haystack.GetTypeInfo().GetGenericArguments().Any(argType => ContainsInferableType(argType, needle));

    [Pure]
    public StringifiedExpression DispatchIndex(Expression e)
    {
        var kids = KidsBuilder.Create();

        var ie = (IndexExpression)e;
        kids.Add(NestExpression(ie.NodeType, ie.Object ?? throw new("Assumption: indexer expressions have a receiver")));

        var args = ie.Indexer == null
            ? ie.Arguments.Select(SingleChildDispatch)
            : GetArgumentsForMethod(ie.Indexer.GetIndexParameters(), ie.Arguments);

        kids.Add(ArgListDispatch(args, ie, "[", "]"));
        return kids.Finish();
    }

    [Pure]
    public StringifiedExpression DispatchInvoke(Expression e)
    {
        var kids = KidsBuilder.Create();

        var ie = (InvocationExpression)e;
        if (ie.Expression.NodeType == ExpressionType.Lambda) {
            kids.Add("new " + TypeNameToCode(ie.Expression.Type));
        }

        kids.Add(NestExpression(ie.NodeType, ie.Expression));
        var invokeMethod = ie.Expression.Type.GetTypeInfo().GetMethod("Invoke") ?? throw new("Assumption: all delegates have a method Invoke");
        var args = GetArgumentsForMethod(invokeMethod, ie.Arguments);
        kids.Add(ArgListDispatch(args, ie));
        return kids.Finish();
    }

    [Pure]
    public StringifiedExpression DispatchConstant(Expression e)
    {
        var kids = KidsBuilder.Create();

        var const_Val = ((ConstantExpression)e).Value;
        var codeRepresentation = PlainObjectToCode(const_Val, e.Type);
        //e.Type.IsVisible
        if (codeRepresentation == null) {
            var typeClass = e.Type.GuessTypeClass();
            if (typeClass == ReflectionHelpers.TypeClass.NormalType) // probably this!
            {
                kids.Add("this"); //TODO:verify that all this references refer to the same object!
            } else {
                throw new ArgumentOutOfRangeException(
                    nameof(e),
                    "Can't print constant " + (const_Val?.ToString() ?? "<null>")
                    + " in expr of type " + e.Type
                );
            }
        } else {
            kids.Add(codeRepresentation);
        }

        return kids.Finish();
    }

    [Pure]
    public StringifiedExpression DispatchConditional(Expression e)
    {
        var kids = KidsBuilder.Create();

        var ce = (ConditionalExpression)e;
        kids.Add(NestExpression(ce.NodeType, ce.Test));
        kids.Add(" ? ", e);
        kids.Add(NestExpression(ce.NodeType, ce.IfTrue));
        kids.Add(" : ");
        kids.Add(NestExpression(ce.NodeType, ce.IfFalse));
        return kids.Finish();
    }

    [Pure]
    public StringifiedExpression DispatchListInit(Expression e)
    {
        var kids = KidsBuilder.Create();

        var lie = (ListInitExpression)e;
        kids.Add("new ", lie);
        kids.Add(TypeNameToCode(lie.NewExpression.Type));
        if (lie.NewExpression.Arguments.Any()) {
            kids.Add(ArgListDispatch(GetArgumentsForMethod(lie.NewExpression.Constructor ?? throw new("Assumption: Constructor cannot be omitted when it has arguments: " + lie.NewExpression.Type), lie.NewExpression.Arguments)));
        }

        kids.Add(" { ");
        kids.Add(JoinDispatch(lie.Initializers.Select(DispatchElementInit), ", "));
        kids.Add(" }");
        return kids.Finish();
    }

    [Pure]
    StringifiedExpression DispatchElementInit(ElementInit elemInit)
    {
        if (elemInit.Arguments.Count != 1) {
            return StringifiedExpression.WithChildren(ArgListDispatch(elemInit.Arguments.Select(SingleChildDispatch), null, "{ ", " }").ToArray()); //??
        } else {
            return SingleChildDispatch(elemInit.Arguments.Single());
        }
    }

    [Pure]
    StringifiedExpression DispatchMemberBinding(MemberBinding mb)
    {
        var kids = KidsBuilder.Create();

        kids.Add(mb.Member.Name + " = ");
        if (mb is MemberMemberBinding mmb) {
            kids.Add("{ ");
            kids.Add(JoinDispatch(mmb.Bindings.Select(DispatchMemberBinding), ", "));
            kids.Add(" }");
        } else if (mb is MemberListBinding mlb) {
            kids.Add("{ ");
            kids.Add(JoinDispatch(mlb.Initializers.Select(DispatchElementInit), ", "));
            kids.Add(" }");
        } else if (mb is MemberAssignment assignment) {
            kids.Add(SingleChildDispatch(assignment.Expression));
        } else {
            throw new NotImplementedException("Member binding of unknown type: " + mb.GetType());
        }

        return kids.Finish();
    }

    [Pure]
    public StringifiedExpression DispatchMemberInit(Expression e)
    {
        var kids = KidsBuilder.Create();

        var mie = (MemberInitExpression)e;
        kids.Add("new ", mie);
        var newExpr = mie.NewExpression;
        kids.Add(TypeNameToCode(newExpr.Type));
        if (newExpr.Arguments.Any()) {
            kids.Add(ArgListDispatch(GetArgumentsForMethod(newExpr.Constructor ?? throw new("Assumption: Constructor cannot be omitted when it has arguments: " + newExpr.Type), newExpr.Arguments)));
        }

        kids.Add(" { ");
        kids.Add(JoinDispatch(mie.Bindings.Select(DispatchMemberBinding), ", "));
        kids.Add(" }");
        return kids.Finish();
    }

    [Pure]
    public StringifiedExpression DispatchNew(Expression e)
    {
        var kids = KidsBuilder.Create();

        var ne = (NewExpression)e;
        if (ne.Type.GuessTypeClass() == ReflectionHelpers.TypeClass.AnonymousType) {
            var parameters = ne.Type.GetTypeInfo().GetConstructors().Single().GetParameters();
            var props = ne.Type.GetTypeInfo().GetProperties();
            if (
                !parameters.Select(p => (p.Name ?? "", p.ParameterType))
                    .SequenceEqual(props.Select(p => (p.Name, p.PropertyType)))) {
                throw new InvalidOperationException(
                    "Constructor params for anonymous type don't match it's properties!"
                );
            }

            if (!parameters.Select(p => p.ParameterType).SequenceEqual(ne.Arguments.Select(argE => argE.Type))) {
                throw new InvalidOperationException(
                    "Constructor Arguments for anonymous type don't match it's type signature!"
                );
            }

            kids.Add("new { ");
            for (var i = 0; i < props.Length; i++) {
                kids.Add(props[i].Name + " = ");
                kids.Add(SingleChildDispatch(ne.Arguments[i]));
                if (i + 1 < props.Length) {
                    kids.Add(", ");
                }
            }

            kids.Add(" }");
        } else {
            kids.Add("new " + TypeNameToCode(ne.Type), ne);
            if (ne.Arguments.Count == 0) {
                kids.Add("()");
            } else {
                kids.Add(ArgListDispatch(GetArgumentsForMethod(ne.Constructor ?? throw new("Assumption: any new-expression with arguments must have a constructor"), ne.Arguments)));
            }
        }

        //TODO: deal with anonymous types.
        return kids.Finish();
    }

    [Pure]
    public StringifiedExpression DispatchNewArrayInit(Expression e)
    {
        var kids = KidsBuilder.Create();

        var nae = (NewArrayExpression)e;
        var arrayElemType = nae.Type.GetElementType() ?? throw new("Assumption: all arrays have an element type");
        var isDelegate = typeof(Delegate).GetTypeInfo().IsAssignableFrom(arrayElemType);
        var implicitTypeOK = !isDelegate && nae.Expressions.Any()
            && nae.Expressions.All(expr => expr.Type == arrayElemType);
        kids.Add("new" + (implicitTypeOK ? "" : " " + TypeNameToCode(arrayElemType)) + "[] ", nae);
        kids.Add(ArgListDispatch(nae.Expressions.Select(SingleChildDispatch), null, "{ ", " }"));
        return kids.Finish();
    }

    [Pure]
    public StringifiedExpression DispatchNewArrayBounds(Expression e)
    {
        var kids = KidsBuilder.Create();

        var nae = (NewArrayExpression)e;
        var arrayElemType = nae.Type.GetElementType() ?? throw new("Assumption: all arrays have an element type");
        kids.Add("new " + TypeNameToCode(arrayElemType), nae);
        kids.Add(ArgListDispatch(nae.Expressions.Select(SingleChildDispatch), null, "[", "]"));
        return kids.Finish();
    }

    [Pure]
    public StringifiedExpression DispatchBlock(Expression e)
    {
        var kids = KidsBuilder.Create();

        var be = (BlockExpression)e;
        var hasReturn = be.Type != typeof(void);
        var statements = hasReturn ? be.Expressions.Take(be.Expressions.Count - 1) : be.Expressions;

        kids.Add("{ ");

        foreach (var v in be.Variables) {
            kids.Add(StatementDispatch(TypeNameToCode(v.Type), v, ExpressionType.Block));
        }

        foreach (var child in statements) {
            kids.Add(StatementDispatch(child, ExpressionType.Block));
        }

        if (hasReturn) {
            kids.Add(StatementDispatch("return", be.Result, ExpressionType.Block));
        }

        kids.Add("}");
        return kids.Finish();
    }
    #endregion

    #region Easy Cases
    [Pure]
    public StringifiedExpression DispatchPower(Expression e)
    {
        var kids = KidsBuilder.Create();

        kids.Add("Math.Pow", e);
        var binaryExpression = (BinaryExpression)e;
        kids.Add(ArgListDispatch(new[] { binaryExpression.Left, binaryExpression.Right, }.Select(SingleChildDispatch)));
        return kids.Finish();
    }

    [Pure]
    public StringifiedExpression DispatchAdd(Expression e)
        => BinaryDispatch("+", e);

    [Pure]
    public StringifiedExpression DispatchAddChecked(Expression e)
        => BinaryDispatch("+", e); //TODO: checked

    [Pure]
    public StringifiedExpression DispatchAnd(Expression e)
        => BinaryDispatch("&", e);

    [Pure]
    public StringifiedExpression DispatchAndAlso(Expression e)
        => BinaryDispatch("&&", e);

    [Pure]
    public StringifiedExpression DispatchArrayLength(Expression e)
    {
        var kids = KidsBuilder.Create();

        kids.Add(NestExpression(e.NodeType, ((UnaryExpression)e).Operand));
        kids.Add(".Length", e);
        return kids.Finish();
    }

    [Pure]
    public StringifiedExpression DispatchArrayIndex(Expression e)
    {
        var kids = KidsBuilder.Create();

        var binaryExpression = (BinaryExpression)e;
        kids.Add(NestExpression(e.NodeType, binaryExpression.Left));
        kids.Add("[", e);
        kids.Add(NestExpression(null, binaryExpression.Right));
        kids.Add("]");
        return kids.Finish();
    }

    [Pure]
    public StringifiedExpression DispatchCoalesce(Expression e)
        => ((BinaryExpression)e).Left is ConstantExpression ce && ((BinaryExpression)e).Right is ConstantExpression && ce.Type == e.Type && ce.Type == typeof(string) && ce.Value != null
            ? this.ExpressionDispatch(ce) //for some weird reason the compile sometimes generates redundant null-coalescing operators.  Get rid of em!
            : BinaryDispatch("??", e);

    [Pure]
    public StringifiedExpression DispatchConvert(Expression e)
        => UnaryDispatchConvert(e);

    [Pure]
    public StringifiedExpression DispatchConvertChecked(Expression e)
        => UnaryDispatchConvert(e);

    //TODO: get explicit and implicit conversion operators right.
    [Pure]
    public StringifiedExpression DispatchDivide(Expression e)
        => BinaryDispatch("/", e);

    [Pure]
    public StringifiedExpression DispatchEqual(Expression e)
        => BinaryDispatch("==", e);

    [Pure]
    public StringifiedExpression DispatchExclusiveOr(Expression e)
        => BinaryDispatch("^", e);

    [Pure]
    public StringifiedExpression DispatchGreaterThan(Expression e)
        => BinaryDispatch(">", e);

    [Pure]
    public StringifiedExpression DispatchGreaterThanOrEqual(Expression e)
        => BinaryDispatch(">=", e);

    [Pure]
    public StringifiedExpression DispatchLeftShift(Expression e)
        => BinaryDispatch("<<", e);

    [Pure]
    public StringifiedExpression DispatchLessThan(Expression e)
        => BinaryDispatch("<", e);

    [Pure]
    public StringifiedExpression DispatchLessThanOrEqual(Expression e)
        => BinaryDispatch("<=", e);

    [Pure]
    public StringifiedExpression DispatchModulo(Expression e)
        => BinaryDispatch("%", e);

    [Pure]
    public StringifiedExpression DispatchMultiply(Expression e)
        => BinaryDispatch("*", e);

    [Pure]
    public StringifiedExpression DispatchMultiplyChecked(Expression e)
        => BinaryDispatch("*", e);

    [Pure]
    public StringifiedExpression DispatchNegate(Expression e)
        => UnaryDispatch("-", e);

    [Pure]
    public StringifiedExpression DispatchUnaryPlus(Expression e)
        => UnaryDispatch("+", e);

    [Pure]
    public StringifiedExpression DispatchNegateChecked(Expression e)
        => UnaryDispatch("-", e);

    [Pure]
    public StringifiedExpression DispatchNot(Expression e)
        => UnaryDispatch(e.Type == typeof(bool) || e.Type == typeof(bool?) ? "!" : "~", e);

    [Pure]
    public StringifiedExpression DispatchNotEqual(Expression e)
        => BinaryDispatch("!=", e);

    [Pure]
    public StringifiedExpression DispatchOr(Expression e)
        => BinaryDispatch("|", e);

    [Pure]
    public StringifiedExpression DispatchOrElse(Expression e)
        => BinaryDispatch("||", e);

    [Pure]
    public StringifiedExpression DispatchParameter(Expression e)
    {
        var parameterExpression = (ParameterExpression)e;
        // ReSharper disable once ConstantNullCoalescingCondition
        return StringifiedExpression.TextAndExpr(parameterExpression.Name ?? parameterExpression.Type.Name + parameterExpression.GetHashCode(), e);
    }

    [Pure]
    public StringifiedExpression DispatchQuote(Expression e)
        => StringifiedExpression.WithChildren(NestExpression(e.NodeType, ((UnaryExpression)e).Operand).ToArray());

    [Pure]
    public StringifiedExpression DispatchRightShift(Expression e)
        => BinaryDispatch(">>", e);

    [Pure]
    public StringifiedExpression DispatchSubtract(Expression e)
        => BinaryDispatch("-", e);

    [Pure]
    public StringifiedExpression DispatchSubtractChecked(Expression e)
        => BinaryDispatch("-", e);

    [Pure]
    public StringifiedExpression DispatchTypeAs(Expression e)
        => UnaryPostfixDispatch(" as " + TypeNameToCode(e.Type), e);

    [Pure]
    public StringifiedExpression DispatchTypeIs(Expression e)
        => TypeOpDispatch("is", e);

    [Pure]
    public StringifiedExpression DispatchAssign(Expression e)
        => BinaryDispatch("=", e);

    [Pure]
    public StringifiedExpression DispatchDecrement(Expression e)
        => UnaryPostfixDispatch(" - 1", e);

    [Pure]
    public StringifiedExpression DispatchIncrement(Expression e)
        => UnaryPostfixDispatch(" + 1", e);

    [Pure]
    public StringifiedExpression DispatchAddAssign(Expression e)
        => BinaryDispatch("+=", e);

    [Pure]
    public StringifiedExpression DispatchAndAssign(Expression e)
        => BinaryDispatch("&=", e);

    [Pure]
    public StringifiedExpression DispatchDivideAssign(Expression e)
        => BinaryDispatch("/=", e);

    [Pure]
    public StringifiedExpression DispatchExclusiveOrAssign(Expression e)
        => BinaryDispatch("^=", e);

    [Pure]
    public StringifiedExpression DispatchLeftShiftAssign(Expression e)
        => BinaryDispatch("<<=", e);

    [Pure]
    public StringifiedExpression DispatchModuloAssign(Expression e)
        => BinaryDispatch("%=", e);

    [Pure]
    public StringifiedExpression DispatchMultiplyAssign(Expression e)
        => BinaryDispatch("*=", e);

    [Pure]
    public StringifiedExpression DispatchOrAssign(Expression e)
        => BinaryDispatch("|=", e);

    [Pure]
    public StringifiedExpression DispatchRightShiftAssign(Expression e)
        => BinaryDispatch(">>=", e);

    [Pure]
    public StringifiedExpression DispatchSubtractAssign(Expression e)
        => BinaryDispatch("-=", e);

    [Pure]
    public StringifiedExpression DispatchAddAssignChecked(Expression e)
        => BinaryDispatch("+=", e);

    [Pure]
    public StringifiedExpression DispatchMultiplyAssignChecked(Expression e)
        => BinaryDispatch("*=", e);

    [Pure]
    public StringifiedExpression DispatchSubtractAssignChecked(Expression e)
        => BinaryDispatch("-=", e);

    [Pure]
    public StringifiedExpression DispatchPreIncrementAssign(Expression e)
        => UnaryDispatch("++", e);

    [Pure]
    public StringifiedExpression DispatchPreDecrementAssign(Expression e)
        => UnaryDispatch("--", e);

    [Pure]
    public StringifiedExpression DispatchPostIncrementAssign(Expression e)
        => UnaryPostfixDispatch("++", e);

    [Pure]
    public StringifiedExpression DispatchPostDecrementAssign(Expression e)
        => UnaryPostfixDispatch("--", e);

    [Pure]
    public StringifiedExpression DispatchOnesComplement(Expression e)
        => UnaryDispatch("~", e);
    #endregion

    #region Unused by C#'s expression support; or unavailable in the language at all.
    [Pure]
    public StringifiedExpression DispatchTypeEqual(Expression e)
        => throw new NotImplementedException();

    [Pure]
    public StringifiedExpression DispatchDebugInfo(Expression e)
        => throw new NotImplementedException();

    [Pure]
    public StringifiedExpression DispatchDynamic(Expression e)
        => throw new NotImplementedException();

    [Pure]
    public StringifiedExpression DispatchDefault(Expression e)
    {
        var defExpr = (DefaultExpression)e;

        return StringifiedExpression.TextOnly("default(" + TypeNameToCode(defExpr.Type) + ")");
    }

    [Pure]
    public StringifiedExpression DispatchExtension(Expression e)
        => throw new NotImplementedException();

    [Pure]
    public StringifiedExpression DispatchGoto(Expression e)
        => throw new NotImplementedException();

    [Pure]
    public StringifiedExpression DispatchLabel(Expression e)
        => throw new NotImplementedException();

    [Pure]
    public StringifiedExpression DispatchRuntimeVariables(Expression e)
        => throw new NotImplementedException();

    [Pure]
    public StringifiedExpression DispatchLoop(Expression e)
        => throw new NotImplementedException();

    [Pure]
    public StringifiedExpression DispatchSwitch(Expression e)
        => throw new NotImplementedException();

    [Pure]
    public StringifiedExpression DispatchThrow(Expression e)
    {
        var kids = KidsBuilder.Create();
        var ue = (UnaryExpression)e;

        kids.Add("throw ");
        kids.Add(this.ExpressionDispatch(ue.Operand));

        return kids.Finish();
    }

    [Pure]
    public StringifiedExpression DispatchTry(Expression e)
        => throw new NotImplementedException();

    [Pure]
    public StringifiedExpression DispatchUnbox(Expression e)
        => throw new NotImplementedException();

    [Pure]
    public StringifiedExpression DispatchPowerAssign(Expression e)
        => throw new NotImplementedException();

    [Pure]
    public StringifiedExpression DispatchIsTrue(Expression e)
        => throw new NotImplementedException();

    [Pure]
    public StringifiedExpression DispatchIsFalse(Expression e)
        => throw new NotImplementedException();
    #endregion
}


text:
package com.fanlehai.hadoop.serialize.compress;

import com.hadoop.compression.lzo.LzopCodec;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.*;
import org.apache.hadoop.io.IOUtils;

import java.io.*;

/*
 *
 * 读取hdfs上文件,进行lzo压缩保存到hdfs;
 * 读取hdfs上用lzo压缩的文件;
 *
 * 命令行参数:
 * compress
 *
 *
 */

public class LzopFileReadWrite {

	public static void main(String... args) throws Exception {
		Configuration config = new Configuration();

		LzopCodec codec = new LzopCodec();
		codec.setConf(config);

		Path srcFile = new Path(args[0]);
		Path restoredFile = new Path(args[0] + ".restored");

		Path destFile = compress(srcFile, config);
		decompress(destFile, restoredFile, config);
	}

	public static Path compress(Path src, Configuration config) throws IOException {
		Path destFile = new Path(src.toString() + new LzopCodec().getDefaultExtension());

		LzopCodec codec = new LzopCodec();
		codec.setConf(config);

		FileSystem hdfs = FileSystem.get(config);
		InputStream is = null;
		OutputStream os = null;
		try {
			is = hdfs.open(src);
			os = codec.createOutputStream(hdfs.create(destFile));

			IOUtils.copyBytes(is, os, config);
		} finally {
			IOUtils.closeStream(os);
			IOUtils.closeStream(is);
		}
		return destFile;
	}

	public static void decompress(Path src, Path dest, Configuration config) throws IOException {
		LzopCodec codec = new LzopCodec();
		codec.setConf(config);

		FileSystem hdfs = FileSystem.get(config);
		InputStream is = null;
		OutputStream os = null;
		try {
			is = codec.createInputStream(hdfs.open(src));
			os = hdfs.create(dest);

			IOUtils.copyBytes(is, os, config);
		} finally {
			IOUtils.closeStream(os);
			IOUtils.closeStream(is);
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
package com.test.logging.jul;

import java.util.logging.Logger;

import org.junit.After;
import org.junit.Before;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

import com.test.logging.common.LoggingTest;
import com.test.logging.common.ProfilerOptions;
import com.test.logging.common.TestFactoryType;
import static com.test.logging.common.Util.sleepForIOCatchup;

/** JUL logger test */
public class JulTest {

    /** Profiler options */
    private static final ProfilerOptions opts = new ProfilerOptions("Java Util Logging Profiler");

    /** Different types of tests */
    private static final TestFactoryType[] allTypes = TestFactory.getSupportedTypes();

    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
    }

    @AfterClass
    public static void tearDownAfterClass() throws Exception {
    }

    @Before
    public void setUp() throws Exception {
    }

    @After
    public void tearDown() throws Exception {
    }

    @Test
    public void testSyncFileLogger() {
        // Synchronous file logger
        System.out.println("(((((((((((((   SYNC FILE LOGGER   ))))))))))))))))");
        Logger logger = Logger.getLogger("SyncFileLogger");
        // Iterate through all unit work types and execute test scenarios
        for (TestFactoryType t : allTypes) {
            new LoggingTest<Logger>(t.toString() + "-Sync", new TestFactory(t, logger), opts).run();
        }
    }

}


text:
package org.qirx.cms.elasticsearch

import play.api.libs.ws.WSClient
import play.api.libs.ws.WSResponse
import play.api.libs.json.JsObject
import play.api.libs.json.Json.obj
import scala.concurrent.Future
import scala.concurrent.ExecutionContext

class IndexStore(
  endpoint: String,
  indexName: String,
  metaId: String,
  client: WSClient)(implicit ec: ExecutionContext) {

  private val documentEndpoint =
    s"$endpoint/$indexName/$metaId"

  private val idMappingsEndpoint =
    s"$endpoint/$indexName/${metaId}_id_mappings"

  private def url(url: String) = client.url(url)

  def save(id: String, document: JsObject): Future[Unit] =
    getIndexId(id)
      .flatMap {
        case Some(indexId) => overrideDocument(indexId, document)
        case None => saveNewDocument(id, document)
      }

  def list(fieldSet: Set[String]): Future[Seq[JsObject]] = {

    var searchUrl = url(documentEndpoint + "/_search")
    if (fieldSet.nonEmpty)
      searchUrl = searchUrl.withQueryString(fieldSetAsQueryString(fieldSet))

    searchUrl.get.map(responseAsSeq andThen extractDocuments)
  }

  def get(id: String, fieldSet: Set[String]): Future[Option[JsObject]] =
    getIndexId(id).flatMap {
      case Some(indexId) =>
        url(documentEndpoint + "/" + indexId)
          .withQueryString(fieldSetAsQueryString(fieldSet))
          .get
          .map(responseAsJsObject andThen extractDocument)
      case None => futureOfNone
    }

  def addId(id: String, newId: String): Future[Unit] =
    getIndexId(id).flatMap {
      case Some(indexId) =>
        url(idMappingsEndpoint + "/" + indexId + "/_update")
          .withQueryString(refresh)
          .post(
            obj(
              "script" -> "ctx._source.ids += id",
              "params" -> obj("id" -> newId)

            )
          )
          .map(toUnit)
      case None => futureOfUnit
    }

  def deleteAll(): Future[Unit] = {
    val deleteDocuments =
      url(documentEndpoint + "/_query")
        .withBody(matchAllQuery)
        .withQueryString(refresh)
        .delete

    val deleteIdMappings =
      url(idMappingsEndpoint + "/_query")
        .withBody(matchAllQuery)
        .withQueryString(refresh)
        .delete

    Future.sequence(Seq(deleteDocuments, deleteIdMappings)).map(toUnit)
  }

  def delete(id: String): Future[Unit] =
    getIndexId(id).flatMap {
      case Some(indexId) =>
        val removeDocument =
          url(documentEndpoint + "/" + indexId)
            .withQueryString(refresh)
            .delete

        val removeIdMapping =
          url(idMappingsEndpoint + "/" + indexId)
            .withQueryString(refresh)
            .delete

        Future.sequence(Seq(removeDocument, removeIdMapping)).map(toUnit)
      case None =>
        println("delete", id)
        Future successful (())
    }

  def exists(id: String): Future[Boolean] =
    url(idMappingsEndpoint + "/_count")
      .withBody(searchIdQuery(id))
      .get
      .map(r => (r.json \ "count").as[Int] > 0)

  private val toUnit: Any => Unit = _ => ()

  private def getIndexId(id: String): Future[Option[String]] =
    searchIdMappings(id)
      .get
      .map(responseAsSeq andThen (_.headOption) andThen extractId)

  private def searchIdMappings(id: String) =
    url(idMappingsEndpoint + "/_search").withBody(searchIdQuery(id))

  private val responseAsSeq: WSResponse => Seq[JsObject] = {
    case response if response.status == 200 =>
      (response.json \ "hits" \ "hits").as[Seq[JsObject]]
    case response => Seq.empty
  }

  private val extractId: Option[JsObject] => Option[String] =
    _ map { o => (o \ "_id").as[String] }

  private def overrideDocument(indexId: String, document: JsObject) =
    url(documentEndpoint + "/" + indexId)
      .withQueryString(refresh)
      .put(document)
      .map { _ => () }

  private def saveNewDocument(id: String, document: JsObject) =
    storeNewDocument(document)
      .flatMap(indexId => createIdMapping(indexId, id))
      .map(toUnit)

  private def storeNewDocument(document: JsObject) =
    url(documentEndpoint)
      .withQueryString(refresh)
      .post(document)
      .map(responseAsJsObject andThen (o => (o \ "_id").as[String]))

  private def createIdMapping(indexId: String, id: String) =
    url(idMappingsEndpoint + "/" + indexId)
      .withQueryString(refresh)
      .put(obj("ids" -> Seq(id)))

  private def searchIdQuery(id: String) =
    obj(
      "query" -> obj(
        "term" -> obj("ids" -> id)
      )
    )

  private val responseAsJsObject: WSResponse => JsObject =
    _.json.as[JsObject]

  private val extractDocuments: Seq[JsObject] => Seq[JsObject] =
    _.map(extractDocument).flatten

  private val extractDocument: JsObject => Option[JsObject] =
    o => (o \ "_source").asOpt[JsObject]

  private val futureOfNone = Future successful None
  private val futureOfUnit = Future successful (())

  private def fieldSetAsQueryString(fieldSet: Set[String]) =
    "_source" -> fieldSet.mkString(",")

  private val matchAllQuery =
    obj(
      "query" -> obj(
        "match_all" -> obj()
      )
    )

  private val refresh = "refresh" -> "true"

}


text:
package org.apache.sentry.binding.hive.authz;

import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;

import org.apache.hadoop.hive.ql.plan.HiveOperation;
import org.apache.sentry.binding.hive.authz.HiveAuthzPrivileges.HiveExtendedOperation;
import org.apache.sentry.binding.hive.authz.HiveAuthzPrivileges.HiveOperationScope;
import org.apache.sentry.binding.hive.authz.HiveAuthzPrivileges.HiveOperationType;
import org.apache.sentry.core.common.Action;
import org.apache.sentry.core.model.db.DBModelAction;
import org.apache.sentry.core.model.db.DBModelAuthorizable.AuthorizableType;

public class HiveAuthzPrivilegesMap {
  private static final Map <HiveOperation, HiveAuthzPrivileges> hiveAuthzStmtPrivMap =
    new HashMap<HiveOperation, HiveAuthzPrivileges>();
  private static final Map <HiveExtendedOperation, HiveAuthzPrivileges> hiveAuthzExtendedPrivMap =
    new HashMap<HiveExtendedOperation, HiveAuthzPrivileges>();

  static {
    HiveAuthzPrivileges tableDDLPrivilege = new HiveAuthzPrivileges.AuthzPrivilegeBuilder().
        addOutputObjectPriviledge(AuthorizableType.Table, EnumSet.of(DBModelAction.ALL)).
        addInputObjectPriviledge(AuthorizableType.URI, EnumSet.of(DBModelAction.SELECT)).
        setOperationScope(HiveOperationScope.TABLE).
        setOperationType(HiveOperationType.DDL).
        build();
    /* Currently Hive treats both select and insert as Query
     * The difference is that the insert also has output table entities
     */
    HiveAuthzPrivileges tableQueryPrivilege = new HiveAuthzPrivileges.AuthzPrivilegeBuilder().
        addInputObjectPriviledge(AuthorizableType.Table, EnumSet.of(DBModelAction.SELECT)).
        addOutputObjectPriviledge(AuthorizableType.Table, EnumSet.of(DBModelAction.INSERT)).
        addOutputObjectPriviledge(AuthorizableType.URI, EnumSet.of(DBModelAction.INSERT)).
        setOperationScope(HiveOperationScope.TABLE).
        setOperationType(HiveOperationType.QUERY).
        build();
    HiveAuthzPrivileges tableLoadPrivilege = new HiveAuthzPrivileges.AuthzPrivilegeBuilder().
        addInputObjectPriviledge(AuthorizableType.URI, EnumSet.of(DBModelAction.SELECT)).
        addOutputObjectPriviledge(AuthorizableType.Table, EnumSet.of(DBModelAction.INSERT)).
        setOperationScope(HiveOperationScope.TABLE).
        setOperationType(HiveOperationType.DATA_LOAD).
        build();

    HiveAuthzPrivileges tableExportPrivilege = new HiveAuthzPrivileges.AuthzPrivilegeBuilder().
        addInputObjectPriviledge(AuthorizableType.Table, EnumSet.of(DBModelAction.SELECT)).
        addOutputObjectPriviledge(AuthorizableType.URI, EnumSet.of(DBModelAction.INSERT)).
        setOperationScope(HiveOperationScope.TABLE).
        setOperationType(HiveOperationType.DATA_UNLOAD).
        build();

    HiveAuthzPrivileges tableMetaDataPrivilege = new HiveAuthzPrivileges.AuthzPrivilegeBuilder().
        addInputObjectPriviledge(AuthorizableType.Table, EnumSet.of(DBModelAction.SELECT, DBModelAction.INSERT)).
        setOperationScope(HiveOperationScope.TABLE).
        setOperationType(HiveOperationType.INFO).
        build();

    HiveAuthzPrivileges dbDDLPrivilege = new HiveAuthzPrivileges.AuthzPrivilegeBuilder().
        addOutputObjectPriviledge(AuthorizableType.Db, EnumSet.of(DBModelAction.ALL)).
        addInputObjectPriviledge(AuthorizableType.URI, EnumSet.of(DBModelAction.ALL)).
        setOperationScope(HiveOperationScope.DATABASE).
        setOperationType(HiveOperationType.DDL).
        build();

    HiveAuthzPrivileges dbImportPrivilege = new HiveAuthzPrivileges.AuthzPrivilegeBuilder().
        addOutputObjectPriviledge(AuthorizableType.Db, EnumSet.of(DBModelAction.ALL)).
        addInputObjectPriviledge(AuthorizableType.URI, EnumSet.of(DBModelAction.SELECT)).
        setOperationScope(HiveOperationScope.DATABASE).
        setOperationType(HiveOperationType.DDL).
        build();

    HiveAuthzPrivileges createViewPrivilege = new HiveAuthzPrivileges.AuthzPrivilegeBuilder().
    addOutputObjectPriviledge(AuthorizableType.Db, EnumSet.of(DBModelAction.ALL)).
    addInputObjectPriviledge(AuthorizableType.Table, EnumSet.of(DBModelAction.SELECT)).
    addInputObjectPriviledge(AuthorizableType.URI, EnumSet.of(DBModelAction.SELECT)).
    setOperationScope(HiveOperationScope.DATABASE).
    setOperationType(HiveOperationType.DDL).
    build();

    HiveAuthzPrivileges dbMetaDataPrivilege = new HiveAuthzPrivileges.AuthzPrivilegeBuilder().
      addInputObjectPriviledge(AuthorizableType.Db, EnumSet.of(DBModelAction.SELECT)).
      setOperationScope(HiveOperationScope.DATABASE).
      setOperationType(HiveOperationType.INFO).
      build();

    HiveAuthzPrivileges tableDMLPrivilege = new HiveAuthzPrivileges.AuthzPrivilegeBuilder().
        addOutputObjectPriviledge(AuthorizableType.Table, EnumSet.of(DBModelAction.INSERT)).
        setOperationScope(HiveOperationScope.TABLE).
        setOperationType(HiveOperationType.DML).
        build();
    HiveAuthzPrivileges serverPrivilege = new HiveAuthzPrivileges.AuthzPrivilegeBuilder().
        addInputObjectPriviledge(AuthorizableType.Server, EnumSet.of(DBModelAction.ALL)).
        addOutputObjectPriviledge(AuthorizableType.Server, EnumSet.of(DBModelAction.ALL)).
        setOperationScope(HiveOperationScope.SERVER).
        setOperationType(HiveOperationType.DDL).
        build();

    HiveAuthzPrivileges anyPrivilege = new HiveAuthzPrivileges.AuthzPrivilegeBuilder().
        addInputObjectPriviledge(AuthorizableType.Table, EnumSet.of(DBModelAction.SELECT, DBModelAction.INSERT)).
        addInputObjectPriviledge(AuthorizableType.URI, EnumSet.of(DBModelAction.SELECT)).
        setOperationScope(HiveOperationScope.CONNECT).
        setOperationType(HiveOperationType.QUERY).
        build();

    hiveAuthzStmtPrivMap.put(HiveOperation.ALTERTABLE_ADDCOLS, dbDDLPrivilege);
    hiveAuthzStmtPrivMap.put(HiveOperation.ALTERTABLE_REPLACECOLS, dbDDLPrivilege);
    hiveAuthzStmtPrivMap.put(HiveOperation.ALTERTABLE_RENAMECOL, dbDDLPrivilege);
    hiveAuthzStmtPrivMap.put(HiveOperation.ALTERTABLE_RENAMEPART, dbDDLPrivilege);
    hiveAuthzStmtPrivMap.put(HiveOperation.ALTERTABLE_RENAME, dbDDLPrivilege);
    hiveAuthzStmtPrivMap.put(HiveOperation.ALTERTABLE_DROPPARTS, dbDDLPrivilege);
    hiveAuthzStmtPrivMap.put(HiveOperation.ALTERTABLE_ADDPARTS, dbDDLPrivilege);
    hiveAuthzStmtPrivMap.put(HiveOperation.ALTERTABLE_TOUCH, dbDDLPrivilege);
    hiveAuthzStmtPrivMap.put(HiveOperation.ALTERTABLE_ARCHIVE, dbDDLPrivilege);
    hiveAuthzStmtPrivMap.put(HiveOperation.ALTERTABLE_UNARCHIVE, dbDDLPrivilege);
    hiveAuthzStmtPrivMap.put(HiveOperation.ALTERTABLE_SERIALIZER, dbDDLPrivilege);
    hiveAuthzStmtPrivMap.put(HiveOperation.ALTERTABLE_PROPERTIES, dbDDLPrivilege);
    hiveAuthzStmtPrivMap.put(HiveOperation.ALTERPARTITION_SERIALIZER, dbDDLPrivilege);
    hiveAuthzStmtPrivMap.put(HiveOperation.ALTERTABLE_SERDEPROPERTIES, dbDDLPrivilege);
    hiveAuthzStmtPrivMap.put(HiveOperation.ALTERPARTITION_SERDEPROPERTIES, dbDDLPrivilege);
    hiveAuthzStmtPrivMap.put(HiveOperation.ALTERTABLE_CLUSTER_SORT, dbDDLPrivilege);
    hiveAuthzStmtPrivMap.put(HiveOperation.ANALYZE_TABLE, tableQueryPrivilege);
    hiveAuthzStmtPrivMap.put(HiveOperation.SWITCHDATABASE, anyPrivilege);
    // SHOWDATABASES
    // SHOWTABLES
    hiveAuthzStmtPrivMap.put(HiveOperation.SHOWCOLUMNS, tableMetaDataPrivilege);
    hiveAuthzStmtPrivMap.put(HiveOperation.SHOW_TABLESTATUS, tableMetaDataPrivilege);
    hiveAuthzStmtPrivMap.put(HiveOperation.SHOW_TBLPROPERTIES, tableMetaDataPrivilege);
    hiveAuthzStmtPrivMap.put(HiveOperation.SHOW_CREATETABLE, tableMetaDataPrivilege);
    // SHOWFUNCTIONS
    hiveAuthzStmtPrivMap.put(HiveOperation.SHOWINDEXES, tableMetaDataPrivilege);
    hiveAuthzStmtPrivMap.put(HiveOperation.SHOWPARTITIONS, tableMetaDataPrivilege);
    // SHOWLOCKS
    hiveAuthzStmtPrivMap.put(HiveOperation.CREATEFUNCTION, anyPrivilege);
    hiveAuthzStmtPrivMap.put(HiveOperation.DROPFUNCTION, anyPrivilege);
    hiveAuthzStmtPrivMap.put(HiveOperation.CREATEVIEW, createViewPrivilege);
    hiveAuthzStmtPrivMap.put(HiveOperation.DROPVIEW, dbDDLPrivilege);
    hiveAuthzStmtPrivMap.put(HiveOperation.CREATEINDEX, dbDDLPrivilege);
    hiveAuthzStmtPrivMap.put(HiveOperation.DROPINDEX, dbDDLPrivilege);
    hiveAuthzStmtPrivMap.put(HiveOperation.DROPDATABASE, serverPrivilege);
    hiveAuthzStmtPrivMap.put(HiveOperation.DROPTABLE, dbDDLPrivilege);
    hiveAuthzStmtPrivMap.put(HiveOperation.EXPORT, tableExportPrivilege);
    hiveAuthzStmtPrivMap.put(HiveOperation.IMPORT, dbImportPrivilege);
    hiveAuthzStmtPrivMap.put(HiveOperation.LOAD, tableLoadPrivilege);
    hiveAuthzStmtPrivMap.put(HiveOperation.ALTERINDEX_REBUILD, tableDDLPrivilege);
    hiveAuthzStmtPrivMap.put(HiveOperation.ALTERVIEW_PROPERTIES, tableDDLPrivilege);
    hiveAuthzStmtPrivMap.put(HiveOperation.LOCKTABLE, tableDMLPrivilege);
    hiveAuthzStmtPrivMap.put(HiveOperation.UNLOCKTABLE, tableDMLPrivilege);
    // CREATEROLE
    // DROPROLE
    // GRANT_PRIVILEGE
    // REVOKE_PRIVILEGE
    // SHOW_GRANT
    // GRANT_ROLE
    // REVOKE_ROLE
    // SHOW_ROLE_GRANT
    hiveAuthzStmtPrivMap.put(HiveOperation.ALTERTABLE_PROTECTMODE, dbDDLPrivilege);
    hiveAuthzStmtPrivMap.put(HiveOperation.ALTERPARTITION_PROTECTMODE, dbDDLPrivilege);
    hiveAuthzStmtPrivMap.put(HiveOperation.ALTERTABLE_FILEFORMAT, dbDDLPrivilege);
    hiveAuthzStmtPrivMap.put(HiveOperation.ALTERPARTITION_FILEFORMAT, dbDDLPrivilege);
    hiveAuthzStmtPrivMap.put(HiveOperation.ALTERTABLE_LOCATION, serverPrivilege);
    hiveAuthzStmtPrivMap.put(HiveOperation.ALTERPARTITION_LOCATION, serverPrivilege);
    hiveAuthzStmtPrivMap.put(HiveOperation.CREATEDATABASE, serverPrivilege);
    hiveAuthzStmtPrivMap.put(HiveOperation.CREATETABLE, dbDDLPrivilege);
    hiveAuthzStmtPrivMap.put(HiveOperation.CREATETABLE_AS_SELECT,
        new HiveAuthzPrivileges.AuthzPrivilegeBuilder().
        addInputObjectPriviledge(AuthorizableType.Table, EnumSet.of(DBModelAction.SELECT)).
        addOutputObjectPriviledge(AuthorizableType.Db, EnumSet.of(DBModelAction.ALL)).
        setOperationScope(HiveOperationScope.DATABASE).
        setOperationType(HiveOperationType.DDL).
        build());
    hiveAuthzStmtPrivMap.put(HiveOperation.QUERY, tableQueryPrivilege);
    hiveAuthzStmtPrivMap.put(HiveOperation.ALTERINDEX_PROPS, dbDDLPrivilege);
    hiveAuthzStmtPrivMap.put(HiveOperation.ALTERDATABASE, dbDDLPrivilege);
    hiveAuthzStmtPrivMap.put(HiveOperation.DESCDATABASE, dbMetaDataPrivilege);
    hiveAuthzStmtPrivMap.put(HiveOperation.DESCTABLE, tableMetaDataPrivilege);
    hiveAuthzStmtPrivMap.put(HiveOperation.ALTERTABLE_MERGEFILES, dbDDLPrivilege);
    hiveAuthzStmtPrivMap.put(HiveOperation.ALTERPARTITION_MERGEFILES, dbDDLPrivilege);
    hiveAuthzStmtPrivMap.put(HiveOperation.ALTERTABLE_SKEWED, dbDDLPrivilege);
    hiveAuthzStmtPrivMap.put(HiveOperation.ALTERTBLPART_SKEWED_LOCATION, dbDDLPrivilege);

    hiveAuthzExtendedPrivMap.put(HiveExtendedOperation.TRANSFORM, serverPrivilege);
  }

  public static HiveAuthzPrivileges getHiveAuthzPrivileges(HiveOperation hiveStmtOp) {
    return hiveAuthzStmtPrivMap.get(hiveStmtOp);
  }

  public static HiveAuthzPrivileges getHiveExtendedAuthzPrivileges(HiveExtendedOperation hiveExtOp) {
    return hiveAuthzExtendedPrivMap.get(hiveExtOp);
  }
}


text:
What is a good EPUB reader on Linux
================================================================================
If the habit on reading books on electronic tablets is still on its way, reading books on a computer is even rarer. It is hard enough to focus on the classics of the 16th century literature, so who needs the Facebook chat pop up sound in the background in addition? But if for some reasons you wish to open an electronic book in your computer, chances are that you will need specific software. Indeed, most editors agreed with using the EPUB format for electronic books (for "Electronic PUBlication"). Hopefully, Linux is not deprived of good programs capable of dealing with such format. In short, here is a non-exhaustive list of good EPUB readers on Linux.

### 1. Calibre ###

![](https://farm6.staticflickr.com/5577/14975176155_0989766bb3_z.jpg)

Let's dive in with maybe the biggest name of that list: [Calibre][1]. More than just an ebook reader, Calibre is a fully packaged e-library. It supports a plethora of formats (almost every I can think of), integrates a reader, a manager, a meta-data editor which can download covers from the Internet, an EPUB editor, a news reader, and a search engine to download additional books. To top it all, the interface is slick and has nothing to envy to other professional software. The only potential downside is that if you are looking for an EPUB reader, and are not interested in the whole library manager aspect, the program is too heavy for your needs.

### 2. FBReader ###

![](https://farm4.staticflickr.com/3900/14975176165_f2e4afd2fa_o.jpg)

[FBReader][2] is also a library manager, but in a lighter way than Calibre. The interface is more sober, and is clearly cut in two: (1) the library aspect where you can add files, edit the meta-data, or download new books, and (2) the reader aspect. If you like simplicity, you might enjoy this program. I personally appreciate its straightforward tag and series system for classifying books.

### 3. Cool Reader ###

![](https://farm6.staticflickr.com/5594/14975176195_ac46952150.jpg)

For all of you who are just looking for a way to visualize the content of an EPUB file, I recommend [Cool Reader][5]. In the spirit of Linux applications which do only one thing and do it well, Cool Reader is optimized to just open an EPUB file, and navigate through it via handy shortcuts. And since it is based on Qt, it also follows Qt's mentality by giving a ton of settings to mess around with.

### 4. Okular ###

![](https://farm6.staticflickr.com/5559/14788504729_5a2ec2c11b_z.jpg)

Since we were talking about Qt applications, one of KDE's main document viewer, [Okular][3], also has the capacity to view EPUB files, once an EPUB library has been installed on the system. However, this is probably not a very good option if you are not a KDE user.

### 5. pPub ###

![](https://farm4.staticflickr.com/3835/14788504789_e7c742fa20_z.jpg)

[pPub][4] is an old project that you can still find on Github. Its latest change seems to have been made two years ago. However, pPub is one of those programs that really deserve a second life. Written in Python and based on GTK3 and WebKit, pPub is lightweight and intuitive. The interface probably needs a little updating and is beyond sober, but the core is very good. It even supports JavaScript. So please, someone kick that up again.

### 6. epub ###

![](https://farm4.staticflickr.com/3871/14788844378_16fb51a1b9_z.jpg)

If all you need is a quick and easy way to check the content of an EPUB file, without caring about any fancy GUI, maybe an EPUB reader with command line interface might just do. [epub][6] is a minimalistic EPUB reader written in Python, which allows you to read an EPUB file in a terminal environment. You can switch between chapter/TOC views, up/down a page, and nothing more. This is as simple as any EPUB reader can possibly get.

### 7. Sigil ###

![](https://farm4.staticflickr.com/3921/14788640417_7940627871_z.jpg)

Finally, last of the list is not actually an EPUB reader, but more of a standalone editor. [Sigil][7] is able to extract the content of an EPUB file, and break it down for what it really is: xhtml text, images, styles, and sometimes audio. The interface is a lot more complex than the one for a basic reader, but remains clear and well thought, on par with the features it provides. I particularly appreciate the tab system. If you are familiar with editing web pages, you will be in know territory here.

To conclude, there are a lot of open source EPUB readers out there. Some do nothing more, while others go way beyond that. As usual, I recommend using the one that makes the most sense for you to use. If you know more good EPUB readers on Linux that you like, please let us know in the comments.

--------------------------------------------------------------------------------

via: http://xmodulo.com/2014/08/good-epub-reader-linux.html

作者:[Adrien Brochard][a]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)

本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创翻译,[Linux中国](http://linux.cn/) 荣誉推出

[a]:http://xmodulo.com/author/adrien
[1]:http://calibre-ebook.com/
[2]:http://fbreader.org/
[3]:http://okular.kde.org/
[4]:https://github.com/sakisds/pPub
[5]:http://crengine.sourceforge.net/
[6]:https://github.com/rupa/epub
[7]:https://github.com/user-none/Sigil


text:
package com.lothrazar.cyclic.block.anvil;

import com.lothrazar.cyclic.base.ScreenBase;
import com.lothrazar.cyclic.gui.ButtonMachineRedstone;
import com.lothrazar.cyclic.gui.EnergyBar;
import com.lothrazar.cyclic.registry.TextureRegistry;
import com.mojang.blaze3d.matrix.MatrixStack;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.util.text.ITextComponent;

public class ScreenAnvil extends ScreenBase<ContainerAnvil> {

  private ButtonMachineRedstone btnRedstone;
  private EnergyBar energy;
  //  private TimerBar timer;

  public ScreenAnvil(ContainerAnvil screenContainer, PlayerInventory inv, ITextComponent titleIn) {
    super(screenContainer, inv, titleIn);
    this.energy = new EnergyBar(this, TileAnvilAuto.MAX);
  }

  @Override
  public void init() {
    super.init();
    energy.guiLeft = guiLeft;
    energy.guiTop = guiTop;
    int x, y;
    x = guiLeft + 8;
    y = guiTop + 8;
    btnRedstone = addButton(new ButtonMachineRedstone(x, y, TileAnvilAuto.Fields.REDSTONE.ordinal(), container.tile.getPos()));
  }

  @Override
  public void render(MatrixStack ms, int mouseX, int mouseY, float partialTicks) {
    this.renderBackground(ms);
    super.render(ms, mouseX, mouseY, partialTicks);
    this.renderHoveredTooltip(ms, mouseX, mouseY);//renderHoveredToolTip
    if (TileAnvilAuto.POWERCONF.get() > 0)
      energy.renderHoveredToolTip(ms, mouseX, mouseY, container.tile.getEnergy());
    btnRedstone.onValueUpdate(container.tile);
  }

  @Override
  protected void drawGuiContainerForegroundLayer(MatrixStack ms, int mouseX, int mouseY) {
    this.drawButtonTooltips(ms, mouseX, mouseY);
    this.drawName(ms, this.title.getString());
  }

  @Override
  protected void drawGuiContainerBackgroundLayer(MatrixStack ms, float partialTicks, int mouseX, int mouseY) {
    this.drawBackground(ms, TextureRegistry.INVENTORY);
    this.drawSlot(ms, 54, 34);
    this.drawSlotLarge(ms, 104, 30);
    if (TileAnvilAuto.POWERCONF.get() > 0)
      energy.draw(ms, container.tile.getEnergy());
  }
}


text:
package hbase.keyDesign;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;

public class TableDesignDriver {
	private final static DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy.MM.dd hh:mm:ss");
	public static void main(String[] args) throws IOException {
		List<Book> books = generateTestSet();
		Configuration conf = HBaseConfiguration.create();

		DataFacade facade = new FlatAndWideTableDataFacade(conf);
		printTestSet(books);
		exercixeFacade(facade, books);
		facade.close();

		facade = new TallAndNarrowTableDataFacade(conf);
		exercixeFacade(facade, books);
		facade.close();
	}

	private static void printTestSet(List<Book> testBooks) {
		System.out.println("----------------");
		System.out.println("Test set has [" + testBooks.size() + "] Books:");
		System.out.println("----------------");
		for (Book book : testBooks){
			System.out.println(book);
		}
	}

	private static List<Book> generateTestSet(){
		List<Book> books = new ArrayList<Book>();
		books.add(new Book("author1", "Title1", new Date(11111111)));
		books.add(new Book("author1", "Title2", new Date(22222222)));
		books.add(new Book("author1", "Title3", new Date(33333333)));
		books.add(new Book("author2", "Title4", new Date(44444444)));
		books.add(new Book("author2", "Title5", new Date(55555555)));
		return books;
	}

	public static void exercixeFacade(DataFacade facade, List<Book> testBooks) throws IOException{
		System.out.println("----------------");
		System.out.println("Running against facade: " + facade.getClass());
		System.out.println("----------------");
		for (Book book : testBooks){
			facade.save(book);
		}
		getBooks(facade, "author1", new Date(22222222), new Date(33333333));
		getBooks(facade, "author3", new Date(55555555), new Date(55555555));
	}

	private static void getBooks(DataFacade facade, String authorId, Date start, Date end)
			throws IOException {
		System.out.println("Selecting books for author [" + authorId + "] " +
				"between [" + DATE_FORMAT.format(start) + "] " +
				"and [" + DATE_FORMAT.format(end) + "]");

		for ( Book book : facade.getBooks(authorId, start, end)){
			System.out.println("  " + book);
		}
	}
}


text:
package org.apache.camel.component.jetty.rest;

import org.apache.camel.BindToRegistry;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.jetty.BaseJettyTest;
import org.apache.camel.component.jetty.JettyRestHttpBinding;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;

public class RestJettyGetToDTest extends BaseJettyTest {

    @BindToRegistry("mybinding")
    private JettyRestHttpBinding binding = new JettyRestHttpBinding();

    @Test
    public void testJettyProducerGet() {
        String out = template.requestBody("http://localhost:" + getPort() + "/users/123/basic", null, String.class);
        assertEquals("123;Donald Duck", out);
    }

    @Override
    protected RouteBuilder createRouteBuilder() {
        return new RouteBuilder() {
            @Override
            public void configure() {
                // configure to use jetty on localhost with the given port
                restConfiguration().component("jetty").host("localhost").port(getPort()).endpointProperty("httpBindingRef",
                        "#mybinding");

                // use the rest DSL to define the rest services
                rest("/users/").get("{id}/basic").to("direct:basic");
                from("direct:basic").toD("seda:${header.id}");
                from("seda:123").to("mock:input").process(new Processor() {
                    public void process(Exchange exchange) {
                        String id = exchange.getIn().getHeader("id", String.class);
                        exchange.getMessage().setBody(id + ";Donald Duck");
                    }
                });
            }
        };
    }

}


text:
using UnityEngine;
using System.Collections;

public class KeyScript : MonoBehaviour {

	public VillagerDControl Player;
	public Vector3 Hidden = new Vector3(350,350,0);
	// Use this for initialization
	void Start () {

	}

	// When the player collides with the key, it sets the player to be able to complete the level
	void OnCollisionEnter2D (Collision2D collider) {
		if(collider.gameObject.tag=="Player"){
			Player.Key = true;
			this.gameObject.transform.position = Hidden;
		}
	}
}


text:
using System;
using System.Diagnostics;

namespace Zenos.Runtime
{
    public struct TypeManagerHandle
    {
        private readonly IntPtr _handleValue;

        internal TypeManagerHandle(IntPtr handleValue)
        {
            _handleValue = handleValue;
        }

        internal unsafe TypeManagerHandle(TypeManager* typeManager)
        {
            var p = (long)(typeManager) + 1;

            _handleValue = new IntPtr(p);
        }

        public bool IsNull => _handleValue == IntPtr.Zero;

        public bool IsTypeManager
        {
            get
            {
                unsafe
                {
                    return (((int)(byte*)_handleValue) & 0x1) == 0x1;
                }
            }
        }

        private IntPtr AsOsModuleIntPtr
        {
            get
            {
                Debug.Assert(!IsTypeManager);
                return _handleValue;
            }
        }

        internal unsafe TypeManager* AsTypeManagerPtr
        {
            get
            {
                Debug.Assert(IsTypeManager);
                unsafe
                {
                    return (TypeManager*)(((byte*)(void*)_handleValue) - 1);
                }
            }
        }

        public static  implicit operator TypeManagerHandle(System.Runtime.TypeManagerHandle handle) =>
            new TypeManagerHandle(handle.GetIntPtrUNSAFE());
    }
}


text:
using UnityEngine;
using System.Collections;

public class Tipstrigger3 : MonoBehaviour {

	// Use this for initialization
	void Start () {

	}

	// Update is called once per frame
	void Update () {

	}
	public GUIText textHints;
	void OnTriggerEnter(Collider col){
		if(col.gameObject.tag == "First Person Controller"){
				textHints.SendMessage("ShowHint",
			"Scott and Mimi ______ to Las Vegas twice.\nA. have gone(turn right)\nB. went (turn left)");
		}
	}
}


text:
require 'spec_helper'

module Spree
  describe Api::V1::ClassificationsController, type: :controller do
    let(:taxon) do
      taxon = create(:taxon)

      3.times do
        product = create(:product)
        product.taxons << taxon
      end
      taxon
    end

    before do
      stub_authentication!
    end

    context "as a user" do
      it "cannot change the order of a product" do
        api_put :update, taxon_id: taxon, product_id: taxon.products.first, position: 1
        expect(response.status).to eq(401)
      end
    end

    context "as an admin" do
      sign_in_as_admin!

      let(:last_product) { taxon.products.last }

      it "can change the order a product" do
        classification = taxon.classifications.find_by(product_id: last_product.id)
        expect(classification.position).to eq(3)
        api_put :update, taxon_id: taxon.id, product_id: last_product.id, position: 0
        expect(response.status).to eq(200)
        expect(classification.reload.position).to eq(1)
      end

      it "should touch the taxon" do
        taxon.update_attributes(updated_at: Time.current - 10.seconds)
        taxon_last_updated_at = taxon.updated_at
        api_put :update, taxon_id: taxon.id, product_id: last_product.id, position: 0
        taxon.reload
        expect(taxon_last_updated_at.to_i).to_not eq(taxon.updated_at.to_i)
      end
    end
  end
end


text:
<?php

namespace Symfony\Component\Config\Tests\Resource;

use PHPUnit\Framework\TestCase;
use Symfony\Component\Config\Resource\GlobResource;

class GlobResourceTest extends TestCase
{
    protected function tearDown(): void
    {
        $dir = \dirname(__DIR__).'/Fixtures';
        @rmdir($dir.'/TmpGlob');
        @unlink($dir.'/TmpGlob');
        @unlink($dir.'/Resource/TmpGlob');
        touch($dir.'/Resource/.hiddenFile');
    }

    public function testIterator()
    {
        $dir = \dirname(__DIR__).\DIRECTORY_SEPARATOR.'Fixtures';
        $resource = new GlobResource($dir, '/Resource', true);

        $paths = iterator_to_array($resource);

        $file = $dir.'/Resource'.\DIRECTORY_SEPARATOR.'ConditionalClass.php';
        $this->assertEquals([$file => new \SplFileInfo($file)], $paths);
        $this->assertInstanceOf(\SplFileInfo::class, current($paths));
        $this->assertSame($dir, $resource->getPrefix());

        $resource = new GlobResource($dir, '/**/Resource', true);

        $paths = iterator_to_array($resource);

        $file = $dir.\DIRECTORY_SEPARATOR.'Resource'.\DIRECTORY_SEPARATOR.'ConditionalClass.php';
        $this->assertEquals([$file => $file], $paths);
        $this->assertInstanceOf(\SplFileInfo::class, current($paths));
        $this->assertSame($dir, $resource->getPrefix());
    }

    public function testIteratorForExclusionDoesntIterateThroughSubfolders()
    {
        $dir = \dirname(__DIR__).\DIRECTORY_SEPARATOR.'Fixtures';
        $resource = new GlobResource($dir, \DIRECTORY_SEPARATOR.'Exclude', true, true);

        $paths = iterator_to_array($resource);

        $file = $dir.\DIRECTORY_SEPARATOR.'Exclude';
        $this->assertArrayHasKey($file, $paths);
        $this->assertCount(1, $paths);
    }

    public function testIteratorSkipsFoldersForGivenExcludedPrefixes()
    {
        $dir = \dirname(__DIR__).\DIRECTORY_SEPARATOR.'Fixtures';
        $resource = new GlobResource($dir, '/*Exclude*', true, false, [$dir.\DIRECTORY_SEPARATOR.'Exclude' => true]);

        $paths = iterator_to_array($resource);

        $file = $dir.\DIRECTORY_SEPARATOR.'Exclude'.\DIRECTORY_SEPARATOR.'AnExcludedFile.txt';
        $this->assertArrayNotHasKey($file, $paths);

        $file = $dir.\DIRECTORY_SEPARATOR.'Exclude'.\DIRECTORY_SEPARATOR.'ExcludeToo'.\DIRECTORY_SEPARATOR.'AnotheExcludedFile.txt';
        $this->assertArrayNotHasKey($file, $paths);
    }

    public function testIteratorSkipsSubfoldersForGivenExcludedPrefixes()
    {
        $dir = \dirname(__DIR__).\DIRECTORY_SEPARATOR.'Fixtures';
        $resource = new GlobResource($dir, '/*Exclude/*', true, false, [$dir.\DIRECTORY_SEPARATOR.'Exclude' => true]);

        $paths = iterator_to_array($resource);

        $file = $dir.\DIRECTORY_SEPARATOR.'Exclude'.\DIRECTORY_SEPARATOR.'AnExcludedFile.txt';
        $this->assertArrayNotHasKey($file, $paths);

        $file = $dir.\DIRECTORY_SEPARATOR.'Exclude'.\DIRECTORY_SEPARATOR.'ExcludeToo'.\DIRECTORY_SEPARATOR.'AnotheExcludedFile.txt';
        $this->assertArrayNotHasKey($file, $paths);
    }

    public function testIteratorSkipsFoldersWithForwardSlashForGivenExcludedPrefixes()
    {
        $dir = \dirname(__DIR__).\DIRECTORY_SEPARATOR.'Fixtures';
        $resource = new GlobResource($dir, '/*Exclude*', true, false, [$dir.'/Exclude' => true]);

        $paths = iterator_to_array($resource);

        $file = $dir.\DIRECTORY_SEPARATOR.'Exclude/AnExcludedFile.txt';
        $this->assertArrayNotHasKey($file, $paths);

        $file = $dir.\DIRECTORY_SEPARATOR.'Exclude'.\DIRECTORY_SEPARATOR.'ExcludeToo'.\DIRECTORY_SEPARATOR.'AnotheExcludedFile.txt';
        $this->assertArrayNotHasKey($file, $paths);
    }

    public function testIsFreshNonRecursiveDetectsNewFile()
    {
        $dir = \dirname(__DIR__).'/Fixtures';
        $resource = new GlobResource($dir, '/*', false);

        $this->assertTrue($resource->isFresh(0));

        mkdir($dir.'/TmpGlob');
        $this->assertTrue($resource->isFresh(0));

        rmdir($dir.'/TmpGlob');
        $this->assertTrue($resource->isFresh(0));

        touch($dir.'/TmpGlob');
        $this->assertFalse($resource->isFresh(0));

        unlink($dir.'/TmpGlob');
        $this->assertTrue($resource->isFresh(0));
    }

    public function testIsFreshNonRecursiveDetectsRemovedFile()
    {
        $dir = \dirname(__DIR__).'/Fixtures';
        $resource = new GlobResource($dir, '/*', false);

        touch($dir.'/TmpGlob');
        touch($dir.'/.TmpGlob');
        $this->assertTrue($resource->isFresh(0));

        unlink($dir.'/.TmpGlob');
        $this->assertTrue($resource->isFresh(0));

        unlink($dir.'/TmpGlob');
        $this->assertFalse($resource->isFresh(0));
    }

    public function testIsFreshRecursiveDetectsRemovedFile()
    {
        $dir = \dirname(__DIR__).'/Fixtures';
        $resource = new GlobResource($dir, '/*', true);

        touch($dir.'/Resource/TmpGlob');
        $this->assertTrue($resource->isFresh(0));

        unlink($dir.'/Resource/TmpGlob');
        $this->assertFalse($resource->isFresh(0));

        touch($dir.'/Resource/TmpGlob');
        $this->assertTrue($resource->isFresh(0));

        unlink($dir.'/Resource/.hiddenFile');
        $this->assertTrue($resource->isFresh(0));
    }

    public function testIsFreshRecursiveDetectsNewFile()
    {
        $dir = \dirname(__DIR__).'/Fixtures';
        $resource = new GlobResource($dir, '/*', true);

        $this->assertTrue($resource->isFresh(0));

        touch($dir.'/Resource/TmpGlob');
        $this->assertFalse($resource->isFresh(0));
    }

    public function testBraceFallback()
    {
        $dir = \dirname(__DIR__).\DIRECTORY_SEPARATOR.'Fixtures';
        $resource = new GlobResource($dir, '/*{/*/*.txt,.x{m,n}l}', true);

        $p = new \ReflectionProperty($resource, 'globBrace');
        $p->setAccessible(true);
        $p->setValue($resource, 0);

        $expected = [
            $dir.'/Exclude/ExcludeToo/AnotheExcludedFile.txt',
            $dir.'/ExcludeTrailingSlash/exclude/baz.txt',
            $dir.'/foo.xml',
        ];

        $this->assertSame($expected, array_keys(iterator_to_array($resource)));
    }

    public function testUnbalancedBraceFallback()
    {
        $dir = \dirname(__DIR__).\DIRECTORY_SEPARATOR.'Fixtures';
        $resource = new GlobResource($dir, '/*{/*/*.txt,.x{m,nl}', true);

        $p = new \ReflectionProperty($resource, 'globBrace');
        $p->setAccessible(true);
        $p->setValue($resource, 0);

        $this->assertSame([], array_keys(iterator_to_array($resource)));
    }

    public function testSerializeUnserialize()
    {
        $dir = \dirname(__DIR__).\DIRECTORY_SEPARATOR.'Fixtures';
        $resource = new GlobResource($dir, '/Resource', true);

        $newResource = unserialize(serialize($resource));

        $p = new \ReflectionProperty($resource, 'globBrace');
        $p->setAccessible(true);

        $this->assertEquals($p->getValue($resource), $p->getValue($newResource));
    }
}


text:
package hudson.cli;

import hudson.Extension;
import jenkins.model.Jenkins;
import org.jenkinsci.remoting.nio.NioChannelHub;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.DataOutputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.Socket;
import java.security.GeneralSecurityException;
import java.security.PrivateKey;
import java.security.Signature;

/**
 * {@link CliProtocol} Version 2, which adds transport encryption.
 *
 * @author Kohsuke Kawaguchi
 * @since 1.467
 */
@Extension
public class CliProtocol2 extends CliProtocol {
    @Override
    public String getName() {
        return "CLI2-connect";
    }

    @Override
    public void handle(Socket socket) throws IOException, InterruptedException {
        new Handler2(nio.getHub(), socket).run();
    }

    protected static class Handler2 extends Handler {
        /**
         * @deprecated as of 1.559
         *      Use {@link #Handler2(NioChannelHub, Socket)}
         */
        public Handler2(Socket socket) {
            super(socket);
        }

        public Handler2(NioChannelHub hub, Socket socket) {
            super(hub, socket);
        }

        @Override
        public void run() throws IOException, InterruptedException {
            try {
                DataOutputStream out = new DataOutputStream(socket.getOutputStream());
                out.writeUTF("Welcome");

                // perform coin-toss and come up with a session key to encrypt data
                Connection c = new Connection(socket);
                byte[] secret = c.diffieHellman(true).generateSecret();
                SecretKey sessionKey = new SecretKeySpec(Connection.fold(secret,128/8),"AES");
                c = c.encryptConnection(sessionKey,"AES/CFB8/NoPadding");

                try {
                    // HACK: TODO: move the transport support into modules
                    Class<?> cls = Jenkins.getInstance().pluginManager.uberClassLoader.loadClass("org.jenkinsci.main.modules.instance_identity.InstanceIdentity");
                    Object iid = cls.getDeclaredMethod("get").invoke(null);
                    PrivateKey instanceId = (PrivateKey)cls.getDeclaredMethod("getPrivate").invoke(iid);

                    // send a signature to prove our identity
                    Signature signer = Signature.getInstance("SHA1withRSA");
                    signer.initSign(instanceId);
                    signer.update(secret);
                    c.writeByteArray(signer.sign());
                } catch (ClassNotFoundException e) {
                    throw new Error(e);
                } catch (IllegalAccessException e) {
                    throw new Error(e);
                } catch (InvocationTargetException e) {
                    throw new Error(e);
                } catch (NoSuchMethodException e) {
                    throw new Error(e);
                }

                runCli(c);
            } catch (GeneralSecurityException e) {
                throw new IOException("Failed to encrypt the CLI channel",e);
            }
        }
    }
}


text:
import {NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {AppComponent} from './app.component';
import {RequestService} from './services/request.service';
import {HttpModule} from '@angular/http';
import {FormsModule} from '@angular/forms';
import {NgbModule} from '@ng-bootstrap/ng-bootstrap';
import {InputTagComponent} from "./input-tag.component";
import {InputWithTagsComponent} from "./input-with-tags.component";

@NgModule({
  imports: [BrowserModule, HttpModule, FormsModule, NgbModule.forRoot()],
  declarations: [AppComponent, InputWithTagsComponent, InputTagComponent],
  bootstrap: [AppComponent],
  providers: [RequestService],
  entryComponents: [InputTagComponent],
})
export class AppModule {
}


text:
package org.joda.beans.impl.light;

import java.util.NoSuchElementException;

import org.joda.beans.Bean;
import org.joda.beans.BeanBuilder;
import org.joda.beans.MetaProperty;

/**
 * Implementation of {@code BeanBuilder} that builds light beans.
 *
 * @param <B>  the bean type
 */
class LightBeanBuilder<B extends Bean>
        implements BeanBuilder<B> {

    /** The meta-bean. */
    private final LightMetaBean<B> metaBean;
    /** The data. */
    private final Object[] data;

    //-----------------------------------------------------------------------
    /**
     * Constructs the builder wrapping the target bean.
     *
     * @param metaBean  the target meta-bean, not null
     */
    LightBeanBuilder(LightMetaBean<B> metaBean, Object[] data) {
        this.metaBean = metaBean;
        this.data = data;
    }

    //-----------------------------------------------------------------------
    @Override
    public Object get(String propertyName) {
        return get(metaBean.metaProperty(propertyName));
    }

    @Override
    @SuppressWarnings("unchecked")
    public <P> P get(MetaProperty<P> metaProperty) {
        return (P) data[index(metaProperty)];
    }

    //-----------------------------------------------------------------------
    @Override
    public BeanBuilder<B> set(String propertyName, Object value) {
        return set(metaBean.metaProperty(propertyName), value);
    }

    @Override
    public BeanBuilder<B> set(MetaProperty<?> metaProperty, Object value) {
        data[index(metaProperty)] = value;
        return this;
    }

    @SuppressWarnings("deprecation")
    private int index(MetaProperty<?> metaProperty) {
        if (metaProperty instanceof LightMetaProperty) {
            int index = ((LightMetaProperty<?>) metaProperty).getConstructorIndex();
            if (index < 0) {
                throw new NoSuchElementException("Derived property cannot be set: " + metaProperty.name());
            }
            return index;
        }
        if (metaProperty instanceof AbstractLightMetaProperty) {
            try {
                int index = ((AbstractLightMetaProperty<?>) metaProperty).getConstructorIndex();
                if (index < 0) {
                    throw new NoSuchElementException("Derived property cannot be set: " + metaProperty.name());
                }
                return index;
            } catch (ClassCastException ex) {
                for (MetaProperty<?> mp : metaBean.metaPropertyIterable()) {
                    if (mp.equals(metaProperty)) {
                        return ((LightMetaProperty<?>) mp).getConstructorIndex();
                    }
                }
                throw new NoSuchElementException("Unknown property: " + metaProperty.name());
            }
        }
        return index(metaBean.metaProperty(metaProperty.name()));
    }

    //-----------------------------------------------------------------------
    @Override
    public B build() {
        return metaBean.build(data);
    }

    //-----------------------------------------------------------------------
    /**
     * Returns a string that summarises the builder.
     *
     * @return a summary string, not null
     */
    @Override
    public String toString() {
        return "BeanBuilder for " + metaBean.beanName();
    }

}


text:
<?php

namespace Zend\Tag\Cloud\Decorator\Exception;

use Zend\Tag\Exception\ExceptionInterface as Exception;

/**
 * Exception class for Zend_Tag_Cloud_Decorator
 */
interface ExceptionInterface extends Exception
{}


text:
//= require can.jquery-all
//= require models/cacheable

(function(can) {

  can.Model.Cacheable("CMS.Models.NotificationConfig", {
    root_object: "notification_config",
    root_collection: "notification_configs",
    category: "person",
    findAll: "GET /api/notification_configs",
    findOne: "GET /api/notification_configs/{id}",
    create: "POST /api/notification_configs",
    update: "PUT /api/notification_configs/{id}",
    destroy: "DELETE /api/notification_configs/{id}",
    active: "POST /api/set_active_notifications",

    findActive: function(){
      if(GGRC.current_user === null || GGRC.current_user === undefined){
        return $.when([]);
      }
      return this.findAll({person_id: GGRC.current_user.id});
    },
    setActive: function(active){
      var existing_types, all_types, valid_types;

      if(!GGRC.current_user){
        console.warn('User object is not set.');
        return $.when();
      }

      valid_types = $.map($('input[name=notifications]'), function(input){
        return input.value;
      });

      return this.findActive().then(function(configs){

        existing_types = $.map(configs, function(config){
          return config.notif_type;
        });
        all_types = $.map(valid_types, function(type){
          var index = existing_types.indexOf(type);
          if(index == -1){
            // Create a new notificationConfig if it doesn't exist yet
            return new CMS.Models.NotificationConfig({
              person_id: GGRC.current_user.id,
              notif_type: type,
              enable_flag: null,
              context: {id: null}
            });
          }
          return configs[index];
        });
        return $.when.apply($, $.map(all_types, function(config){
          var enabled = active.indexOf(config.notif_type) != -1;
          if(config.attr('enable_flag') === enabled){
            // There was no change to this config object
            return;
          }
          if(!config.id){
            // This is a new object so no need for refresh()
            config.attr('enable_flag', enabled);
            return config.save();
          }
          return config.refresh().then(function(refreshed_config){
            refreshed_config.attr('enable_flag', enabled);
            return refreshed_config.save();
          });
        }));
      });
    }
  }, {});

})(window.can);


text:
import React, { Component } from 'react';
import PropTypes from 'prop-types';

import './HomePage.css'
import logo from './logo.png';

class HomePage extends Component {
  render() {
    // Keep styles in JS
    const style = {
      text: {
        textAlign: 'center'
      },
      header: {
        height: '150px',
        padding: '20px',
        color: 'white',
        marginBottom: '20px'
      },
      logo: {
        animation: 'logo-spin infinite 20s linear',
        height: '80px'
      }
    }

    return (

Welcome to Rasowide

          <button onClick={this.props.onGoEditor}> Editor </button>

    );
  }
}

HomePage.propTypes = {
  onGoEditor: PropTypes.func.isRequired,
}

export default HomePage;


text:
module AnalyticsPusher
  module Helpers
    # Returns a meta tag with the request forgery protection token for forms to use. Put this in your head.
    def analytics_pusher_meta_tag
      meta_tags = ""
      meta_tags << %(<meta name="track-pageview" content="#{Rack::Utils.escape_html(@_pageview_to_track)}" />) if track_pageview?
      meta_tags << %(<meta name="track-event" content="#{Rack::Utils.escape_html(@_event_to_track)}" />) if track_event?
      meta_tags.html_safe
    end
  end
end


text: Playing around with TensorFlow


text:
<template name="blogIndex">

    {{#if blogAdmin}}
      <button>New</button>
    {{/if}}
    {{#each posts}}

{{title}}

        {{#if blogAdmin}}
          <button>Edit</button>
        {{/if}}

By: {{authorName}}

        <time itemprop="datePublished">{{publishedDateText}}</time>

{{description}}

    {{/each}}

</template>


text:
name: 💡 Feature request
about: Ideas for new features or improvements
---

:clipboard: **Description**

<!-- A clear and concise description of the new feature. -->

:microphone: **Motivation**

<!--
Please explain why this feature should be implemented and how it would be used.

- What is the specific use case?
-->

:bulb: **Alternatives**

<!--- Are there other ways the goal could be accomplished? -->


text:
using System;

namespace ZitaAsteria
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main(string[] args)
        {
            if (System.Diagnostics.Debugger.IsAttached)
            {
                using (ZAsteroidsGameClass game = new ZAsteroidsGameClass())
                {
                    game.Window.Title = "ZAsteroids";

                    game.Run();
                }
            }
            else
            try
            {
                using (ZAsteroidsGameClass game = new ZAsteroidsGameClass())
                {
                    game.Window.Title = "ZAsteroids";

                    game.Run();
                }
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(
                    "ZAsteroids 0.8 Error\r\n\r\n" +
                    "Message = " + ex.Message + "\r\n" +
                    "Stack trace = \r\n" + ex.StackTrace);
            }
        }
    }
}


text:
create table AWARD_SYNC_CHANGE (
  AWARD_SYNC_CHANGE_ID   NUMBER(22,0),
  AWARD_ID            NUMBER(22,0) NOT NULL,
  XML_CHANGES         CLOB,
  CLASS_NAME          VARCHAR2(100) NOT NULL,
  ATTRIBUTE_NAME      VARCHAR2(50),
  OBJECT_DESC         VARCHAR2(500),
  DATA_DESC	          VARCHAR2(500),
  SYNC_TYPE           CHAR(1) NOT NULL,
  SYNC_DESCEND    VARCHAR2(6),
  SYNC_FABRICATED_DESCEND CHAR(1) NOT NULL,
  SYNC_COST_SHARE_DESCEND CHAR(1) NOT NULL,
  UPDATE_TIMESTAMP    DATE NOT NULL,
  UPDATE_USER         VARCHAR2(60) NOT NULL,
  VER_NBR             NUMBER(8,0) NOT NULL,
  OBJ_ID              VARCHAR2(36) NOT NULL
);

ALTER TABLE AWARD_SYNC_CHANGE
	ADD CONSTRAINT PK_AWARD_SYNC_CHANGE
		PRIMARY KEY (AWARD_SYNC_CHANGE_ID);


text:
config package
==============

Submodules
----------

.. automodule:: config.cli
    :members:
    :undoc-members:
    :show-inheritance:

.. automodule:: config.configure
    :members:
    :undoc-members:
    :show-inheritance:

.. automodule:: config.manager
    :members:
    :undoc-members:
    :show-inheritance:

Module contents
---------------

.. automodule:: config
    :members:
    :undoc-members:
    :show-inheritance:


text: Small HeaderApproved


text:
{
"Edition Styles" : "Edition Styles",
"New Edition Class" : "New Edition Class",
"Load Stylesheet" : "Last Stilark",
"Delete Classes" : "Slett Classes",
"Import stylesheet (located in /css) WARNING: This will clear anything in the Edition Styles panel and cannot be undone!" : "Import stilark (ligger i / css) ADVARSEL: Dette vil fjerne noe i Edition Styles panelet og kan ikke omgjøres!",
"Nothing is selected for deletion." : "Ingenting er valgt for sletting.",
"Are you sure you want to permanently DELETE the following class(es)?" : "Er du sikker på at du vil slette følgende klassen (e)?",
"This will also delete ALL compound or multiple selectors that use this class!\nTHIS CANNOT BE UNDONE" : "Dette vil også slette ALLE sammensatte eller flere velgere som bruker denne klassen! \ NDette kan ikke angres",
"Missing Class Name" : "Missing Klasse Navn",
"#ID declarations not supported" : "#ID Erklæringer støttes ikke",
"Parent-Child declarations are preserved, but are also split with any new declarations added to list so they can be applied individually." : "Foreldre-barn erklæringer er bevart, men er også delt med noen nye erklæringer lagt til listen, slik at de kan brukes individuelt.",
"Nested Rules found but cannot be imported." : "Nestede Regler funnet, men kan ikke importeres.",
"Rules inside @media blocks were not imported." : "Reglene innemedia blokker ble ikke importert.",
"Compound selectors found, only importing the first selector from each" : "Sammensatte velgere funnet, bare importere den første velgeren fra hver"
};