text:
import xpidl
import header
import sys
import os
import string

# === Utils

def warn(msg):
    sys.stderr.write(msg + '\n')

def makeQuote(filename):
    return filename.replace(' ', '\\ ')  # enjoy!

# === Types

def isVoidType(type):
    """ Return True if the given xpidl type is void. """
    return type.kind == 'builtin' and type.name == 'void'

def isStringType(t):
    t = xpidl.unaliasType(t)
    return t.kind == 'native' and (t.specialtype == 'astring' or t.specialtype == 'domstring');

def isInterfaceType(t):
    t = xpidl.unaliasType(t)
    assert t.kind in ('builtin', 'native', 'interface', 'forward')
    return t.kind in ('interface', 'forward')

def isSpecificInterfaceType(t, name):
    """ True if `t` is an interface type with the given name, or a forward
    declaration or typedef aliasing it.

    `name` must not be the name of a typedef but the actual name of the
    interface.
    """
    t = xpidl.unaliasType(t)
    return t.kind in ('interface', 'forward') and t.name == name

def isVariantType(t):
    return isSpecificInterfaceType(t, 'nsIVariant')

# === Reading the file

class UserError(Exception):
    pass

def findIDL(includePath, irregularFilenames, interfaceName):
    filename = irregularFilenames.get(interfaceName, interfaceName) + '.idl'
    for d in includePath:
        # Not os.path.join: we need a forward slash even on Windows because
        # this filename ends up in makedepend output.
        path = d + '/' + filename
        if os.path.exists(path):
            return path
    raise UserError("No IDL file found for interface %s "
                    "in include path %r"
                    % (interfaceName, includePath))

# === Generating code

argumentUnboxingTemplates = {
    'octet':
        "    uint32_t ${name}_u32;\n"
        "    if (!JS_ValueToECMAUint32(cx, ${argVal}, &${name}_u32))\n"
        "        return JS_FALSE;\n"
        "    uint8_t ${name} = uint8_t(${name}_u32);\n",

    'short':
        "    int32_t ${name}_i32;\n"
        "    if (!JS_ValueToECMAInt32(cx, ${argVal}, &${name}_i32))\n"
        "        return JS_FALSE;\n"
        "    int16_t ${name} = int16_t(${name}_i32);\n",

    'unsigned short':
        "    uint32_t ${name}_u32;\n"
        "    if (!JS_ValueToECMAUint32(cx, ${argVal}, &${name}_u32))\n"
        "        return JS_FALSE;\n"
        "    uint16_t ${name} = uint16_t(${name}_u32);\n",

    'long':
        "    int32_t ${name};\n"
        "    if (!JS_ValueToECMAInt32(cx, ${argVal}, &${name}))\n"
        "        return JS_FALSE;\n",

    'unsigned long':
        "    uint32_t ${name};\n"
        "    if (!JS_ValueToECMAUint32(cx, ${argVal}, &${name}))\n"
        "        return JS_FALSE;\n",

    'long long':
        "    int64_t ${name};\n"
        "    if (!JS::ToInt64(cx, ${argVal}, &${name}))\n"
        "        return JS_FALSE;\n",

    'unsigned long long':
        "    uint64_t ${name};\n"
        "    if (!JS::ToUint64(cx, ${argVal}, &${name}))\n"
        "        return JS_FALSE;\n",

    'float':
        "    double ${name}_dbl;\n"
        "    if (!JS_ValueToNumber(cx, ${argVal}, &${name}_dbl))\n"
        "        return JS_FALSE;\n"
        "    float ${name} = (float) ${name}_dbl;\n",

    'double':
        "    double ${name};\n"
        "    if (!JS_ValueToNumber(cx, ${argVal}, &${name}))\n"
        "        return JS_FALSE;\n",

    'boolean':
        "    bool ${name};\n"
        "    JS_ValueToBoolean(cx, ${argVal}, &${name});\n",

    '[astring]':
        "    xpc_qsAString ${name}(cx, ${argVal}, ${argPtr});\n"
        "    if (!${name}.IsValid())\n"
        "        return JS_FALSE;\n",

    '[domstring]':
        "    xpc_qsDOMString ${name}(cx, ${argVal}, ${argPtr}, "
        "xpc_qsDOMString::e${nullBehavior}, "
        "xpc_qsDOMString::e${undefinedBehavior});\n"
        "    if (!${name}.IsValid())\n"
        "        return JS_FALSE;\n",

    'string':
        "    JSAutoByteString ${name}_bytes;\n"
        "    if (!xpc_qsJsvalToCharStr(cx, ${argVal}, &${name}_bytes))\n"
        "        return JS_FALSE;\n"
        "    char *${name} = ${name}_bytes.ptr();\n",

    'wstring':
        "    const PRUnichar *${name};\n"
        "    if (!xpc_qsJsvalToWcharStr(cx, ${argVal}, ${argPtr}, &${name}))\n"
        "        return JS_FALSE;\n",

    '[cstring]':
        "    xpc_qsACString ${name}(cx, ${argVal}, ${argPtr});\n"
        "    if (!${name}.IsValid())\n"
        "        return JS_FALSE;\n",

    '[utf8string]':
        "    xpc_qsAUTF8String ${name}(cx, ${argVal}, ${argPtr});\n"
        "    if (!${name}.IsValid())\n"
        "        return JS_FALSE;\n",

    '[jsval]':
        "    jsval ${name} = ${argVal};\n"
    }

# From JSData2Native.
#
# Omitted optional arguments are treated as though the caller had passed JS
# `null`; this behavior is from XPCWrappedNative::CallMethod. The 'jsval' type,
# however, defaults to 'undefined'.
#
def writeArgumentUnboxing(f, i, name, type, optional, rvdeclared,
                          nullBehavior, undefinedBehavior):
    # f - file to write to
    # i - int or None - Indicates the source jsval.  If i is an int, the source
    #     jsval is argv[i]; otherwise it is *vp.  But if Python i >= C++ argc,
    #     which can only happen if optional is True, the argument is missing;
    #     use JSVAL_NULL as the source jsval instead.
    # name - str - name of the native C++ variable to create.
    # type - xpidl.{Interface,Native,Builtin} - IDL type of argument
    # optional - bool - True if the parameter is optional.
    # rvdeclared - bool - False if no |nsresult rv| has been declared earlier.

    typeName = xpidl.getBuiltinOrNativeTypeName(type)

    isSetter = (i is None)

    if isSetter:
        argPtr = "vp"
        argVal = "*vp"
    elif optional:
        if typeName == "[jsval]":
            val = "JSVAL_VOID"
        else:
            val = "JSVAL_NULL"
        argVal = "(%d < argc ? argv[%d] : %s)" % (i, i, val)
        argPtr = "(%d < argc ? &argv[%d] : NULL)" % (i, i)
    else:
        argVal = "argv[%d]" % i
        argPtr = "&" + argVal

    params = {
        'name': name,
        'argVal': argVal,
        'argPtr': argPtr,
        'nullBehavior': nullBehavior or 'DefaultNullBehavior',
        'undefinedBehavior': undefinedBehavior or 'DefaultUndefinedBehavior'
        }

    if typeName is not None:
        template = argumentUnboxingTemplates.get(typeName)
        if template is not None:
            f.write(string.Template(template).substitute(params))
            return rvdeclared
        # else fall through; the type isn't supported yet.
    elif isInterfaceType(type):
        if type.name == 'nsIVariant':
            # Totally custom.
            template = (
                "    nsCOMPtr<nsIVariant> ${name}(already_AddRefed<nsIVariant>("
                "XPCVariant::newVariant(cx, ${argVal})));\n"
                "    if (!${name}) {\n"
                "        xpc_qsThrowBadArg(cx, NS_ERROR_INVALID_ARG, vp, %d);\n"
                "        return JS_FALSE;\n"
                "    }\n") % i
            f.write(string.Template(template).substitute(params))
            return rvdeclared
        elif type.name == 'nsIAtom':
            # Should have special atomizing behavior.  Fall through.
            pass
        else:
            if not rvdeclared:
                f.write("    nsresult rv;\n");
            f.write("    %s *%s;\n" % (type.name, name))
            f.write("    xpc_qsSelfRef %sref;\n" % name)
            f.write("    rv = xpc_qsUnwrapArg<%s>("
                    "cx, %s, &%s, &%sref.ptr, %s);\n"
                    % (type.name, argVal, name, name, argPtr))
            f.write("    if (NS_FAILED(rv)) {\n")
            if isSetter:
                f.write("        xpc_qsThrowBadSetterValue("
                        "cx, rv, JSVAL_TO_OBJECT(*tvr.jsval_addr()), id);\n")
            else:
                f.write("        xpc_qsThrowBadArgWithDetails(cx, rv, %d, %s, %s);\n" % (i, "\"\"", "\"\""))
            f.write("        return JS_FALSE;\n"
                    "    }\n")
            return True

    warn("Unable to unbox argument of type %s (native type %s)" % (type.name, typeName))
    if i is None:
        src = '*vp'
    else:
        src = 'argv[%d]' % i
    f.write("    !; // TODO - Unbox argument %s = %s\n" % (name, src))
    return rvdeclared

def writeResultDecl(f, member, varname):
    type = member.realtype

    if isVoidType(type):
        return  # nothing to declare

    t = xpidl.unaliasType(type)
    if t.kind == 'builtin':
        if not t.nativename.endswith('*'):
            if type.kind == 'typedef':
                typeName = type.name  # use it
            else:
                typeName = t.nativename
            f.write("    %s %s;\n" % (typeName, varname))
            return
    elif t.kind == 'native':
        name = xpidl.getBuiltinOrNativeTypeName(t)
        if name in ('[domstring]', '[astring]'):
            f.write("    nsString %s;\n" % varname)
            return
        elif name == '[jsval]':
            return  # nothing to declare; see special case in outParamForm
    elif t.kind in ('interface', 'forward'):
        if member.kind == 'method' and member.notxpcom:
            f.write("    %s *%s;\n" % (type.name, varname))
        else:
            f.write("    nsCOMPtr<%s> %s;\n" % (type.name, varname))
        return

    warn("Unable to declare result of type %s" % type.name)
    f.write("    !; // TODO - Declare out parameter `%s`.\n" % varname)

def outParamForm(name, type):
    type = xpidl.unaliasType(type)
    # If we start allowing [jsval] return types here, we need to tack
    # the return value onto the arguments list in the callers,
    # possibly, and handle properly returning it too.  See bug 604198.
    assert type.kind != 'native' or type.specialtype != 'jsval'
    if type.kind == 'builtin':
        return '&' + name
    elif type.kind == 'native':
        if type.specialtype == 'jsval':
            return 'vp'
        elif type.modifier == 'ref':
            if isStringType(type):
                return '(nsAString&)' + name
            return name
        else:
            return '&' + name
    else:
        return 'getter_AddRefs(%s)' % name

# From NativeData2JS.
resultConvTemplates = {
    'void':
            "    ${jsvalRef} = JSVAL_VOID;\n"
            "    return JS_TRUE;\n",

    'octet':
        "    ${jsvalRef} = INT_TO_JSVAL(int32_t(result));\n"
        "    return JS_TRUE;\n",

    'short':
        "    ${jsvalRef} = INT_TO_JSVAL(int32_t(result));\n"
        "    return JS_TRUE;\n",

    'long':
        "    ${jsvalRef} = INT_TO_JSVAL(result);\n"
        "    return JS_TRUE;\n",

    'long long':
        "    return xpc_qsInt64ToJsval(cx, result, ${jsvalPtr};\n",

    'unsigned short':
        "    ${jsvalRef} = INT_TO_JSVAL(int32_t(result));\n"
        "    return JS_TRUE;\n",

    'unsigned long':
        "    ${jsvalRef} = UINT_TO_JSVAL(result);\n"
        "    return JS_TRUE;\n",

    'unsigned long long':
        "    return xpc_qsUint64ToJsval(cx, result, ${jsvalPtr});\n",

    'float':
        "    ${jsvalRef} = JS_NumberValue(result);\n"
        "    return JS_TRUE;\n",

    'double':
        "    ${jsvalRef} = JS_NumberValue(result);\n"
        "    return JS_TRUE;\n",

    'boolean':
        "    ${jsvalRef} = (result ? JSVAL_TRUE : JSVAL_FALSE);\n"
        "    return JS_TRUE;\n",

    '[astring]':
        "    return xpc::StringToJsval(cx, result, ${jsvalPtr});\n",

    '[domstring]':
        "    return xpc::StringToJsval(cx, result, ${jsvalPtr});\n",

    '[jsval]':
        # Here there's nothing to convert, because the result has already been
        # written directly to *rv. See the special case in outParamForm.
        "    return JS_TRUE;\n"
    }

def writeResultConv(f, type, interfaceResultTemplate, jsvalPtr, jsvalRef):
    """ Emit code to convert the C++ variable `result` to a jsval.

    The emitted code contains a return statement; it returns JS_TRUE on
    success, JS_FALSE on error.
    """
    # From NativeData2JS.
    typeName = xpidl.getBuiltinOrNativeTypeName(type)
    if typeName is not None:
        template = resultConvTemplates.get(typeName)
    elif isInterfaceType(type):
        if isVariantType(type):
            template =  ("    XPCLazyCallContext lccx(JS_CALLER, cx, obj);\n"
                         "    return xpc_qsVariantToJsval(lccx, result, ${jsvalPtr});\n")
        else:
            template = ("    if (!result) {\n"
                        "      *${jsvalPtr} = JSVAL_NULL;\n"
                        "      return JS_TRUE;\n"
                        "    }\n")
            template += interfaceResultTemplate

    if template is not None:
        values = {'jsvalRef': jsvalRef,
                  'jsvalPtr': jsvalPtr,
                  'typeName': type.name}
        f.write(string.Template(template).substitute(values))
        return
    # else fall through; this type isn't supported yet

    warn("Unable to convert result of type %s" % type.name)
    f.write("    !; // TODO - Convert `result` to jsval, store in `%s`.\n"
            % jsvalRef)
    f.write("    return xpc_qsThrow(cx, NS_ERROR_UNEXPECTED); // FIXME\n")

def validateParam(member, param):
    def pfail(msg):
        raise UserError(
            member.iface.name + '.' + member.name + ": "
            "parameter " + param.name + ": " + msg)

    if param.iid_is is not None:
        pfail("iid_is parameters are not supported.")
    if param.size_is is not None:
        pfail("size_is parameters are not supported.")
    if param.retval:
        pfail("Unexpected retval parameter!")
    if param.paramtype in ('out', 'inout'):
        pfail("inout parameters are not supported.")
    if param.const or param.array or param.shared:
        pfail("I am a simple caveman.")

# returns the number of arguments that a method takes in JS (including optional arguments)
def argumentsLength(member):
    assert member.kind == 'method'

    inArgs = len(member.params)
    if inArgs and member.notxpcom and member.params[inArgs - 1].paramtype == 'out':
        if member.params[inArgs - 1].realtype.kind != 'native' or member.params[inArgs - 1].realtype.nativename != 'nsWrapperCache':
            pfail("We only support a wrapper cache as out argument")
        inArgs -= 1
    return inArgs

def writeStub(f, customMethodCalls, member, stubName, writeThisUnwrapping, writeCheckForFailure, writeResultWrapping, isSetter=False):
    """ Write a single quick stub (a custom SpiderMonkey getter/setter/method)
    for the specified XPCOM interface-member.
    """
    if member.kind == 'method' and member.forward:
        member = member.iface.namemap[member.forward]

    isAttr = (member.kind == 'attribute')
    isMethod = (member.kind == 'method')
    assert isAttr or isMethod
    isNotxpcom = isMethod and member.notxpcom
    isGetter = isAttr and not isSetter

    signature = "static JSBool\n"
    if isAttr:
        # JSPropertyOp signature.
        if isSetter:
            signature += "%s(JSContext *cx, JSHandleObject obj, JSHandleId id, JSBool strict,%s JSMutableHandleValue vp_)\n"
        else:
            signature += "%s(JSContext *cx, JSHandleObject obj, JSHandleId id,%s JSMutableHandleValue vp_)\n"
    else:
        # JSFastNative.
        signature += "%s(JSContext *cx, unsigned argc,%s jsval *vp)\n"

    customMethodCall = customMethodCalls.get(stubName, None)

    if customMethodCall is None:
        customMethodCall = customMethodCalls.get(member.iface.name + '_', None)
        if customMethodCall is not None:
            if isMethod:
                code = customMethodCall.get('code', None)
            elif isGetter:
                code = customMethodCall.get('getter_code', None)
            else:
                code = customMethodCall.get('setter_code', None)
        else:
            code = None

        if code is not None:
            templateName = member.iface.name
            if isGetter:
                templateName += '_Get'
            elif isSetter:
                templateName += '_Set'

            # Generate the code for the stub, calling the template function
            # that's shared between the stubs. The stubs can't have additional
            # arguments, only the template function can.
            callTemplate = signature % (stubName, '')
            callTemplate += "{\n"

            argumentValues = (customMethodCall['additionalArgumentValues']
                              % header.methodNativeName(member))
            if isAttr:
                callTemplate += ("    return %s(cx, obj, id%s, %s, vp_);\n"
                                 % (templateName, ", strict" if isSetter else "", argumentValues))
            else:
                callTemplate += ("    return %s(cx, argc, %s, vp);\n"
                                 % (templateName, argumentValues))
            callTemplate += "}\n\n"

            # Fall through and create the template function stub called from the
            # real stubs, but only generate the stub once. Otherwise, just write
            # out the call to the template function and return.
            templateGenerated = templateName + '_generated'
            if templateGenerated in customMethodCall:
                f.write(callTemplate)
                return
            customMethodCall[templateGenerated] = True

            stubName = templateName
        else:
            callTemplate = ""
    else:
        callTemplate = ""
        code = customMethodCall.get('code', None)

    # Function prolog.

    # Only template functions can have additional arguments.
    if customMethodCall is None or not 'additionalArguments' in customMethodCall:
        additionalArguments = ''
    else:
        additionalArguments = " %s," % customMethodCall['additionalArguments']
    f.write(signature % (stubName, additionalArguments))
    f.write("{\n")
    f.write("    XPC_QS_ASSERT_CONTEXT_OK(cx);\n")

    # Convert JSMutableHandleValue to jsval*
    if isAttr:
        f.write("    jsval *vp = vp_.address();\n")

    # For methods, compute "this".
    if isMethod:
        f.write("    JSObject *obj = JS_THIS_OBJECT(cx, vp);\n"
                "    if (!obj)\n"
                "        return JS_FALSE;\n")

    selfname = writeThisUnwrapping(f, member, isMethod, isGetter, customMethodCall)

    rvdeclared = False
    if isMethod:
        inArgs = argumentsLength(member)
        # If there are any required arguments, check argc.
        requiredArgs = inArgs
        while requiredArgs and member.params[requiredArgs-1].optional:
            requiredArgs -= 1
        if requiredArgs:
            f.write("    if (argc < %d)\n" % requiredArgs)
            f.write("        return xpc_qsThrow(cx, "
                    "NS_ERROR_XPC_NOT_ENOUGH_ARGS);\n")

        # Convert in-parameters.
        if inArgs > 0:
            f.write("    jsval *argv = JS_ARGV(cx, vp);\n")
        for i in range(inArgs):
            param = member.params[i]
            argName = 'arg%d' % i
            argTypeKey = argName + 'Type'
            if customMethodCall is None or not argTypeKey in customMethodCall:
                validateParam(member, param)
                realtype = param.realtype
            else:
                realtype = xpidl.Forward(name=customMethodCall[argTypeKey],
                                         location='', doccomments='')
            # Emit code to convert this argument from jsval.
            rvdeclared = writeArgumentUnboxing(
                f, i, argName, realtype,
                optional=param.optional,
                rvdeclared=rvdeclared,
                nullBehavior=param.null,
                undefinedBehavior=param.undefined)
        if inArgs < len(member.params):
            f.write("    nsWrapperCache *cache;\n")
    elif isSetter:
        rvdeclared = writeArgumentUnboxing(f, None, 'arg0', member.realtype,
                                           optional=False,
                                           rvdeclared=rvdeclared,
                                           nullBehavior=member.null,
                                           undefinedBehavior=member.undefined)

    canFail = not isNotxpcom and (customMethodCall is None or customMethodCall.get('canFail', True))
    if canFail and not rvdeclared:
        f.write("    nsresult rv;\n")
        rvdeclared = True

    if code is not None:
        f.write("%s\n" % code)

    if code is None or (isGetter and callTemplate is ""):
        debugGetter = code is not None
        if debugGetter:
            f.write("#ifdef DEBUG\n")
            f.write("    nsresult debug_rv;\n")
            f.write("    nsCOMPtr<%s> debug_self;\n"
                    "    CallQueryInterface(self, getter_AddRefs(debug_self));\n"
                    % member.iface.name);
            prefix = 'debug_'
        else:
            prefix = ''

        resultname = prefix + 'result'
        selfname = prefix + selfname
        nsresultname = prefix + 'rv'

        # Prepare out-parameter.
        if isMethod or isGetter:
            writeResultDecl(f, member, resultname)

        # Call the method.
        if isMethod:
            comName = header.methodNativeName(member)
            argv = ['arg' + str(i) for i in range(inArgs)]
            if inArgs < len(member.params):
                argv.append(outParamForm('cache', member.params[inArgs].realtype))
            if member.implicit_jscontext:
                argv.append('cx')
            if member.optional_argc:
                argv.append('argc - %d' % requiredArgs)
            if not isNotxpcom and not isVoidType(member.realtype):
                argv.append(outParamForm(resultname, member.realtype))
            args = ', '.join(argv)
        else:
            comName = header.attributeNativeName(member, isGetter)
            if isGetter:
                args = outParamForm(resultname, member.realtype)
            else:
                args = "arg0"
            if member.implicit_jscontext:
                args = "cx, " + args

        f.write("    ")
        if canFail or debugGetter:
            f.write("%s = " % nsresultname)
        elif isNotxpcom:
            f.write("%s = " % resultname)
        f.write("%s->%s(%s);\n" % (selfname, comName, args))

        if debugGetter:
            checkSuccess = "NS_SUCCEEDED(debug_rv)"
            if canFail:
                checkSuccess += " == NS_SUCCEEDED(rv)"
            f.write("    NS_ASSERTION(%s && "
                    "xpc_qsSameResult(debug_result, result),\n"
                    "                 \"Got the wrong answer from the custom "
                    "method call!\");\n" % checkSuccess)
            f.write("#endif\n")

    if canFail:
        # Check for errors.
        writeCheckForFailure(f, isMethod, isGetter)

    # Convert the return value.
    if isMethod or isGetter:
        writeResultWrapping(f, member, 'vp', '*vp')
    else:
        f.write("    return JS_TRUE;\n")

    # Epilog.
    f.write("}\n\n")

    # Now write out the call to the template function.
    if customMethodCall is not None:
        f.write(callTemplate)

redpajama_set_name: RedPajamaGithub


text:
package hue

import (
	"bytes"
	"encoding/json"
)

type client struct {
	conn server
}

func NewHTTPClient(addr string) *client {
	return &client{conn: &httpServer{addr: addr}}
}

func (c *client) Get(uri string, responseObj interface{}) error {
	resultBytes, err := c.conn.Do("GET", uri, nil)
	if err != nil {
		return err
	}

	err = decode(resultBytes, responseObj)
	if err != nil {
		_, errors, err := decodeAPIResult(resultBytes)
		if err != nil {
			return err
		}
		return &APIError{errors}
	}

	return nil
}

func (c *client) Post(uri string, requestObj interface{}) ([]APISuccessDetail, error) {
	return c.Send("POST", uri, requestObj)
}

func (c *client) Put(uri string, requestObj interface{}) ([]APISuccessDetail, error) {
	return c.Send("PUT", uri, requestObj)
}

func (c *client) Send(method string, uri string, requestObj interface{}) ([]APISuccessDetail, error) {
	requestBytes, err := encode(requestObj)
	if err != nil {
		return nil, err
	}

	resultBytes, err := c.conn.Do(method, uri, requestBytes)
	if err != nil {
		return nil, err
	}

	successes, errors, err := decodeAPIResult(resultBytes)
	if err != nil {
		return nil, err
	}
	if len(errors) != 0 {
		return successes, &APIError{errors}
	}

	return successes, nil
}

func decodeAPIResult(resultBytes []byte) ([]APISuccessDetail, []APIErrorDetail, error) {
	// Decode api result
	var responseObj []*APIResult
	err := decode(resultBytes, &responseObj)
	if err != nil {
		return nil, nil, err
	}

	// Create slice of successes and errors
	successes := make([]APISuccessDetail, 0, 5)
	errors := make([]APIErrorDetail, 0, 5)
	for _, result := range responseObj {
		if result.Success != nil {
			successes = append(successes, *result.Success)
		}
		if result.Error != nil {
			errors = append(errors, *result.Error)
		}
	}

	// Set slice to nil if empty
	if len(successes) == 0 {
		successes = nil
	}
	if len(errors) == 0 {
		errors = nil
	}

	return successes, errors, nil
}

func encode(requestObj interface{}) ([]byte, error) {
	var requestBytes []byte
	var err error

	if requestObj != nil {
		requestBytes, err = json.Marshal(requestObj)
		if err != nil {
			return nil, err
		}
	}

	return requestBytes, nil
}

func decode(resultBytes []byte, responseObj interface{}) error {
	decoder := json.NewDecoder(bytes.NewReader(resultBytes))
	return decoder.Decode(responseObj)
}

func decodeAPIError(resultBytes []byte) error {
	// Parse the error response
	var apiErrorDetails []map[string]*APIErrorDetail
	err := decode(resultBytes, &apiErrorDetails)
	if err != nil {
		return err
	}

	// Build APIError structure with slice of errors
	apiError := &APIError{}
	apiError.Errors = make([]APIErrorDetail, 0, 1)
	for _, apiErrorDetail := range apiErrorDetails {
		apiError.Errors = append(apiError.Errors, *apiErrorDetail["error"])
	}

	return apiError
}

type APIResult struct {
	Success *APISuccessDetail `json:"success"`
	Error   *APIErrorDetail   `json:"error"`
}

type APISuccessDetail map[string]interface{}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright (C) 2012 Google Inc.

Licensed under the Apache License, Version 2.0 (the "License"); you may not
use this file except in compliance with the License. You may obtain a copy of
the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under
the License.
 -->
<scr:component xmlns:scr="http://www.osgi.org/xmlns/scr/v1.1.0"
    name="org.ros.zeroconf.node"
    immediate="true"
    activate="startup" deactivate="shutdown">
  <implementation class="org.ros.zeroconf.node.internal.NodeZeroconfImpl"/>

  <service>
    <provide interface="org.ros.zeroconf.node.NodeZeroconf"/>
  </service>

  <reference interface="org.ros.osgi.common.RosEnvironment"
     name="rosEnvironment" bind="setRosEnvironment" unbind="unsetRosEnvironment" cardinality="1..1"
        policy="dynamic"/>

  <reference interface="org.ros.zeroconf.common.RosZeroconf"
     name="rosZeroconf" bind="setRosZeroconf" unbind="unsetRosZeroconf" cardinality="1..1"
        policy="dynamic" />

  <reference interface="org.ros.master.uri.SwitchableMasterUriProvider"
     name="masterUriProvider" bind="setMasterUriProvider" unbind="unsetMasterUriProvider" cardinality="0..1"
        policy="dynamic" />
</scr:component>


text:
package org.sterl.training.spring.config.client;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.authentication.configurers.provisioning.InMemoryUserDetailsManagerConfigurer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import lombok.Data;

@EnableWebSecurity
@Configuration
public class SpringBootSecurityConfig extends WebSecurityConfigurerAdapter {
    @Value("${clients}") String clients;
    @Autowired ObjectMapper objectMapper;

    final TypeReference<HashMap<String,UserData>> TYPE = new TypeReference<>() {};

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        final HashMap<String, UserData> users = objectMapper.readValue(clients, TYPE);
        final InMemoryUserDetailsManagerConfigurer<AuthenticationManagerBuilder> authz = auth.inMemoryAuthentication();

        users.entrySet().forEach(e -> authz.withUser(e.getKey()).password(e.getValue().getPassword()).roles(e.getValue().arrayRoles()));
    }

    /** TODO update users, e.g. as soon the refresh event occurs
    @EventListener(RefreshScopeRefreshedEvent.class)
    public void onRefresh(RefreshScopeRefreshedEvent event) {
    }
    */

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf()
            .disable()
            .httpBasic()
         .and()
            .authorizeRequests()
            .antMatchers("/**").authenticated()
        ;
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Data
    static class UserData {
        private static final String[] EMPTY = {};
        private String password;
        private Set<String> roles = new HashSet<>();

        String[] arrayRoles() {
            if (roles == null || roles.isEmpty()) return EMPTY;
            else return roles.toArray(new String[roles.size()]);
        }
    }
}


text:
package org.jetbrains.buildserver.achievements.controller;

import jetbrains.buildServer.users.SUser;
import jetbrains.buildServer.web.openapi.PagePlaces;
import jetbrains.buildServer.web.openapi.PlaceId;
import jetbrains.buildServer.web.openapi.PluginDescriptor;
import jetbrains.buildServer.web.openapi.SimpleCustomTab;
import jetbrains.buildServer.web.util.SessionUser;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.buildserver.achievements.impl.Achievement;
import org.jetbrains.buildserver.achievements.AchievementsConfig;
import org.jetbrains.buildserver.achievements.impl.AchievementsGrantor;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

public class MyAchievementsTab extends SimpleCustomTab {
  private static final String TAB_TITLE = "My Achievements";
  private final AchievementsGrantor myAchievementsGrantor;
  private final AchievementsConfig myAchievementsConfig;

  public MyAchievementsTab(@NotNull PagePlaces pagePlaces, @NotNull PluginDescriptor pluginDescriptor, @NotNull AchievementsGrantor achievementsGrantor, @NotNull AchievementsConfig achievementsConfig) {
    super(pagePlaces);
    setPluginName(pluginDescriptor.getPluginName());
    setPlaceId(PlaceId.MY_TOOLS_TABS);
    setIncludeUrl(pluginDescriptor.getPluginResourcesPath("/myAchievements.jsp"));
    setTabTitle(TAB_TITLE);
    register();

    myAchievementsConfig = achievementsConfig;
    myAchievementsGrantor = achievementsGrantor;
  }

  @NotNull
  @Override
  public String getTabTitle(@NotNull HttpServletRequest request) {
    final SUser user = SessionUser.getUser(request);
    List<Achievement> granted = myAchievementsGrantor.getGrantedAchievements(user);
    return TAB_TITLE + (granted.isEmpty() ? "" : "" + granted.size() + "");
  }

  @Override
  public void fillModel(@NotNull Map<String, Object> model, @NotNull HttpServletRequest request) {
    super.fillModel(model, request);
    final SUser user = SessionUser.getUser(request);

    List<Achievement> granted = myAchievementsGrantor.getGrantedAchievements(user);

    List<Achievement> available = new ArrayList<Achievement>();
    available.addAll(myAchievementsConfig.getAchievements());
    available.removeAll(granted);

    model.put("grantedAchievements", granted);
    model.put("availableAchievements", available);
    model.put("allAchievementsMap", myAchievementsGrantor.getAchievementUsersMap());
    model.put("achievementsEnabled", myAchievementsGrantor.isEnabled(user));
  }
}


text:
using base::TimeDelta;
using content::DownloadItem;

namespace {

// Per DownloadItem data used by DownloadItemModel. The model doesn't keep any
// state since there could be multiple models associated with a single
// DownloadItem, and the lifetime of the model is shorter than the DownloadItem.
class DownloadItemModelData : public base::SupportsUserData::Data {
 public:
  // Get the DownloadItemModelData object for |download|. Returns NULL if
  // there's no model data.
  static const DownloadItemModelData* Get(const DownloadItem* download);

  // Get the DownloadItemModelData object for |download|. Creates a model data
  // object if not found. Always returns a non-NULL pointer, unless OOM.
  static DownloadItemModelData* GetOrCreate(DownloadItem* download);

  bool should_show_in_shelf() const { return should_show_in_shelf_; }
  void set_should_show_in_shelf(bool should_show_in_shelf) {
    should_show_in_shelf_ = should_show_in_shelf;
  }

  bool should_notify_ui() const { return should_notify_ui_; }
  void set_should_notify_ui(bool should_notify_ui) {
    should_notify_ui_ = should_notify_ui;
  }

  bool should_prefer_opening_in_browser() const {
    return should_prefer_opening_in_browser_;
  }
  void set_should_prefer_opening_in_browser(bool preference) {
    should_prefer_opening_in_browser_ = preference;
  }

 private:
  DownloadItemModelData();
  virtual ~DownloadItemModelData() {}

  static const char kKey[];

  // Whether the download should be displayed in the download shelf. True by
  // default.
  bool should_show_in_shelf_;

  // Whether the UI should be notified when the download is ready to be
  // presented.
  bool should_notify_ui_;

  // Whether the download should be opened in the browser vs. the system handler
  // for the file type.
  bool should_prefer_opening_in_browser_;
};

// static
const char DownloadItemModelData::kKey[] = "DownloadItemModelData key";

// static
const DownloadItemModelData* DownloadItemModelData::Get(
    const DownloadItem* download) {
  return static_cast<const DownloadItemModelData*>(download->GetUserData(kKey));
}

// static
DownloadItemModelData* DownloadItemModelData::GetOrCreate(
    DownloadItem* download) {
  DownloadItemModelData* data =
      static_cast<DownloadItemModelData*>(download->GetUserData(kKey));
  if (data == NULL) {
    data = new DownloadItemModelData();
    download->SetUserData(kKey, data);
  }
  return data;
}

DownloadItemModelData::DownloadItemModelData()
    : should_show_in_shelf_(true),
      should_notify_ui_(false),
      should_prefer_opening_in_browser_(false) {
}

base::string16 InterruptReasonStatusMessage(int reason) {
  int string_id = IDS_DOWNLOAD_INTERRUPTED_STATUS;

  switch (static_cast<content::DownloadInterruptReason>(reason)) {
    case content::DOWNLOAD_INTERRUPT_REASON_FILE_ACCESS_DENIED:
      string_id = IDS_DOWNLOAD_INTERRUPTED_STATUS_ACCESS_DENIED;
      break;
    case content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE:
      string_id = IDS_DOWNLOAD_INTERRUPTED_STATUS_DISK_FULL;
      break;
    case content::DOWNLOAD_INTERRUPT_REASON_FILE_NAME_TOO_LONG:
      string_id = IDS_DOWNLOAD_INTERRUPTED_STATUS_PATH_TOO_LONG;
      break;
    case content::DOWNLOAD_INTERRUPT_REASON_FILE_TOO_LARGE:
      string_id = IDS_DOWNLOAD_INTERRUPTED_STATUS_FILE_TOO_LARGE;
      break;
    case content::DOWNLOAD_INTERRUPT_REASON_FILE_VIRUS_INFECTED:
      string_id = IDS_DOWNLOAD_INTERRUPTED_STATUS_VIRUS;
      break;
    case content::DOWNLOAD_INTERRUPT_REASON_FILE_TRANSIENT_ERROR:
      string_id = IDS_DOWNLOAD_INTERRUPTED_STATUS_TEMPORARY_PROBLEM;
      break;
    case content::DOWNLOAD_INTERRUPT_REASON_FILE_BLOCKED:
      string_id = IDS_DOWNLOAD_INTERRUPTED_STATUS_BLOCKED;
      break;
    case content::DOWNLOAD_INTERRUPT_REASON_FILE_SECURITY_CHECK_FAILED:
      string_id = IDS_DOWNLOAD_INTERRUPTED_STATUS_SECURITY_CHECK_FAILED;
      break;
    case content::DOWNLOAD_INTERRUPT_REASON_FILE_TOO_SHORT:
      string_id = IDS_DOWNLOAD_INTERRUPTED_STATUS_FILE_TOO_SHORT;
      break;
    case content::DOWNLOAD_INTERRUPT_REASON_NETWORK_INVALID_REQUEST:
    case content::DOWNLOAD_INTERRUPT_REASON_NETWORK_FAILED:
      string_id = IDS_DOWNLOAD_INTERRUPTED_STATUS_NETWORK_ERROR;
      break;
    case content::DOWNLOAD_INTERRUPT_REASON_NETWORK_TIMEOUT:
      string_id = IDS_DOWNLOAD_INTERRUPTED_STATUS_NETWORK_TIMEOUT;
      break;
    case content::DOWNLOAD_INTERRUPT_REASON_NETWORK_DISCONNECTED:
      string_id = IDS_DOWNLOAD_INTERRUPTED_STATUS_NETWORK_DISCONNECTED;
      break;
    case content::DOWNLOAD_INTERRUPT_REASON_NETWORK_SERVER_DOWN:
      string_id = IDS_DOWNLOAD_INTERRUPTED_STATUS_SERVER_DOWN;
      break;
    case content::DOWNLOAD_INTERRUPT_REASON_SERVER_FAILED:
      string_id = IDS_DOWNLOAD_INTERRUPTED_STATUS_SERVER_PROBLEM;
      break;
    case content::DOWNLOAD_INTERRUPT_REASON_SERVER_BAD_CONTENT:
      string_id = IDS_DOWNLOAD_INTERRUPTED_STATUS_NO_FILE;
      break;
    case content::DOWNLOAD_INTERRUPT_REASON_USER_CANCELED:
      string_id = IDS_DOWNLOAD_STATUS_CANCELLED;
      break;
    case content::DOWNLOAD_INTERRUPT_REASON_USER_SHUTDOWN:
      string_id = IDS_DOWNLOAD_INTERRUPTED_STATUS_SHUTDOWN;
      break;
    case content::DOWNLOAD_INTERRUPT_REASON_CRASH:
      string_id = IDS_DOWNLOAD_INTERRUPTED_STATUS_CRASH;
      break;
    case content::DOWNLOAD_INTERRUPT_REASON_NONE:
      NOTREACHED();
      // fallthrough
    case content::DOWNLOAD_INTERRUPT_REASON_SERVER_NO_RANGE:
    case content::DOWNLOAD_INTERRUPT_REASON_SERVER_PRECONDITION:
    case content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED:
      string_id = IDS_DOWNLOAD_INTERRUPTED_STATUS;
  }

  return l10n_util::GetStringUTF16(string_id);
}

base::string16 InterruptReasonMessage(int reason) {
  int string_id = IDS_DOWNLOAD_INTERRUPTED_STATUS;
  base::string16 status_text;

  switch (static_cast<content::DownloadInterruptReason>(reason)) {
    case content::DOWNLOAD_INTERRUPT_REASON_FILE_ACCESS_DENIED:
      string_id = IDS_DOWNLOAD_INTERRUPTED_DESCRIPTION_ACCESS_DENIED;
      break;
    case content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE:
      string_id = IDS_DOWNLOAD_INTERRUPTED_DESCRIPTION_DISK_FULL;
      break;
    case content::DOWNLOAD_INTERRUPT_REASON_FILE_NAME_TOO_LONG:
      string_id = IDS_DOWNLOAD_INTERRUPTED_DESCRIPTION_PATH_TOO_LONG;
      break;
    case content::DOWNLOAD_INTERRUPT_REASON_FILE_TOO_LARGE:
      string_id = IDS_DOWNLOAD_INTERRUPTED_DESCRIPTION_FILE_TOO_LARGE;
      break;
    case content::DOWNLOAD_INTERRUPT_REASON_FILE_VIRUS_INFECTED:
      string_id = IDS_DOWNLOAD_INTERRUPTED_DESCRIPTION_VIRUS;
      break;
    case content::DOWNLOAD_INTERRUPT_REASON_FILE_TRANSIENT_ERROR:
      string_id = IDS_DOWNLOAD_INTERRUPTED_DESCRIPTION_TEMPORARY_PROBLEM;
      break;
    case content::DOWNLOAD_INTERRUPT_REASON_FILE_BLOCKED:
      string_id = IDS_DOWNLOAD_INTERRUPTED_DESCRIPTION_BLOCKED;
      break;
    case content::DOWNLOAD_INTERRUPT_REASON_FILE_SECURITY_CHECK_FAILED:
      string_id = IDS_DOWNLOAD_INTERRUPTED_DESCRIPTION_SECURITY_CHECK_FAILED;
      break;
    case content::DOWNLOAD_INTERRUPT_REASON_FILE_TOO_SHORT:
      string_id = IDS_DOWNLOAD_INTERRUPTED_DESCRIPTION_FILE_TOO_SHORT;
      break;
    case content::DOWNLOAD_INTERRUPT_REASON_NETWORK_INVALID_REQUEST:
    case content::DOWNLOAD_INTERRUPT_REASON_NETWORK_FAILED:
      string_id = IDS_DOWNLOAD_INTERRUPTED_DESCRIPTION_NETWORK_ERROR;
      break;
    case content::DOWNLOAD_INTERRUPT_REASON_NETWORK_TIMEOUT:
      string_id = IDS_DOWNLOAD_INTERRUPTED_DESCRIPTION_NETWORK_TIMEOUT;
      break;
    case content::DOWNLOAD_INTERRUPT_REASON_NETWORK_DISCONNECTED:
      string_id = IDS_DOWNLOAD_INTERRUPTED_DESCRIPTION_NETWORK_DISCONNECTED;
      break;
    case content::DOWNLOAD_INTERRUPT_REASON_NETWORK_SERVER_DOWN:
      string_id = IDS_DOWNLOAD_INTERRUPTED_DESCRIPTION_SERVER_DOWN;
      break;
    case content::DOWNLOAD_INTERRUPT_REASON_SERVER_FAILED:
      string_id = IDS_DOWNLOAD_INTERRUPTED_DESCRIPTION_SERVER_PROBLEM;
      break;
    case content::DOWNLOAD_INTERRUPT_REASON_SERVER_BAD_CONTENT:
      string_id = IDS_DOWNLOAD_INTERRUPTED_DESCRIPTION_NO_FILE;
      break;
    case content::DOWNLOAD_INTERRUPT_REASON_USER_CANCELED:
      string_id = IDS_DOWNLOAD_STATUS_CANCELLED;
      break;
    case content::DOWNLOAD_INTERRUPT_REASON_USER_SHUTDOWN:
      string_id = IDS_DOWNLOAD_INTERRUPTED_DESCRIPTION_SHUTDOWN;
      break;
    case content::DOWNLOAD_INTERRUPT_REASON_CRASH:
      string_id = IDS_DOWNLOAD_INTERRUPTED_DESCRIPTION_CRASH;
      break;
    case content::DOWNLOAD_INTERRUPT_REASON_NONE:
      NOTREACHED();
      // fallthrough
    case content::DOWNLOAD_INTERRUPT_REASON_SERVER_NO_RANGE:
    case content::DOWNLOAD_INTERRUPT_REASON_SERVER_PRECONDITION:
    case content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED:
      string_id = IDS_DOWNLOAD_INTERRUPTED_STATUS;
  }

  status_text = l10n_util::GetStringUTF16(string_id);

  return status_text;
}

} // namespace

// -----------------------------------------------------------------------------
// DownloadItemModel

DownloadItemModel::DownloadItemModel(DownloadItem* download)
    : download_(download) {}

DownloadItemModel::~DownloadItemModel() {}

base::string16 DownloadItemModel::GetInterruptReasonText() const {
  if (download_->GetState() != DownloadItem::INTERRUPTED ||
      download_->GetLastReason() ==
      content::DOWNLOAD_INTERRUPT_REASON_USER_CANCELED) {
    return base::string16();
  }
  return InterruptReasonMessage(download_->GetLastReason());
}

base::string16 DownloadItemModel::GetStatusText() const {
  base::string16 status_text;
  switch (download_->GetState()) {
    case DownloadItem::IN_PROGRESS:
      status_text = GetInProgressStatusString();
      break;
    case DownloadItem::COMPLETE:
      if (download_->GetFileExternallyRemoved()) {
        status_text = l10n_util::GetStringUTF16(IDS_DOWNLOAD_STATUS_REMOVED);
      } else {
        status_text.clear();
      }
      break;
    case DownloadItem::CANCELLED:
      status_text = l10n_util::GetStringUTF16(IDS_DOWNLOAD_STATUS_CANCELLED);
      break;
    case DownloadItem::INTERRUPTED: {
      content::DownloadInterruptReason reason = download_->GetLastReason();
      if (reason != content::DOWNLOAD_INTERRUPT_REASON_USER_CANCELED) {
        base::string16 interrupt_reason = InterruptReasonStatusMessage(reason);
        status_text = l10n_util::GetStringFUTF16(
            IDS_DOWNLOAD_STATUS_INTERRUPTED, interrupt_reason);
      } else {
        // Same as DownloadItem::CANCELLED.
        status_text = l10n_util::GetStringUTF16(IDS_DOWNLOAD_STATUS_CANCELLED);
      }
      break;
    }
    default:
      NOTREACHED();
  }

  return status_text;
}

base::string16 DownloadItemModel::GetTabProgressStatusText() const {
  int64 total = GetTotalBytes();
  int64 size = download_->GetReceivedBytes();
  base::string16 received_size = ui::FormatBytes(size);
  base::string16 amount = received_size;

  // Adjust both strings for the locale direction since we don't yet know which
  // string we'll end up using for constructing the final progress string.
  base::i18n::AdjustStringForLocaleDirection(&amount);

  if (total) {
    base::string16 total_text = ui::FormatBytes(total);
    base::i18n::AdjustStringForLocaleDirection(&total_text);

    base::i18n::AdjustStringForLocaleDirection(&received_size);
    amount = l10n_util::GetStringFUTF16(
        IDS_DOWNLOAD_TAB_PROGRESS_SIZE, received_size, total_text);
  } else {
    amount.assign(received_size);
  }
  int64 current_speed = download_->CurrentSpeed();
  base::string16 speed_text = ui::FormatSpeed(current_speed);
  base::i18n::AdjustStringForLocaleDirection(&speed_text);

  base::TimeDelta remaining;
  base::string16 time_remaining;
  if (download_->IsPaused())
    time_remaining = l10n_util::GetStringUTF16(IDS_DOWNLOAD_PROGRESS_PAUSED);
  else if (download_->TimeRemaining(&remaining))
    time_remaining = ui::TimeFormat::TimeRemaining(remaining);

  if (time_remaining.empty()) {
    base::i18n::AdjustStringForLocaleDirection(&amount);
    return l10n_util::GetStringFUTF16(
        IDS_DOWNLOAD_TAB_PROGRESS_STATUS_TIME_UNKNOWN, speed_text, amount);
  }
  return l10n_util::GetStringFUTF16(
      IDS_DOWNLOAD_TAB_PROGRESS_STATUS, speed_text, amount, time_remaining);
}

base::string16 DownloadItemModel::GetTooltipText(const gfx::FontList& font_list,
                                                 int max_width) const {
  base::string16 tooltip = gfx::ElideFilename(
      download_->GetFileNameToReportUser(), font_list, max_width);
  content::DownloadInterruptReason reason = download_->GetLastReason();
  if (download_->GetState() == DownloadItem::INTERRUPTED &&
      reason != content::DOWNLOAD_INTERRUPT_REASON_USER_CANCELED) {
    tooltip += base::ASCIIToUTF16("\n");
    tooltip += gfx::ElideText(InterruptReasonStatusMessage(reason),
                             font_list, max_width, gfx::ELIDE_AT_END);
  }
  return tooltip;
}

base::string16 DownloadItemModel::GetWarningText(const gfx::FontList& font_list,
                                                 int base_width) const {
  // Should only be called if IsDangerous().
  DCHECK(IsDangerous());
  base::string16 elided_filename =
      gfx::ElideFilename(download_->GetFileNameToReportUser(), font_list,
                        base_width);
  switch (download_->GetDangerType()) {
    case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL: {
      return l10n_util::GetStringUTF16(IDS_PROMPT_MALICIOUS_DOWNLOAD_URL);
    }
    case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE: {
      if (download_crx_util::IsExtensionDownload(*download_)) {
        return l10n_util::GetStringUTF16(
            IDS_PROMPT_DANGEROUS_DOWNLOAD_EXTENSION);
      } else {
        return l10n_util::GetStringFUTF16(IDS_PROMPT_DANGEROUS_DOWNLOAD,
                                          elided_filename);
      }
    }
    case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT:
    case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_HOST: {
      return l10n_util::GetStringFUTF16(IDS_PROMPT_MALICIOUS_DOWNLOAD_CONTENT,
                                        elided_filename);
    }
    case content::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT: {
      return l10n_util::GetStringFUTF16(IDS_PROMPT_UNCOMMON_DOWNLOAD_CONTENT,
                                        elided_filename);
    }
    case content::DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED: {
      return l10n_util::GetStringFUTF16(
          IDS_PROMPT_DOWNLOAD_CHANGES_SETTINGS, elided_filename);
    }
    case content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS:
    case content::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT:
    case content::DOWNLOAD_DANGER_TYPE_USER_VALIDATED:
    case content::DOWNLOAD_DANGER_TYPE_MAX: {
      break;
    }
  }
  NOTREACHED();
  return base::string16();
}

base::string16 DownloadItemModel::GetWarningConfirmButtonText() const {
  // Should only be called if IsDangerous()
  DCHECK(IsDangerous());
  if (download_->GetDangerType() ==
          content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE &&
      download_crx_util::IsExtensionDownload(*download_)) {
    return l10n_util::GetStringUTF16(IDS_CONTINUE_EXTENSION_DOWNLOAD);
  } else {
    return l10n_util::GetStringUTF16(IDS_CONFIRM_DOWNLOAD);
  }
}

int64 DownloadItemModel::GetCompletedBytes() const {
  return download_->GetReceivedBytes();
}

int64 DownloadItemModel::GetTotalBytes() const {
  return download_->AllDataSaved() ? download_->GetReceivedBytes() :
                                     download_->GetTotalBytes();
}

// TODO(asanka,rdsmith): Once 'open' moves exclusively to the
//     ChromeDownloadManagerDelegate, we should calculate the percentage here
//     instead of calling into the DownloadItem.
int DownloadItemModel::PercentComplete() const {
  return download_->PercentComplete();
}

bool DownloadItemModel::IsDangerous() const {
  return download_->IsDangerous();
}

bool DownloadItemModel::MightBeMalicious() const {
  if (!IsDangerous())
    return false;
  switch (download_->GetDangerType()) {
    case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL:
    case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT:
    case content::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT:
    case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_HOST:
    case content::DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED:
      return true;

    case content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS:
    case content::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT:
    case content::DOWNLOAD_DANGER_TYPE_USER_VALIDATED:
    case content::DOWNLOAD_DANGER_TYPE_MAX:
      // We shouldn't get any of these due to the IsDangerous() test above.
      NOTREACHED();
      // Fallthrough.
    case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE:
      return false;
  }
  NOTREACHED();
  return false;
}

// If you change this definition of malicious, also update
// DownloadManagerImpl::NonMaliciousInProgressCount.
bool DownloadItemModel::IsMalicious() const {
  if (!MightBeMalicious())
    return false;
  switch (download_->GetDangerType()) {
    case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL:
    case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT:
    case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_HOST:
    case content::DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED:
      return true;

    case content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS:
    case content::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT:
    case content::DOWNLOAD_DANGER_TYPE_USER_VALIDATED:
    case content::DOWNLOAD_DANGER_TYPE_MAX:
    case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE:
      // We shouldn't get any of these due to the MightBeMalicious() test above.
      NOTREACHED();
      // Fallthrough.
    case content::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT:
      return false;
  }
  NOTREACHED();
  return false;
}

bool DownloadItemModel::ShouldAllowDownloadFeedback() const {
#if defined(FULL_SAFE_BROWSING)
  if (!IsDangerous())
    return false;
  return safe_browsing::DownloadFeedbackService::IsEnabledForDownload(
      *download_);
#else
  return false;
#endif
}

bool DownloadItemModel::ShouldRemoveFromShelfWhenComplete() const {
  switch (download_->GetState()) {
    case DownloadItem::IN_PROGRESS:
      // If the download is dangerous or malicious, we should display a warning
      // on the shelf until the user accepts the download.
      if (IsDangerous())
        return false;

      // If the download is an extension, temporary, or will be opened
      // automatically, then it should be removed from the shelf on completion.
      // TODO(asanka): The logic for deciding opening behavior should be in a
      //               central location. http://crbug.com/167702
      return (download_crx_util::IsExtensionDownload(*download_) ||
              download_->IsTemporary() ||
              download_->GetOpenWhenComplete() ||
              download_->ShouldOpenFileBasedOnExtension());

    case DownloadItem::COMPLETE:
      // If the download completed, then rely on GetAutoOpened() to check for
      // opening behavior. This should accurately reflect whether the download
      // was successfully opened.  Extensions, for example, may fail to open.
      return download_->GetAutoOpened() || download_->IsTemporary();

    case DownloadItem::CANCELLED:
    case DownloadItem::INTERRUPTED:
      // Interrupted or cancelled downloads should remain on the shelf.
      return false;

    case DownloadItem::MAX_DOWNLOAD_STATE:
      NOTREACHED();
  }

  NOTREACHED();
  return false;
}

bool DownloadItemModel::ShouldShowDownloadStartedAnimation() const {
  return !download_->IsSavePackageDownload() &&
      !download_crx_util::IsExtensionDownload(*download_);
}

bool DownloadItemModel::ShouldShowInShelf() const {
  const DownloadItemModelData* data = DownloadItemModelData::Get(download_);
  return !data || data->should_show_in_shelf();
}

void DownloadItemModel::SetShouldShowInShelf(bool should_show) {
  DownloadItemModelData* data = DownloadItemModelData::GetOrCreate(download_);
  data->set_should_show_in_shelf(should_show);
}

bool DownloadItemModel::ShouldNotifyUI() const {
  const DownloadItemModelData* data = DownloadItemModelData::Get(download_);
  return data && data->should_notify_ui();
}

void DownloadItemModel::SetShouldNotifyUI(bool should_notify) {
  DownloadItemModelData* data = DownloadItemModelData::GetOrCreate(download_);
  data->set_should_notify_ui(should_notify);
}

bool DownloadItemModel::ShouldPreferOpeningInBrowser() const {
  const DownloadItemModelData* data = DownloadItemModelData::Get(download_);
  return data && data->should_prefer_opening_in_browser();
}

void DownloadItemModel::SetShouldPreferOpeningInBrowser(bool preference) {
  DownloadItemModelData* data = DownloadItemModelData::GetOrCreate(download_);
  data->set_should_prefer_opening_in_browser(preference);
}

base::string16 DownloadItemModel::GetProgressSizesString() const {
  base::string16 size_ratio;
  int64 size = GetCompletedBytes();
  int64 total = GetTotalBytes();
  if (total > 0) {
    ui::DataUnits amount_units = ui::GetByteDisplayUnits(total);
    base::string16 simple_size = ui::FormatBytesWithUnits(size, amount_units, false);

    // In RTL locales, we render the text "size/total" in an RTL context. This
    // is problematic since a string such as "123/456 MB" is displayed
    // as "MB 123/456" because it ends with an LTR run. In order to solve this,
    // we mark the total string as an LTR string if the UI layout is
    // right-to-left so that the string "456 MB" is treated as an LTR run.
    base::string16 simple_total = base::i18n::GetDisplayStringInLTRDirectionality(
        ui::FormatBytesWithUnits(total, amount_units, true));
    size_ratio = l10n_util::GetStringFUTF16(IDS_DOWNLOAD_STATUS_SIZES,
                                            simple_size, simple_total);
  } else {
    size_ratio = ui::FormatBytes(size);
  }
  return size_ratio;
}

base::string16 DownloadItemModel::GetInProgressStatusString() const {
  DCHECK_EQ(DownloadItem::IN_PROGRESS, download_->GetState());

  TimeDelta time_remaining;
  // time_remaining is only known if the download isn't paused.
  bool time_remaining_known = (!download_->IsPaused() &&
                               download_->TimeRemaining(&time_remaining));

  // Indication of progress. (E.g.:"100/200 MB" or "100MB")
  base::string16 size_ratio = GetProgressSizesString();

  // The download is a CRX (app, extension, theme, ...) and it is being unpacked
  // and validated.
  if (download_->AllDataSaved() &&
      download_crx_util::IsExtensionDownload(*download_)) {
    return l10n_util::GetStringUTF16(IDS_DOWNLOAD_STATUS_CRX_INSTALL_RUNNING);
  }

  // A paused download: "100/120 MB, Paused"
  if (download_->IsPaused()) {
    return l10n_util::GetStringFUTF16(
        IDS_DOWNLOAD_STATUS_IN_PROGRESS, size_ratio,
        l10n_util::GetStringUTF16(IDS_DOWNLOAD_PROGRESS_PAUSED));
  }

  // A download scheduled to be opened when complete: "Opening in 10 secs"
  if (download_->GetOpenWhenComplete()) {
    if (!time_remaining_known)
      return l10n_util::GetStringUTF16(IDS_DOWNLOAD_STATUS_OPEN_WHEN_COMPLETE);

    return l10n_util::GetStringFUTF16(
        IDS_DOWNLOAD_STATUS_OPEN_IN,
        ui::TimeFormat::TimeDurationShort(time_remaining));
  }

  // In progress download with known time left: "100/120 MB, 10 secs left"
  if (time_remaining_known) {
    return l10n_util::GetStringFUTF16(
        IDS_DOWNLOAD_STATUS_IN_PROGRESS, size_ratio,
        ui::TimeFormat::TimeRemaining(time_remaining));
  }

  // In progress download with no known time left and non-zero completed bytes:
  // "100/120 MB" or "100 MB"
  if (GetCompletedBytes() > 0)
    return size_ratio;

  // Instead of displaying "0 B" we say "Starting..."
  return l10n_util::GetStringUTF16(IDS_DOWNLOAD_STATUS_STARTING);
}

void DownloadItemModel::OpenUsingPlatformHandler() {
  DownloadService* download_service =
      DownloadServiceFactory::GetForBrowserContext(
          download_->GetBrowserContext());
  if (!download_service)
    return;

  ChromeDownloadManagerDelegate* delegate =
      download_service->GetDownloadManagerDelegate();
  if (!delegate)
    return;
  delegate->OpenDownloadUsingPlatformHandler(download_);
  RecordDownloadOpenMethod(DOWNLOAD_OPEN_METHOD_USER_PLATFORM);
}


text:
#import "FBLPromise+Catch.h"

#import <XCTest/XCTest.h>

#import "FBLPromise+Async.h"
#import "FBLPromise+Do.h"
#import "FBLPromise+Testing.h"
#import "FBLPromise+Then.h"
#import "FBLPromisesTestHelpers.h"

@interface FBLPromiseCatchTests : XCTestCase
@end

@implementation FBLPromiseCatchTests

- (void)testPromiseDoesNotCallThenAfterReject {
  // Act.
  FBLPromise *promise = [[[[[FBLPromise do:^id {
    return [NSError errorWithDomain:FBLPromiseErrorDomain code:42 userInfo:nil];
  }] then:^id(id __unused _) {
    XCTFail();
    return nil;
  }] then:^id(id __unused _) {
    XCTFail();
    return nil;
  }] then:^id(id __unused _) {
    XCTFail();
    return nil;
  }] catch:^(NSError *error) {
    XCTAssertEqual(error.code, 42);
  }];

  // Assert.
  XCTAssert(FBLWaitForPromisesWithTimeout(10));
  XCTAssertEqualObjects(promise.error.domain, FBLPromiseErrorDomain);
  XCTAssertEqual(promise.error.code, 42);
  XCTAssertNil(promise.value);
}

- (void)testPromiseDoesNotCallThenAfterAsyncReject {
  // Act.
  FBLPromise *promise =
      [[[[[FBLPromise async:^(FBLPromiseFulfillBlock __unused _, FBLPromiseRejectBlock reject) {
        FBLDelay(0.1, ^{
          reject([NSError errorWithDomain:FBLPromiseErrorDomain code:42 userInfo:nil]);
        });
      }] then:^id(id __unused _) {
        XCTFail();
        return nil;
      }] then:^id(id __unused _) {
        XCTFail();
        return nil;
      }] then:^id(id __unused _) {
        XCTFail();
        return nil;
      }] catch:^(NSError *error) {
        XCTAssertEqual(error.code, 42);
      }];

  // Assert.
  XCTAssert(FBLWaitForPromisesWithTimeout(10));
  XCTAssertEqualObjects(promise.error.domain, FBLPromiseErrorDomain);
  XCTAssertEqual(promise.error.code, 42);
  XCTAssertNil(promise.value);
}

- (void)testPromiseCallsSubsequentCatchAfterReject {
  // Arrange.
  NSUInteger __block count = 0;
  NSUInteger const expectedCount = 3;

  // Act.
  FBLPromise *promise = [[[[[FBLPromise do:^id {
    return [NSError errorWithDomain:FBLPromiseErrorDomain code:42 userInfo:nil];
  }] then:^id(id __unused _) {
    XCTFail();
    return nil;
  }] catch:^(NSError *error) {
    XCTAssertEqual(error.code, 42);
    ++count;
  }] catch:^(NSError *error) {
    XCTAssertEqual(error.code, 42);
    ++count;
  }] catch:^(NSError *error) {
    XCTAssertEqual(error.code, 42);
    ++count;
  }];

  // Assert.
  XCTAssert(FBLWaitForPromisesWithTimeout(10));
  XCTAssertEqual(count, expectedCount);
  XCTAssertEqualObjects(promise.error.domain, FBLPromiseErrorDomain);
  XCTAssertEqual(promise.error.code, 42);
  XCTAssertNil(promise.value);
}

- (void)testPromiseCallsSubsequentCatchAfterAsyncReject {
  // Arrange.
  NSUInteger __block count = 0;
  NSUInteger const expectedCount = 3;

  // Act.
  FBLPromise *promise =
      [[[[[FBLPromise async:^(FBLPromiseFulfillBlock __unused _, FBLPromiseRejectBlock reject) {
        FBLDelay(0.1, ^{
          reject([NSError errorWithDomain:FBLPromiseErrorDomain code:42 userInfo:nil]);
        });
      }] then:^id(id __unused _) {
        XCTFail();
        return nil;
      }] catch:^(NSError *error) {
        XCTAssertEqual(error.code, 42);
        ++count;
      }] catch:^(NSError *error) {
        XCTAssertEqual(error.code, 42);
        ++count;
      }] catch:^(NSError *error) {
        XCTAssertEqual(error.code, 42);
        ++count;
      }];

  // Assert.
  XCTAssert(FBLWaitForPromisesWithTimeout(10));
  XCTAssertEqual(count, expectedCount);
  XCTAssertEqualObjects(promise.error.domain, FBLPromiseErrorDomain);
  XCTAssertEqual(promise.error.code, 42);
  XCTAssertNil(promise.value);
}

- (void)testPromiseNoRejectAfterFulfill {
  // Act.
  FBLPromise<NSNumber *> *promise =
      [[[[FBLPromise async:^(FBLPromiseFulfillBlock fulfill, FBLPromiseRejectBlock reject) {
        fulfill(@42);
        reject([NSError errorWithDomain:FBLPromiseErrorDomain code:42 userInfo:nil]);
      }] then:^id(NSNumber *value) {
        XCTAssertEqualObjects(value, @42);
        return value;
      }] catch:^(NSError __unused *_) {
        XCTFail();
      }] then:^id(NSNumber *value) {
        XCTAssertEqualObjects(value, @42);
        return value;
      }];

  // Assert.
  XCTAssert(FBLWaitForPromisesWithTimeout(10));
  XCTAssertEqualObjects(promise.value, @42);
  XCTAssertNil(promise.error);
}

- (void)testPromiseNoFulfillAfterReject {
  // Act.
  FBLPromise<NSNumber *> *promise =
      [[[[[FBLPromise async:^(FBLPromiseFulfillBlock fulfill, FBLPromiseRejectBlock reject) {
        reject([NSError errorWithDomain:FBLPromiseErrorDomain code:42 userInfo:nil]);
        fulfill(@42);
      }] then:^id(id __unused _) {
        XCTFail();
        return nil;
      }] catch:^(NSError *error) {
        XCTAssertEqual(error.code, 42);
      }] then:^id(id __unused _) {
        XCTFail();
        return nil;
      }] catch:^(NSError *error) {
        XCTAssertEqual(error.code, 42);
      }];

  // Assert.
  XCTAssert(FBLWaitForPromisesWithTimeout(10));
  XCTAssertEqualObjects(promise.error.domain, FBLPromiseErrorDomain);
  XCTAssertEqual(promise.error.code, 42);
  XCTAssertNil(promise.value);
}

- (void)testPromiseNoDoubleReject {
  // Act.
  FBLPromise *promise =
      [[[FBLPromise async:^(FBLPromiseFulfillBlock __unused _, FBLPromiseRejectBlock reject) {
        FBLDelay(0.1, ^{
          reject([NSError errorWithDomain:FBLPromiseErrorDomain code:42 userInfo:nil]);
          reject([NSError errorWithDomain:FBLPromiseErrorDomain code:13 userInfo:nil]);
        });
      }] catch:^(NSError *error) {
        XCTAssertEqual(error.code, 42);
      }] catch:^(NSError *error) {
        XCTAssertEqual(error.code, 42);
      }];

  // Assert.
  XCTAssert(FBLWaitForPromisesWithTimeout(10));
  XCTAssertEqualObjects(promise.error.domain, FBLPromiseErrorDomain);
  XCTAssertEqual(promise.error.code, 42);
  XCTAssertNil(promise.value);
}

- (void)testPromiseThenReturnError {
  // Act.
  FBLPromise *promise = [[[[[FBLPromise do:^id {
    return @42;
  }] then:^id(id __unused _) {
    return [NSError errorWithDomain:FBLPromiseErrorDomain code:42 userInfo:nil];
  }] then:^id(id __unused _) {
    XCTFail();
    return nil;
  }] then:^id(id __unused _) {
    XCTFail();
    return nil;
  }] catch:^(NSError *error) {
    XCTAssertEqual(error.code, 42);
  }];

  // Assert.
  XCTAssert(FBLWaitForPromisesWithTimeout(10));
  XCTAssertEqualObjects(promise.error.domain, FBLPromiseErrorDomain);
  XCTAssertEqual(promise.error.code, 42);
  XCTAssertNil(promise.value);
}

- (void)testPromiseCatchInitiallyRejected {
  // Act.
  FBLPromise<NSNumber *> *initiallyRejectedPromise = [FBLPromise
      resolvedWith:[NSError errorWithDomain:FBLPromiseErrorDomain code:42 userInfo:nil]];
  FBLPromise<NSNumber *> *promise = [[initiallyRejectedPromise then:^id(id __unused _) {
    XCTFail();
    return nil;
  }] catch:^(NSError *error) {
    XCTAssertEqual(error.code, 42);
  }];

  // Assert.
  XCTAssert(FBLWaitForPromisesWithTimeout(10));
  XCTAssertEqualObjects(initiallyRejectedPromise.error.domain, FBLPromiseErrorDomain);
  XCTAssertEqual(initiallyRejectedPromise.error.code, 42);
  XCTAssertNil(initiallyRejectedPromise.value);
  XCTAssertEqualObjects(promise.error.domain, FBLPromiseErrorDomain);
  XCTAssertEqual(promise.error.code, 42);
  XCTAssertNil(promise.value);
}

/**
 Promise created with `catch` should not deallocate until it gets resolved.
 */
- (void)testPromiseCatchNoDeallocUntilRejected {
  // Arrange.
  FBLPromise *promise = [FBLPromise pendingPromise];
  FBLPromise __weak *weakExtendedPromise1;
  FBLPromise __weak *weakExtendedPromise2;

  // Act.
  @autoreleasepool {
    XCTAssertNil(weakExtendedPromise1);
    XCTAssertNil(weakExtendedPromise2);
    weakExtendedPromise1 = [promise catch:^(NSError __unused *_){}];
    weakExtendedPromise2 = [promise catch:^(NSError __unused *_){}];
    XCTAssertNotNil(weakExtendedPromise1);
    XCTAssertNotNil(weakExtendedPromise2);
  }

  // Assert.
  XCTAssertNotNil(weakExtendedPromise1);
  XCTAssertNotNil(weakExtendedPromise2);

  [promise reject:[NSError errorWithDomain:FBLPromiseErrorDomain code:42 userInfo:nil]];
  XCTAssert(FBLWaitForPromisesWithTimeout(10));

  XCTAssertNil(weakExtendedPromise1);
  XCTAssertNil(weakExtendedPromise2);
}

@end


text:
(function () {
  'use strict';

  describe('Jobs List Controller Tests', function () {
    // Initialize global variables
    var JobsListController,
      $scope,
      $httpBackend,
      $state,
      Authentication,
      JobsService,
      mockJob;

    // The $resource service augments the response object with methods for updating and deleting the resource.
    // If we were to use the standard toEqual matcher, our tests would fail because the test values would not match
    // the responses exactly. To solve the problem, we define a new toEqualData Jasmine matcher.
    // When the toEqualData matcher compares two objects, it takes only object properties into
    // account and ignores methods.
    beforeEach(function () {
      jasmine.addMatchers({
        toEqualData: function (util, customEqualityTesters) {
          return {
            compare: function (actual, expected) {
              return {
                pass: angular.equals(actual, expected)
              };
            }
          };
        }
      });
    });

    // Then we can start by loading the main application module
    beforeEach(module(ApplicationConfiguration.applicationModuleName));

    // The injector ignores leading and trailing underscores here (i.e. _$httpBackend_).
    // This allows us to inject a service but then attach it to a variable
    // with the same name as the service.
    beforeEach(inject(function ($controller, $rootScope, _$state_, _$httpBackend_, _Authentication_, _JobsService_) {
      // Set a new global scope
      $scope = $rootScope.$new();

      // Point global variables to injected services
      $httpBackend = _$httpBackend_;
      $state = _$state_;
      Authentication = _Authentication_;
      JobsService = _JobsService_;

      // create mock article
      mockJob = new JobsService({
        _id: '525a8422f6d0f87f0e407a33',
        name: 'Job Name'
      });

      // Mock logged in user
      Authentication.user = {
        roles: ['user']
      };

      // Initialize the Jobs List controller.
      JobsListController = $controller('JobsListController as vm', {
        $scope: $scope
      });

      // Spy on state go
      spyOn($state, 'go');
    }));

    describe('Instantiate', function () {
      var mockJobList;

      beforeEach(function () {
        mockJobList = [mockJob, mockJob];
      });

      it('should send a GET request and return all Jobs', inject(function (JobsService) {
        // Set POST response
        $httpBackend.expectGET('api/jobs').respond(mockJobList);

        $httpBackend.flush();

        // Test form inputs are reset
        expect($scope.vm.jobs.length).toEqual(2);
        expect($scope.vm.jobs[0]).toEqual(mockJob);
        expect($scope.vm.jobs[1]).toEqual(mockJob);

      }));
    });
  });
}());


text:
class ProjectFlow
  include DomainFlow::Map

  def initialize
    initial :collecting

    status :collecting do
      to :collected, event: :finish, who: [Department.new(:business)]
    end

    status :collected do
      to :estimated, event: :estimate, who: [Department.new(:design)]
    end

    status :estimated do
      to :submitted,  event: :adopt,  who: :design_department_manager
      to :collecting, event: :reject, who: :design_department_manager
    end

    status :submitted do
      to :initiation, event: :dispose, who: :managers
      to :miscarried, event: :reject,  who: :managers
    end

    status :initiation do
      to :designed, event: :design, who: [Department.new(:design)]
    end

    status :designed do
      to :budgeted, event: :budget, who: [Department.new(:design)]
    end

    status :budgeted do
      to :drafting, event: :dispose, who: :managers
      to :designed, event: :reject,  who: :managers
    end

    status :drafting do
      to :signed, sub: :contract, field: :state
    end

    status :signed do
      to :ready, event: :finish, who: [Department.new(:project)]
    end

    term :creator, :who do |doc|
      doc.creator
    end

  end
end


text:
namespace ManualStringProcessing
{
    using System;
    using System.Text;

    class UnicodeCharacters
    {
        static void Main(string[] args)
        {
            string input = Console.ReadLine();

            foreach (char symbol in input)
            {
                Console.Write($"\\u{GetUnicodeCode(symbol):X4}".ToLower());
            }
            Console.WriteLine();
        }

        private static int GetUnicodeCode(char character)
        {
            UTF32Encoding encoding = new UTF32Encoding();
            byte[] bytes = encoding.GetBytes(character.ToString().ToCharArray());

            return BitConverter.ToInt32(bytes, 0);
        }
    }
}


text:
struct Foo : public Nano::Observer
{
    bool handler_a(const char* sl) const
    {
        std::cout << sl << std::endl;
        return true;
    }
    bool handler_b(const char* sl, std::size_t ln)
    {
        std::cout << sl << " [on line: " << ln << "]" << std::endl;
        return true;
    }
    static bool handler_c(const char* sl)
    {
        std::cout << sl << std::endl;
        return true;
    }
};

bool handler_d(const char* sl, std::size_t ln)
{
    std::cout << sl << " [on line: " << ln << "]" << std::endl;
    return false;
}

void handler_e()
{
    // Empty definition
}

//------------------------------------------------------------------------------

int main()
{
    // Declare Nano::Signals using function signature syntax
    Nano::Signal<bool(const char*)> signal_one;
    Nano::Signal<bool(const char*, std::size_t)> signal_two;

    // Test void slot types
    Nano::Signal<void()> signal_three;
    signal_three.connect<handler_e>();
    signal_three();

    // Test using function objects
    std::function<bool(const char*, std::size_t)> fo;

    fo = [&](const char* sl, std::size_t ln)
    {
        std::cout << sl << " [on line: " << ln << "]" << std::endl;
        // Test indirectly disconnecting the currently emitting slot
        signal_two.disconnect(fo);
        return true;
    };

    // Create a new scope to test automatic disconnect
    {
        Foo foo;

        // Connect member functions to Nano::Signals
        signal_one.connect<&Foo::handler_a>(&foo);
        signal_two.connect<&Foo::handler_b>(&foo);

        // Signal one should not be empty
        assert(!signal_one.empty());

        // Connect a static member function
        signal_one.connect<Foo::handler_c>();

        // Connect a free function
        signal_two.connect<handler_d>();

        // Emit Signals
        signal_one("we get signal");
        signal_two("main screen turn on", __LINE__);

        std::vector<bool> status;

        // Emit Signals and accumulate SRVs (signal return values)
        signal_one.emit_accumulate([&](bool srv)
        {
            status.push_back(srv);
        }
        ,"how are you gentlemen");

        // Disconnect member functions from a Nano::Signal
        signal_one.disconnect<&Foo::handler_a>(foo);
        signal_two.disconnect<&Foo::handler_b>(foo);

        // Disconnect a static member function
        signal_one.disconnect<Foo::handler_c>();

        // Disconnect a free function
        signal_two.disconnect<handler_d>();

        // Emit again to test disconnects
        signal_one("THIS SHOULD NOT APPEAR");
        signal_two("THIS SHOULD NOT APPEAR", __LINE__);

        // Connecting function objects (or any object defining a suitable operator())
        signal_two.connect(&fo);

        // Test indirectly disconnecting the currently emitting slot
        signal_two("indirect disconnect", __LINE__);

        // Disconnecting function objects (test convenience overload)
        signal_two.disconnect(fo);

        // Test auto disconnect
        signal_one.connect<&Foo::handler_a>(foo);

        // Test copying, (currently deleted because of issue #15)
        //Nano::Signal<void()> signal_four = signal_three;
        //signal_four();

        // Test removeAll()
        signal_two.connect<&Foo::handler_b>(&foo);
        signal_two.removeAll();

        // Test multiple explicit removeAll()
        signal_two.removeAll();
    }
    // Signal one should be empty
    assert(signal_one.empty());

    // If this appears then automatic disconnect did not work
    signal_one("THIS SHOULD NOT APPEAR");

    #ifdef NANO_USE_DEPRECATED

    // Test deprecated emit interface
    signal_one("we get signal");
    signal_two("main screen turn on", __LINE__);

    std::vector<bool> status;

    // Emit Signals and accumulate SRVs (signal return values)
    signal_one("how are you gentlemen", [&](bool srv)
    {
        status.push_back(srv);
    });

    #endif

    // Pause the screen
    std::cin.get();
}


text:
class EngineersController < ApplicationController
  before_action :set_engineer, only: [:show, :edit, :update, :destroy]
  protect_from_forgery with: :null_session, if: Proc.new { |c| c.request.format == 'application/json' }
  skip_before_filter  :verify_authenticity_token

  # GET /engineers
  # GET /engineers.json
  def index
    @engineers = Engineer.where(rentee_id: params[:rentee_id])
    @rentee = Rentee.find(params[:rentee_id])
    # @renteeId = Rentee.find(params[:tokens])
  end

  # GET /engineers/1
  # GET /engineers/1.json
  def show

  end

  # GET /engineers/new
  def new
    @rentee = Rentee.find(params[:rentee_id])
    @engineer = Engineer.new
  end

  # GET /engineers/1/edit
  def edit
    @rentee = Rentee.find(params[:rentee_id])
  end

  # POST /engineers
  # POST /engineers.json
  def create
    @engineer = Engineer.new(engineer_params)
    r = Rentee.find(params[:rentee_id])
    @engineer.rentee = r
      if @engineer.save
      end

    respond_to do |format|
      if @engineer.save
        format.html { redirect_to [@engineer.rentee, @engineer], notice: 'Engineer was successfully created.' }
        format.json { render :show, status: :created, location: @engineer }
      else
        format.html { render :new }
        format.json { render json: @engineer.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /engineers/1
  # PATCH/PUT /engineers/1.json
  def update
    numTokens = params[:engineer][:tokens].to_i
    engineerId = params[:id]
    renteeId = params[:rentee_id]
    engineerTokens = Engineer.find(engineerId).tokens
    if engineerTokens == nil
      engineerTokens = 0
    end
    renteeTokens = Rentee.find(renteeId).tokens

    if numTokens <= renteeTokens
      renteeTokens = renteeTokens - numTokens
      Rentee.update(renteeId, :tokens => renteeTokens)
      engineerTokens = engineerTokens + numTokens

    else
      flash[:alert] = "Not enough tokens. Please purchase more tokens"
    end

    respond_to do |format|
      if @engineer.update(:tokens => engineerTokens)
        format.html { redirect_to :back, notice: 'Engineer was successfully updated.' }
        format.json { render :show, status: :ok, location: [@engineer.rentee, @engineer] }
      else
        format.html { render :edit }
        format.json { render json: @engineer.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /engineers/1
  # DELETE /engineers/1.json
  def destroy
    @engineer.destroy
    respond_to do |format|
      format.html { redirect_to engineers_url, notice: 'Engineer was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_engineer
      @engineer = Engineer.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def engineer_params
      params.require(:engineer).permit(:name, :phone, :tokens)
    end
end


text:
package de.terrestris.shoguncore.util.enumeration;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;

/**
 * @author Daniel Koch
 * @author terrestris GmbH & Co. KG
 */
public class HttpEnum {

    /**
     * A enum type for the allowed event format.
     */
    public static enum EventType {
        REQUEST("REQUEST"),
        RESPONSE("RESPONSE");

        private final String value;

        /**
         * Enum constructor
         *
         * @param value
         */
        private EventType(String value) {
            this.value = value;
        }

        /**
         * Static method to get an enum based on a string value.
         * This method is annotated with {@link JsonCreator},
         * which allows the client to send case insensitive string
         * values (like "jSon"), which will be converted to the
         * correct enum value.
         *
         * @param inputValue
         * @return
         */
        @JsonCreator
        public static EventType fromString(String inputValue) {
            if (inputValue != null) {
                for (EventType type : EventType.values()) {
                    if (inputValue.equalsIgnoreCase(type.value)) {
                        return type;
                    }
                }
            }
            return null;
        }

        /**
         * This method is annotated with {@link JsonValue},
         * so that jackson will serialize the enum value to
         * the (lowercase) {@link #value}.
         */
        @Override
        @JsonValue
        public String toString() {
            return value;
        }
    }

}


text:
package cz.atlascon.diff;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import cz.atlascon.avro.*;
import org.apache.avro.generic.GenericRecord;
import org.apache.avro.specific.SpecificRecord;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.Map;

/**
 * Created by Barbora Cigánková on 20.01.2017.
 */
public class RecordDiffTest {
    private PrimitiveSpecificRecord primitiveSpecificRecord1 = new PrimitiveSpecificRecord("string", 1L, 2d, true, 3, 4f,
            ByteBuffer.wrap("a".getBytes()));
    private PrimitiveSpecificRecord primitiveSpecificRecord2 = new PrimitiveSpecificRecord("string1", 1L, 3d, false, 4, 5f,
            ByteBuffer.wrap("b".getBytes()));
    private Map<String, Object> map1 = Maps.newHashMap();
    private Map<String, Object> map2 = Maps.newHashMap();
    private List<Object> list1 = Lists.newArrayList();
    private List<Object> list2 = Lists.newArrayList();
    private RecordSpecificRecord recordSpecificRecord1 = new RecordSpecificRecord(primitiveSpecificRecord1, map1, list1, TestEnum.TESTA);
    private RecordSpecificRecord recordSpecificRecord2 = new RecordSpecificRecord(primitiveSpecificRecord2, map2, list2, true);
    private Map<String, Object> map3 = Maps.newHashMap();
    private Map<String, Object> map4 = Maps.newHashMap();
    private MapSpecificRecord mapSpecificRecord3 = new MapSpecificRecord(map3);
    private MapSpecificRecord mapSpecificRecord4 = new MapSpecificRecord(map4);
    private Map<String, Object> map5 = Maps.newHashMap();
    private Map<String, Object> map6 = Maps.newHashMap();
    private List<Object> list3 = Lists.newArrayList();
    private List<Object> list4 = Lists.newArrayList();
    private PrimitiveSpecificRecord primitiveSpecificRecord3 = new PrimitiveSpecificRecord("string3", 5L, 4d, false, 3, 5f,
            ByteBuffer.wrap("a".getBytes()));
    private PrimitiveSpecificRecord primitiveSpecificRecord4 = new PrimitiveSpecificRecord("string4", 5L, 3d, false, 4, 5f,
            ByteBuffer.wrap("b".getBytes()));
    private RecordSpecificRecord recordSpecificRecord3 = new RecordSpecificRecord(mapSpecificRecord3, map5, list3, 423f);
    private RecordSpecificRecord recordSpecificRecord4 = new RecordSpecificRecord(mapSpecificRecord4, map6, list4, ByteBuffer.wrap("a".getBytes()));
    private List<Integer> list5 = Lists.newArrayList(4444);
    private List<Integer> list6 = Lists.newArrayList(456);
    private List<Object> list7 = Lists.newArrayList();
    private List<Object> list8 = Lists.newArrayList();
    private ArraySpecificRecord arraySpecificRecord1 = new ArraySpecificRecord(list7);
    private ArraySpecificRecord arraySpecificRecord2 = new ArraySpecificRecord(list8);
    private Map<String, Object> map7 = Maps.newHashMap();
    private Map<String, Object> map8 = Maps.newHashMap();
    private ArraySpecificRecord arraySpecificRecord3 = new ArraySpecificRecord(Lists.newArrayList(map7));
    private ArraySpecificRecord arraySpecificRecord4 = new ArraySpecificRecord(Lists.newArrayList(map8));
    private Map<String, Object> map9 = Maps.newHashMap();
    private Map<String, Object> map10 = Maps.newHashMap();
    private RecordSpecificRecord recordSpecificRecord5 = new RecordSpecificRecord(arraySpecificRecord1, map9, list3, "fff");
    private RecordSpecificRecord recordSpecificRecord6 = new RecordSpecificRecord(arraySpecificRecord2, map10, list4, false);

    @Before
    public void setUp() {
        //the second test
        Map<Object, Object> map7 = Maps.newHashMap();
        Map<Object, Object> map8 = Maps.newHashMap();
        Map<Object, Object> map9 = Maps.newHashMap();
        Map<Object, Object> map10 = Maps.newHashMap();
        Map<Object, Object> map11 = Maps.newHashMap();
        map7.put("a", 5);
        map8.put("b", 6);
        map9.put("c", 6);
        map9.put("d", 3);
        map10.put("e", 7);
        map10.put("e", 8);
        map11.put("e", 6);
        map11.put("e", 4);

        map3.put("same", Maps.newHashMap());
        map3.put("removed", map7);
        map3.put("changed", map10);
        map4.put("same", Maps.newHashMap());
        map4.put("added", map8);
        map4.put("added2", map9);
        map4.put("changed", map11);

        Map<Object, Object> map12 = Maps.newHashMap();
        Map<Object, Object> map13 = Maps.newHashMap();
        Map<Object, Object> map14 = Maps.newHashMap();
        Map<Object, Object> map15 = Maps.newHashMap();
        Map<Object, Object> map16 = Maps.newHashMap();
        map12.put("sameVal", primitiveSpecificRecord1);
        map14.put("changedVal", primitiveSpecificRecord3);
        map16.put("removedVal", "fgghh");
        map5.put("same", map12);
        map5.put("changed", map14);
        map5.put("removed", map16);
        map13.put("addedVal", primitiveSpecificRecord2);
        map15.put("changedVal", primitiveSpecificRecord4);
        map6.put("added", map13);
        map6.put("same", map12);
        map6.put("changed", map15);

        list3.add(primitiveSpecificRecord1);
        list4.add(primitiveSpecificRecord2);
    }

    @Test
    public void shouldCreateAndApplyRecordDiff() throws IOException {
        map1.put("a", 3f);
        map1.put("c", true);
        map2.put("c", true);
        map2.put("b", 5l);

        list1.add("asf");
        list2.add("ddd");

        RecordDiff diff = AvroDiff.createDiff(recordSpecificRecord1, recordSpecificRecord2, recordSpecificRecord1.getSchema());
        GenericRecord modifiedRecord = AvroDiff.applyDiff(recordSpecificRecord1, diff, recordSpecificRecord1.getSchema());

        Assert.assertEquals(modifiedRecord, recordSpecificRecord2);
        Assert.assertNotEquals(modifiedRecord, recordSpecificRecord1);
    }

    @Test
    public void shouldCreateAndApplyMoreComplexRecordDiff() throws IOException {
        RecordDiff diff = AvroDiff.createDiff(recordSpecificRecord3, recordSpecificRecord4, recordSpecificRecord3.getSchema());
        GenericRecord modifiedRecord = AvroDiff.applyDiff(recordSpecificRecord3, diff, recordSpecificRecord3.getSchema());

        Assert.assertEquals(modifiedRecord, recordSpecificRecord4);
        Assert.assertNotEquals(modifiedRecord, recordSpecificRecord3);
    }

    @Test
    public void shouldCreateAndApplyAnotherComplexRecordDiff() throws IOException {
        list7.add(list5);
        list8.add(list6);

        map7.put("same", Lists.newArrayList(primitiveSpecificRecord1));
        map7.put("removed", Lists.newArrayList(primitiveSpecificRecord2));
        map7.put("changed", Lists.newArrayList(primitiveSpecificRecord4));
        map8.put("added", Lists.newArrayList(primitiveSpecificRecord3));
        map8.put("changed", Lists.newArrayList(primitiveSpecificRecord3));

        map9.put("removed", arraySpecificRecord3);
        map9.put("changed", arraySpecificRecord4);
        map10.put("changed", arraySpecificRecord3);
        map10.put("added", arraySpecificRecord1);

        list3.add(primitiveSpecificRecord2);
        list4.add(primitiveSpecificRecord3);

        RecordDiff diff = AvroDiff.createDiff(recordSpecificRecord5, recordSpecificRecord6, recordSpecificRecord5.getSchema());
        GenericRecord modifiedRecord = AvroDiff.applyDiff(recordSpecificRecord5, diff, recordSpecificRecord5.getSchema());

        Assert.assertEquals(modifiedRecord, recordSpecificRecord6);
        Assert.assertNotEquals(modifiedRecord, recordSpecificRecord5);
    }
}


text:
package org.springframework.web.socket.server.support;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.http.HttpStatus;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.util.Assert;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;
import org.springframework.web.util.WebUtils;

/**
 * An interceptor to check request {@code Origin} header value against a collection of
 * allowed origins.
 *
 * @author Sebastien Deleuze
 * @since 4.1.2
 */
public class OriginHandshakeInterceptor implements HandshakeInterceptor {

	protected Log logger = LogFactory.getLog(getClass());

	private final List<String> allowedOrigins;

	/**
	 * Default constructor with only same origin requests allowed.
	 */
	public OriginHandshakeInterceptor() {
		this.allowedOrigins = new ArrayList<String>();
	}

	/**
	 * Constructor using the specified allowed origin values.
	 *
	 * @see #setAllowedOrigins(Collection)
	 */
	public OriginHandshakeInterceptor(Collection<String> allowedOrigins) {
		this();
		setAllowedOrigins(allowedOrigins);
	}

	/**
	 * Configure allowed {@code Origin} header values. This check is mostly designed for
	 * browser clients. There is nothing preventing other types of client to modify the
	 * {@code Origin} header value.
	 *
	 *
Each provided allowed origin must start by "http://", "https://" or be "*"
	 * (means that all origins are allowed).
	 *
	 * @see RFC 6454: The Web Origin Concept
	 */
	public void setAllowedOrigins(Collection<String> allowedOrigins) {
		Assert.notNull(allowedOrigins, "Allowed origin Collection must not be null");
		for (String allowedOrigin : allowedOrigins) {
			Assert.isTrue(allowedOrigin.equals("*") || allowedOrigin.startsWith("http://") ||
					allowedOrigin.startsWith("https://"), "Invalid allowed origin provided: \"" +
					allowedOrigin + "\". It must start with \"http://\", \"https://\" or be \"*\"");
		}
		this.allowedOrigins.clear();
		this.allowedOrigins.addAll(allowedOrigins);
	}

	/**
	 * @see #setAllowedOrigins(Collection)
	 * @since 4.1.5
	 */
	public Collection<String> getAllowedOrigins() {
		return Collections.unmodifiableList(this.allowedOrigins);
	}

	@Override
	public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
			WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
		if (!WebUtils.isValidOrigin(request, this.allowedOrigins)) {
			response.setStatusCode(HttpStatus.FORBIDDEN);
			if (logger.isDebugEnabled()) {
				logger.debug("Handshake request rejected, Origin header value "
						+ request.getHeaders().getOrigin() + " not allowed");
			}
			return false;
		}
		return true;
	}

	@Override
	public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response,
			WebSocketHandler wsHandler, Exception exception) {
	}

}