text:
import * as React from "react";
import {
    shallow,
    mount,
    render,
    CommonWrapper,
    ShallowWrapper,
    ReactWrapper,
    configure,
    EnzymeAdapter,
    ShallowRendererProps,
    ComponentClass as EnzymeComponentClass
} from "enzyme";
import { Component, ReactElement, ReactNode, HTMLAttributes, ComponentClass, StatelessComponent } from "react";

// Help classes/interfaces
interface MyComponentProps {
    stringProp: string;
    numberProp: number;
}

interface AnotherComponentProps {
    anotherStringProp?: string;
    anotherNumberProp?: number;
}

interface StatelessProps {
    stateless: string;
}

interface AnotherStatelessProps {
    anotherStateless: string;
}

interface MyComponentState {
    stateProperty: string;
}

interface MyRenderPropProps {
    children: (params: string) => ReactNode;
}

interface MyProviderProps {
    children: ReactElement | ReactElement[];
    value: string;
}

function toComponentType<T>(Component: ComponentClass<T> | StatelessComponent<T>): ComponentClass<T> | StatelessComponent<T> {
  return Component;
}

class MyComponent extends Component<MyComponentProps, MyComponentState> {
    handleEcho(value: string) {
        return value;
    }
    setState(...args: any[]) {
        console.log(args);
    }
}
class MyComponentPropsOnly extends Component<MyComponentProps> {
    handleEcho(value: string) {
        return value;
    }
}

class AnotherComponent extends Component<AnotherComponentProps> {
    setState(...args: any[]) {
        console.log(args);
    }

    handleAnotherEcho(value: string) {
      return value;
    }
}

interface OptionalFunctionProp {
    functionProp?(): void;
    requiredFunctionProp(): void;
    singleArg(arg: any): void;
    multipleArg(arg1: number, arg2: string, arg3: boolean): void;
    multipleReturn(): void | number | boolean | undefined | null | string;
    nonFun?: number;
}

class MyRenderPropComponent extends Component<MyRenderPropProps> {}

const MyStatelessComponent = (props: StatelessProps) => ;

const AnotherStatelessComponent = (props: AnotherStatelessProps) => ;

const ComponentType = toComponentType(MyComponent);

const MyFunctionPropComponent = (props: OptionalFunctionProp) => ;

const CommonWrapperHelper = {
    test_invoke: (wrapper: CommonWrapper<OptionalFunctionProp, any, any>) => {
        // should accept the names of props that are functions
        wrapper.invoke('functionProp'); // $ExpectType (() => void) | undefined
        wrapper.invoke('requiredFunctionProp'); // $ExpectType () => void
        wrapper.invoke('singleArg'); // $ExpectType (arg: any) => void
        wrapper.invoke('multipleArg'); // $ExpectType (arg1: number, arg2: string, arg3: boolean) => void
        wrapper.invoke('multipleReturn'); // $ExpectType () => string | number | boolean | void | null | undefined
        wrapper.invoke(undefined); // $ExpectError
        wrapper.invoke(null); // $ExpectError
        wrapper.invoke('nonFun'); // $ExpectError
    },
};

// Enzyme.configure
function configureTest() {
    const configureAdapter: { adapter: EnzymeAdapter } = { adapter: {} };
    configure(configureAdapter);

    const configureAdapterAndDisableLifecycle: typeof configureAdapter & Pick<ShallowRendererProps, "disableLifecycleMethods"> = {
        adapter: {},
        disableLifecycleMethods: true,
    };
    configure(configureAdapterAndDisableLifecycle);
}

// ShallowWrapper
function ShallowWrapperTest() {
    let shallowWrapper: ShallowWrapper<MyComponentProps, MyComponentState> =
        shallow<MyComponentProps, MyComponentState>(<MyComponent stringProp="value" numberProp={1} />);

    let reactElement: ReactElement;
    let reactElements: ReactElement[];
    let domElement: Element;
    let buttonElement: HTMLButtonElement;
    let boolVal: boolean;
    let stringVal: string;
    let numOrStringVal: number | string | undefined;
    let elementWrapper: ShallowWrapper<HTMLAttributes<{}>>;
    let anotherStatelessWrapper: ShallowWrapper<AnotherStatelessProps, never>;
    let anotherComponentWrapper: ShallowWrapper<AnotherComponentProps, any>;

    // testStatePropsInstanceFn(shallow<MyComponent>(<MyComponent stringProp="value" numberProp={1}/>));
    function testStatePropsInstance() {
        const wrapper = shallow<MyComponent>(<MyComponent stringProp="value" numberProp={1}/>);

        const {
            numberProp, // $ExpectType number
            stringProp // $ExpectType string
        } = wrapper.props();
        const {
            stateProperty // $ExpectType string
        } = wrapper.state();
        const {
            handleEcho // $ExpectType (value: string) => string
        } = wrapper.instance();

        // $ExpectError
        wrapper.setState({stateProperty: 123});
        // $ExpectError
        wrapper.setState({statePropertyzasd: 'hello'});
        wrapper.setState({stateProperty: 'hello'});

        // $ExpectError
        wrapper.setProps({numberProp: '123'});
        // $ExpectError
        wrapper.setProps({numberPropzasd: 'hello'});
        wrapper.setProps({numberProp: 123});
    }

    function test_props_state_inferring() {
        let wrapper: ShallowWrapper<MyComponentProps, MyComponentState>;
        wrapper = shallow(<MyComponent stringProp="value" numberProp={1} />);
        wrapper.state().stateProperty;
        wrapper.props().stringProp.toUpperCase();
    }

    function test_shallow_options() {
        shallow(<MyComponent stringProp="1" numberProp={1} />, {
            context: {
                test: "a",
            },
            lifecycleExperimental: true,
            disableLifecycleMethods: true
        });
    }

    function test_find() {
        anotherComponentWrapper = shallowWrapper.find(AnotherComponent);
        anotherStatelessWrapper = shallowWrapper.find(AnotherStatelessComponent);
        shallowWrapper = shallowWrapper.find({ prop: 'value' });
        elementWrapper = shallowWrapper.find('.selector');
        // Since AnotherComponent does not have a constructor, it cannot match the
        // previous selector overload of ComponentClass { new(props?, contenxt? ) }
        const s1: EnzymeComponentClass<AnotherComponentProps> = AnotherComponent;
    }

    function test_invoke() {
        CommonWrapperHelper.test_invoke(shallow<OptionalFunctionProp>(
            <MyFunctionPropComponent
                requiredFunctionProp={() => {} }
                singleArg={() => {} }
                multipleArg={() => {} }
                multipleReturn={() => {} }
                nonFun={1}
            />));
    }

    function test_findWhere() {
        shallowWrapper =
            shallowWrapper.findWhere((aShallowWrapper: ShallowWrapper<MyComponentProps, MyComponentState>) => true);
    }

    function test_filter() {
        anotherComponentWrapper = shallowWrapper.filter(AnotherComponent);
        anotherStatelessWrapper = shallowWrapper.filter(AnotherStatelessComponent);
        // NOTE: The following calls to filter do not narrow down the possible type of the result based
        //       on the type of the param, so the return type should not be different than the original
        //       "this". This is a special case for "filter" vs other methods like "find", because "filter"
        //       is guaranteed to return only a subset of the existing list of components/elements without
        //       finding/adding more.
        shallowWrapper = shallowWrapper.filter({ numberProp: 12 });
        shallowWrapper = shallowWrapper.filter('.selector');
    }

    function test_filterWhere() {
        shallowWrapper =
            shallowWrapper.filterWhere(wrapper => {
                wrapper.props().stringProp;
                return true;
            });
    }

    function test_contains() {
        boolVal = shallowWrapper.contains(
);
    }

    function test_containsMatchingElement() {
        boolVal = shallowWrapper.contains(
);
    }

    function test_containsAllMatchingElements() {
        boolVal = shallowWrapper.containsAllMatchingElements([
]);
    }

    function test_containsAnyMatchingElement() {
        boolVal = shallowWrapper.containsAnyMatchingElements([
]);
    }

    function test_dive() {
        interface TmpProps {
            foo: any;
        }

        interface TmpState {
            bar: any;
        }

        const diveWrapper: ShallowWrapper<TmpProps, TmpState> = shallowWrapper.dive<TmpProps, TmpState>({ context: { foobar: 'barfoo' } });
        const diveWrapper2 = shallowWrapper.dive<MyComponent>({ context: { foobar: 'barfoo' } });
    }

    function test_hostNodes() {
        shallowWrapper.hostNodes();
    }

    function test_equals() {
        boolVal = shallowWrapper.equals(
);
    }

    function test_matchesElement() {
        boolVal = shallowWrapper.matchesElement(
);
    }

    function test_hasClass() {
        boolVal = shallowWrapper.find('.my-button').hasClass('disabled');
    }

    function test_is() {
        boolVal = shallowWrapper.is('.some-class');
    }

    function test_isEmpty() {
        boolVal = shallowWrapper.isEmpty();
    }

    function test_exists() {
        boolVal = shallowWrapper.exists();
    }

    function test_not() {
        elementWrapper = shallowWrapper.find('.foo').not('.bar');
    }

    function test_children() {
        shallowWrapper = shallowWrapper.children();
        anotherComponentWrapper = shallowWrapper.children(AnotherComponent);
        anotherStatelessWrapper = shallowWrapper.children(AnotherStatelessComponent);
        shallowWrapper = shallowWrapper.children({ prop: 'value' });
        elementWrapper = shallowWrapper.children('.selector');
    }

    function test_childAt() {
        const childWrapper: ShallowWrapper<any, any> = shallowWrapper.childAt(0);

        interface TmpType1 {
            foo: any;
        }

        interface TmpType2 {
            bar: any;
        }

        const childWrapper2: ShallowWrapper<TmpType1, TmpType2> = shallowWrapper.childAt<TmpType1, TmpType2>(0);
    }

    function test_parents() {
        shallowWrapper = shallowWrapper.parents();
        anotherComponentWrapper = shallowWrapper.parents(AnotherComponent);
        anotherStatelessWrapper = shallowWrapper.parents(AnotherStatelessComponent);
        shallowWrapper = shallowWrapper.parents({ prop: 'myprop' });
        elementWrapper = shallowWrapper.parents('.selector');
    }

    function test_parent() {
        shallowWrapper = shallowWrapper.parent();
    }

    function test_closest() {
        anotherComponentWrapper = shallowWrapper.closest(AnotherComponent);
        anotherStatelessWrapper = shallowWrapper.closest(AnotherStatelessComponent);
        shallowWrapper = shallowWrapper.closest({ prop: 'myprop' });
        elementWrapper = shallowWrapper.closest('.selector');
    }

    function test_shallow() {
        shallowWrapper = shallowWrapper.shallow();
    }

    function test_unmount() {
        shallowWrapper = shallowWrapper.unmount();
    }

    function test_text() {
        stringVal = shallowWrapper.text();
    }

    function test_html() {
        stringVal = shallowWrapper.html();
    }

    function test_get() {
        reactElement = shallowWrapper.get(1);
    }

    function test_getNode() {
        reactElement = shallowWrapper.getNode();
    }

    function test_getNodes() {
        reactElements = shallowWrapper.getNodes();
    }

    function test_getElement() {
        reactElement = shallowWrapper.getElement();
    }

    function test_getElements() {
        reactElements = shallowWrapper.getElements();
    }

    function test_getDOMNode() {
        domElement = shallowWrapper.getDOMNode();
        buttonElement = shallowWrapper.getDOMNode<HTMLButtonElement>();
    }

    function test_at() {
        shallowWrapper = shallowWrapper.at(1);
    }

    function test_first() {
        shallowWrapper = shallowWrapper.first();
    }

    function test_last() {
        shallowWrapper = shallowWrapper.last();
    }

    function test_slice() {
        shallowWrapper = shallowWrapper.slice(1);
        shallowWrapper = shallowWrapper.slice(1, 3);
    }

    function test_tap() {
        shallowWrapper.tap((intercepter) => { });
    }

    function test_state() {
        const state: MyComponentState = shallowWrapper.state();
        const prop: string = shallowWrapper.state('stateProperty');
        const prop2: number = shallowWrapper.state<number>('key');
        const prop3 = shallowWrapper.state('key');
    }

    function test_context() {
        shallowWrapper.context();
        shallowWrapper.context('key');
        const tmp: string = shallowWrapper.context<string>('key');
    }

    function test_props() {
        const props: MyComponentProps = shallowWrapper.props();
        const props2: AnotherComponentProps = shallowWrapper.find(AnotherComponent).props();
        const props3: AnotherStatelessProps = shallowWrapper.find(AnotherStatelessComponent).props();
        const props4: HTMLAttributes<any> = shallowWrapper.find('.selector').props();
    }

    function test_prop() {
        const tmp: number = shallowWrapper.prop('numberProp');
        const tmp2: string = shallowWrapper.prop<string>('key');
        const tmp3 = shallowWrapper.prop('key');
    }

    function test_key() {
        stringVal = shallowWrapper.key();
    }

    function test_simulate(...args: any[]) {
        shallowWrapper.simulate('click');
        shallowWrapper.simulate('click', args);
    }

    function test_simulateError(error: any) {
        shallowWrapper.simulateError(error);
    }

    function test_setState() {
        shallowWrapper = shallowWrapper.setState({ stateProperty: 'state' });
        shallowWrapper = shallowWrapper.setState({ stateProperty: 'state' }, () => console.log('state updated'));
    }

    function test_setProps() {
        shallowWrapper = shallowWrapper.setProps({ stringProp: 'foo' });
        shallowWrapper = shallowWrapper.setProps({ stringProp: 'foo' }, () => console.log('props update'));
    }

    function test_setContext() {
        shallowWrapper = shallowWrapper.setContext({ name: 'baz' });
    }

    function test_instance() {
        const myComponent = shallowWrapper.instance() as MyComponent;
        myComponent.handleEcho('it works');

        const wrapper = shallow<MyComponent>(<MyComponent stringProp="value" numberProp={1}/>);
        wrapper.instance().handleEcho('it works');

        const wrapperPropsOnly = shallow<MyComponentProps>(<MyComponent stringProp="value" numberProp={1}/>);
        wrapperPropsOnly.setProps({stringProp: 'new value'});
        // $ExpectError
        wrapperPropsOnly.instance().handleEcho;
    }

    function test_update() {
        shallowWrapper = shallowWrapper.update();
    }

    function test_debug() {
        stringVal = shallowWrapper.debug();
        stringVal = shallowWrapper.debug({ verbose: false });
        stringVal = shallowWrapper.debug({ ignoreProps: true });
        stringVal = shallowWrapper.debug({ ignoreProps: true, verbose: true });
    }

    function test_type() {
        const type: string | StatelessComponent<MyComponentProps> | ComponentClass<MyComponentProps> = shallowWrapper.type();
    }

    function test_name() {
        stringVal = shallowWrapper.name();
    }

    function test_forEach() {
        shallowWrapper =
            shallowWrapper.forEach(wrapper => wrapper.shallow().props().stringProp);
    }

    function test_map() {
        const arrayNumbers: number[] =
            shallowWrapper.map(wrapper => wrapper.props().numberProp);
    }

    function test_reduce() {
        const total: number =
            shallowWrapper.reduce(
                (amount: number, n: ShallowWrapper<MyComponentProps, MyComponentState>) => amount + n.props().numberProp
            );
    }

    function test_reduceRight() {
        const total: number =
            shallowWrapper.reduceRight<number>(
                (amount: number, n: ShallowWrapper<MyComponentProps, MyComponentState>) => amount + n.prop('numberProp')
            );
    }

    function test_some() {
        boolVal = shallowWrapper.some(AnotherComponent);
        boolVal = shallowWrapper.some(AnotherStatelessComponent);
        boolVal = shallowWrapper.some({ prop: 'myprop' });
        boolVal = shallowWrapper.some('.selector');
    }

    function test_someWhere() {
        boolVal = shallowWrapper.someWhere((aShallowWrapper: ShallowWrapper<MyComponentProps, MyComponentState>) => true);
    }

    function test_every() {
        boolVal = shallowWrapper.every(AnotherComponent);
        boolVal = shallowWrapper.every(AnotherStatelessComponent);
        boolVal = shallowWrapper.every({ prop: 'myprop' });
        boolVal = shallowWrapper.every('.selector');
    }

    function test_everyWhere() {
        boolVal = shallowWrapper.everyWhere((aShallowWrapper: ShallowWrapper<MyComponentProps, MyComponentState>) => true);
    }

    function test_isEmptyRender() {
        boolVal = shallowWrapper.isEmptyRender();
    }

    function test_svg() {
        numOrStringVal = shallowWrapper.find('svg').props().strokeWidth;
    }

    function test_constructor() {
        let anyWrapper: ShallowWrapper;
        anyWrapper = new ShallowWrapper(<MyComponent stringProp="1" numberProp={1} />);
        shallowWrapper = new ShallowWrapper<MyComponentProps, MyComponentState>(<MyComponent stringProp="1" numberProp={1} />);
        shallowWrapper = new ShallowWrapper<MyComponentProps, MyComponentState>([<MyComponent stringProp="1" numberProp={1} />, <MyComponent stringProp="1" numberProp={1} />]);
        shallowWrapper = new ShallowWrapper<MyComponentProps, MyComponentState>(<MyComponent stringProp="1" numberProp={1} />, shallowWrapper);
        shallowWrapper = new ShallowWrapper<MyComponentProps, MyComponentState>(<MyComponent stringProp="1" numberProp={1} />, undefined, { lifecycleExperimental: true });
        shallowWrapper = new ShallowWrapper<MyComponentProps, MyComponentState>(<MyComponent stringProp="1" numberProp={1} />, shallowWrapper, { lifecycleExperimental: true });
    }

    function test_renderProp() {
        let shallowWrapper = new ShallowWrapper<MyRenderPropProps>(<MyRenderPropComponent children={(params) =>
} />);
        shallowWrapper = shallowWrapper.renderProp('children')('test');
    }

    function test_getWrappingComponent() {
        const MyContext = React.createContext('test');
        function MyProvider(props: MyProviderProps) {
            const { children, value } = props;
            return (
                <MyContext.Provider value={value}>
                    {children}
                </MyContext.Provider>
              );
        }
        const shallowWrapper = shallow<MyRenderPropProps>(<MyRenderPropComponent children={(params) =>
} />, {
            wrappingComponent: MyProvider,
        });
        const provider = shallowWrapper.getWrappingComponent();
        provider.setProps({ value: 'test new' });
    }
}

// ReactWrapper
function ReactWrapperTest() {
    let reactWrapper: ReactWrapper<MyComponentProps, MyComponentState> =
        mount<MyComponentProps, MyComponentState>(<MyComponent stringProp="value" numberProp={1} />);

    let reactElement: ReactElement;
    let reactElements: ReactElement[];
    let domElement: Element;
    let buttonElement: HTMLButtonElement;
    let boolVal: boolean;
    let stringVal: string;
    let elementWrapper: ReactWrapper<HTMLAttributes<{}>>;
    let anotherStatelessWrapper: ReactWrapper<AnotherStatelessProps, never>;
    let anotherComponentWrapper: ReactWrapper<AnotherComponentProps, any>;

    function testStatePropsInstance() {
        const wrapper = mount<MyComponent>(<MyComponent stringProp="value" numberProp={1}/>);

        const {
            numberProp, // $ExpectType number
            stringProp // $ExpectType string
        } = wrapper.props();
        const {
            stateProperty // $ExpectType string
        } = wrapper.state();
        const {
            handleEcho // $ExpectType (value: string) => string
        } = wrapper.instance();

        // $ExpectError
        wrapper.setState({stateProperty: 123});
        // $ExpectError
        wrapper.setState({statePropertyzasd: 'hello'});
        wrapper.setState({stateProperty: 'hello'});

        // $ExpectError
        wrapper.setProps({numberProp: '123'});
        // $ExpectError
        wrapper.setProps({numberPropzasd: 'hello'});
        wrapper.setProps({numberProp: 123});
    }

    function test_prop_state_inferring() {
        let wrapper: ReactWrapper<MyComponentProps, MyComponentState>;
        wrapper = mount(<MyComponent stringProp="value" numberProp={1} />);
        wrapper.state().stateProperty;
        wrapper.props().stringProp.toUpperCase();
    }

    function test_unmount() {
        reactWrapper = reactWrapper.unmount();
    }

    function test_mount() {
        reactWrapper = reactWrapper.mount();

        mount(<MyComponent stringProp='1' numberProp={1} />, {
            attachTo: document.getElementById('test'),
            context: {
                a: "b"
            }
        });
    }

    function test_ref() {
        reactWrapper = reactWrapper.ref('refName');

        interface TmpType1 {
            foo: string;
        }

        interface TmpType2 {
            bar: string;
        }

        const tmp: ReactWrapper<TmpType1, TmpType2> = reactWrapper.ref<TmpType1, TmpType2>('refName');
    }

    function test_detach() {
        reactWrapper.detach();
    }

    function test_hostNodes() {
        reactWrapper.hostNodes();
    }

    function test_find() {
        elementWrapper = reactWrapper.find('.selector');
        anotherComponentWrapper = reactWrapper.find(AnotherComponent);
        anotherStatelessWrapper = reactWrapper.find(AnotherStatelessComponent);
        reactWrapper = reactWrapper.find({ prop: 'myprop' });
    }

    function test_findWithType() {
      const anotherComponentTypedWrapper = reactWrapper.find<AnotherComponent>(AnotherComponent);
      anotherComponentTypedWrapper.instance().handleAnotherEcho('it works');
    }

    function test_findWhere() {
        reactWrapper =
            reactWrapper.findWhere((aReactWrapper: ReactWrapper<MyComponentProps, MyComponentState>) => true);
    }

    function test_filter() {
        anotherComponentWrapper = reactWrapper.filter(AnotherComponent);
        anotherStatelessWrapper = reactWrapper.filter(AnotherStatelessComponent);
        // NOTE: The following calls to filter do not narrow down the possible type of the result based
        //       on the type of the param, so the return type should not be different than the original
        //       "this". This is a special case for "filter" vs other methods like "find", because "filter"
        //       is guaranteed to return only a subset of the existing list of components/elements without
        //       finding/adding more.
        reactWrapper = reactWrapper.filter({ numberProp: 12 });
        reactWrapper = reactWrapper.filter('.selector');
    }

    function test_filterWhere() {
        reactWrapper =
            reactWrapper.filterWhere(wrapper => {
                wrapper.props().stringProp;
                return true;
            });
    }

    function test_contains() {
        boolVal = reactWrapper.contains(
);
    }

    function test_containsMatchingElement() {
        boolVal = reactWrapper.contains(
);
    }

    function test_containsAllMatchingElements() {
        boolVal = reactWrapper.containsAllMatchingElements([
]);
    }

    function test_containsAnyMatchingElement() {
        boolVal = reactWrapper.containsAnyMatchingElements([
]);
    }

    function test_equals() {
        boolVal = reactWrapper.equals(
);
    }

    function test_matchesElement() {
        boolVal = reactWrapper.matchesElement(
);
    }

    function test_hasClass() {
        boolVal = reactWrapper.find('.my-button').hasClass('disabled');
    }

    function test_invoke() {
        CommonWrapperHelper.test_invoke(mount<OptionalFunctionProp>(
            <MyFunctionPropComponent
                requiredFunctionProp={() => {} }
                singleArg={() => {} }
                multipleArg={() => {} }
                multipleReturn={() => {} }
                nonFun={1}
            />));
    }

    function test_is() {
        boolVal = reactWrapper.is('.some-class');
    }

    function test_isEmpty() {
        boolVal = reactWrapper.isEmpty();
    }

    function test_not() {
        elementWrapper = reactWrapper.find('.foo').not('.bar');
    }

    function test_children() {
        reactWrapper = reactWrapper.children();
        anotherComponentWrapper = reactWrapper.children(AnotherComponent);
        anotherStatelessWrapper = reactWrapper.children(AnotherStatelessComponent);
        reactWrapper = reactWrapper.children({ prop: 'myprop' });
        elementWrapper = reactWrapper.children('.selector');
    }

    function test_childAt() {
        const childWrapper: ReactWrapper<any, any> = reactWrapper.childAt(0);

        interface TmpType1 {
            foo: any;
        }

        interface TmpType2 {
            bar: any;
        }

        const childWrapper2: ReactWrapper<TmpType1, TmpType2> = reactWrapper.childAt<TmpType1, TmpType2>(0);
    }

    function test_parents() {
        reactWrapper = reactWrapper.parents();
        anotherComponentWrapper = reactWrapper.parents(AnotherComponent);
        anotherStatelessWrapper = reactWrapper.parents(AnotherStatelessComponent);
        reactWrapper = reactWrapper.parents({ prop: 'myprop' });
        elementWrapper = reactWrapper.parents('.selector');
    }

    function test_parent() {
        reactWrapper = reactWrapper.parent();
    }

    function test_closest() {
        anotherComponentWrapper = reactWrapper.closest(AnotherComponent);
        anotherStatelessWrapper = reactWrapper.closest(AnotherStatelessComponent);
        reactWrapper = reactWrapper.closest({ prop: 'myprop' });
        elementWrapper = reactWrapper.closest('.selector');
    }

    function test_text() {
        stringVal = reactWrapper.text();
    }

    function test_html() {
        stringVal = reactWrapper.html();
    }

    function test_get() {
        reactElement = reactWrapper.get(1);
    }

    function test_getNode() {
        reactElement = reactWrapper.getNode();
    }

    function test_getNodes() {
        reactElements = reactWrapper.getNodes();
    }

    function test_getElement() {
        reactElement = reactWrapper.getElement();
    }

    function test_getElements() {
        reactElements = reactWrapper.getElements();
    }

    function test_getDOMNode() {
        domElement = reactWrapper.getDOMNode();
        buttonElement = reactWrapper.getDOMNode<HTMLButtonElement>();
    }

    function test_at() {
        reactWrapper = reactWrapper.at(1);
    }

    function test_first() {
        reactWrapper = reactWrapper.first();
    }

    function test_last() {
        reactWrapper = reactWrapper.last();
    }

    function test_slice() {
        reactWrapper = reactWrapper.slice(1);
        reactWrapper = reactWrapper.slice(1, 3);
    }

    function test_tap() {
        reactWrapper.tap((intercepter) => { });
    }

    function test_state() {
        const state: MyComponentState = reactWrapper.state();
        const prop: string = reactWrapper.state('stateProperty');
        const prop2: number = reactWrapper.state<number>('key');
        const prop3 = reactWrapper.state('key');
    }

    function test_context() {
        reactWrapper.context();
        reactWrapper.context('key');
        const tmp: string = reactWrapper.context<string>('key');
    }

    function test_props() {
        const props: MyComponentProps = reactWrapper.props();
        const props2: AnotherComponentProps = reactWrapper.find(AnotherComponent).props();
        const props3: AnotherStatelessProps = reactWrapper.find(AnotherStatelessComponent).props();
        const props4: HTMLAttributes<any> = reactWrapper.find('.selector').props();
    }

    function test_prop() {
        const tmp: number = reactWrapper.prop('numberProp');
        const tmp2: string = reactWrapper.prop<string>('key');
        const tmp3 = reactWrapper.prop('key');
    }

    function test_key() {
        stringVal = reactWrapper.key();
    }

    function test_simulate(...args: any[]) {
        reactWrapper.simulate('click');
        reactWrapper.simulate('click', args);
    }

    function test_setState() {
        reactWrapper = reactWrapper.setState({ stateProperty: 'state' });
        reactWrapper = reactWrapper.setState({ stateProperty: 'state' }, () => console.log('state set'));
    }

    function test_setProps() {
        reactWrapper = reactWrapper.setProps({ stringProp: 'foo' });
        reactWrapper = reactWrapper.setProps({ stringProp: 'foo' }, () => console.log('props set'));
    }

    function test_setContext() {
        reactWrapper = reactWrapper.setContext({ name: 'baz' });
    }

    function test_instance() {
        const myComponent = reactWrapper.instance() as MyComponent;
        myComponent.handleEcho('it works');

        const wrapperPropsOnly = mount<MyComponentProps>(<MyComponent stringProp="value" numberProp={1}/>);
        wrapperPropsOnly.setProps({stringProp: 'new value'});
        // $ExpectError
        wrapperPropsOnly.instance().handleEcho;

        const wrapper = mount<MyComponent>(<MyComponent stringProp="value" numberProp={1}/>);
        wrapper.instance().handleEcho('it works');
    }

    function test_update() {
        reactWrapper = reactWrapper.update();
    }

    function test_debug() {
        stringVal = reactWrapper.debug();
        stringVal = reactWrapper.debug({ verbose: false });
        stringVal = reactWrapper.debug({ ignoreProps: true });
        stringVal = reactWrapper.debug({ ignoreProps: true, verbose: true });
    }

    function test_type() {
        const type: string | StatelessComponent<MyComponentProps> | ComponentClass<MyComponentProps> = reactWrapper.type();
    }

    function test_name() {
        stringVal = reactWrapper.name();
    }

    function test_forEach() {
        reactWrapper =
            reactWrapper.forEach(wrapper => wrapper.props().stringProp);
    }

    function test_map() {
        const arrayNumbers: number[] =
            reactWrapper.map(wrapper => wrapper.props().numberProp);
    }

    function test_reduce() {
        const total: number =
            reactWrapper.reduce<number>(
                (amount: number, n: ReactWrapper<MyComponentProps, MyComponentState>) => amount + n.prop('numberProp')
            );
    }

    function test_reduceRight() {
        const total: number =
            reactWrapper.reduceRight<number>(
                (amount: number, n: ReactWrapper<MyComponentProps, MyComponentState>) => amount + n.prop('numberProp')
            );
    }

    function test_some() {
        boolVal = reactWrapper.some(AnotherComponent);
        boolVal = reactWrapper.some(AnotherStatelessComponent);
        boolVal = reactWrapper.some({ prop: 'myprop' });
        boolVal = reactWrapper.some('.selector');
    }

    function test_someWhere() {
        boolVal = reactWrapper.someWhere((aReactWrapper: ReactWrapper<MyComponentProps, MyComponentState>) => true);
    }

    function test_every() {
        boolVal = reactWrapper.every(AnotherComponent);
        boolVal = reactWrapper.every(AnotherStatelessComponent);
        boolVal = reactWrapper.every({ prop: 'myprop' });
        boolVal = reactWrapper.every('.selector');
    }

    function test_everyWhere() {
        boolVal = reactWrapper.everyWhere((aReactWrapper: ReactWrapper<MyComponentProps, MyComponentState>) => true);
    }

    function test_isEmptyRender() {
        boolVal = reactWrapper.isEmptyRender();
    }

    function test_constructor() {
        let anyWrapper: ReactWrapper;
        anyWrapper = new ReactWrapper(<MyComponent stringProp="1" numberProp={1} />);
        reactWrapper = new ReactWrapper<MyComponentProps, MyComponentState>(<MyComponent stringProp="1" numberProp={1} />);
        reactWrapper = new ReactWrapper<MyComponentProps, MyComponentState>([<MyComponent stringProp="1" numberProp={1} />, <MyComponent stringProp="1" numberProp={1} />]);
        reactWrapper = new ReactWrapper<MyComponentProps, MyComponentState>(<MyComponent stringProp="1" numberProp={1} />, reactWrapper);
        reactWrapper = new ReactWrapper<MyComponentProps, MyComponentState>(<MyComponent stringProp="1" numberProp={1} />, undefined, { attachTo: document.createElement('div') });
        reactWrapper = new ReactWrapper<MyComponentProps, MyComponentState>(<MyComponent stringProp="1" numberProp={1} />, reactWrapper, { attachTo: document.createElement('div') });
    }

    function test_component_type() {
      const wrapper1 = shallow(
<ComponentType stringProp={"S"} numberProp={1} />
);
      wrapper1.find<MyComponentProps>(ComponentType).props().stringProp; // $ExpectType string

      const wrapper2 = mount(
<ComponentType stringProp={"S"} numberProp={1} />
);
      wrapper2.find<MyComponentProps>(ComponentType).props().stringProp; // $ExpectType string
    }

    function test_getWrappingComponent() {
        const MyContext = React.createContext('test');
        function MyProvider(props: MyProviderProps) {
            const { children, value } = props;
            return <MyContext.Provider value={value}>{children}</MyContext.Provider>;
        }
        const wrapper = mount<MyRenderPropProps>(
            <MyRenderPropComponent children={params =>
} />,
            {
                wrappingComponent: MyProvider,
            }
        );
        const provider = wrapper.getWrappingComponent();
        provider.setProps({ value: 'test new' });
    }
}

// CheerioWrapper
function CheerioWrapperTest() {
    const wrapper: Cheerio =
        shallow(
).render() ||
        mount(
).render();

    wrapper.toggleClass('className');
}


text:
insert into KRIM_PERM_T (PERM_ID, OBJ_ID, VER_NBR, PERM_TMPL_ID, NMSPC_CD, NM, DESC_TXT, ACTV_IND)
    VALUES (KRIM_PERM_ID_BS_S.NEXTVAL, sys_guid(), 1, (SELECT PERM_TMPL_ID FROM KRIM_PERM_TMPL_T WHERE NM = 'Perform Document Action'), 'KC-PD', 'Delete Proposal', 'Delete a Proposal', 'Y');

COMMIT;

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace sisadmineiquia\Http\Controllers;

use sisadmineiquia\Http\Requests;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
use Carbon\Carbon;
use Session;
use DB;
//para usuario
use sisadmineiquia\User;
use Illuminate\Support\Facades\Auth;

use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
// Validación de formularios.
use Validator;

// Hash de contraseñas.
use Hash;

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('home');
    }

        public function edit($id)
    {
       return view("auth.edit",["user"=>User::findOrFail($id)]);
    }

    public function update(Request $request,$id)
    {

        // Realizamos la validación de datos recibidos del formulario.
        $rules=array(
            'passwordactual'=>'required|min:6',
            'password'=>'required|min:6',
            'password_confirmation'=>'required|same:password',
            );

        // Llamamos a Validator pasándole las reglas de validación.
        $validator=Validator::make($request->all(),$rules);

        // Si falla la validación redireccionamos de nuevo al formulario
        // enviando la variable Input (que contendrá todos los Input recibidos)
        // y la variable errors que contendrá los mensajes de error de validator.
        if ($validator->fails())
        {
            return Redirect::to('home/'.$id.'/edit')
            ->withInput()
            ->withErrors($validator->messages());
        }else{
            if(Hash::check($request->get('passwordactual'), Auth::user()->password)){
                 $affectedRows = User::where('id','=',$id)
                ->update(['password' =>bcrypt($request->get('password'))]);
                Session::flash('update','Su usuario se ha actualizado correctamente!!!');
                return Redirect::to('home/'.$id.'/edit');

            }else{
                Session::flash('update','La contraseña actual no concide con su usuario!!!');
                return Redirect::to('home/'.$id.'/edit');
            }

            }
    }
}


text:
class BugsController < ApplicationController
  before_action :set_bug, only: [:show, :edit, :update, :destroy, :change]
  before_action :authenticate_user!

  # GET /bugs
  # GET /bugs.json
  def index
    # @bugs = current_user.bugs
    @to_do = current_user.bugs.where(state: "to_do")
    @doing = current_user.bugs.where(state: "doing")
    @done  = current_user.bugs.where(state: "done")
  end

  # GET /bugs/1
  # GET /bugs/1.json
  def show
  end

  # GET /bugs/new
  def new
    @bug = Bug.new
  end

  # GET /bugs/1/edit
  def edit
  end

  # POST /bugs
  # POST /bugs.json
  def create
    @bug = current_user.bugs.new(bug_params)

    respond_to do |format|
      if @bug.save
        format.html { redirect_to @bug, notice: 'Bug criado com sucesso.' }
        format.json { render :show, status: :created, location: @bug }
      else
        format.html { render :new }
        format.json { render json: @bug.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /bugs/1
  # PATCH/PUT /bugs/1.json
  def update
    respond_to do |format|
      if @bug.update(bug_params)
        format.html { redirect_to @bug, notice: 'Bug atualizado com sucesso.' }
        format.json { render :show, status: :ok, location: @bug }
      else
        format.html { render :edit }
        format.json { render json: @bug.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /bugs/1
  # DELETE /bugs/1.json
  def destroy
    @bug.destroy
    respond_to do |format|
      format.html { redirect_to bugs_url, notice: 'Bug removido com sucesso.' }
      format.json { head :no_content }
    end
  end

  def change
    @bug.update_attributes(state: params[:state])
    respond_to do |format|
      format.html { redirect_to bugs_url, notice: 'Bug alterado com sucesso.' }
      format.json { head :no_content }
    end
  end

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

    # Never trust parameters from the scary internet, only allow the white list through.
    def bug_params
      params.require(:bug).permit(:content, :state)
    end
end


text:
mmp-application-reporting
=========================

The mmp-application-reporting library.

Licensed under the Apache License, Version 2.0 (the "License")

You may obtain a copy of the License at

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


text:
package com.microsoft.azure.management.devtestlabs.v2018_09_15.implementation;

import com.microsoft.azure.management.devtestlabs.v2018_09_15.ApplicableSchedule;
import com.microsoft.azure.arm.model.implementation.WrapperImpl;
import java.util.Map;

class ApplicableScheduleImpl extends WrapperImpl<ApplicableScheduleInner> implements ApplicableSchedule {
    private final DevTestLabsManager manager;
    ApplicableScheduleImpl(ApplicableScheduleInner inner, DevTestLabsManager manager) {
        super(inner);
        this.manager = manager;
    }

    @Override
    public DevTestLabsManager manager() {
        return this.manager;
    }

    @Override
    public String id() {
        return this.inner().id();
    }

    @Override
    public ScheduleInner labVmsShutdown() {
        return this.inner().labVmsShutdown();
    }

    @Override
    public ScheduleInner labVmsStartup() {
        return this.inner().labVmsStartup();
    }

    @Override
    public String location() {
        return this.inner().location();
    }

    @Override
    public String name() {
        return this.inner().name();
    }

    @Override
    public Map<String, String> tags() {
        return this.inner().getTags();
    }

    @Override
    public String type() {
        return this.inner().type();
    }

}


text:
namespace CK {
  namespace Component {
    namespace Accessibility {

      /**
       Force enable or disable accessibility.
       @param enabled A Boolean value that determines whether accessibility is enabled.
       @discussion Used for testing. All current unit tests at the date of adding this where written under the
       assumption that accessibility is not enabled. When setting to YES remember to set to NO on teardown.
       */
      void SetForceAccessibilityEnabled(BOOL enabled);
    }
  }
}


text:
declare module 'torrent-parser' {
import torrentParser = require('~torrent-parser/torrent-parser');

export = torrentParser;
}


text:
from typing import List
import logging
from pathlib import Path
import itertools

import parsy

from elm_doc import elm_parser
from elm_doc.elm_parser import Chunk

logger = logging.getLogger(__name__)

def strip_ports_from_file(elm_file: Path) -> None:
    source = elm_file.read_text()
    stripped = strip_ports_from_string(source, str(elm_file))
    elm_file.write_text(stripped)

def strip_ports_from_string(source: str, source_path: str = '<unknown>') -> str:
    output = []
    for chunk in elm_parser.iter_line_chunks(source):
        if chunk.is_port_function():
            output.extend(_rewrite_port_function(chunk, source_path))
        elif chunk.is_port_module():
            output.extend(_rewrite_port_module(chunk))
        else:
            output.extend(chunk.raw_lines())
    return ''.join(output)

def _rewrite_port_module(chunk: Chunk) -> List[str]:
    output = []
    for line in chunk.lines:
        if line.raw.startswith('port module'):
            output.append(line.raw[len('port '):])
        else:
            output.append(line.raw)
    return output

def _rewrite_port_function(chunk: Chunk, source_path: str) -> List[str]:
    output = []

    trailing_non_sources = list(reversed(list(itertools.takewhile(
        lambda l: not l.is_source(), reversed(chunk.lines)))))
    declaration_lines = chunk.lines[:-len(trailing_non_sources)] if trailing_non_sources else chunk.lines

    for line in declaration_lines:
        if line.raw.startswith('port '):
            output.append(line.raw[len('port '):])
        else:
            # These lines may contain comments which, semantically
            # speaking, belong to the next function: the output may
            # not make sense to human reader. Since our audience is
            # the Elm compiler, we don't care that much.
            output.append(line.raw)

    # If this chunk is the very last lines of a file, we may need to add a newline.
    if (not trailing_non_sources) and (not chunk.lines[-1].raw.endswith('\n')):
        output.append('\n')

    try:
        one_liner = ''.join([raw.strip() for raw in chunk.non_comment_raw_lines()])
        port_info = elm_parser.parse_port_declaration(one_liner)
        output.append(_make_dummy_port_implementation(port_info) + '\n')
    except parsy.ParseError:
        line_num = chunk.lines[0].number
        logger.error('''{}:{}: failed to parse a port declaration. We parsed it as:

  {}

If this is a valid port declaration, please submit a bug report'''.format(
            source_path, line_num, one_liner))
        raise

    for trailing_line in trailing_non_sources:
        output.append(trailing_line.raw)

    return output

def _make_dummy_port_implementation(port_info: elm_parser.PortInfo) -> str:
    parts = [port_info.name]

    # arguments
    for i, _ in enumerate(port_info.args):
        parts.append('a{}'.format(i))

    parts.append('=')
    parts.append('{}.none'.format(port_info.port_type.value))
    return ' '.join(parts)


text:
<?xml version="1.0" encoding="utf-8"?>

<game>
	<title>Happy Bard</title>
	<release-date>21 April, 2014</release-date>

	<favicon-url>http://digitaluzu.com/images/happybard_favicon.png</favicon-url>
	<press-can-request-copy>TRUE</press-can-request-copy>

	<platforms>
		<platform>
			<name>Apple App Store (iOS)</name>
			<link>http://itunes.apple.com/app/happy-bard/id855121015</link>
		</platform>
        <platform>
			<name>Google Play (Android)</name>
			<link>https://play.google.com/store/apps/details?id=com.DigitalUzu.HappyBard</link>
		</platform>
	</platforms>

	<prices>
		<price>
			<currency>FREE</currency>
		</price>
	</prices>

	<description>
	Embark on an epic journey. Jump over pipes. Collect hats. Master the lute.

	SAVE... THE... WORLD!
	</description>

	<history>
	Happy Bard was originally created for #flappyjam - a game jam with a theme of the infamous Flappy Bird game.

	The #flappyjam version of Happy Bard received a lot of positive feedback for its gameplay and visuals. There were Let's Play videos popping up on YouTube, and it even received some press from sites such as TouchArcade and JayIsGames.

	Happy Bard was ranked #11 out of 762 #flappyjam entries.

	Eventually, Happy Bard was released for mobile devices in anticipation of the 23rd of April (often called "Bards Day"), as this day is associated with the birth and death of William Shakespeare.
	</history>

	<features>
		<feature>Pipes.</feature>
		<feature>Hats.</feature>
		<feature>Double jumping.</feature>
		<feature>Triple jumping.</feature>
		<feature>Infinite jumping.</feature>
		<feature>Procedural pipe positioning with height adjustment heuristics.</feature>
		<feature>Infinite pipe generation for endless gameplay.</feature>
		<feature>Online leaderboards and achievements.</feature>
	</features>

	<additionals>
		<additional>
			<title>Happy Bard (Flappy Jam Post-Mortem)</title>
			<description>Reviews and "Let's Play" videos of the original #flappyjam version of Happy Bard: </description>
			<link>http://www.shy.am/2014/02/happy-bard/</link>
		</additional>
	</additionals>

	<credits>
		<credit>
			<person>Shyam Guthikonda</person>
			<role>Developer - Digital Uzu</role>
		</credit>
	</credits>
</game>


text:
"""
    KubeVirt API

    This is KubeVirt API an add-on for Kubernetes.

    OpenAPI spec version: 1.0.0
    Contact: kubevirt-dev@googlegroups.com
    Generated by: https://github.com/swagger-api/swagger-codegen.git
"""

from pprint import pformat
from six import iteritems
import re

class V1beta1DataVolumeBlankImage(object):
    """
    NOTE: This class is auto generated by the swagger code generator program.
    Do not edit the class manually.
    """

    """
    Attributes:
      swagger_types (dict): The key is attribute name
                            and the value is attribute type.
      attribute_map (dict): The key is attribute name
                            and the value is json key in definition.
    """
    swagger_types = {

    }

    attribute_map = {

    }

    def __init__(self):
        """
        V1beta1DataVolumeBlankImage - a model defined in Swagger
        """

    def to_dict(self):
        """
        Returns the model properties as a dict
        """
        result = {}

        for attr, _ in iteritems(self.swagger_types):
            value = getattr(self, attr)
            if isinstance(value, list):
                result[attr] = list(map(
                    lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
                    value
                ))
            elif hasattr(value, "to_dict"):
                result[attr] = value.to_dict()
            elif isinstance(value, dict):
                result[attr] = dict(map(
                    lambda item: (item[0], item[1].to_dict())
                    if hasattr(item[1], "to_dict") else item,
                    value.items()
                ))
            else:
                result[attr] = value

        return result

    def to_str(self):
        """
        Returns the string representation of the model
        """
        return pformat(self.to_dict())

    def __repr__(self):
        """
        For `print` and `pprint`
        """
        return self.to_str()

    def __eq__(self, other):
        """
        Returns true if both objects are equal
        """
        if not isinstance(other, V1beta1DataVolumeBlankImage):
            return False

        return self.__dict__ == other.__dict__

    def __ne__(self, other):
        """
        Returns true if both objects are not equal
        """
        return not self == other


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta {{ URL::asset('') }}{{ URL::asset('') }}http-equiv="X-UA-Compatible" content="IE=edge">
    <title>@lang('view.Login') - @lang('view.TBM')</title>

    <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">

    <link rel="stylesheet" href="{{ URL::asset('css/bootstrap.min.css') }}">
    <link rel="stylesheet" href="{{ URL::asset('css/font-awesome.min.css') }}">
    <link rel="stylesheet" href="{{ URL::asset('css/AdminLTE.min.css') }}">
    <link rel="stylesheet" href="{{ URL::asset('vendor/iCheck/square/blue.css') }}">

    <link rel="stylesheet" href="{{ URL::asset('css/ionicons.min.css') }}">

        TBM @lang('view.TBM')@lang('view.Login')

        {{--
Sign in to start your session
--}}

        <form method="post" action="{{ url('/login') }}">
            {!! csrf_field() !!}

has('email') ? ' has-error' : '' }}">
                <input type="email" class="form-control" name="email" value="{{ old('email') }}" placeholder="Email">

                @if ($errors->has('email'))

                        {{ $errors->first('email') }}

                @endif

has('password') ? ' has-error' : '' }}">
                <input type="password" class="form-control" placeholder="Password" name="password">

                @if ($errors->has('password'))

                    {{ $errors->first('password') }}

                @endif

                            <input type="checkbox" name="remember"> Remember Me

                    <button type="submit" class="btn btn-primary btn-block btn-flat">Sign In</button>

        </form>

        I forgot my password

        Register a new membership


text:
package org.lttpp.eemory.oauth.impl;

import org.eclipse.jetty.util.log.AbstractLogger;
import org.eclipse.jetty.util.log.Logger;
import org.lttpp.eemory.util.LogUtil;

public class EclipseErrorLog extends AbstractLogger {

    private final String name;

    public EclipseErrorLog() {
        this(EclipseErrorLog.class.getName());
    }

    public EclipseErrorLog(final String name) {
        this.name = name;
    }

    @Override
    public void debug(final Throwable thrown) {
        nop();
    }

    @Override
    public void debug(final String message, final Object... args) {
        nop();
    }

    @Override
    public void debug(final String message, final Throwable args) {
        nop();
    }

    @Override
    public String getName() {
        return name;
    }

    @Override
    public void ignore(final Throwable thrown) {
        nop();
    }

    @Override
    public void info(final Throwable thrown) {
        nop();
    }

    @Override
    public void info(final String message, final Object... args) {
        nop();
    }

    @Override
    public void info(final String message, final Throwable args) {
        nop();
    }

    @Override
    public boolean isDebugEnabled() {
        return false;
    }

    @Override
    public void setDebugEnabled(final boolean debugEnabled) {
        nop();
    }

    @Override
    public void warn(final Throwable thrown) {
        LogUtil.logWarning(thrown);
    }

    @Override
    public void warn(final String message, final Object... args) {
        LogUtil.logWarning(format(message, args));
    }

    @Override
    public void warn(final String message, final Throwable thrown) {
        LogUtil.logWarning(message, thrown);
    }

    @Override
    protected Logger newLogger(final String name) {
        return new EclipseErrorLog(name);
    }

    private String format(String msg, final Object... args) {
        msg = String.valueOf(msg); // Avoids NPE
        String braces = "{}";
        StringBuilder builder = new StringBuilder();
        int start = 0;
        for (Object arg : args) {
            int bracesIndex = msg.indexOf(braces, start);
            if (bracesIndex < 0) {
                builder.append(msg.substring(start));
                builder.append(" ");
                builder.append(arg);
                start = msg.length();
            } else {
                builder.append(msg.substring(start, bracesIndex));
                builder.append(String.valueOf(arg));
                start = bracesIndex + braces.length();
            }
        }
        builder.append(msg.substring(start));
        return builder.toString();
    }

    private void nop() {

    }

}


text:
package net.karlmartens.platform.io;

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.util.Collection;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

/**
 * @author kmartens
 *
 */
final class Deserializers {

    private final Map<Class<?>, Deserializer<?>> _map = new HashMap<>();
    private boolean _useGenericObjectDeserializer = false;

    void useGenericObjectDeserializer() {
        _useGenericObjectDeserializer = true;
    }

  <T> Deserializers addDeserializer(Class<T> type,
            Deserializer<T> deserializer) {
        _map.put(type, deserializer);
        return this;
    }

    @SuppressWarnings("unchecked")
    <T> Deserializer<T> getDeserializer(Class<T> type) {
        Deserializer<T> candidate = (Deserializer<T>) _map.get(type);
        if (candidate != null)
            return candidate;

        if (type.isEnum())
            return new EnumDeserializer<>(type);

        if (type.isArray()) {
            Class<?> componentType = type.getComponentType();
            Deserializer<?> deserializer = getDeserializer(componentType);
            return (Deserializer<T>) ArrayDeserializer.create(componentType,
                    deserializer);
        }

        if (_useGenericObjectDeserializer) {
            return GenericFieldsObjectDeserializer.create(this, type);
        }

        throw new IllegalStateException(String.format(Locale.US,
                "No deserializer for the type '%s'.", type));
    }

    @SuppressWarnings("unchecked")
    public <T> Deserializer<T> getDeserializer(Field field) {
      Class<T> type = (Class<T>)field.getType();
      if (Collection.class.isAssignableFrom(type)) {
        ParameterizedType pType = (ParameterizedType)field.getGenericType();
        Class<?> componentType = (Class<?>)pType.getActualTypeArguments()[0];
        Deserializer<?> deserializer = getDeserializer(componentType);
        return (Deserializer<T>) CollectionDeserializer.create(type, deserializer);
      }

      if (Map.class.isAssignableFrom(type)) {
        ParameterizedType pType = (ParameterizedType)field.getGenericType();
        Class<?> keyType = (Class<?>)pType.getActualTypeArguments()[0];
        Class<?> valueType = (Class<?>)pType.getActualTypeArguments()[1];
        Deserializer<?> keyDeserializer = getDeserializer(keyType);
        Deserializer<?> valueDeserializer = getDeserializer(valueType);
        return (Deserializer<T>) MapDeserializer.create(type, keyDeserializer, valueDeserializer);
      }

      return getDeserializer(type);
    }

}


text:
package com.maxifier.guice.events;

import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Filter(matcher = HandleAnnotated.Matcher.class)
public @interface HandleAnnotated {
    Class<? extends Annotation>[] value();

    public class Matcher implements EventClassMatcher {
        private final Class<? extends Annotation>[] value;

        @MatcherConstructor
        public Matcher(HandleAnnotated h) {
            value = h.value();
            for (Class<? extends Annotation> v : value) {
                if (!v.isAnnotationPresent(EventGroup.class)) {
                    throw new RuntimeException("Error while parsing " + h + ": annotation class " + v + " doesn't have @EventGroup annotation");
                }
            }
        }

        @Override
        public boolean matches(Class event) {
            for (Class<? extends Annotation> c : value) {
                if (event.isAnnotationPresent(c)) {
                    return true;
                }
            }
            return false;
        }
    }
}


text:
"""
Service Support: module definition
"""
from anaf.services.cron import tickets_escalate
PROPERTIES = {
    'title': 'Service Support',
    'details': 'Service delivery and support management',
    'url': '/services/',
    'system': False,
    'type': 'major'
}

URL_PATTERNS = [
    '^/services/',
]

#
# Cron
#

CRON = [tickets_escalate]


text:
import os
import sublime
import sublime_plugin
from datetime import datetime
from .archiver import Archiver
from .command import CommandWithStatus
from .settings import BACKUP_DIRECTORY_NAME

class SublimeSyncRestore(sublime_plugin.ApplicationCommand, CommandWithStatus):

    def __init__(self, *args, **kwargs):
        super(SublimeSyncRestore, self).__init__(*args, **kwargs)
        self.running = False
        self.backups = []
        self.backup_path = os.path.join(os.path.dirname(__file__), BACKUP_DIRECTORY_NAME)

    def restore(self, index):
        """
        Starts restore process
        """
        if index != -1:
            backup = self.backups[index]

            # Move pacakges directories to a .bak
            self.set_message(u"Moving directories...")
            archiver = Archiver()
            archiver.move_packages_to_backup_dirs()

            # Unpack backup
            self.set_message(u"Unpacking backup...")
            archiver.unpack_packages(os.path.join(self.backup_path, backup[1]))

            # Delete moved directories
            self.set_message(u"Deleting old directories...")
            archiver.remove_backup_dirs()

            self.set_message(u"Your Sublime Text has been restored !")
            self.unset_message()
            self.running = False

    def datetime_from_filename(self, filename):
        """
        Returns a datetime object from a filename with timestamp
        """
        return datetime.fromtimestamp(float(os.path.splitext(filename)[0]))

    def get_backups(self):
        """
        Retrieves a list of backup archives
        """
        self.backups = []

        for f in os.listdir(self.backup_path):
            if os.path.isfile(os.path.join(self.backup_path, f)):
                try:
                    d = self.datetime_from_filename(f)
                    self.backups.append(['Backup on %s' % d.strftime('%c'), f])
                except Exception:
                    pass

        self.backups.sort(key=lambda item: self.datetime_from_filename(item[1]), reverse=True)

    def start(self):
        """
        Restores a backup
        """
        self.get_backups()

        if self.backups:
            self.running = True
            sublime.active_window().show_quick_panel(self.backups, self.restore)
        else:
            self.set_message("No backups found")
            self.unset_message()

    def run(self, *args):
        if self.running:
            self.set_quick_message("Already working on a restore...")
            return
        sublime.set_timeout_async(self.start, 0)


text:
"""This implements an ANSI terminal emulator as a subclass of screen.

$Id: ANSI.py 491 2007-12-16 20:04:57Z noah $
"""
# references:
#     http://www.retards.org/terminals/vt102.html
#     http://vt100.net/docs/vt102-ug/contents.html
#     http://vt100.net/docs/vt220-rm/
#     http://www.termsys.demon.co.uk/vtansi.htm

import screen
import FSM
import copy
import string

def Emit(fsm):

    screen = fsm.memory[0]
    screen.write_ch(fsm.input_symbol)

def StartNumber(fsm):

    fsm.memory.append(fsm.input_symbol)

def BuildNumber(fsm):

    ns = fsm.memory.pop()
    ns = ns + fsm.input_symbol
    fsm.memory.append(ns)

def DoBackOne(fsm):

    screen = fsm.memory[0]
    screen.cursor_back()

def DoBack(fsm):

    count = int(fsm.memory.pop())
    screen = fsm.memory[0]
    screen.cursor_back(count)

def DoDownOne(fsm):

    screen = fsm.memory[0]
    screen.cursor_down()

def DoDown(fsm):

    count = int(fsm.memory.pop())
    screen = fsm.memory[0]
    screen.cursor_down(count)

def DoForwardOne(fsm):

    screen = fsm.memory[0]
    screen.cursor_forward()

def DoForward(fsm):

    count = int(fsm.memory.pop())
    screen = fsm.memory[0]
    screen.cursor_forward(count)

def DoUpReverse(fsm):

    screen = fsm.memory[0]
    screen.cursor_up_reverse()

def DoUpOne(fsm):

    screen = fsm.memory[0]
    screen.cursor_up()

def DoUp(fsm):

    count = int(fsm.memory.pop())
    screen = fsm.memory[0]
    screen.cursor_up(count)

def DoHome(fsm):

    c = int(fsm.memory.pop())
    r = int(fsm.memory.pop())
    screen = fsm.memory[0]
    screen.cursor_home(r, c)

def DoHomeOrigin(fsm):

    c = 1
    r = 1
    screen = fsm.memory[0]
    screen.cursor_home(r, c)

def DoEraseDown(fsm):

    screen = fsm.memory[0]
    screen.erase_down()

def DoErase(fsm):

    arg = int(fsm.memory.pop())
    screen = fsm.memory[0]
    if arg == 0:
        screen.erase_down()
    elif arg == 1:
        screen.erase_up()
    elif arg == 2:
        screen.erase_screen()

def DoEraseEndOfLine(fsm):

    screen = fsm.memory[0]
    screen.erase_end_of_line()

def DoEraseLine(fsm):

    screen = fsm.memory[0]
    if arg == 0:
        screen.end_of_line()
    elif arg == 1:
        screen.start_of_line()
    elif arg == 2:
        screen.erase_line()

def DoEnableScroll(fsm):

    screen = fsm.memory[0]
    screen.scroll_screen()

def DoCursorSave(fsm):

    screen = fsm.memory[0]
    screen.cursor_save_attrs()

def DoCursorRestore(fsm):

    screen = fsm.memory[0]
    screen.cursor_restore_attrs()

def DoScrollRegion(fsm):

    screen = fsm.memory[0]
    r2 = int(fsm.memory.pop())
    r1 = int(fsm.memory.pop())
    screen.scroll_screen_rows(r1, r2)

def DoMode(fsm):

    screen = fsm.memory[0]
    mode = fsm.memory.pop()  # Should be 4
    # screen.setReplaceMode ()

def Log(fsm):

    screen = fsm.memory[0]
    fsm.memory = [screen]
    fout = open('log', 'a')
    fout.write(fsm.input_symbol + ',' + fsm.current_state + '\n')
    fout.close()

class term (screen.screen):
    """This is a placeholder.
    In theory I might want to add other terminal types.
    """

    def __init__(self, r=24, c=80):
        screen.screen.__init__(self, r, c)

class ANSI (term):

    """This class encapsulates a generic terminal. It filters a stream and
    maintains the state of a screen object. """

    def __init__(self, r=24, c=80):

        term.__init__(self, r, c)

        #self.screen = screen (24,80)
        self.state = FSM.FSM('INIT', [self])
        self.state.set_default_transition(Log, 'INIT')
        self.state.add_transition_any('INIT', Emit, 'INIT')
        self.state.add_transition('\x1b', 'INIT', None, 'ESC')
        self.state.add_transition_any('ESC', Log, 'INIT')
        self.state.add_transition('(', 'ESC', None, 'G0SCS')
        self.state.add_transition(')', 'ESC', None, 'G1SCS')
        self.state.add_transition_list('AB012', 'G0SCS', None, 'INIT')
        self.state.add_transition_list('AB012', 'G1SCS', None, 'INIT')
        self.state.add_transition('7', 'ESC', DoCursorSave, 'INIT')
        self.state.add_transition('8', 'ESC', DoCursorRestore, 'INIT')
        self.state.add_transition('M', 'ESC', DoUpReverse, 'INIT')
        self.state.add_transition('>', 'ESC', DoUpReverse, 'INIT')
        self.state.add_transition('<', 'ESC', DoUpReverse, 'INIT')
        # Selects application keypad.
        self.state.add_transition('=', 'ESC', None, 'INIT')
        self.state.add_transition('#', 'ESC', None, 'GRAPHICS_POUND')
        self.state.add_transition_any('GRAPHICS_POUND', None, 'INIT')
        self.state.add_transition('[', 'ESC', None, 'ELB')
        # ELB means Escape Left Bracket. That is ^[[
        self.state.add_transition('H', 'ELB', DoHomeOrigin, 'INIT')
        self.state.add_transition('D', 'ELB', DoBackOne, 'INIT')
        self.state.add_transition('B', 'ELB', DoDownOne, 'INIT')
        self.state.add_transition('C', 'ELB', DoForwardOne, 'INIT')
        self.state.add_transition('A', 'ELB', DoUpOne, 'INIT')
        self.state.add_transition('J', 'ELB', DoEraseDown, 'INIT')
        self.state.add_transition('K', 'ELB', DoEraseEndOfLine, 'INIT')
        self.state.add_transition('r', 'ELB', DoEnableScroll, 'INIT')
        self.state.add_transition('m', 'ELB', None, 'INIT')
        self.state.add_transition('?', 'ELB', None, 'MODECRAP')
        self.state.add_transition_list(
            string.digits, 'ELB', StartNumber, 'NUMBER_1')
        self.state.add_transition_list(
            string.digits, 'NUMBER_1', BuildNumber, 'NUMBER_1')
        self.state.add_transition('D', 'NUMBER_1', DoBack, 'INIT')
        self.state.add_transition('B', 'NUMBER_1', DoDown, 'INIT')
        self.state.add_transition('C', 'NUMBER_1', DoForward, 'INIT')
        self.state.add_transition('A', 'NUMBER_1', DoUp, 'INIT')
        self.state.add_transition('J', 'NUMBER_1', DoErase, 'INIT')
        self.state.add_transition('K', 'NUMBER_1', DoEraseLine, 'INIT')
        self.state.add_transition('l', 'NUMBER_1', DoMode, 'INIT')
        # It gets worse... the 'm' code can have infinite number of
        # number;number;number before it. I've never seen more than two,
        # but the specs say it's allowed. crap!
        self.state.add_transition('m', 'NUMBER_1', None, 'INIT')
        # LED control. Same problem as 'm' code.
        self.state.add_transition('q', 'NUMBER_1', None, 'INIT')

        # \E[?47h appears to be "switch to alternate screen"
        # \E[?47l restores alternate screen... I think.
        self.state.add_transition_list(
            string.digits, 'MODECRAP', StartNumber, 'MODECRAP_NUM')
        self.state.add_transition_list(
            string.digits,
            'MODECRAP_NUM',
            BuildNumber,
            'MODECRAP_NUM')
        self.state.add_transition('l', 'MODECRAP_NUM', None, 'INIT')
        self.state.add_transition('h', 'MODECRAP_NUM', None, 'INIT')

# RM   Reset Mode                Esc [ Ps l                   none
        self.state.add_transition(';', 'NUMBER_1', None, 'SEMICOLON')
        self.state.add_transition_any('SEMICOLON', Log, 'INIT')
        self.state.add_transition_list(
            string.digits, 'SEMICOLON', StartNumber, 'NUMBER_2')
        self.state.add_transition_list(
            string.digits, 'NUMBER_2', BuildNumber, 'NUMBER_2')
        self.state.add_transition_any('NUMBER_2', Log, 'INIT')
        self.state.add_transition('H', 'NUMBER_2', DoHome, 'INIT')
        self.state.add_transition('f', 'NUMBER_2', DoHome, 'INIT')
        self.state.add_transition('r', 'NUMBER_2', DoScrollRegion, 'INIT')
        # It gets worse... the 'm' code can have infinite number of
        # number;number;number before it. I've never seen more than two,
        # but the specs say it's allowed. crap!
        self.state.add_transition('m', 'NUMBER_2', None, 'INIT')
        # LED control. Same problem as 'm' code.
        self.state.add_transition('q', 'NUMBER_2', None, 'INIT')

    def process(self, c):

        self.state.process(c)

    def process_list(self, l):

        self.write(l)

    def write(self, s):

        for c in s:
            self.process(c)

    def flush(self):

        pass

    def write_ch(self, ch):
        """This puts a character at the current cursor position. cursor
        position if moved forward with wrap-around, but no scrolling is done if
        the cursor hits the lower-right corner of the screen. """

        #\r and \n both produce a call to crlf().
        ch = ch[0]

        if ch == '\r':
            #    self.crlf()
            return
        if ch == '\n':
            self.crlf()
            return
        if ch == chr(screen.BS):
            self.cursor_back()
            self.put_abs(self.cur_r, self.cur_c, ' ')
            return

        if ch not in string.printable:
            fout = open('log', 'a')
            fout.write('Nonprint: ' + str(ord(ch)) + '\n')
            fout.close()
            return
        self.put_abs(self.cur_r, self.cur_c, ch)
        old_r = self.cur_r
        old_c = self.cur_c
        self.cursor_forward()
        if old_c == self.cur_c:
            self.cursor_down()
            if old_r != self.cur_r:
                self.cursor_home(self.cur_r, 1)
            else:
                self.scroll_up()
                self.cursor_home(self.cur_r, 1)
                self.erase_line()

#    def test (self):
#
#        import sys
#        write_text = 'I\'ve got a ferret sticking up my nose.\n' + \
#        '(He\'s got a ferret sticking up his nose.)\n' + \
#        'How it got there I can\'t tell\n' + \
#        'But now it\'s there it hurts like hell\n' + \
#        'And what is more it radically affects my sense of smell.\n' + \
#        '(His sense of smell.)\n' + \
#        'I can see a bare-bottomed mandril.\n' + \
#        '(Slyly eyeing his other nostril.)\n' + \
#        'If it jumps inside there too I really don\'t know what to do\n' + \
#        'I\'ll be the proud posessor of a kind of nasal zoo.\n' + \
#        '(A nasal zoo.)\n' + \
#        'I\'ve got a ferret sticking up my nose.\n' + \
#        '(And what is worst of all it constantly explodes.)\n' + \
#        '"Ferrets don\'t explode," you say\n' + \
#        'But it happened nine times yesterday\n' + \
#        'And I should know for each time I was standing in the way.\n' + \
#        'I\'ve got a ferret sticking up my nose.\n' + \
#        '(He\'s got a ferret sticking up his nose.)\n' + \
#        'How it got there I can\'t tell\n' + \
#        'But now it\'s there it hurts like hell\n' + \
#        'And what is more it radically affects my sense of smell.\n' + \
#        '(His sense of smell.)'
#        self.fill('.')
#        self.cursor_home()
#        for c in write_text:
#            self.write_ch (c)
#        print str(self)
#
# if __name__ == '__main__':
#    t = ANSI(6,65)
#    t.test()


text:
import threading
import time

def run(n):
    semaphore.acquire()
    time.sleep(1)
    print("run the thread:%s\n" % n)
    semaphore.release()

num = 0
semaphore = threading.BoundedSemaphore(5)

for i in range(22):
    t = threading.Thread(target=run, args=("t-%s" % i,))
    t.start()

while threading.active_count() != 1:
    pass
else:
    print('---all threads done---')


text:
cask "font-kirang-haerang" do
  version :latest
  sha256 :no_check

  url "https://github.com/google/fonts/raw/main/ofl/kiranghaerang/KirangHaerang-Regular.ttf",
      verified: "github.com/google/fonts/"
  name "Kirang Haerang"
  homepage "https://fonts.google.com/specimen/Kirang+Haerang"

  font "KirangHaerang-Regular.ttf"
end


text:
namespace extensions {

namespace language_settings_private = api::language_settings_private;

#if defined(OS_CHROMEOS)
using chromeos::input_method::InputMethodDescriptors;
using chromeos::input_method::InputMethodManager;
using chromeos::input_method::InputMethodUtil;
#endif

LanguageSettingsPrivateGetLanguageListFunction::
    LanguageSettingsPrivateGetLanguageListFunction() {
}

LanguageSettingsPrivateGetLanguageListFunction::
    ~LanguageSettingsPrivateGetLanguageListFunction() {
}

ExtensionFunction::ResponseAction
LanguageSettingsPrivateGetLanguageListFunction::Run() {
  // Collect the language codes from the supported accept-languages.
  const std::string app_locale = g_browser_process->GetApplicationLocale();
  std::vector<std::string> language_codes;
  l10n_util::GetAcceptLanguagesForLocale(app_locale, &language_codes);

  // Map of display name -> {language code, native display name}.
  typedef std::pair<std::string, base::string16> LanguagePair;
  typedef std::map<base::string16, LanguagePair,
      l10n_util::StringComparator<base::string16>> LanguageMap;

  // Collator used to sort display names in the current locale.
  UErrorCode error = U_ZERO_ERROR;
  std::unique_ptr<icu::Collator> collator(
      icu::Collator::createInstance(icu::Locale(app_locale.c_str()), error));
  if (U_FAILURE(error))
    collator.reset();
  LanguageMap language_map(
      l10n_util::StringComparator<base::string16>(collator.get()));

  // Build the list of display names and the language map.
  for (const auto& code : language_codes) {
    base::string16 display_name = l10n_util::GetDisplayNameForLocale(
        code, app_locale, false);
    base::string16 native_display_name = l10n_util::GetDisplayNameForLocale(
        code, code, false);
    language_map[display_name] = std::make_pair(code, native_display_name);
  }

  // Get the list of available locales (display languages) and convert to a set.
  const std::vector<std::string>& locales = l10n_util::GetAvailableLocales();
  const base::hash_set<std::string> locale_set(
      locales.begin(), locales.end());

  // Get the list of spell check languages and convert to a set.
  std::vector<std::string> spellcheck_languages;
  chrome::spellcheck_common::SpellCheckLanguages(&spellcheck_languages);
  const base::hash_set<std::string> spellcheck_language_set(
      spellcheck_languages.begin(), spellcheck_languages.end());

  // Get the list of translatable languages and convert to a set.
  std::vector<std::string> translate_languages;
  translate::TranslateDownloadManager::GetSupportedLanguages(
      &translate_languages);
  const base::hash_set<std::string> translate_language_set(
      translate_languages.begin(), translate_languages.end());

  // Build the language list from the language map.
  std::unique_ptr<base::ListValue> language_list(new base::ListValue);
  for (const auto& entry : language_map) {
    const base::string16& display_name = entry.first;
    const LanguagePair& pair = entry.second;

    language_settings_private::Language language;
    language.code = pair.first;

    base::string16 adjusted_display_name(display_name);
    base::i18n::AdjustStringForLocaleDirection(&adjusted_display_name);
    language.display_name = base::UTF16ToUTF8(adjusted_display_name);

    base::string16 adjusted_native_display_name(pair.second);
    base::i18n::AdjustStringForLocaleDirection(&adjusted_native_display_name);
    language.native_display_name =
        base::UTF16ToUTF8(adjusted_native_display_name);

    // Set optional fields only if they differ from the default.
    if (base::i18n::StringContainsStrongRTLChars(display_name))
      language.display_name_rtl.reset(new bool(true));
    if (locale_set.count(pair.first) > 0)
      language.supports_ui.reset(new bool(true));
    if (spellcheck_language_set.count(pair.first) > 0)
      language.supports_spellcheck.reset(new bool(true));
    if (translate_language_set.count(pair.first) > 0)
      language.supports_translate.reset(new bool(true));

    language_list->Append(language.ToValue());
  }
  return RespondNow(OneArgument(language_list.release()));
}

LanguageSettingsPrivateSetLanguageListFunction::
    LanguageSettingsPrivateSetLanguageListFunction()
    : chrome_details_(this) {
}

LanguageSettingsPrivateSetLanguageListFunction::
    ~LanguageSettingsPrivateSetLanguageListFunction() {
}

ExtensionFunction::ResponseAction
LanguageSettingsPrivateSetLanguageListFunction::Run() {
  std::unique_ptr<language_settings_private::SetLanguageList::Params>
      parameters =
          language_settings_private::SetLanguageList::Params::Create(*args_);
  EXTENSION_FUNCTION_VALIDATE(parameters.get());
#if 0

  std::unique_ptr<translate::TranslatePrefs> translate_prefs =
      ChromeTranslateClient::CreateTranslatePrefs(
          chrome_details_.GetProfile()->GetPrefs());
  translate_prefs->UpdateLanguageList(parameters->language_codes);
#endif
  return RespondNow(NoArguments());
}

LanguageSettingsPrivateGetSpellcheckDictionaryStatusesFunction::
    LanguageSettingsPrivateGetSpellcheckDictionaryStatusesFunction() {
}

LanguageSettingsPrivateGetSpellcheckDictionaryStatusesFunction::
    ~LanguageSettingsPrivateGetSpellcheckDictionaryStatusesFunction() {
}

ExtensionFunction::ResponseAction
LanguageSettingsPrivateGetSpellcheckDictionaryStatusesFunction::Run() {
  LanguageSettingsPrivateDelegate* delegate =
      LanguageSettingsPrivateDelegateFactory::GetForBrowserContext(
          browser_context());

  return RespondNow(OneArgument(
      language_settings_private::GetSpellcheckDictionaryStatuses::Results::
          Create(delegate->GetHunspellDictionaryStatuses())));
}

LanguageSettingsPrivateGetSpellcheckWordsFunction::
    LanguageSettingsPrivateGetSpellcheckWordsFunction() {
}

LanguageSettingsPrivateGetSpellcheckWordsFunction::
    ~LanguageSettingsPrivateGetSpellcheckWordsFunction() {
}

ExtensionFunction::ResponseAction
LanguageSettingsPrivateGetSpellcheckWordsFunction::Run() {
  SpellcheckService* service =
      SpellcheckServiceFactory::GetForContext(browser_context());
  SpellcheckCustomDictionary* dictionary = service->GetCustomDictionary();

  if (dictionary->IsLoaded())
    return RespondNow(OneArgument(GetSpellcheckWords().release()));

  dictionary->AddObserver(this);
  AddRef();  // Balanced in OnCustomDictionaryLoaded().
  return RespondLater();
}

void
LanguageSettingsPrivateGetSpellcheckWordsFunction::OnCustomDictionaryLoaded() {
  SpellcheckService* service =
      SpellcheckServiceFactory::GetForContext(browser_context());
  service->GetCustomDictionary()->RemoveObserver(this);
  Respond(OneArgument(GetSpellcheckWords().release()));
  Release();
}

void
LanguageSettingsPrivateGetSpellcheckWordsFunction::OnCustomDictionaryChanged(
    const SpellcheckCustomDictionary::Change& dictionary_change) {
  NOTREACHED() << "SpellcheckCustomDictionary::Observer: "
                  "OnCustomDictionaryChanged() called before "
                  "OnCustomDictionaryLoaded()";
}

std::unique_ptr<base::ListValue>
LanguageSettingsPrivateGetSpellcheckWordsFunction::GetSpellcheckWords() const {
  SpellcheckService* service =
      SpellcheckServiceFactory::GetForContext(browser_context());
  SpellcheckCustomDictionary* dictionary = service->GetCustomDictionary();
  DCHECK(dictionary->IsLoaded());

  // TODO(michaelpg): Sort using app locale.
  std::unique_ptr<base::ListValue> word_list(new base::ListValue());
  const std::set<std::string>& words = dictionary->GetWords();
  for (const std::string& word : words)
    word_list->AppendString(word);
  return word_list;
}

LanguageSettingsPrivateAddSpellcheckWordFunction::
    LanguageSettingsPrivateAddSpellcheckWordFunction() {
}

LanguageSettingsPrivateAddSpellcheckWordFunction::
    ~LanguageSettingsPrivateAddSpellcheckWordFunction() {
}

ExtensionFunction::ResponseAction
LanguageSettingsPrivateAddSpellcheckWordFunction::Run() {
  std::unique_ptr<language_settings_private::AddSpellcheckWord::Params> params =
      language_settings_private::AddSpellcheckWord::Params::Create(*args_);
  EXTENSION_FUNCTION_VALIDATE(params.get());

  SpellcheckService* service =
      SpellcheckServiceFactory::GetForContext(browser_context());
  bool success = service->GetCustomDictionary()->AddWord(params->word);

  return RespondNow(OneArgument(new base::FundamentalValue(success)));
}

LanguageSettingsPrivateRemoveSpellcheckWordFunction::
    LanguageSettingsPrivateRemoveSpellcheckWordFunction() {
}

LanguageSettingsPrivateRemoveSpellcheckWordFunction::
    ~LanguageSettingsPrivateRemoveSpellcheckWordFunction() {
}

ExtensionFunction::ResponseAction
LanguageSettingsPrivateRemoveSpellcheckWordFunction::Run() {
  std::unique_ptr<language_settings_private::RemoveSpellcheckWord::Params>
      params = language_settings_private::RemoveSpellcheckWord::Params::Create(
          *args_);
  EXTENSION_FUNCTION_VALIDATE(params.get());

  SpellcheckService* service =
      SpellcheckServiceFactory::GetForContext(browser_context());
  bool success = service->GetCustomDictionary()->RemoveWord(params->word);

  return RespondNow(OneArgument(new base::FundamentalValue(success)));
}

LanguageSettingsPrivateGetTranslateTargetLanguageFunction::
    LanguageSettingsPrivateGetTranslateTargetLanguageFunction()
    : chrome_details_(this) {
}

LanguageSettingsPrivateGetTranslateTargetLanguageFunction::
    ~LanguageSettingsPrivateGetTranslateTargetLanguageFunction() {
}

ExtensionFunction::ResponseAction
LanguageSettingsPrivateGetTranslateTargetLanguageFunction::Run() {
  return RespondNow(OneArgument(new base::StringValue("")));
#if 0
      TranslateService::GetTargetLanguage(
          chrome_details_.GetProfile()->GetPrefs()))));
#endif
}

#if defined(OS_CHROMEOS)
// Populates the vector of input methods using information in the list of
// descriptors. Used for languageSettingsPrivate.getInputMethodLists().
void PopulateInputMethodListFromDescriptors(
    const InputMethodDescriptors& descriptors,
    std::vector<language_settings_private::InputMethod>* input_methods) {
  InputMethodManager* manager = InputMethodManager::Get();
  InputMethodUtil* util = manager->GetInputMethodUtil();
  scoped_refptr<InputMethodManager::State> ime_state =
      manager->GetActiveIMEState();
  if (!ime_state.get())
    return;

  // Get the list of enabled IDs and convert to a set for membership testing.
  const std::vector<std::string>& active_ids_list =
      ime_state->GetActiveInputMethodIds();
  const std::set<std::string> active_ids(
      active_ids_list.begin(), active_ids_list.end());

  for (const auto& descriptor : descriptors) {
    language_settings_private::InputMethod input_method;
    input_method.id = descriptor.id();
    input_method.display_name = util->GetLocalizedDisplayName(descriptor);
    input_method.language_codes = descriptor.language_codes();
    bool enabled = active_ids.find(input_method.id) != active_ids.end();
    if (enabled)
      input_method.enabled.reset(new bool(true));
    if (descriptor.options_page_url().is_valid())
      input_method.has_options_page.reset(new bool(true));
    input_methods->push_back(std::move(input_method));
  }
}
#endif

LanguageSettingsPrivateGetInputMethodListsFunction::
    LanguageSettingsPrivateGetInputMethodListsFunction() {
}

LanguageSettingsPrivateGetInputMethodListsFunction::
    ~LanguageSettingsPrivateGetInputMethodListsFunction() {
}

ExtensionFunction::ResponseAction
LanguageSettingsPrivateGetInputMethodListsFunction::Run() {
#if !defined(OS_CHROMEOS)
  EXTENSION_FUNCTION_VALIDATE(false);
  return RespondNow(NoArguments());
#else
  language_settings_private::InputMethodLists input_method_lists;
  InputMethodManager* manager = InputMethodManager::Get();

  chromeos::ComponentExtensionIMEManager* component_extension_manager =
      manager->GetComponentExtensionIMEManager();
  PopulateInputMethodListFromDescriptors(
      component_extension_manager->GetAllIMEAsInputMethodDescriptor(),
      &input_method_lists.component_extension_imes);

  scoped_refptr<InputMethodManager::State> ime_state =
      manager->GetActiveIMEState();
  if (ime_state.get()) {
    InputMethodDescriptors ext_ime_descriptors;
    ime_state->GetInputMethodExtensions(&ext_ime_descriptors);
    PopulateInputMethodListFromDescriptors(
        ext_ime_descriptors,
        &input_method_lists.third_party_extension_imes);
  }

  return RespondNow(OneArgument(input_method_lists.ToValue()));
#endif
}

LanguageSettingsPrivateAddInputMethodFunction::
    LanguageSettingsPrivateAddInputMethodFunction() {
}

LanguageSettingsPrivateAddInputMethodFunction::
    ~LanguageSettingsPrivateAddInputMethodFunction() {
}

ExtensionFunction::ResponseAction
LanguageSettingsPrivateAddInputMethodFunction::Run() {
  return RespondNow(OneArgument(new base::FundamentalValue(true)));
}

LanguageSettingsPrivateRemoveInputMethodFunction::
    LanguageSettingsPrivateRemoveInputMethodFunction() {
}

LanguageSettingsPrivateRemoveInputMethodFunction::
    ~LanguageSettingsPrivateRemoveInputMethodFunction() {
}

ExtensionFunction::ResponseAction
LanguageSettingsPrivateRemoveInputMethodFunction::Run() {
  return RespondNow(OneArgument(new base::FundamentalValue(true)));
}

}  // namespace extensions


text:
.class Landroid/support/v4/app/NavUtils$NavUtilsImplBase;
.super Ljava/lang/Object;
.source "NavUtils.java"

# interfaces
.implements Landroid/support/v4/app/NavUtils$NavUtilsImpl;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/support/v4/app/NavUtils;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x8
    name = "NavUtilsImplBase"
.end annotation

# direct methods
.method constructor <init>()V
    .locals 0

    .prologue
    .line 49
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public getParentActivityIntent(Landroid/app/Activity;)Landroid/content/Intent;
    .locals 9
    .param p1, "activity"    # Landroid/app/Activity;

    .prologue
    const/4 v8, 0x0

    .line 53
    invoke-static {p1}, Landroid/support/v4/app/NavUtils;->getParentActivityName(Landroid/app/Activity;)Ljava/lang/String;

    move-result-object v3

    .line 54
    .local v3, "parentName":Ljava/lang/String;
    if-nez v3, :cond_0

    return-object v8

    .line 57
    :cond_0
    new-instance v4, Landroid/content/ComponentName;

    invoke-direct {v4, p1, v3}, Landroid/content/ComponentName;-><init>(Landroid/content/Context;Ljava/lang/String;)V

    .line 59
    .local v4, "target":Landroid/content/ComponentName;
    :try_start_0
    invoke-static {p1, v4}, Landroid/support/v4/app/NavUtils;->getParentActivityName(Landroid/content/Context;Landroid/content/ComponentName;)Ljava/lang/String;

    move-result-object v1

    .line 60
    .local v1, "grandparent":Ljava/lang/String;
    if-nez v1, :cond_1

    .line 61
    invoke-static {v4}, Landroid/support/v4/content/IntentCompat;->makeMainActivity(Landroid/content/ComponentName;)Landroid/content/Intent;

    move-result-object v2

    .line 63
    .local v2, "parentIntent":Landroid/content/Intent;
    :goto_0
    return-object v2

    .line 62
    .end local v2    # "parentIntent":Landroid/content/Intent;
    :cond_1
    new-instance v5, Landroid/content/Intent;

    invoke-direct {v5}, Landroid/content/Intent;-><init>()V

    invoke-virtual {v5, v4}, Landroid/content/Intent;->setComponent(Landroid/content/ComponentName;)Landroid/content/Intent;
    :try_end_0
    .catch Landroid/content/pm/PackageManager$NameNotFoundException; {:try_start_0 .. :try_end_0} :catch_0

    move-result-object v2

    .restart local v2    # "parentIntent":Landroid/content/Intent;
    goto :goto_0

    .line 64
    .end local v1    # "grandparent":Ljava/lang/String;
    .end local v2    # "parentIntent":Landroid/content/Intent;
    :catch_0
    move-exception v0

    .line 65
    .local v0, "e":Landroid/content/pm/PackageManager$NameNotFoundException;
    const-string/jumbo v5, "NavUtils"

    new-instance v6, Ljava/lang/StringBuilder;

    invoke-direct {v6}, Ljava/lang/StringBuilder;-><init>()V

    const-string/jumbo v7, "getParentActivityIntent: bad parentActivityName \'"

    invoke-virtual {v6, v7}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v6

    invoke-virtual {v6, v3}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v6

    .line 66
    const-string/jumbo v7, "\' in manifest"

    .line 65
    invoke-virtual {v6, v7}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v6

    invoke-virtual {v6}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v6

    invoke-static {v5, v6}, Landroid/util/Log;->e(Ljava/lang/String;Ljava/lang/String;)I

    .line 67
    return-object v8
.end method

.method public getParentActivityName(Landroid/content/Context;Landroid/content/pm/ActivityInfo;)Ljava/lang/String;
    .locals 4
    .param p1, "context"    # Landroid/content/Context;
    .param p2, "info"    # Landroid/content/pm/ActivityInfo;

    .prologue
    const/4 v3, 0x0

    .line 86
    iget-object v1, p2, Landroid/content/pm/ActivityInfo;->metaData:Landroid/os/Bundle;

    if-nez v1, :cond_0

    return-object v3

    .line 87
    :cond_0
    iget-object v1, p2, Landroid/content/pm/ActivityInfo;->metaData:Landroid/os/Bundle;

    const-string/jumbo v2, "android.support.PARENT_ACTIVITY"

    invoke-virtual {v1, v2}, Landroid/os/Bundle;->getString(Ljava/lang/String;)Ljava/lang/String;

    move-result-object v0

    .line 88
    .local v0, "parentActivity":Ljava/lang/String;
    if-nez v0, :cond_1

    return-object v3

    .line 89
    :cond_1
    const/4 v1, 0x0

    invoke-virtual {v0, v1}, Ljava/lang/String;->charAt(I)C

    move-result v1

    const/16 v2, 0x2e

    if-ne v1, v2, :cond_2

    .line 90
    new-instance v1, Ljava/lang/StringBuilder;

    invoke-direct {v1}, Ljava/lang/StringBuilder;-><init>()V

    invoke-virtual {p1}, Landroid/content/Context;->getPackageName()Ljava/lang/String;

    move-result-object v2

    invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v1

    invoke-virtual {v1, v0}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v1

    invoke-virtual {v1}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v0

    .line 92
    :cond_2
    return-object v0
.end method

.method public navigateUpTo(Landroid/app/Activity;Landroid/content/Intent;)V
    .locals 1
    .param p1, "activity"    # Landroid/app/Activity;
    .param p2, "upIntent"    # Landroid/content/Intent;

    .prologue
    .line 79
    const/high16 v0, 0x4000000

    invoke-virtual {p2, v0}, Landroid/content/Intent;->addFlags(I)Landroid/content/Intent;

    .line 80
    invoke-virtual {p1, p2}, Landroid/app/Activity;->startActivity(Landroid/content/Intent;)V

    .line 81
    invoke-virtual {p1}, Landroid/app/Activity;->finish()V

    .line 78
    return-void
.end method

.method public shouldUpRecreateTask(Landroid/app/Activity;Landroid/content/Intent;)Z
    .locals 3
    .param p1, "activity"    # Landroid/app/Activity;
    .param p2, "targetIntent"    # Landroid/content/Intent;

    .prologue
    const/4 v1, 0x0

    .line 73
    invoke-virtual {p1}, Landroid/app/Activity;->getIntent()Landroid/content/Intent;

    move-result-object v2

    invoke-virtual {v2}, Landroid/content/Intent;->getAction()Ljava/lang/String;

    move-result-object v0

    .line 74
    .local v0, "action":Ljava/lang/String;
    if-eqz v0, :cond_0

    const-string/jumbo v2, "android.intent.action.MAIN"

    invoke-virtual {v0, v2}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z

    move-result v2

    if-eqz v2, :cond_1

    :cond_0
    :goto_0
    return v1

    :cond_1
    const/4 v1, 0x1

    goto :goto_0
.end method


text:
from .resource import Resource

class LoadBalancer(Resource):
    """LoadBalancer resource.

    Variables are only populated by the server, and will be ignored when
    sending a request.

    :param id: Resource ID.
    :type id: str
    :ivar name: Resource name.
    :vartype name: str
    :ivar type: Resource type.
    :vartype type: str
    :param location: Resource location.
    :type location: str
    :param tags: Resource tags.
    :type tags: dict[str, str]
    :param sku: The load balancer SKU.
    :type sku: ~azure.mgmt.network.v2017_10_01.models.LoadBalancerSku
    :param frontend_ip_configurations: Object representing the frontend IPs to
     be used for the load balancer
    :type frontend_ip_configurations:
     list[~azure.mgmt.network.v2017_10_01.models.FrontendIPConfiguration]
    :param backend_address_pools: Collection of backend address pools used by
     a load balancer
    :type backend_address_pools:
     list[~azure.mgmt.network.v2017_10_01.models.BackendAddressPool]
    :param load_balancing_rules: Object collection representing the load
     balancing rules Gets the provisioning
    :type load_balancing_rules:
     list[~azure.mgmt.network.v2017_10_01.models.LoadBalancingRule]
    :param probes: Collection of probe objects used in the load balancer
    :type probes: list[~azure.mgmt.network.v2017_10_01.models.Probe]
    :param inbound_nat_rules: Collection of inbound NAT Rules used by a load
     balancer. Defining inbound NAT rules on your load balancer is mutually
     exclusive with defining an inbound NAT pool. Inbound NAT pools are
     referenced from virtual machine scale sets. NICs that are associated with
     individual virtual machines cannot reference an Inbound NAT pool. They
     have to reference individual inbound NAT rules.
    :type inbound_nat_rules:
     list[~azure.mgmt.network.v2017_10_01.models.InboundNatRule]
    :param inbound_nat_pools: Defines an external port range for inbound NAT
     to a single backend port on NICs associated with a load balancer. Inbound
     NAT rules are created automatically for each NIC associated with the Load
     Balancer using an external port from this range. Defining an Inbound NAT
     pool on your Load Balancer is mutually exclusive with defining inbound Nat
     rules. Inbound NAT pools are referenced from virtual machine scale sets.
     NICs that are associated with individual virtual machines cannot reference
     an inbound NAT pool. They have to reference individual inbound NAT rules.
    :type inbound_nat_pools:
     list[~azure.mgmt.network.v2017_10_01.models.InboundNatPool]
    :param outbound_nat_rules: The outbound NAT rules.
    :type outbound_nat_rules:
     list[~azure.mgmt.network.v2017_10_01.models.OutboundNatRule]
    :param resource_guid: The resource GUID property of the load balancer
     resource.
    :type resource_guid: str
    :param provisioning_state: Gets the provisioning state of the PublicIP
     resource. Possible values are: 'Updating', 'Deleting', and 'Failed'.
    :type provisioning_state: str
    :param etag: A unique read-only string that changes whenever the resource
     is updated.
    :type etag: str
    """

    _validation = {
        'name': {'readonly': True},
        'type': {'readonly': True},
    }

    _attribute_map = {
        'id': {'key': 'id', 'type': 'str'},
        'name': {'key': 'name', 'type': 'str'},
        'type': {'key': 'type', 'type': 'str'},
        'location': {'key': 'location', 'type': 'str'},
        'tags': {'key': 'tags', 'type': '{str}'},
        'sku': {'key': 'sku', 'type': 'LoadBalancerSku'},
        'frontend_ip_configurations': {'key': 'properties.frontendIPConfigurations', 'type': '[FrontendIPConfiguration]'},
        'backend_address_pools': {'key': 'properties.backendAddressPools', 'type': '[BackendAddressPool]'},
        'load_balancing_rules': {'key': 'properties.loadBalancingRules', 'type': '[LoadBalancingRule]'},
        'probes': {'key': 'properties.probes', 'type': '[Probe]'},
        'inbound_nat_rules': {'key': 'properties.inboundNatRules', 'type': '[InboundNatRule]'},
        'inbound_nat_pools': {'key': 'properties.inboundNatPools', 'type': '[InboundNatPool]'},
        'outbound_nat_rules': {'key': 'properties.outboundNatRules', 'type': '[OutboundNatRule]'},
        'resource_guid': {'key': 'properties.resourceGuid', 'type': 'str'},
        'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
        'etag': {'key': 'etag', 'type': 'str'},
    }

    def __init__(self, *, id: str=None, location: str=None, tags=None, sku=None, frontend_ip_configurations=None, backend_address_pools=None, load_balancing_rules=None, probes=None, inbound_nat_rules=None, inbound_nat_pools=None, outbound_nat_rules=None, resource_guid: str=None, provisioning_state: str=None, etag: str=None, **kwargs) -> None:
        super(LoadBalancer, self).__init__(id=id, location=location, tags=tags, **kwargs)
        self.sku = sku
        self.frontend_ip_configurations = frontend_ip_configurations
        self.backend_address_pools = backend_address_pools
        self.load_balancing_rules = load_balancing_rules
        self.probes = probes
        self.inbound_nat_rules = inbound_nat_rules
        self.inbound_nat_pools = inbound_nat_pools
        self.outbound_nat_rules = outbound_nat_rules
        self.resource_guid = resource_guid
        self.provisioning_state = provisioning_state
        self.etag = etag


text:
 Standalone application to download/copy files from different protocols. For known protocols `http`, `https`, `ftp` and `file` handler is not requied, for other protocols handler should be provided and an entry needs to be added in `url.stream.handlers`

example `url.stream.handlers = telnet:org.saravana.handler.TelnetHandler,snmp:org.saravana.handler.SnmpHandler`

# Technologies

   1. Java 8
   2. SpringBoot 1.4.0

# Run

	java -jar downloader-{version}.jar [URLs]

# Build Status

[![Build Status](https://travis-ci.org/nsaravanas/downloader.svg?branch=master)](https://travis-ci.org/nsaravanas/downloader)