text:
(function($){

    module("events");

    test("multiselectopen", function(){
        expect(27);

        // inject widget
        el = $("<select multiple><option value='foo'>foo</option></select>").appendTo(body);
        el.multiselect({
            open: function(e,ui){
                ok( true, 'option: multiselect("open") fires open callback' );
                equal(this, el[0], "option: context of callback");
                equal(e.type, 'multiselectopen', 'option: event type in callback');
                equal(menu().css("display"), 'block', 'menu display css property equals block');
                deepEqual(ui, {}, 'option: ui hash in callback');
            }
        })
        .bind("multiselectopen", function(e,ui){
            ok(true, 'event: multiselect("open") fires multiselectopen event');
            equal(this, el[0], 'event: context of event');
            deepEqual(ui, {}, 'event: ui hash');
        });

        // now try to open it..
        el.multiselect("open")

        // make sure the width of the menu and button are equivalent
        equal( button().outerWidth(), menu().outerWidth(), 'button and menu widths are equivalent');

        // close
        el.multiselect("close");

        // make sure a click event on the button opens the menu as well.
        button().trigger("click");
        el.multiselect("close");

        // make sure a click event on a span inside the button opens the menu as well.
        button().find("span:first").trigger("click");

        // reset for next test
        el.multiselect("destroy").remove();

        // now try returning false prevent opening
        el = $("<select></select>")
            .appendTo(body)
            .multiselect()
            .bind("multiselectbeforeopen", function(){
                ok( true, "event: binding multiselectbeforeopen to return false (prevent from opening)" );
                return false;
            })
            .multiselect("open");

        ok( !el.multiselect("isOpen"), "multiselect is not open after multiselect('open')" );
        el.multiselect("destroy").remove();
    });

    test("multiselectclose", function(){
        expect(25);

        // inject widget
        el = $("<select multiple><option>foo</option></select>").appendTo(body);
        el.multiselect({
            close: function(e,ui){
                ok( true, 'option: multiselect("close") fires close callback' );
                equal(this, el[0], "option: context of callback");
                equal(e.type, 'multiselectclose', 'option: event type in callback');
                equal(menu().css("display"), 'none', 'menu display css property equals none');
                deepEqual(ui, {}, 'option: ui hash');
            }
        })
        .bind("multiselectclose", function(e,ui){
            ok(true, 'multiselect("close") fires multiselectclose event');
            equal(this, el[0], 'event: context of event');
            deepEqual(ui, {}, 'event: ui hash');
        })
        .multiselect("open")
        .multiselect("close")
        .multiselect("open");

        // make sure a click event on the button closes the menu as well.
        button().click();
        el.multiselect("open");

        // make sure a click event on a span inside the button closes the menu as well.
        button().find("span:first").click();

        // make sure that the menu is actually closed.  see issue #68
        ok( el.multiselect('isOpen') === false, 'menu is indeed closed' );

        el.multiselect("destroy").remove();
    });

    test("multiselectbeforeclose", function(){
        expect(8);

        // inject widget
        el = $("<select multiple></select>").appendTo(body);
        el.multiselect({
            beforeclose: function(e,ui){
                ok( true, 'option: multiselect("beforeclose") fires close callback' );
                equal(this, el[0], "option: context of callback");
                equal(e.type, 'multiselectbeforeclose', 'option: event type in callback');
                deepEqual(ui, {}, 'option: ui hash');
            }
        })
        .bind("multiselectbeforeclose", function(e,ui){
            ok(true, 'multiselect("beforeclose") fires multiselectclose event');
            equal(this, el[0], 'event: context of event');
            deepEqual(ui, {}, 'event: ui hash');
        })
        .multiselect("open")
        .multiselect("close");

        el.multiselect("destroy").remove();

        // test 'return false' functionality
        el = $("<select multiple></select>").appendTo(body);
        el.multiselect({
            beforeclose: function(){
                return false;
            }
        });

        el.multiselect('open').multiselect('close');
        ok( menu().is(':visible') && el.multiselect("isOpen"), "returning false inside callback prevents menu from closing" );
        el.multiselect("destroy").remove();
    });

    test("multiselectclick", function(){
        expect(32);

        var times = 0;

        // inject widget
        el = $("<select multiple><option value='1'>Option 1</option><option value='2'>Option 2</option></select>")
            .appendTo(body);

        el.multiselect({
            click: function(e,ui){
                ok(true, 'option: triggering the click event on the second checkbox fires the click callback' );
                equal(this, el[0], "option: context of callback");
                equal(e.type, 'multiselectclick', 'option: event type in callback');
                equal(ui.value, "2", "option: ui.value equals");
                equal(ui.text, "Option 2", "option: ui.text equals");

                if(times === 0) {
                    equal(ui.checked, true, "option: ui.checked equals");
                } else if(times === 1) {
                    equal(ui.checked, false, "option: ui.checked equals");
                }

                equal(ui.extraParameters, undefined, "option: ui.extraParameters equals");
            }
        })
        .bind("multiselectclick", function(e,ui){
            ok(true, 'event: triggering the click event on the second checkbox triggers multiselectclick');
            equal(this, el[0], 'event: context of event');
            equal(ui.value, "2", "event: ui.value equals");
            equal(ui.text, "Option 2", "event: ui.text equals");

            if(times === 0) {
                equal(ui.checked, true, "option: ui.checked equals");
            } else if(times === 1) {
                equal(ui.checked, false, "option: ui.checked equals");
            }

            equal(ui.extraParameters, undefined, "option: ui.extraParameters equals");
        })
        .bind("change", function(e){
            if(++times === 1){
                equal(el.val().join(), "2", "event: select element val() within the change event is correct" );
            } else {
                equal(el.val(), null, "event: select element val() within the change event is correct" );
            }

            ok(true, "event: the select's change event fires");
        })
        .multiselect("open");

        // trigger a click event on the input
        var lastInput = menu().find("input").last();
        lastInput[0].click();

        // trigger once more.
        lastInput[0].click();

        // make sure it has focus
        equal(true, lastInput.is(":focus"), "The input has focus");

        // make sure menu isn't closed automatically
        equal( true, el.multiselect('isOpen'), 'menu stays open' );

        el.multiselect("destroy").remove();
    });

    test("multiselectclick, with extraParameters", function(){
        expect(28);

        var times = 0;

        // inject widget
        el = $("<select multiple><option value='1'>Option 1</option><option value='2'>Option 2</option></select>")
            .appendTo(body);

        el.multiselect({
            click: function(e,ui){
                ok(true, 'option: triggering the click event on the second checkbox fires the click callback' );
                equal(this, el[0], "option: context of callback");
                equal(e.type, 'multiselectclick', 'option: event type in callback');
                equal(ui.value, "2", "option: ui.value equals");
                equal(ui.text, "Option 2", "option: ui.text equals");
                equal(ui.extraParameters, "test parameter", "option: ui.extraParameters equals");
            }
        })
        .bind("multiselectclick", function(e,ui){
            ok(true, 'event: triggering the click event on the second checkbox triggers multiselectclick');
            equal(this, el[0], 'event: context of event');
            equal(ui.value, "2", "event: ui.value equals");
            equal(ui.text, "Option 2", "event: ui.text equals");
            equal(ui.extraParameters, "test parameter", "option: ui.extraParameters equals");
        })
        .bind("change", function(e){
            if(times === 0){
                equal(el.val().join(), "2", "event: select element val() within the change event is correct" );
            } else {
                equal(el.val(), null, "event: select element val() within the change event is correct" );
            }

            times++;

            ok(true, "event: the select's change event fires");
        })
        .multiselect("open");

        // trigger a click event on the input with extra parameter
        var lastInput = menu().find("input").last();
        $(lastInput[0]).trigger('click', 'test parameter');

        // trigger once more.
        $(lastInput[0]).trigger('click', 'test parameter');

        // make sure it has focus
        equal(true, lastInput.is(":focus"), "The input has focus");

        // make sure menu isn't closed automatically
        equal(true, el.multiselect('isOpen'), 'menu stays open');

        el.multiselect("destroy").remove();
    });

    test("multiselectcheckall", function(){
        expect(10);

        // inject widget
        el = $('<select multiple><option value="1">Option 1</option><option value="2">Option 2</option></select>').appendTo(body);

        el.multiselect({
            checkAll: function(e,ui){
                ok( true, 'option: multiselect("checkAll") fires checkall callback' );
                equal(this, el[0], "option: context of callback");
                equal(e.type, 'multiselectcheckall', 'option: event type in callback');
                deepEqual(ui, {}, 'option: ui hash in callback');
            }
        })
        .bind("multiselectcheckall", function(e,ui){
            ok( true, 'event: multiselect("checkall") fires multiselectcheckall event' );
            equal(this, el[0], 'event: context of event');
            deepEqual(ui, {}, 'event: ui hash');
        })
        .bind("change", function(){
            ok(true, "event: the select's change event fires");
            equal( el.val().join(), "1,2", "event: select element val() within the change event is correct" );
        })
        .multiselect("open")
        .multiselect("checkAll");

        equal(menu().find("input").first().is(":focus"), true, "The first input has focus");

        el.multiselect("destroy").remove();
    });

    test("multiselectuncheckall", function(){
        expect(10);

        // inject widget
        el = $('<select multiple><option value="1">Option 1</option><option value="2">Option 2</option></select>').appendTo(body);

        el.multiselect({
            uncheckAll: function(e,ui){
                ok( true, 'option: multiselect("uncheckAll") fires uncheckall callback' );
                equal(this, el[0], "option: context of callback");
                equal(e.type, 'multiselectuncheckall', 'option: event type in callback');
                deepEqual(ui, {}, 'option: ui hash in callback');
            }
        })
        .bind("multiselectuncheckall", function(e,ui){
            ok( true, 'event: multiselect("uncheckall") fires multiselectuncheckall event' );
            equal(this, el[0], 'event: context of event');
            deepEqual(ui, {}, 'event: ui hash');
        })
        .bind("change", function(){
            ok(true, "event: the select's change event fires");
            equal( el.val(), null, "event: select element val() within the change event is correct" );
        })
        .multiselect("open")
        .multiselect("uncheckAll");

        equal(menu().find("input").first().is(":focus"), true, "The first input has focus");

        el.multiselect("destroy").remove();
    });

    test("multiselectbeforeoptgrouptoggle", function(){
        expect(10);

        // inject widget
        el = $('<select multiple><optgroup label="Set One"><option value="1">Option 1</option><option value="2">Option 2</option></optgroup></select>')
          .appendTo(body);

        el.bind("change", function(){
            ok(true, "the select's change event fires");
        })
        .multiselect({
            beforeoptgrouptoggle: function(e,ui){
                equal(this, el[0], "option: context of callback");
                equal(e.type, 'multiselectbeforeoptgrouptoggle', 'option: event type in callback');
                equal(ui.label, "Set One", 'option: ui.label equals');
                equal(ui.inputs.length, 2, 'option: number of inputs in the ui.inputs key');
            }
        })
        .bind("multiselectbeforeoptgrouptoggle", function(e,ui){
            ok( true, 'option: multiselect("uncheckall") fires multiselectuncheckall event' );
            equal(this, el[0], 'event: context of event');
            equal(ui.label, "Set One", 'event: ui.label equals');
            equal(ui.inputs.length, 2, 'event: number of inputs in the ui.inputs key');
        })
        .multiselect("open");

        menu().find("li.ui-multiselect-optgroup-label a").click();

        el.multiselect("destroy").remove();
        el = el.clone();

        // test return false preventing checkboxes from activating
        el.bind("change", function(){
            ok( true ); // should not fire
        }).multiselect({
            beforeoptgrouptoggle: function(){
                return false;
            },
            // if this fires the expected count will be off.  just a redundant way of checking that return false worked
            optgrouptoggle: function(){
                ok( true );
            }
        }).appendTo( body );

        var label = menu().find("li.ui-multiselect-optgroup-label a").click();
        equal( menu().find(":input:checked").length, 0, "when returning false inside the optgrouptoggle handler, no checkboxes are checked" );
        el.multiselect("destroy").remove();
    });

    test("multiselectoptgrouptoggle", function(){
        expect(12);

        // inject widget
        el = $('<select multiple><optgroup label="Set One"><option value="1">Option 1</option><option value="2">Option 2</option></optgroup></select>').appendTo(body);

        el.multiselect({
            optgrouptoggle: function(e,ui){
                equal(this, el[0], "option: context of callback");
                equal(e.type, 'multiselectoptgrouptoggle', 'option: event type in callback');
                equal(ui.label, "Set One", 'option: ui.label equals');
                equal(ui.inputs.length, 2, 'option: number of inputs in the ui.inputs key');
                equal(ui.checked, true, 'option: ui.checked equals true');
            }
        })
        .bind("multiselectoptgrouptoggle", function(e,ui){
            ok( true, 'option: multiselect("uncheckall") fires multiselectuncheckall event' );
            equal(this, el[0], 'event: context of event');
            equal(ui.label, "Set One", 'event: ui.label equals');
            equal(ui.inputs.length, 2, 'event: number of inputs in the ui.inputs key');
            equal(ui.checked, true, 'event: ui.checked equals true');
        })
        .multiselect("open");

        // trigger native click event on optgroup
        menu().find("li.ui-multiselect-optgroup-label a").click();
        equal(menu().find(":input:checked").length, 2, "both checkboxes are actually checked" );

        equal(menu().find("input").first().is(":focus"), true, "The first input has focus");

        el.multiselect("destroy").remove();
    });

})(jQuery);


text:
package org.apache.maven.continuum.web.action;

import org.apache.continuum.builder.distributed.manager.DistributedBuildManager;
import org.apache.continuum.configuration.BuildAgentConfiguration;
import org.apache.continuum.configuration.BuildAgentGroupConfiguration;
import org.apache.continuum.web.action.AbstractActionTest;
import org.apache.continuum.web.action.admin.BuildAgentAction;
import org.apache.maven.continuum.Continuum;
import org.apache.maven.continuum.configuration.ConfigurationService;
import org.junit.Before;
import org.junit.Test;

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

import static org.mockito.Mockito.*;

public class BuildAgentActionTest
    extends AbstractActionTest
{
    private BuildAgentAction action;

    private Continuum continuum;

    private ConfigurationService configurationService;

    private DistributedBuildManager distributedBuildManager;

    private List<BuildAgentConfiguration> buildAgents;

    @Before
    public void setUp()
        throws Exception
    {
        continuum = mock( Continuum.class );
        configurationService = mock( ConfigurationService.class );
        distributedBuildManager = mock( DistributedBuildManager.class );

        action = new BuildAgentAction();
        action.setContinuum( continuum );

        buildAgents = new ArrayList<BuildAgentConfiguration>();
    }

    @Test
    public void testAddBuildAgent()
        throws Exception
    {
        when( continuum.getConfiguration() ).thenReturn( configurationService );
        when( configurationService.getBuildAgents() ).thenReturn( buildAgents );
        when( continuum.getDistributedBuildManager() ).thenReturn( distributedBuildManager );

        BuildAgentConfiguration buildAgent = new BuildAgentConfiguration();
        buildAgent.setUrl( "http://sample/agent" );
        action.setBuildAgent( buildAgent );
        action.save();

        verify( configurationService ).addBuildAgent( any( BuildAgentConfiguration.class ) );
        verify( configurationService ).store();
        verify( distributedBuildManager ).update( any( BuildAgentConfiguration.class ) );
    }

    @Test
    public void testDeleteBuildAgent()
        throws Exception
    {
        List<BuildAgentGroupConfiguration> buildAgentGroups = new ArrayList<BuildAgentGroupConfiguration>();

        when( continuum.getDistributedBuildManager() ).thenReturn( distributedBuildManager );
        when( distributedBuildManager.isBuildAgentBusy( anyString() ) ).thenReturn( false );
        when( continuum.getConfiguration() ).thenReturn( configurationService );
        when( configurationService.getBuildAgentGroups() ).thenReturn( buildAgentGroups );
        when( configurationService.getBuildAgents() ).thenReturn( buildAgents );

        BuildAgentConfiguration buildAgent = new BuildAgentConfiguration();
        buildAgent.setUrl( "http://sample/agent" );

        action.setConfirmed( true );
        action.setBuildAgent( buildAgent );
        action.delete();

        verify( distributedBuildManager, never() ).removeDistributedBuildQueueOfAgent( anyString() );
        verify( distributedBuildManager, never() ).reload();
        verify( configurationService, never() ).removeBuildAgent( any( BuildAgentConfiguration.class ) );
        verify( configurationService, never() ).store();
    }
}

redpajama_set_name: RedPajamaGithub


text:
// Type definitions for node-forge 0.10.0
// Project: https://github.com/digitalbazaar/forge
// Definitions by: Seth Westphal       <https://github.com/westy92>
//                 Kay Schecker        <https://github.com/flynetworks>
//                 Aakash Goenka       <https://github.com/a-k-g>
//                 Rafal2228           <https://github.com/rafal2228>
//                 Beeno Tung          <https://github.com/beenotung>
//                 Joe Flateau         <https://github.com/joeflateau>
//                 Nikita Koryabkin    <https://github.com/Apologiz>
//                 timhwang21          <https://github.com/timhwang21>
//                 supaiku0            <https://github.com/supaiku0>
//                 Anders Kaseorg      <https://github.com/andersk>
//                 Sascha Zarhuber     <https://github.com/saschazar21>
//                 Rogier Schouten     <https://github.com/rogierschouten>
//                 Ivan Aseev          <https://github.com/aseevia>
//                 Wiktor Kwapisiewicz <https://github.com/wiktor-k>
//                 Ligia Frangello     <https://github.com/frangello>
//                 Dmitry Avezov       <https://github.com/avezov>
//                 Jose Fuentes        <https://github.com/j-fuentes>
//                 Anya Reyes          <https://github.com/darkade>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.6

/// <reference types="node" />

declare module "node-forge" {
    type Byte = number;
    type Bytes = string;
    type Hex = string;
    type Base64 = string;
    type Utf8 = string;
    type OID = string;
    type Encoding = "raw" | "utf8";

    namespace jsbn {
        interface RandomGenerator {
            nextBytes(bytes: number[]): void;
        }
        class BigInteger {
            static ZERO: BigInteger;
            static ONE: BigInteger;
            constructor(a: null);
            constructor(a: number, c: RandomGenerator);
            constructor(a: number, b: number, c: RandomGenerator);
            constructor(a: string, b?: number);
            constructor(a: number[], b?: number);
            constructor(a: BigInteger);
            data: number[];
            t: number;
            s: number;
            am(i: number, x: number, w: BigInteger, j: number, c: number, n: number): number;
            toString(b?: number): string;
            bitLength(): number;
            negate(): BigInteger;
            abs(): BigInteger;
            compareTo(a: BigInteger): number;
            bitLength(): number;
            mod(a: BigInteger): BigInteger;
            modPowInt(e: number, m: BigInteger): BigInteger;
            clone(): BigInteger;
            intValue(): number;
            byteValue(): number;
            shortValue(): number;
            signum(): number;
            toByteArray(): number[];
            equals(a: BigInteger): boolean;
            min(a: BigInteger): BigInteger;
            max(a: BigInteger): BigInteger;
            and(a: BigInteger): BigInteger;
            or(a: BigInteger): BigInteger;
            xor(a: BigInteger): BigInteger;
            andNot(a: BigInteger): BigInteger;
            not(): BigInteger;
            shiftLeft(n: number): BigInteger;
            shiftRight(n: number): BigInteger;
            getLowestSetBit(): number;
            bitCount(): number;
            testBit(n: number): boolean;
            clearBit(n: number): BigInteger
            flipBit(n: number): BigInteger
            add(a: BigInteger): BigInteger;
            subtract(a: BigInteger): BigInteger;
            multiply(a: BigInteger): BigInteger;
            square(): BigInteger;
            divide(a: BigInteger): BigInteger;
            remainder(a: BigInteger): BigInteger;
            divideAndRemainder(a: BigInteger): BigInteger[]; // Array of 2 items
            pow(e: number): BigInteger;
            modPow(e: BigInteger, m: BigInteger): BigInteger;
            gcd(a: BigInteger): BigInteger;
            modInverse(m: BigInteger): BigInteger;
            isProbablePrime(t: number): boolean;
        }
    }

    namespace pem {

        interface EncodeOptions {
            maxline?: number | undefined;
        }

        interface ObjectPEM {
            type: string;
            body: Bytes;
            procType?: any;
            contentDomain?: any;
            dekInfo?: any;
            headers?: any[] | undefined;
        }

        function encode(msg: ObjectPEM, options?: EncodeOptions): string;
        function decode(str: string): ObjectPEM[];
    }

    namespace pki {
        type PEM = string;
        type PublicKey = rsa.PublicKey | ed25519.Key;
        type PrivateKey = rsa.PrivateKey | ed25519.Key;
        type EncryptionOptions = {
            algorithm?: 'aes128' | 'aes192' | 'aes256' | '3des' | undefined;
            count?: number | undefined;
            saltSize?: number | undefined;
            prfAlgorithm?: 'sha1' | 'sha224' | 'sha256' | 'sha384' | 'sha512' | undefined;
            legacy?: boolean | undefined;
        };

        interface ByteBufferFingerprintOptions {
            /**
             * @description The type of fingerprint. If not specified, defaults to 'RSAPublicKey'
             */
            type?: 'SubjectPublicKeyInfo' | 'RSAPublicKey' | undefined;
            /**
             * @description the delimiter to use between bytes for `hex` encoded output
             */
            delimiter?: string | undefined;
            /**
             * @description if not specified defaults to `md.md5`
             */
            md?: md.MessageDigest | undefined;
        }

        interface HexFingerprintOptions extends ByteBufferFingerprintOptions {
            /**
             * @description if not specified, the function will return `ByteStringBuffer`
             */
            encoding: 'hex';
        }

        interface BinaryFingerprintOptions extends ByteBufferFingerprintOptions {
            /**
             * @description if not specified, the function will return `ByteStringBuffer`
             */
            encoding: 'binary';
        }

        interface KeyPair {
            publicKey: PublicKey;
            privateKey: PrivateKey;
        }

        interface oids {
            [key: string]: string;
        }
        var oids: oids;

        namespace rsa {
            type EncryptionScheme = 'RSAES-PKCS1-V1_5' | 'RSA-OAEP' | 'RAW' | 'NONE' | null;
            type SignatureScheme = 'RSASSA-PKCS1-V1_5' | pss.PSS | 'NONE' | null;

            interface PublicKey {
                n: jsbn.BigInteger;
                e: jsbn.BigInteger;
                encrypt(data: Bytes, scheme?: EncryptionScheme, schemeOptions?: any): Bytes;
                verify(digest: Bytes, signature: Bytes, scheme?: SignatureScheme): boolean;
            }

            interface PrivateKey {
                n: jsbn.BigInteger;
                e: jsbn.BigInteger;
                d: jsbn.BigInteger;
                p: jsbn.BigInteger;
                q: jsbn.BigInteger;
                dP: jsbn.BigInteger;
                dQ: jsbn.BigInteger;
                qInv: jsbn.BigInteger;
                decrypt(data: Bytes, scheme?: EncryptionScheme, schemeOptions?: any): Bytes;
                sign(md: md.MessageDigest, scheme?: SignatureScheme): Bytes;
            }

            interface KeyPair {
                publicKey: PublicKey;
                privateKey: PrivateKey;
            }

            interface GenerateKeyPairOptions {
                bits?: number | undefined;
                e?: number | undefined;
                workerScript?: string | undefined;
                workers?: number | undefined;
                workLoad?: number | undefined;
                prng?: any;
                algorithm?: string | undefined;
            }

            function setPublicKey(n: jsbn.BigInteger, e: jsbn.BigInteger): PublicKey;

            function generateKeyPair(bits?: number, e?: number, callback?: (err: Error, keypair: KeyPair) => void): KeyPair;
            function generateKeyPair(options?: GenerateKeyPairOptions, callback?: (err: Error, keypair: KeyPair) => void): KeyPair;
        }

        namespace ed25519 {
            type NativeBuffer = Buffer | Uint8Array;
            type Key = NativeBuffer;

            type ToNativeBufferParameters = {
                message: NativeBuffer | util.ByteBuffer
            } | {
                message: string;
                encoding: 'binary' | 'utf8';
            };

            // `string`s will be converted by toNativeBuffer with `encoding: 'binary'`
            type BinaryBuffer = NativeBuffer | util.ByteBuffer | string;

            namespace constants {
                const PUBLIC_KEY_BYTE_LENGTH = 32;
                const PRIVATE_KEY_BYTE_LENGTH = 64;
                const SEED_BYTE_LENGTH = 32;
                const SIGN_BYTE_LENGTH = 64;
                const HASH_BYTE_LENGTH = 64;
            }

            // generateKeyPair does not currently accept `util.ByteBuffer` as the seed.
            function generateKeyPair(options?: { seed?: NativeBuffer | string | undefined }): {
                publicKey: NativeBuffer;
                privateKey: NativeBuffer;
            };

            function publicKeyFromPrivateKey(options: { privateKey: BinaryBuffer }): NativeBuffer;

            function sign(options: ToNativeBufferParameters & {
                privateKey: BinaryBuffer
            }): NativeBuffer;

            function verify(options: ToNativeBufferParameters & {
                signature: BinaryBuffer,
                publicKey: BinaryBuffer
            }): boolean;
        }

        interface CertificateFieldOptions {
            name?: string | undefined;
            type?: string | undefined;
            shortName?: string | undefined;
        }

        interface CertificateField extends CertificateFieldOptions {
            valueConstructed?: boolean | undefined;
            valueTagClass?: asn1.Class | undefined;
            value?: any[] | string | undefined;
            extensions?: any[] | undefined;
        }

        interface Certificate {
            version: number;
            serialNumber: string;
            signature: any;
            siginfo: any;
            validity: {
                notBefore: Date;
                notAfter: Date;
            };
            issuer: {
                getField(sn: string | CertificateFieldOptions): any;
                addField(attr: CertificateField): void;
                attributes: any[];
                hash: any;
            };
            subject: {
                getField(sn: string | CertificateFieldOptions): any;
                addField(attr: CertificateField): void;
                attributes: any[];
                hash: any;
            };
            extensions: any[];
            privateKey: PrivateKey;
            publicKey: PublicKey;
            md: any;
            /**
             * Sets the subject of this certificate.
             *
             * @param attrs the array of subject attributes to use.
             * @param uniqueId an optional a unique ID to use.
             */
            setSubject(attrs: CertificateField[], uniqueId?: string): void;
            /**
              * Sets the issuer of this certificate.
              *
              * @param attrs the array of subject attributes to use.
              * @param uniqueId an optional a unique ID to use.
              */
            setIssuer(attrs: CertificateField[], uniqueId?: string): void;
            /**
              * Sets the extensions of this certificate.
              *
              * @param exts the array of extensions to use.
              */
            setExtensions(exts: any[]): void;
            /**
             * Gets an extension by its name or id.
             *
             * @param options the name to use or an object with:
             *          name the name to use.
             *          id the id to use.
             *
             * @return the extension or null if not found.
             */
            getExtension(options: string | {name: string;} | {id: number;}): {} | undefined;

            /**
             * Signs this certificate using the given private key.
             *
             * @param key the private key to sign with.
             * @param md the message digest object to use (defaults to forge.md.sha1).
             */
            sign(key: pki.PrivateKey, md?: md.MessageDigest): void;
            /**
             * Attempts verify the signature on the passed certificate using this
             * certificate's public key.
             *
             * @param child the certificate to verify.
             *
             * @return true if verified, false if not.
             */
            verify(child: Certificate): boolean;

            /**
             * Gets an issuer or subject attribute from its name, type, or short name.
             *
             * @param options a short name string or an object with:
             *          shortName the short name for the attribute.
             *          name the name for the attribute.
             *          type the type for the attribute.
             *
             * @return the attribute.
             */
            getAttribute(opts: string | GetAttributeOpts): Attribute | null;

            /**
             * Returns true if this certificate's issuer matches the passed
             * certificate's subject. Note that no signature check is performed.
             *
             * @param parent the certificate to check.
             *
             * @return true if this certificate's issuer matches the passed certificate's
             *         subject.
             */
            isIssuer(parent: Certificate): boolean;

            /**
             * Returns true if this certificate's subject matches the issuer of the
             * given certificate). Note that not signature check is performed.
             *
             * @param child the certificate to check.
             *
             * @return true if this certificate's subject matches the passed
             *         certificate's issuer.
             */
            issued(child: Certificate): boolean;
        }

        /**
         * Attribute members to search on; any one hit will return the attribute
         */
        interface GetAttributeOpts {
            /**
             * OID
             */
            type?: string | undefined;
            /**
             * Long name
             */
            name?: string | undefined;
            /**
             * Short name
             */
            shortName?: string | undefined;
        }

        interface Attribute {
            /**
             * e.g. challengePassword
             */
            name: string;
            /**
             * Short name, if available (e.g. 'CN' for 'commonName')
             */
            shortName?: string | undefined;
            /**
             * OID, e.g. '1.2.840.113549.1.9.7'
             */
            type: string;
            /**
             * Attribute value
             */
            value: any;
            /**
             * Attribute value data type
             */
            valueTagClass: number;
            /**
             * Extensions
             */
            extensions?: any[] | undefined
        }

        interface CAStore {
            addCertificate(cert: Certificate | string): void;
            hasCertificate(cert: Certificate | string): boolean;
            removeCertificate(cert: Certificate | string): Certificate | null;
            listAllCertificates(): pki.Certificate[];
            getIssuer(subject: Certificate): Certificate | null;
            getBySubject(subject: string): Certificate | null;
        }

        function certificateFromAsn1(obj: asn1.Asn1, computeHash?: boolean): Certificate;

        function certificationRequestFromAsn1(obj: asn1.Asn1, computeHash?: boolean): Certificate;

        function certificateToAsn1(cert: Certificate): asn1.Asn1;

        function certificationRequestToAsn1(cert: Certificate): asn1.Asn1;

        function decryptRsaPrivateKey(pem: PEM, passphrase?: string): rsa.PrivateKey;

        function createCertificate(): Certificate;

        function certificationRequestToPem(cert: Certificate, maxline?: number): PEM;

        function certificationRequestFromPem(pem: PEM, computeHash?: boolean, strict?: boolean): Certificate;

        function createCertificationRequest(): Certificate;

        function certificateToPem(cert: Certificate, maxline?: number): PEM;

        function certificateFromPem(pem: PEM, computeHash?: boolean, strict?: boolean): Certificate;

        function createCaStore(certs?: ReadonlyArray<Certificate | pki.PEM>): CAStore;

        function verifyCertificateChain(
            caStore: CAStore,
            chain: Certificate[],
            options?: ((verified: boolean | string, depth: number, certs: Certificate[]) => boolean) | {
                verify?: ((verified: boolean | string, depth: number, certs: Certificate[]) => boolean) | undefined,
                validityCheckDate?: Date | null | undefined
            }): boolean;

        function pemToDer(pem: PEM): util.ByteStringBuffer;

        function privateKeyToPem(key: PrivateKey, maxline?: number): PEM;

        function privateKeyInfoToPem(key: asn1.Asn1, maxline?: number): PEM;

        function publicKeyToPem(key: PublicKey, maxline?: number): PEM;

        function publicKeyToRSAPublicKeyPem(key: PublicKey, maxline?: number): PEM;

        function publicKeyFromPem(pem: PEM): rsa.PublicKey;

        function privateKeyFromPem(pem: PEM): rsa.PrivateKey;

        function decryptPrivateKeyInfo(obj: asn1.Asn1, password: string): asn1.Asn1;

        function encryptPrivateKeyInfo(obj: asn1.Asn1, password: string, options?: EncryptionOptions): asn1.Asn1;

        function encryptedPrivateKeyFromPem(pem: PEM): asn1.Asn1;

        function encryptedPrivateKeyToPem(obj: asn1.Asn1): PEM;

        function decryptRsaPrivateKey(pem: PEM, password: string): rsa.PrivateKey;

        function encryptRsaPrivateKey(privateKey: PrivateKey, password: string, options?: EncryptionOptions): PEM;

        function privateKeyFromAsn1(privateKey: asn1.Asn1): PrivateKey;

        function privateKeyToAsn1(privateKey: PrivateKey): asn1.Asn1;

        function publicKeyFromAsn1(publicKey: asn1.Asn1): PublicKey;

        function publicKeyToAsn1(publicKey: PublicKey): asn1.Asn1;

        function publicKeyToRSAPublicKey(publicKey: PublicKey): any;

        type setRsaPublicKey = typeof rsa.setPublicKey;

        function wrapRsaPrivateKey(privateKey: asn1.Asn1): asn1.Asn1;

        function getPublicKeyFingerprint(publicKey: PublicKey, options?: ByteBufferFingerprintOptions): util.ByteStringBuffer;
        function getPublicKeyFingerprint(publicKey: PublicKey, options: HexFingerprintOptions): Hex;
        function getPublicKeyFingerprint(publicKey: PublicKey, options: BinaryFingerprintOptions): Bytes;
    }

    namespace random {
        function getBytes(count: number, callback?: (err: Error | null, bytes: Bytes) => any): Bytes;
        function getBytesSync(count: number): Bytes;
        type CB = (_: any, seed: string) => void;
        interface Random {
            seedFileSync: (needed: number) => string;
            seedFile: (needed: number, cb: CB) => void;
        }
        function createInstance(): Random;
    }

    namespace ssh {
        interface FingerprintOptions {
            /**
             * @description the delimiter to use between bytes for `hex` encoded output
             */
            delimiter?: string | undefined;
            /**
             * @description if not specified, the function will return `ByteStringBuffer`
             */
            encoding?: 'hex' | 'binary' | undefined;
            /**
             * @description if not specified defaults to `md.md5`
             */
            md?: md.MessageDigest | undefined;
        }

        /**
         * @description Encodes a private RSA key as an OpenSSH file
         */
        function privateKeyToOpenSSH(privateKey: pki.PrivateKey, passphrase?: string): string;

        /**
         * @description Encodes (and optionally encrypts) a private RSA key as a Putty PPK file
         */
        function privateKeyToPutty(privateKey: pki.PrivateKey, passphrase?: string, comment?: string): string;

        /**
         * @description Encodes a public RSA key as an OpenSSH file
         */
        function publicKeyToOpenSSH(publicKey: pki.PublicKey, comment?: string): string | pki.PEM;

        /**
         * @description Gets the SSH fingerprint for the given public key
         */
        function getPublicKeyFingerprint(publicKey: pki.PublicKey, options?: FingerprintOptions): util.ByteStringBuffer | Hex | string;
    }

    namespace asn1 {
        enum Class {
            UNIVERSAL = 0x00,
            APPLICATION = 0x40,
            CONTEXT_SPECIFIC = 0x80,
            PRIVATE = 0xC0,
        }

        enum Type {
            NONE = 0,
            BOOLEAN = 1,
            INTEGER = 2,
            BITSTRING = 3,
            OCTETSTRING = 4,
            NULL = 5,
            OID = 6,
            ODESC = 7,
            EXTERNAL = 8,
            REAL = 9,
            ENUMERATED = 10,
            EMBEDDED = 11,
            UTF8 = 12,
            ROID = 13,
            SEQUENCE = 16,
            SET = 17,
            PRINTABLESTRING = 19,
            IA5STRING = 22,
            UTCTIME = 23,
            GENERALIZEDTIME = 24,
            BMPSTRING = 30,
        }

        interface Asn1 {
            tagClass: Class;
            type: Type;
            constructed: boolean;
            composed: boolean;
            value: Bytes | Asn1[];
        }

        function create(tagClass: Class, type: Type, constructed: boolean, value: Bytes | Asn1[]): Asn1;
        function fromDer(bytes: Bytes | util.ByteBuffer, strict?: boolean): Asn1;
        function toDer(obj: Asn1): util.ByteBuffer;
        function oidToDer(oid: OID): util.ByteStringBuffer;
        function derToOid(der: util.ByteStringBuffer): OID;
    }

    namespace util {
        function isArray(x: any): boolean;
        function isArrayBuffer(x: any): boolean;
        function isArrayBufferView(x: any): boolean;

        interface ArrayBufferView {
            buffer: ArrayBuffer;
            byteLength: number;
        }

        type ByteBuffer = ByteStringBuffer;
        class ByteStringBuffer {
            constructor(bytes?: Bytes | ArrayBuffer | ArrayBufferView | ByteStringBuffer);
            data: string;
            read: number;
            length(): number;
            isEmpty(): boolean;
            putByte(byte: Byte): ByteStringBuffer;
            fillWithByte(byte: Byte, n: number): ByteStringBuffer;
            putBytes(bytes: Bytes): ByteStringBuffer;
            putString(str: string): ByteStringBuffer;
            putInt16(int: number): ByteStringBuffer;
            putInt24(int: number): ByteStringBuffer;
            putInt32(int: number): ByteStringBuffer;
            putInt16Le(int: number): ByteStringBuffer;
            putInt24Le(int: number): ByteStringBuffer;
            putInt32Le(int: number): ByteStringBuffer;
            putInt(int: number, numOfBits: number): ByteStringBuffer;
            putSignedInt(int: number, numOfBits: number): ByteStringBuffer;
            putBuffer(buffer: ByteStringBuffer): ByteStringBuffer;
            getByte(): number;
            getInt16(): number;
            getInt24(): number;
            getInt32(): number;
            getInt16Le(): number;
            getInt24Le(): number;
            getInt32Le(): number;
            getInt(numOfBits: number): number;
            getSignedInt(numOfBits: number): number;
            getBytes(count?: number): Bytes;
            bytes(count?: number): Bytes;
            at(index: number): Byte;
            setAt(index: number, byte: number): ByteStringBuffer;
            last(): Byte;
            copy(): ByteStringBuffer;
            compact(): ByteStringBuffer;
            clear(): ByteStringBuffer;
            truncate(): ByteStringBuffer;
            toHex(): Hex;
            toString(): string;
        }

        function fillString(char: string, count: number): string;
        function xorBytes(bytes1: string, bytes2: string, count: number): string;
        function hexToBytes(hex: Hex): Bytes;
        function bytesToHex(bytes: Bytes): Hex;
        function int32ToBytes(int: number): Bytes;
        function encode64(bytes: Bytes, maxline?: number): Base64;
        function decode64(encoded: Base64): Bytes;
        function encodeUtf8(str: string): Utf8;
        function decodeUtf8(encoded: Utf8): string;

        function createBuffer(): ByteBuffer;
        function createBuffer(input: Bytes | ArrayBuffer | ArrayBufferView | ByteStringBuffer, encoding?: Encoding): ByteBuffer;

        namespace binary {
            namespace raw {
                function encode(x: Uint8Array): Bytes;
                function decode(str: Bytes, output?: Uint8Array, offset?: number): Uint8Array;
            }
            namespace hex {
                function encode(bytes: Bytes | ArrayBuffer | ArrayBufferView | ByteStringBuffer): Hex;
                function decode(hex: Hex, output?: Uint8Array, offset?: number): Uint8Array;
            }
            namespace base64 {
                function encode(input: Uint8Array, maxline?: number): Base64;
                function decode(input: Base64, output?: Uint8Array, offset?: number): Uint8Array;
            }
        }

        namespace text {
            namespace utf8 {
                function encode(str: string, output?: Uint8Array, offset?: number): Uint8Array;
                function decode(bytes: Uint8Array): Utf8;
            }
            namespace utf16 {
                function encode(str: string, output?: Uint8Array, offset?: number): Uint8Array;
                function decode(bytes: Uint8Array): string;
            }
        }
    }

    namespace pkcs12 {

        interface BagsFilter {
            localKeyId?: string | undefined;
            localKeyIdHex?: string | undefined;
            friendlyName?: string | undefined;
            bagType?: string | undefined;
        }

        interface Bag {
            type: string;
            attributes: any;
            key?: pki.PrivateKey | undefined;
            cert?: pki.Certificate | undefined;
            asn1: asn1.Asn1
        }

        interface Pkcs12Pfx {
            version: string;
            safeContents: {
                encrypted: boolean;
                safeBags: Bag[];
            }[];
            getBags: (filter: BagsFilter) => {
                [key: string]: Bag[] | undefined;
                localKeyId?: Bag[] | undefined;
                friendlyName?: Bag[] | undefined;
            };
            getBagsByFriendlyName: (fiendlyName: string, bagType: string) => Bag[]
            getBagsByLocalKeyId: (localKeyId: string, bagType: string) => Bag[]
        }

        function pkcs12FromAsn1(obj: any, strict?: boolean, password?: string): Pkcs12Pfx;
        function pkcs12FromAsn1(obj: any, password?: string): Pkcs12Pfx;

        function toPkcs12Asn1(
            key: pki.PrivateKey,
            cert: pki.Certificate | pki.Certificate[],
            password: string | null,
            options?: {
                algorithm?: 'aes128' | 'aes192' | 'aes256' | '3des' | undefined,
                count?: number | undefined,
                saltSize?: number | undefined,
                useMac?: boolean | undefined,
                localKeyId?: Hex | undefined,
                friendlyName?: string | undefined,
                generateLocalKeyId?: boolean | undefined,
            },
        ): asn1.Asn1;

        function generateKey(
            password: string | null | undefined,
            salt: util.ByteBuffer,
            id: Byte,
            iter: number,
            n: number,
            md?: md.MessageDigest,
        ): util.ByteBuffer;
    }

    namespace pkcs7 {
        interface PkcsSignedData {
            content?: string | util.ByteBuffer | undefined;
            contentInfo?: { value: any[] } | undefined;

            certificates: pki.Certificate[];

            addCertificate(certificate: pki.Certificate | string): void;
            addSigner(options: {
                key: pki.rsa.PrivateKey | string;
                certificate: pki.Certificate | string;
                digestAlgorithm: string;
                authenticatedAttributes?: { type: string; value?: string | undefined }[] | undefined;
            }): void;
            sign(options?:{
                detached?: boolean | undefined
            }): void;
            toAsn1(): asn1.Asn1;
        }

        function createSignedData(): PkcsSignedData;

        interface PkcsEnvelopedData {
            content?: string | util.ByteBuffer | undefined;
            addRecipient(certificate: pki.Certificate): void;
            encrypt(): void;
            toAsn1(): asn1.Asn1;
        }

        function createEnvelopedData(): PkcsEnvelopedData;

        function messageToPem(msg: PkcsSignedData, maxline?: number): string;

        function messageFromPem(pem: pki.PEM): PkcsEnvelopedData | PkcsSignedData;
    }

    namespace pkcs5 {
        function pbkdf2(password: string, salt: string, iterations: number, keySize: number): string;
        function pbkdf2(password: string, salt: string, iterations: number, keySize: number, messageDigest: md.MessageDigest): string;
        function pbkdf2(password: string, salt: string, iterations: number, keySize: number, callback: (err: Error | null, dk: string | null) => any): void;
        function pbkdf2(password: string, salt: string, iterations: number, keySize: number, messageDigest?: md.MessageDigest, callback?: (err: Error | null, dk: string | null) => any): void;
    }

    namespace md {

        interface MessageDigest {
            update(msg: string, encoding?: Encoding): MessageDigest;
            digest(): util.ByteStringBuffer;
        }

        namespace sha1 {
            function create(): MessageDigest;
        }

        namespace sha256 {
            function create(): MessageDigest;
        }

        namespace sha384 {
            function create(): MessageDigest;
        }

        namespace sha512 {
            function create(): MessageDigest;
        }

        namespace md5 {
            function create(): MessageDigest;
        }

        namespace hmac {
        }
    }

    namespace hmac {

      type Algorithm = "sha1" | "md5" | "sha256" | "sha512";

      interface HMAC {
          digest(): util.ByteBuffer;
          getMact(): util.ByteBuffer;
          start(md: Algorithm, key: string | util.ByteBuffer | null): void;
          update(bytes: string | util.ByteBuffer | Buffer): void;
      }

      function create(): HMAC;
    }

    namespace cipher {

        type Algorithm = "AES-ECB" | "AES-CBC" | "AES-CFB" | "AES-OFB" | "AES-CTR" | "AES-GCM" | "3DES-ECB" | "3DES-CBC" | "DES-ECB" | "DES-CBC";

        function createCipher(algorithm: Algorithm, payload: util.ByteBuffer | Bytes): BlockCipher;
        function createDecipher(algorithm: Algorithm, payload: util.ByteBuffer | Bytes): BlockCipher;

        interface StartOptions {
            iv?: util.ByteBuffer | Byte[] | Bytes | undefined;
            tag?: util.ByteStringBuffer | undefined;
            tagLength?: number | undefined;
            additionalData?: string | undefined;
        }

        interface BlockCipher {
            start: (options?: StartOptions) => void;
            update: (payload: util.ByteBuffer) => void;
            finish: () => boolean;
            output: util.ByteStringBuffer;
            mode: Mode;
        }

        interface Mode {
            tag: util.ByteStringBuffer;
        }
    }

    namespace pss {
        type PSS = any;

        function create(any: any): PSS;
    }

    namespace mgf {
        namespace mgf1 {
            function create(any: any): any;
        }
    }

    namespace tls {
        interface ProtocolVersion {
            major: Byte;
            minor: Byte;
        }

        const Versions: ProtocolVersion[];
        const SupportedVersions: ProtocolVersion[];
        const Version: ProtocolVersion;

        const MaxFragment: number;

        enum ConnectionEnd {
            server = 0,
            client = 1,
        }

        enum PRFAlgorithm {
            tls_prf_sha256 = 0,
        }

        enum BulkCipherAlgorithm {
            rc4 = 0,
            des3 = 1,
            aes = 2,
        }

        enum CipherType {
            stream = 0,
            block = 1,
            aead = 2,
        }

        enum MACAlgorithm {
            hmac_md5 = 0,
            hmac_sha1 = 1,
            hmac_sha256 = 2,
            hmac_sha384 = 3,
            hmac_sha512 = 4,
        }

        enum CompressionMethod {
            none = 0,
            deflate = 1,
        }

        enum ContentType {
            change_cipher_spec = 20,
            alert = 21,
            handshake = 22,
            application_data = 23,
            heartbeat = 24,
        }

        enum HandshakeType {
            hello_request = 0,
            client_hello = 1,
            server_hello = 2,
            certificate = 11,
            server_key_exchange = 12,
            certificate_request = 13,
            server_hello_done = 14,
            certificate_verify = 15,
            client_key_exchange = 16,
            finished = 20,
        }

        namespace Alert {
            enum Level {
                warning = 1,
                fatal = 2,
            }

            enum Description {
                close_notify = 0,
                unexpected_message = 10,
                bad_record_mac = 20,
                decryption_failed = 21,
                record_overflow = 22,
                decompression_failure = 30,
                handshake_failure = 40,
                bad_certificate = 42,
                unsupported_certificate = 43,
                certificate_revoked = 44,
                certificate_expired = 45,
                certificate_unknown = 46,
                illegal_parameter = 47,
                unknown_ca = 48,
                access_denied = 49,
                decode_error = 50,
                decrypt_error = 51,
                export_restriction = 60,
                protocol_version = 70,
                insufficient_security = 71,
                internal_error = 80,
                user_canceled = 90,
                no_renegotiation = 100,
            }
        }

        enum HeartbeatMessageType {
            heartbeat_request = 1,
            heartbeat_response = 2,
        }

        interface CipherSuite {
            id: [Byte, Byte];
            name: string;
        }

        const CipherSuites: { [name: string]: CipherSuite };

        interface CertificateRequest {
            certificate_types: util.ByteBuffer;
            certificate_authorities: util.ByteBuffer;
        }

        type ConnectionState = any;

        interface Connection {
            version: ProtocolVersion;
            entity: ConnectionEnd;
            sessionId: Bytes | null;
            caStore: pki.CAStore;
            sessionCache: SessionCache | null;
            cipherSuites: CipherSuite[];
            connected(conn: Connection): void;
            virtualHost: string | null;
            verifyClient: boolean;
            verify(
                conn: Connection,
                verified: Verified,
                depth: number,
                certs: pki.Certificate[]
            ): Verified;
            getCertificate:
                | ((
                      conn: Connection,
                      hint: CertificateRequest | string[]
                  ) => pki.PEM | ReadonlyArray<pki.PEM>)
                | null;
            getPrivateKey:
                | ((conn: Connection, certificate: pki.Certificate) => pki.PEM)
                | null;
            getSignature:
                | ((
                      conn: Connection,
                      bytes: Bytes,
                      callback: (conn: Connection, bytes: Bytes) => void
                  ) => void)
                | null;
            input: util.ByteBuffer;
            tlsData: util.ByteBuffer;
            data: util.ByteBuffer;
            tlsDataReady(conn: Connection): void;
            dataReady(conn: Connection): void;
            heartbeatReceived:
                | ((conn: Connection, payload: util.ByteBuffer) => void)
                | undefined;
            closed(conn: Connection): void;
            error(conn: Connection, error: TLSError): void;
            deflate: ((inBytes: Bytes) => Bytes) | null;
            inflate: ((inBytes: Bytes) => Bytes) | null;
            reset(clearFail?: boolean): void;
            record: Record | null;
            session: Session | null;
            peerCertificate: pki.Certificate | null;
            state: { pending: ConnectionState | null; current: ConnectionState };
            expect: number;
            fragmented: Record | null;
            records: Record[];
            open: boolean;
            handshakes: number;
            handshaking: boolean;
            isConnected: boolean;
            fail: boolean;
            handshake(sessionId?: Bytes | null): void;
            process(data: Bytes): number;
            prepare(data: Bytes): boolean;
            prepareHeartbeatRequest(
                payload: Bytes | util.ByteBuffer,
                payloadLength?: number
            ): boolean;
            close(clearFail?: boolean): Connection;
        }

        interface Record {
            type: ContentType;
            version: ProtocolVersion;
            length: number;
            fragment: util.ByteBuffer;
            ready?: boolean | undefined;
        }

        interface Session {
            version: ProtocolVersion | null;
            extensions: { [_: string]: object };
            cipherSuite: CipherSuite | null;
            compressionMethod: CompressionMethod | null;
            serverCertificate: pki.Certificate | null;
            clientCertificate: pki.Certificate | null;
            md5: md.MessageDigest;
            sha1: md.MessageDigest;
        }

        interface SessionCache {
            cache: { [key: string]: Session };
            capacity: number;
            order: [Hex];
            getSession(sessionId: Bytes): Session;
            setSession(sessionId: Bytes, session: Session): void;
        }

        function createSessionCache(
            cache?: SessionCache | { [key: string]: Session },
            capacity?: number
        ): SessionCache;

        interface Alert {
            level: Alert.Level;
            description: Alert.Description;
        }

        interface TLSError extends Error {
            message: string;
            send: boolean;
            origin: "server" | "client";
            alert: Alert;
        }

        type Verified = true | { message?: string | undefined; alert?: Alert.Description | undefined };

        function createConnection(options: {
            server?: boolean | undefined;
            sessionId?: Bytes | null | undefined;
            caStore?: pki.CAStore | ReadonlyArray<pki.Certificate> | undefined;
            sessionCache?: SessionCache | { [key: string]: Session } | undefined;
            cipherSuites?: CipherSuite[] | undefined;
            connected(conn: Connection): void;
            virtualHost?: string | undefined;
            verifyClient?: boolean | undefined;
            verify?(
                conn: Connection,
                verified: Verified,
                depth: number,
                certs: pki.Certificate[]
            ): Verified;
            getCertificate?(
                conn: Connection,
                hint: CertificateRequest | string[]
            ): pki.PEM | ReadonlyArray<pki.PEM>;
            getPrivateKey?(conn: Connection, certificate: pki.Certificate): pki.PEM;
            getSignature?(
                conn: Connection,
                bytes: Bytes,
                callback: (conn: Connection, bytes: Bytes) => void
            ): void;
            tlsDataReady(conn: Connection): void;
            dataReady(conn: Connection): void;
            heartbeatReceived?(conn: Connection, payload: util.ByteBuffer): void;
            closed(conn: Connection): void;
            error(conn: Connection, error: TLSError): void;
            deflate?(inBytes: Bytes): Bytes;
            inflate?(inBytes: Bytes): Bytes;
        }): Connection;

        function prf_tls1(
            secret: string,
            label: string,
            seed: string,
            length: number
        ): util.ByteBuffer;

        function hmac_sha1(
            key: string | ReadonlyArray<Byte> | util.ByteBuffer,
            seqNum: [number, number],
            record: Record
        ): Bytes;
    }
}


text:
import { TransactWriteItem, Converter } from 'aws-sdk/clients/dynamodb';
import { TransactMethod } from '../transact-method';
import { InsertItem } from '../../insert-item';

export class TransactInsertItem extends TransactMethod {
	constructor(
		private readonly query: InsertItem
	) {
		super();
	}

	/**
	 * Builds and returns the raw DynamoDB query object.
	 */
	buildRawQuery(): TransactWriteItem {
		const result = this.query.buildRawQuery();

		return {
			Update: {
				TableName: result.TableName,
				Key: Converter.marshall(result.Key),
				ConditionExpression: result.ConditionExpression,
				UpdateExpression: result.UpdateExpression !,
				ExpressionAttributeNames: result.ExpressionAttributeNames,
				ExpressionAttributeValues: result.ExpressionAttributeValues ? Converter.marshall(result.ExpressionAttributeValues) : undefined
			}
		};
	}
}


text:
class ChangeDataFormatInMicropost < ActiveRecord::Migration
  def change
    change_table :microposts do |t|
      t.change :content, :text
    end
  end
end


text:
package org.onosproject.codec;

import java.util.Set;

/**
 * Service for registering and retrieving JSON codecs for various entities.
 */
public interface CodecService {

    /**
     * Returns the set of classes with currently registered codecs.
     *
     * @return set of entity classes
     */
    Set<Class<?>> getCodecs();

    /**
     * Returns the JSON codec for the specified entity class.
     *
     * @param entityClass entity class
     * @param <T>         entity type
     * @return JSON codec; null if no codec available for the class
     */
    <T> JsonCodec<T> getCodec(Class<T> entityClass);

    /**
     * Registers the specified JSON codec for the given entity class.
     *
     * @param entityClass entity class
     * @param codec       JSON codec
     * @param <T>         entity type
     */
    <T> void registerCodec(Class<T> entityClass, JsonCodec<T> codec);

    /**
     * Unregisters the JSON codec for the specified entity class.
     *
     * @param entityClass entity class
     */
    void unregisterCodec(Class<?> entityClass);

}


text:
package aws_ebs

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

	"github.com/golang/glog"
	"k8s.io/kubernetes/pkg/cloudprovider"
	"k8s.io/kubernetes/pkg/cloudprovider/providers/aws"
	"k8s.io/kubernetes/pkg/util/keymutex"
	"k8s.io/kubernetes/pkg/util/runtime"
	"k8s.io/kubernetes/pkg/util/sets"
	"k8s.io/kubernetes/pkg/volume"
)

const (
	diskPartitionSuffix = ""
	diskXVDPath         = "/dev/xvd"
	diskXVDPattern      = "/dev/xvd*"
	maxChecks           = 60
	maxRetries          = 10
	checkSleepDuration  = time.Second
	errorSleepDuration  = 5 * time.Second
)

// Singleton key mutex for keeping attach/detach operations for the same PD atomic
var attachDetachMutex = keymutex.NewKeyMutex()

type AWSDiskUtil struct{}

// Attaches a disk to the current kubelet.
// Mounts the disk to it's global path.
func (diskUtil *AWSDiskUtil) AttachAndMountDisk(b *awsElasticBlockStoreBuilder, globalPDPath string) error {
	glog.V(5).Infof("AttachAndMountDisk(...) called for PD %q. Will block for existing operations, if any. (globalPDPath=%q)\r\n", b.volumeID, globalPDPath)

	// Block execution until any pending detach operations for this PD have completed
	attachDetachMutex.LockKey(b.volumeID)
	defer attachDetachMutex.UnlockKey(b.volumeID)

	glog.V(5).Infof("AttachAndMountDisk(...) called for PD %q. Awake and ready to execute. (globalPDPath=%q)\r\n", b.volumeID, globalPDPath)

	xvdBefore, err := filepath.Glob(diskXVDPattern)
	if err != nil {
		glog.Errorf("Error filepath.Glob(\"%s\"): %v\r\n", diskXVDPattern, err)
	}
	xvdBeforeSet := sets.NewString(xvdBefore...)

	devicePath, err := attachDiskAndVerify(b, xvdBeforeSet)
	if err != nil {
		return err
	}

	// Only mount the PD globally once.
	notMnt, err := b.mounter.IsLikelyNotMountPoint(globalPDPath)
	if err != nil {
		if os.IsNotExist(err) {
			if err := os.MkdirAll(globalPDPath, 0750); err != nil {
				return err
			}
			notMnt = true
		} else {
			return err
		}
	}
	options := []string{}
	if b.readOnly {
		options = append(options, "ro")
	}
	if notMnt {
		err = b.diskMounter.FormatAndMount(devicePath, globalPDPath, b.fsType, options)
		if err != nil {
			os.Remove(globalPDPath)
			return err
		}
	}
	return nil
}

// Unmounts the device and detaches the disk from the kubelet's host machine.
func (util *AWSDiskUtil) DetachDisk(c *awsElasticBlockStoreCleaner) error {
	glog.V(5).Infof("DetachDisk(...) for PD %q\r\n", c.volumeID)

	if err := unmountPDAndRemoveGlobalPath(c); err != nil {
		glog.Errorf("Error unmounting PD %q: %v", c.volumeID, err)
	}

	// Detach disk asynchronously so that the kubelet sync loop is not blocked.
	go detachDiskAndVerify(c)
	return nil
}

func (util *AWSDiskUtil) DeleteVolume(d *awsElasticBlockStoreDeleter) error {
	cloud, err := getCloudProvider()
	if err != nil {
		return err
	}

	deleted, err := cloud.DeleteDisk(d.volumeID)
	if err != nil {
		glog.V(2).Infof("Error deleting EBS Disk volume %s: %v", d.volumeID, err)
		return err
	}
	if deleted {
		glog.V(2).Infof("Successfully deleted EBS Disk volume %s", d.volumeID)
	} else {
		glog.V(2).Infof("Successfully deleted EBS Disk volume %s (actually already deleted)", d.volumeID)
	}
	return nil
}

func (util *AWSDiskUtil) CreateVolume(c *awsElasticBlockStoreProvisioner) (volumeID string, volumeSizeGB int, err error) {
	cloud, err := getCloudProvider()
	if err != nil {
		return "", 0, err
	}

	// AWS volumes don't have Name field, store the name in Name tag
	var tags map[string]string
	if c.options.CloudTags == nil {
		tags = make(map[string]string)
	} else {
		tags = *c.options.CloudTags
	}
	tags["Name"] = volume.GenerateVolumeName(c.options.ClusterName, c.options.PVName, 255) // AWS tags can have 255 characters

	requestBytes := c.options.Capacity.Value()
	// AWS works with gigabytes, convert to GiB with rounding up
	requestGB := int(volume.RoundUpSize(requestBytes, 1024*1024*1024))
	volumeOptions := &aws.VolumeOptions{
		CapacityGB: requestGB,
		Tags:       &tags,
	}

	name, err := cloud.CreateDisk(volumeOptions)
	if err != nil {
		glog.V(2).Infof("Error creating EBS Disk volume: %v", err)
		return "", 0, err
	}
	glog.V(2).Infof("Successfully created EBS Disk volume %s", name)
	return name, int(requestGB), nil
}

// Attaches the specified persistent disk device to node, verifies that it is attached, and retries if it fails.
func attachDiskAndVerify(b *awsElasticBlockStoreBuilder, xvdBeforeSet sets.String) (string, error) {
	var awsCloud *aws.AWSCloud
	for numRetries := 0; numRetries < maxRetries; numRetries++ {
		var err error
		if awsCloud == nil {
			awsCloud, err = getCloudProvider()
			if err != nil || awsCloud == nil {
				// Retry on error. See issue #11321
				glog.Errorf("Error getting AWSCloudProvider while detaching PD %q: %v", b.volumeID, err)
				time.Sleep(errorSleepDuration)
				continue
			}
		}

		if numRetries > 0 {
			glog.Warningf("Retrying attach for EBS Disk %q (retry count=%v).", b.volumeID, numRetries)
		}

		devicePath, err := awsCloud.AttachDisk(b.volumeID, b.plugin.host.GetHostName(), b.readOnly)
		if err != nil {
			glog.Errorf("Error attaching PD %q: %v", b.volumeID, err)
			time.Sleep(errorSleepDuration)
			continue
		}

		devicePaths := getDiskByIdPaths(b.awsElasticBlockStore, devicePath)

		for numChecks := 0; numChecks < maxChecks; numChecks++ {
			path, err := verifyDevicePath(devicePaths)
			if err != nil {
				// Log error, if any, and continue checking periodically. See issue #11321
				glog.Errorf("Error verifying EBS Disk (%q) is attached: %v", b.volumeID, err)
			} else if path != "" {
				// A device path has successfully been created for the PD
				glog.Infof("Successfully attached EBS Disk %q.", b.volumeID)
				return path, nil
			}

			// Sleep then check again
			glog.V(3).Infof("Waiting for EBS Disk %q to attach.", b.volumeID)
			time.Sleep(checkSleepDuration)
		}
	}

	return "", fmt.Errorf("Could not attach EBS Disk %q. Timeout waiting for mount paths to be created.", b.volumeID)
}

// Returns the first path that exists, or empty string if none exist.
func verifyDevicePath(devicePaths []string) (string, error) {
	for _, path := range devicePaths {
		if pathExists, err := pathExists(path); err != nil {
			return "", fmt.Errorf("Error checking if path exists: %v", err)
		} else if pathExists {
			return path, nil
		}
	}

	return "", nil
}

// Detaches the specified persistent disk device from node, verifies that it is detached, and retries if it fails.
// This function is intended to be called asynchronously as a go routine.
func detachDiskAndVerify(c *awsElasticBlockStoreCleaner) {
	glog.V(5).Infof("detachDiskAndVerify(...) for pd %q. Will block for pending operations", c.volumeID)
	defer runtime.HandleCrash()

	// Block execution until any pending attach/detach operations for this PD have completed
	attachDetachMutex.LockKey(c.volumeID)
	defer attachDetachMutex.UnlockKey(c.volumeID)

	glog.V(5).Infof("detachDiskAndVerify(...) for pd %q. Awake and ready to execute.", c.volumeID)

	var awsCloud *aws.AWSCloud
	for numRetries := 0; numRetries < maxRetries; numRetries++ {
		var err error
		if awsCloud == nil {
			awsCloud, err = getCloudProvider()
			if err != nil || awsCloud == nil {
				// Retry on error. See issue #11321
				glog.Errorf("Error getting AWSCloudProvider while detaching PD %q: %v", c.volumeID, err)
				time.Sleep(errorSleepDuration)
				continue
			}
		}

		if numRetries > 0 {
			glog.Warningf("Retrying detach for EBS Disk %q (retry count=%v).", c.volumeID, numRetries)
		}

		devicePath, err := awsCloud.DetachDisk(c.volumeID, c.plugin.host.GetHostName())
		if err != nil {
			glog.Errorf("Error detaching PD %q: %v", c.volumeID, err)
			time.Sleep(errorSleepDuration)
			continue
		}

		devicePaths := getDiskByIdPaths(c.awsElasticBlockStore, devicePath)

		for numChecks := 0; numChecks < maxChecks; numChecks++ {
			allPathsRemoved, err := verifyAllPathsRemoved(devicePaths)
			if err != nil {
				// Log error, if any, and continue checking periodically.
				glog.Errorf("Error verifying EBS Disk (%q) is detached: %v", c.volumeID, err)
			} else if allPathsRemoved {
				// All paths to the PD have been successfully removed
				unmountPDAndRemoveGlobalPath(c)
				glog.Infof("Successfully detached EBS Disk %q.", c.volumeID)
				return
			}

			// Sleep then check again
			glog.V(3).Infof("Waiting for EBS Disk %q to detach.", c.volumeID)
			time.Sleep(checkSleepDuration)
		}

	}

	glog.Errorf("Failed to detach EBS Disk %q. One or more mount paths was not removed.", c.volumeID)
}

// Unmount the global PD mount, which should be the only one, and delete it.
func unmountPDAndRemoveGlobalPath(c *awsElasticBlockStoreCleaner) error {
	globalPDPath := makeGlobalPDPath(c.plugin.host, c.volumeID)

	err := c.mounter.Unmount(globalPDPath)
	os.Remove(globalPDPath)
	return err
}

// Returns the first path that exists, or empty string if none exist.
func verifyAllPathsRemoved(devicePaths []string) (bool, error) {
	allPathsRemoved := true
	for _, path := range devicePaths {
		if exists, err := pathExists(path); err != nil {
			return false, fmt.Errorf("Error checking if path exists: %v", err)
		} else {
			allPathsRemoved = allPathsRemoved && !exists
		}
	}

	return allPathsRemoved, nil
}

// Returns list of all paths for given EBS mount
// This is more interesting on GCE (where we are able to identify volumes under /dev/disk-by-id)
// Here it is mostly about applying the partition path
func getDiskByIdPaths(d *awsElasticBlockStore, devicePath string) []string {
	devicePaths := []string{}
	if devicePath != "" {
		devicePaths = append(devicePaths, devicePath)
	}

	if d.partition != "" {
		for i, path := range devicePaths {
			devicePaths[i] = path + diskPartitionSuffix + d.partition
		}
	}

	return devicePaths
}

// Checks if the specified path exists
func pathExists(path string) (bool, error) {
	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	} else if os.IsNotExist(err) {
		return false, nil
	} else {
		return false, err
	}
}

// Return cloud provider
func getCloudProvider() (*aws.AWSCloud, error) {
	awsCloudProvider, err := cloudprovider.GetCloudProvider("aws", nil)
	if err != nil || awsCloudProvider == nil {
		return nil, err
	}

	// The conversion must be safe otherwise bug in GetCloudProvider()
	return awsCloudProvider.(*aws.AWSCloud), nil
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>WebSocket.Out (playframework)</title>
<meta name="date" content="2013-04-02">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

play.mvc

Interface WebSocket.Out<A>

Enclosing class:

WebSocket<A>

public static interface WebSocket.Out<A>

A WebSocket out.

Method Summary

Methods

Modifier and Type
Method and Description

void
close()

Close this channel.

void
write(A frame)

Writes a frame.

Method Detail

write

void write(A frame)

Writes a frame.

close

void close()

Close this channel.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text: default_app_config = 'apps.blog.apps.BlogConfig'


text:
using System;
using System.Text;
using DykBits.Sql.ObjectModel;
using Microsoft.SqlServer.TransactSql.ScriptDom;

namespace DykBits.Sql
{
    class PgExpressionVisitor : TSqlFragmentVisitor
    {
        private StringBuilder _buffer;
        private PgTable _table;
        public PgExpressionVisitor(StringBuilder buffer)
        {
            _buffer = buffer;
        }
        public PgExpressionVisitor(StringBuilder buffer, PgTable table)
        {
            _buffer = buffer;
            _table = table;
        }
        public override void ExplicitVisit(ExecuteStatement node)
        {
            base.ExplicitVisit(node);
        }
        public override void ExplicitVisit(SetIdentityInsertStatement node)
        {
            _buffer.AppendLine();
            _buffer.Append("-- set identity_insert ");
            node.Table.Accept(this);
            _buffer.Append(node.IsOn ? " on" : " off");
            _buffer.AppendLine();
        }
        public override void ExplicitVisit(Identifier node)
        {
            if (node.QuoteType != QuoteType.NotQuoted)
            {
                _buffer.Append("\"" + node.Value + "\"");
            }
            else
            {
                _buffer.Append(node.Value);
            }
        }
        public override void ExplicitVisit(MultiPartIdentifier node)
        {
            for (int index = 1; index <= node.Identifiers.Count; ++index)
            {
                node.Identifiers[node.Identifiers.Count - index].Accept(this);
                if (index != node.Identifiers.Count)
                {
                    _buffer.Append(".");
                }
            }
        }
        public override void ExplicitVisit(SchemaObjectName node)
        {
            for (int index = 0; index < node.Identifiers.Count; ++index)
            {
                node.Identifiers[index].Accept(this);
                if (index < node.Identifiers.Count - 1)
                {
                    _buffer.Append(".");
                }
            }
        }
        public override void ExplicitVisit(ForeignKeyConstraintDefinition node)
        {
            if (node.ConstraintIdentifier != null)
            {
                node.ConstraintIdentifier.Accept(this);
            }
            _buffer.Append(" foreign key (");
            for (int index = 0; index < node.Columns.Count; ++index)
            {
                node.Columns[index].Accept(this);
                if (index < node.Columns.Count - 1)
                {
                    _buffer.Append(", ");
                }
            }
            _buffer.Append(") references ");
            node.ReferenceTableName.Accept(this);
            _buffer.Append(" (");
            for (int index = 0; index < node.ReferencedTableColumns.Count; ++index)
            {
                node.ReferencedTableColumns[index].Accept(this);
                if (index < node.ReferencedTableColumns.Count - 1)
                {
                    _buffer.Append(", ");
                }
            }
            _buffer.Append(")");
        }
        public override void ExplicitVisit(ColumnWithSortOrder node)
        {
            node.Column.MultiPartIdentifier.Accept(this);
        }
        public override void ExplicitVisit(UniqueConstraintDefinition node)
        {
            if (node.ConstraintIdentifier != null)
            {
                _buffer.Append("constraint ");
                node.ConstraintIdentifier.Accept(this);
            }
            if (node.IsPrimaryKey)
            {
                _buffer.Append(" primary key (");
            }
            else
            {
                _buffer.Append(" unique (");
            }
            for (int index = 0; index < node.Columns.Count; ++index)
            {
                node.Columns[index].Accept(this);
                if (index < node.Columns.Count - 1)
                {
                    _buffer.Append(", ");
                }
            }
            _buffer.Append(")");
        }

        public override void ExplicitVisit(CheckConstraintDefinition node)
        {
            if (node.ConstraintIdentifier != null)
            {
                node.ConstraintIdentifier.Accept(this);
            }
            else
            {
                _buffer.Append($"\"check_{Guid.NewGuid().ToString("N").ToLower()}\"");
            }
            _buffer.Append(" check (");
            node.CheckCondition.Accept(this);
            _buffer.Append(")");
        }
        public override void ExplicitVisit(DefaultConstraintDefinition node)
        {
            _buffer.Append("\talter column ");
            node.Column.Accept(this);
            _buffer.Append(" set default ");

            ScalarExpression expression = node.Expression;
            while (expression is ParenthesisExpression)
            {
                expression = ((ParenthesisExpression)expression).Expression;
            }

            string columnName = node.Column.Value;
            PgTableColumn column = _table.Columns[columnName];
            if (expression is IntegerLiteral literal)
            {
                string value = literal.Value;
                if (column.DataType == "bool")
                {
                    if (value == "0")
                    {
                        value = "(\'f\')";
                    }
                    else
                    {
                        value = "(\'t\')";
                    }
                    _buffer.Append(value);
                    return;
                }
            }
            else if (expression is FunctionCall call)
            {
                string functionName = call.FunctionName.Value.ToLower();
                switch (functionName)
                {
                    case "getutcdate":
                        _buffer.Append("(current_timestamp at time zone 'UTC')");
                        return;
                    case "getdate":
                        _buffer.Append("(localtimestamp)");
                        return;
                    case "suser_sname":
                        _buffer.Append("(session_user)");
                        return;
                    default:
                        throw new InvalidOperationException($"unsupported function {functionName}");
                }
            }
            _buffer.Append("(");
            expression.Accept(this);
            _buffer.Append(")");
        }
        public override void ExplicitVisit(FunctionCall node)
        {
            switch (node.FunctionName.Value.ToLower())
            {
                case "getutcdate":
                    _buffer.Append("current_timestamp at time zone 'UTC'");
                    return;
                default:
                    node.FunctionName.Accept(this);
                    break;
            }
            bool needComma = false;
            _buffer.Append("(");
            for (int index = 0; index < node.Parameters.Count; ++index)
            {
                if (needComma)
                {
                    _buffer.Append(", ");
                }

                node.Parameters[index].Accept(this);
            }
            _buffer.Append(")");
        }
        public override void ExplicitVisit(StringLiteral node)
        {
            _buffer.Append("\'");
            _buffer.Append(node.Value.Replace("\'", "\'\'"));
            _buffer.Append("\'");
        }
        public override void ExplicitVisit(NullLiteral node)
        {
            _buffer.Append("null");
        }
        public override void ExplicitVisit(IntegerLiteral node)
        {
            _buffer.Append(node.Value);
        }
        public override void ExplicitVisit(DefaultLiteral node)
        {
            _buffer.Append("default");
        }
        public override void ExplicitVisit(Literal node)
        {
            if (node is StringLiteral)
            {
                base.ExplicitVisit(node);
            }
            else
            {
                _buffer.Append(node.Value);
            }
        }
        public override void ExplicitVisit(BooleanComparisonExpression node)
        {
            node.FirstExpression.Accept(this);
            switch (node.ComparisonType)
            {
                case BooleanComparisonType.Equals:
                    _buffer.Append(" = ");
                    break;
                case BooleanComparisonType.GreaterThan:
                    _buffer.Append(" > ");
                    break;
                case BooleanComparisonType.GreaterThanOrEqualTo:
                    _buffer.Append(" >= ");
                    break;
                case BooleanComparisonType.LessThan:
                    _buffer.Append(" < ");
                    break;
                case BooleanComparisonType.LessThanOrEqualTo:
                    _buffer.Append(" < ");
                    break;
                case BooleanComparisonType.NotEqualToBrackets:
                    _buffer.Append(" <> ");
                    break;
                case BooleanComparisonType.NotEqualToExclamation:
                    _buffer.Append(" != ");
                    break;
                case BooleanComparisonType.NotGreaterThan:
                    _buffer.Append(" !> ");
                    break;
                case BooleanComparisonType.NotLessThan:
                    _buffer.Append(" !< ");
                    break;
                default:
                    throw new InvalidOperationException();
            }
            node.SecondExpression.Accept(this);
        }
        public override void ExplicitVisit(InPredicate node)
        {
            node.Expression.Accept(this);
            _buffer.Append(" in (");
            bool needComma = false;
            foreach (var value in node.Values)
            {
                if (needComma)
                    _buffer.Append(", ");
                value.Accept(this);
                needComma = true;
            }
            _buffer.Append(")");
        }
        public override void ExplicitVisit(ExistsPredicate node)
        {
            _buffer.Append("exists (");
            node.Subquery.Accept(this);
            _buffer.Append(")");
        }
        public override void ExplicitVisit(ColumnReferenceExpression node)
        {
            node.MultiPartIdentifier.Accept(this);
        }
        public override void ExplicitVisit(LikePredicate node)
        {
            node.FirstExpression.Accept(this);
            if (node.NotDefined)
            {
                _buffer.Append(" not like ");
            }
            node.SecondExpression.Accept(this);
        }
        public override void ExplicitVisit(QuerySpecification node)
        {
            _buffer.Append("select ");

            for (int index = 0; index < node.SelectElements.Count; ++index)
            {
                node.SelectElements[index].Accept(this);
                if (index < node.SelectElements.Count - 1)
                {
                    _buffer.Append(", ");
                }
            }
            if (node.FromClause != null)
            {
                node.FromClause.Accept(this);
            }
            if (node.WhereClause != null)
            {
                node.WhereClause.Accept(this);
            }
            //_buffer.AppendLine(";");
        }
        public override void ExplicitVisit(InsertStatement node)
        {
            _buffer.Append("insert ");
            node.InsertSpecification.Accept(this);
        }
        public override void ExplicitVisit(InsertSpecification node)
        {
            if (node.InsertOption == InsertOption.Into || node.InsertOption == InsertOption.None)
            {
                _buffer.Append("into ");
            }
            else
            {
                throw new InvalidOperationException();
            }

            node.Target.Accept(this);
            _buffer.AppendLine();
            if (node.Columns != null)
            {
                _buffer.Append("\t(");
                for (int index = 0, count = node.Columns.Count - 1; index <= count; ++index)
                {
                    var column = node.Columns[index];
                    column.Accept(this);
                    if (index < count)
                    {
                        _buffer.Append(", ");
                    }
                }
                _buffer.Append(")");
                _buffer.AppendLine();
            }
            node.InsertSource.Accept(this);
        }
        public override void ExplicitVisit(ValuesInsertSource node)
        {
            if (node.IsDefaultValues)
            {
                throw new NotImplementedException();
            }
            _buffer.Append("values");
            _buffer.AppendLine();
            for (int index = 0, count = node.RowValues.Count - 1; index <= count; ++index)
            {
                RowValue rowValue = node.RowValues[index];
                rowValue.Accept(this);
                if (index < count)
                {
                    _buffer.Append(",");
                    _buffer.AppendLine();
                }
            }
            _buffer.Append(";");
            _buffer.AppendLine();
        }
        public override void ExplicitVisit(RowValue node)
        {
            _buffer.Append("\t(");
            for (int index = 0, count = node.ColumnValues.Count - 1; index <= count; ++index)
            {
                var columnValue = node.ColumnValues[index];
                columnValue.Accept(this);
                if (index < count)
                {
                    _buffer.Append(", ");
                }
            }
            _buffer.Append(")");
        }
        public override void ExplicitVisit(BeginEndBlockStatement node)
        {
            _buffer.AppendLine("--begin");

            for (int index = 0; index < node.StatementList.Statements.Count; ++index)
            {
                TSqlStatement statement = node.StatementList.Statements[index];
                statement.Accept(this);
            }
            _buffer.AppendLine();
            _buffer.AppendLine("--end");
        }
        public override void ExplicitVisit(FromClause node)
        {
            _buffer.Append(" from ");
            for (int index = 0; index < node.TableReferences.Count; ++index)
            {
                TableReference table = node.TableReferences[index];
                table.Accept(this);
            }
        }
        public override void ExplicitVisit(NamedTableReference node)
        {
            node.SchemaObject.Accept(this);
            if (node.Alias != null)
            {
                _buffer.Append(" as ");
                node.Alias.Accept(this);
            }
        }
        public override void ExplicitVisit(WhereClause node)
        {
            _buffer.Append(" where ");
            node.SearchCondition.Accept(this);
        }
        public override void ExplicitVisit(BooleanNotExpression node)
        {
            _buffer.Append("not ");
            node.Expression.Accept(this);
        }
        public override void ExplicitVisit(BooleanBinaryExpression node)
        {
            node.FirstExpression.Accept(this);
            if (node.BinaryExpressionType == BooleanBinaryExpressionType.And)
            {
                _buffer.Append(" and ");
            }
            else if (node.BinaryExpressionType == BooleanBinaryExpressionType.Or)
            {
                _buffer.Append(" or ");
            }
            node.SecondExpression.Accept(this);
        }
        public override void ExplicitVisit(BooleanIsNullExpression node)
        {
            node.Expression.Accept(this);
            if (node.IsNot)
                _buffer.Append(" is not null");
            else
                _buffer.Append(" is null");
        }
        public override void ExplicitVisit(BooleanTernaryExpression node)
        {
            node.FirstExpression.Accept(this);
            if (node.TernaryExpressionType == BooleanTernaryExpressionType.Between)
            {
                _buffer.Append(" between ");
            }
            else if (node.TernaryExpressionType == BooleanTernaryExpressionType.NotBetween)
            {
                _buffer.Append(" not between ");
            }

            node.SecondExpression.Accept(this);
            _buffer.Append(" and ");
            node.ThirdExpression.Accept(this);
        }
        public override void ExplicitVisit(BooleanParenthesisExpression node)
        {
            _buffer.Append("(");
            base.ExplicitVisit(node);
            _buffer.Append(")");
        }
        public override void ExplicitVisit(ParenthesisExpression node)
        {
            _buffer.Append("(");
            base.ExplicitVisit(node);
            _buffer.Append(")");
        }
    }
}


text:
class AccountReconcilor;
class ProfileOAuth2TokenService;
class SigninClient;

// The signin flow logic is spread across several classes with varying
// responsibilities:
//
// SigninTracker (this class) - This class listens to notifications from various
// services (SigninManager, OAuth2TokenService) and coalesces them into
// notifications for the UI layer. This is the class that encapsulates the logic
// that determines whether a user is fully logged in or not, and exposes
// callbacks so various pieces of the UI (OneClickSyncStarter) can track the
// current startup state.
//
// SyncSetupHandler - This class is primarily responsible for interacting with
// the web UI for performing system login and sync configuration. Receives
// callbacks from the UI when the user wishes to initiate a login, and
// translates system state (login errors, etc) into the appropriate calls into
// the UI to reflect this status to the user.
//
// LoginUIService - Our desktop UI flows rely on having only a single login flow
// visible to the user at once. This is achieved via LoginUIService
// (a KeyedService that keeps track of the currently visible
// login UI).
//
// SigninManager - Records the currently-logged-in user and handles all
// interaction with the GAIA backend during the signin process. Unlike
// SigninTracker, SigninManager only knows about the GAIA login state and is
// not aware of the state of any signed in services.
//
// OAuth2TokenService - Maintains and manages OAuth2 tokens for the accounts
// connected to this profile.
//
// ProfileSyncService - Provides the external API for interacting with the
// sync framework. Listens for notifications for tokens to know when to startup
// sync, and provides an Observer interface to notify the UI layer of changes
// in sync state so they can be reflected in the UI.
class SigninTracker : public SigninManagerBase::Observer,
                      public OAuth2TokenService::Observer,
                      public MergeSessionHelper::Observer {
 public:
  class Observer {
   public:
    // The signin attempt failed, and the cause is passed in |error|.
    virtual void SigninFailed(const GoogleServiceAuthError& error) = 0;

    // The signin attempt succeeded.
    virtual void SigninSuccess() = 0;

    // The signed in account has been merged into the content area cookie jar.
    // This will be called only after a call to SigninSuccess().
    virtual void MergeSessionComplete(const GoogleServiceAuthError& error) = 0;
  };

  // Creates a SigninTracker that tracks the signin status on the passed
  // classes, and notifies the |observer| on status changes. All of the
  // instances with the exception of |account_reconcilor| must be non-null and
  // must outlive the SigninTracker. |account_reconcilor| will be used if it is
  // non-null.
  SigninTracker(ProfileOAuth2TokenService* token_service,
                SigninManagerBase* signin_manager,
                AccountReconcilor* account_reconcilor,
                SigninClient* client,
                Observer* observer);
  ~SigninTracker() override;

  // SigninManagerBase::Observer implementation.
  void GoogleSigninFailed(const GoogleServiceAuthError& error) override;

  // OAuth2TokenService::Observer implementation.
  void OnRefreshTokenAvailable(const std::string& account_id) override;
  void OnRefreshTokenRevoked(const std::string& account_id) override;

 private:
  // Initializes this by adding notifications and observers.
  void Initialize();

  // MergeSessionHelper::Observer implementation.
  void MergeSessionCompleted(const std::string& account_id,
                             const GoogleServiceAuthError& error) override;

  // The classes whose collective signin status we are tracking.
  ProfileOAuth2TokenService* token_service_;
  SigninManagerBase* signin_manager_;
  AccountReconcilor* account_reconcilor_;

  // The client associated with this instance.
  SigninClient* client_;

  // Weak pointer to the observer we call when the signin state changes.
  Observer* observer_;

  DISALLOW_COPY_AND_ASSIGN(SigninTracker);
};

#endif  // COMPONENTS_SIGNIN_CORE_BROWSER_SIGNIN_TRACKER_H_


text:
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

	<bean id="viewResolver"
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix">
			<value>/WEB-INF/pages/</value>
		</property>
		<property name="suffix">
			<value>.jsp</value>
		</property>
	</bean>

	<bean name="/welcome.htm"
		class="com.springmvc.controller.HelloWorldController" />

</beans>


text:
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "profile.h"

#ifdef ENABLE_PROFILE

/**
   Message strings must be strictly less than this many characters
 */
#define PROFILE_MSG_SIZE (64)

typedef struct
{
  double timestamp;
  char message[PROFILE_MSG_SIZE];
} entry;

static entry* entries = NULL;
static int size = -1;
static int count = -1;

/**
   @param s Maximal number of entries
 */
void
profile_init(int s)
{
  assert(s >= 0);
  count = 0;
  size = s;
  entries = malloc((size_t)size*sizeof(entry));
  for (int i = 0; i < size; i++)
    entries[i].timestamp = -1;
}

/**
   Not currently thread-safe
   Does not copy message
   message is freed by profile_finalize
*/
void profile_entry(double timestamp, const char* message)
{
  entries[count].timestamp = timestamp;
  assert(strlen(message) < PROFILE_MSG_SIZE);
  strncpy(entries[count].message, message, PROFILE_MSG_SIZE);
  count++;
}

void profile_write(int rank, FILE* file)
{
  for (int i = 0; i < count; i++)
    fprintf(file, "[%i] %0.4f: %s\n",
            rank, entries[i].timestamp, entries[i].message);
}

void profile_finalize()
{
  for (int i = 0; i < count; i++)
    free(entries[i].message);
  free(entries);
}

#endif