text:
import copy
import sys
import os
import logging
import re
import json
import mxnet as mx
import numpy as np
from common import assertRaises, models, TemporaryDirectory
from mxnet.base import NotImplementedForSymbol
from mxnet.test_utils import discard_stderr, rand_shape_nd, use_np
from mxnet.util import np_shape
import pickle as pkl

def test_symbol_basic():
    mlist = []
    mlist.append(models.mlp2())
    for m in mlist:
        m.list_arguments()
        m.list_outputs()

def test_symbol_bool():
    x = mx.symbol.Variable('x')
    assertRaises(NotImplementedForSymbol, bool, x)

def test_symbol_compose():
    data = mx.symbol.Variable('data')
    net1 = mx.symbol.FullyConnected(data=data, name='fc1', num_hidden=10)
    net1 = mx.symbol.FullyConnected(data=net1, name='fc2', num_hidden=100)
    net1.list_arguments() == ['data',
                              'fc1_weight', 'fc1_bias',
                              'fc2_weight', 'fc2_bias']

    net2 = mx.symbol.FullyConnected(name='fc3', num_hidden=10)
    net2 = mx.symbol.Activation(data=net2, act_type='relu')
    net2 = mx.symbol.FullyConnected(data=net2, name='fc4', num_hidden=20)

    composed = net2(fc3_data=net1, name='composed')
    multi_out = mx.symbol.Group([composed, net1])
    assert len(multi_out.list_outputs()) == 2
    assert len(multi_out) == 2

def test_symbol_copy():
    data = mx.symbol.Variable('data')
    data_2 = copy.deepcopy(data)
    data_3 = copy.copy(data)
    assert data.tojson() == data_2.tojson()
    assert data.tojson() == data_3.tojson()

def test_symbol_internal():
    data = mx.symbol.Variable('data')
    oldfc = mx.symbol.FullyConnected(data=data, name='fc1', num_hidden=10)
    net1 = mx.symbol.FullyConnected(data=oldfc, name='fc2', num_hidden=100)
    assert net1.list_arguments() == ['data', 'fc1_weight', 'fc1_bias', 'fc2_weight', 'fc2_bias']

    internal =  net1.get_internals()
    fc1 = internal['fc1_output']
    assert fc1.list_arguments() == oldfc.list_arguments()

def test_symbol_children():
    data = mx.symbol.Variable('data')
    oldfc = mx.symbol.FullyConnected(data=data, name='fc1', num_hidden=10)
    net1 = mx.symbol.FullyConnected(data=oldfc, name='fc2', num_hidden=100)

    assert net1.get_children().list_outputs() == ['fc1_output', 'fc2_weight', 'fc2_bias']
    assert len(net1.get_children()) == 3
    assert net1.get_children().get_children().list_outputs() == ['data', 'fc1_weight', 'fc1_bias']
    assert len(net1.get_children().get_children()) == 3
    assert net1.get_children()['fc2_weight'].list_arguments() == ['fc2_weight']
    assert net1.get_children()['fc2_weight'].get_children() is None

    data = mx.sym.Variable('data')
    sliced = mx.sym.SliceChannel(data, num_outputs=3, name='slice')
    concat = mx.sym.Concat(*list(sliced))

    assert concat.get_children().list_outputs() == \
        ['slice_output0', 'slice_output1', 'slice_output2']
    assert sliced.get_children().list_outputs() == ['data']

def test_symbol_pickle():
    mlist = [models.mlp2(), models.conv()]
    data = pkl.dumps(mlist)
    mlist2 = pkl.loads(data)
    for x, y  in zip(mlist, mlist2):
        assert x.tojson() == y.tojson()

def test_symbol_saveload():
    sym = models.mlp2()
    fname = 'tmp_sym.json'
    sym.save(fname)
    data2 = mx.symbol.load(fname)
    # save because of order
    assert sym.tojson() == data2.tojson()
    os.remove(fname)

def test_symbol_infer_type():
    data = mx.symbol.Variable('data')
    f32data = mx.symbol.Cast(data=data, dtype='float32')
    fc1  = mx.symbol.FullyConnected(data = f32data, name='fc1', num_hidden=128)
    mlp  = mx.symbol.SoftmaxOutput(data = fc1, name = 'softmax')

    arg, out, aux = mlp.infer_type(data=np.float16)
    assert arg == [np.float16, np.float32, np.float32, np.float32]
    assert out == [np.float32]
    assert aux == []

    # partial infer type
    arg, out, aux = mlp.infer_type_partial()
    assert arg == [None, np.float32, np.float32, np.float32]
    assert out == [np.float32]
    assert aux == []

def test_symbol_infer_shape():
    num_hidden = 128
    num_dim    = 64
    num_sample = 10

    data = mx.symbol.Variable('data')
    prev = mx.symbol.Variable('prevstate')
    x2h  = mx.symbol.FullyConnected(data=data, name='x2h', num_hidden=num_hidden)
    h2h  = mx.symbol.FullyConnected(data=prev, name='h2h', num_hidden=num_hidden)

    out  = mx.symbol.Activation(data=mx.sym.elemwise_add(x2h, h2h), name='out', act_type='relu')

    # shape inference will fail because information is not available for h2h
    ret  = out.infer_shape(data=(num_sample, num_dim))
    assert ret == (None, None, None)

    arg, out_shapes, aux_shapes = out.infer_shape_partial(data=(num_sample, num_dim))
    arg_shapes = dict(zip(out.list_arguments(), arg))
    assert arg_shapes['data'] == (num_sample, num_dim)
    assert arg_shapes['x2h_weight'] == (num_hidden, num_dim)
    assert arg_shapes['h2h_weight'] == ()

    # now we can do full shape inference
    state_shape = out_shapes[0]
    arg, out_shapes, aux_shapes = out.infer_shape(data=(num_sample, num_dim), prevstate=state_shape)
    arg_shapes = dict(zip(out.list_arguments(), arg))
    assert arg_shapes['data'] == (num_sample, num_dim)
    assert arg_shapes['x2h_weight'] == (num_hidden, num_dim)
    assert arg_shapes['h2h_weight'] == (num_hidden, num_hidden)

    # Partial shape inference with some unknown dimensions
    data_shape = (1, 0, 0, 0)
    data = mx.sym.Variable('data', shape=data_shape)
    weight = mx.sym.Variable('weight')
    cdata = mx.sym.cast(data, dtype='float16')
    cweight = mx.sym.cast(weight, dtype='float16')
    test = mx.sym.Convolution(data=cdata, weight=cweight, pad=(3, 3), num_filter=64, stride=(2, 2), no_bias=True, kernel=(7, 7))

    arg, _, _ = test.infer_shape_partial()
    arg_shapes = dict(zip(test.list_arguments(), arg))
    assert arg_shapes['data'] == data_shape
    assert arg_shapes['weight'] == (64, 0, 7, 7)

def test_symbol_infer_shape_var():
    "Test specifying shape information when constructing a variable"
    shape = (2, 3)
    a = mx.symbol.Variable('a', shape=shape)
    b = mx.symbol.Variable('b')
    c = mx.symbol.elemwise_add(a, b)
    arg_shapes, out_shapes, aux_shapes = c.infer_shape()
    assert arg_shapes[0] == shape
    assert arg_shapes[1] == shape
    assert out_shapes[0] == shape

    overwrite_shape = (5, 6)
    arg_shapes, out_shapes, aux_shapes = c.infer_shape(a=overwrite_shape)
    assert arg_shapes[0] == overwrite_shape
    assert arg_shapes[1] == overwrite_shape
    assert out_shapes[0] == overwrite_shape

def test_symbol_magic_abs():
    for dim in range(1, 7):
        with mx.name.NameManager():
            data = mx.symbol.Variable('data')
            method = data.abs(name='abs0')
            magic = abs(data)
            regular = mx.symbol.abs(data, name='abs0')
            ctx = {'ctx': mx.context.current_context(), 'data': rand_shape_nd(dim)}
            mx.test_utils.check_consistency(
                [method, magic], ctx_list=[ctx, ctx])
            mx.test_utils.check_consistency(
                [regular, magic], ctx_list=[ctx, ctx])

def test_symbol_fluent():
    has_grad = set(['flatten', 'expand_dims', 'flip', 'tile', 'transpose', 'sum', 'nansum', 'prod',
                    'nanprod', 'mean', 'max', 'min', 'reshape', 'broadcast_to', 'split',
                    'broadcast_axes', 'broadcast_like', 'pad', 'swapaxes', 'slice', 'slice_axis', 'slice_like',
                    'take', 'one_hot', 'pick', 'sort', 'topk', 'argsort', 'argmax', 'argmin',
                    'clip', 'abs', 'sign', 'sin', 'cos', 'tan', 'arcsin', 'arccos', 'arctan',
                    'degrees', 'radians', 'sinh', 'cosh', 'tanh', 'arcsinh', 'arccosh', 'arctanh',
                    'exp', 'expm1', 'log', 'log10', 'log2', 'log1p', 'sqrt', 'rsqrt',
                    'square', 'reciprocal' 'reshape_like', 'cbrt', 'rcbrt', 'relu', 'sigmoid',
                    'softmax', 'log_softmax', 'softmin', 'rint', 'ceil', 'floor', 'trunc', 'fix'])

    def check_fluent_regular(func, kwargs, shape=(5, 17, 1), equal_nan=False):
        with mx.name.NameManager():
            data = mx.symbol.Variable('data')
            regular = getattr(mx.symbol, func)(data, name=func+'0', **kwargs)
            fluent = getattr(data, func)(**kwargs)
            check_symbol_consistency(regular, fluent, {'ctx': mx.context.current_context(),
                                                       'data': shape},
                                     skip_grad=func not in has_grad,
                                     equal_nan=equal_nan)

    for func in ['flatten', 'norm', 'round', 'rint', 'fix', 'floor', 'ceil', 'trunc', 'zeros_like',
                 'ones_like', 'abs', 'sign', 'sin', 'cos', 'degrees', 'radians', 'exp', 'expm1',
                 'square', 'reciprocal', 'argmax_channel', 'shape_array', 'size_array']:
        check_fluent_regular(func, {})

    for func in ['arccosh', 'arcsin', 'arccos', 'arctan', 'tan', 'sinh', 'cosh', 'tanh',
                 'arcsinh', 'arctanh', 'log', 'log10', 'log2', 'log1p', 'sqrt', 'rsqrt',
                 'cbrt', 'rcbrt', 'relu', 'sigmoid', 'softmax', 'log_softmax', 'softmin']:
        check_fluent_regular(func, {}, equal_nan=True)

    for func in ['expand_dims', 'flip', 'sort', 'topk', 'argsort', 'argmax', 'argmin']:
        check_fluent_regular(func, {'axis': 1})

    check_fluent_regular('one_hot', {'depth': 15})
    check_fluent_regular('tile', {'reps': (1,2)})
    check_fluent_regular('repeat', {'repeats': 3})
    check_fluent_regular('transpose', {'axes': (1,0,2)})
    check_fluent_regular('split', {'axis': 2, 'num_outputs': 3}, shape=(5, 17, 6))
    check_fluent_regular('slice', {'begin': (2, 5, 1), 'end': (4, 7, 6)}, shape=(5, 17, 6))
    check_fluent_regular('slice_axis', {'axis': 1, 'begin': 5, 'end': 7})
    check_fluent_regular('slice_like', {'axes': (0, -2), 'shape_like': mx.sym.zeros((3, 3))})
    check_fluent_regular('clip', {'a_min': 0.25, 'a_max': 0.75})
    check_fluent_regular('broadcast_axes', {'axis': (2,), 'size': (5,)})
    check_fluent_regular('broadcast_like', {'rhs': mx.sym.ones((1, 5)), 'lhs_axes': (0,), 'rhs_axes': (1,)}, shape=(1,9))
    check_fluent_regular('pad', {'mode': 'constant', 'pad_width': (0,0,0,0,3,0,0,4)}, shape=(5, 17, 2, 3))
    check_fluent_regular('reshape_like', {'rhs': mx.sym.ones((30, 17))}, shape=(5, 17, 2, 3))

    for func in ['sum', 'nansum', 'prod', 'nanprod', 'mean', 'max', 'min', 'norm']:
        check_fluent_regular(func, {'axis': (1, 2)})

    check_fluent_regular('reshape', {'shape': (17, 1, 5)})
    check_fluent_regular('broadcast_to', {'shape': (5, 17, 47)})
    check_fluent_regular('squeeze', {'axis': (1, 3)}, shape=(2, 1, 3, 1, 4))
    check_fluent_regular('squeeze', {}, shape=(2, 1, 3, 1, 4))

def check_symbol_consistency(sym1, sym2, ctx, skip_grad=False, equal_nan=False):
    assert sym1.list_arguments() == sym2.list_arguments()
    assert sym1.list_auxiliary_states() == sym2.list_auxiliary_states()
    assert sym1.list_outputs() == sym2.list_outputs()

    mx.test_utils.check_consistency([sym1, sym2], ctx_list=[ctx, ctx],
                                    grad_req='null' if skip_grad else 'write',
                                    equal_nan=equal_nan)

def test_load_000800():
    with mx.AttrScope(ctx_group='stage1'):
        data = mx.symbol.Variable('data', lr_mult=0.2)
        weight = mx.sym.Variable(name='fc1_weight', lr_mult=1.2)
        fc1  = mx.symbol.FullyConnected(data = data, weight=weight, name='fc1', num_hidden=128, wd_mult=0.3)
        act1 = mx.symbol.Activation(data = fc1, name='relu1', act_type="relu")

    set_stage1 = set(act1.list_arguments())
    with mx.AttrScope(ctx_group='stage2'):
        fc2  = mx.symbol.FullyConnected(data = act1, name = 'fc2', num_hidden = 64, lr_mult=0.01)
        act2 = mx.symbol.Activation(data = fc2, name='relu2', act_type="relu")
        fc3  = mx.symbol.FullyConnected(data = act2, name='fc3', num_hidden=10)
        fc3 = mx.symbol.BatchNorm(fc3, name='batchnorm0')
        sym1  = mx.symbol.SoftmaxOutput(data = fc3, name = 'softmax')

    curr_path = os.path.dirname(os.path.abspath(os.path.expanduser(__file__)))
    sym2 = mx.sym.load(os.path.join(curr_path, 'save_000800.json'))

    attr1 = sym1.attr_dict()
    attr2 = sym2.attr_dict()
    for k, v1 in attr1.items():
        assert k in attr2, k
        v2 = attr2[k]
        for kk, vv1 in v1.items():
            if kk.startswith('__') and kk.endswith('__'):
                assert kk in v2 and v2[kk] == vv1, k + str(v1) + str(v2)

    check_symbol_consistency(sym1, sym2,
        {'ctx': mx.cpu(0), 'group2ctx': {'stage1' : mx.cpu(1), 'stage2' : mx.cpu(2)}, 'data': (1,200)})

def test_blockgrad():
    a = mx.sym.Variable('a')
    b = mx.sym.BlockGrad(2*a)
    exe = b.simple_bind(ctx=mx.cpu(), a=(10,10))

def test_zero_prop():
    data = mx.symbol.Variable('data')
    for i in range(10):
        data = data * data

    exe = data.simple_bind(ctx=mx.cpu(), data=(10, 3, 256, 256))
    big = int(re.search('Total (\d+) MB allocated', exe.debug_str()).group(1))

    exe = data.simple_bind(ctx=mx.cpu(), data=(10, 3, 256, 256), grad_req='null')
    small1 = int(re.search('Total (\d+) MB allocated', exe.debug_str()).group(1))

    data = mx.sym.stop_gradient(data)
    exe = data.simple_bind(ctx=mx.cpu(), data=(10, 3, 256, 256))
    small2 = int(re.search('Total (\d+) MB allocated', exe.debug_str()).group(1))

    assert big > small2
    assert small1 == small2

def test_zero_prop2():
    x = mx.sym.Variable('x')
    idx = mx.sym.Variable('idx')
    y = mx.sym.batch_take(x, idx)
    z = mx.sym.stop_gradient(y)
    exe = z.simple_bind(ctx=mx.cpu(), x=(10, 10), idx=(10,),
                        type_dict={'x': np.float32, 'idx': np.int32})
    exe.forward()
    exe.backward()

    # The following bind() should throw an exception. We discard the expected stderr
    # output for this operation only in order to keep the test logs clean.
    with discard_stderr():
        try:
            y.simple_bind(ctx=mx.cpu(), x=(10, 10), idx=(10,),
                          type_dict={'x': np.float32, 'idx': np.int32})
        except:
            return

    assert False

def test_simple_bind_incomplete_shape_inference_in_one_forward_pass():
    """This is a special case that results in shape inference
    failure after moving simple_bind logic from frontend to backend.
    Added here for testing against the network similar to the following one.

    Network diagram:
    weight --> abs_op --> sum_op --
          \                        |--> add_op
    data   --> fc_op  --> sum_op --

    Given data's shape, if the shape inference starts from weight node,
    then the node entries of negative_op and sum_op are unknown in the
    forward pass. Therefore, there are several unknown shapes after the
    first forward pass is done. Now the backward inference pass starts with
    the assumption that there are no unknown-shape node entries in the forward
    pass, and consequently, leads to CHECK_EQ failure.
    """
    data_shape = (5, 13)
    data = mx.sym.Variable('data')
    fc = mx.sym.FullyConnected(data=data, num_hidden=1, no_bias=True, name='fc')
    modified_weight = mx.sym.abs(fc.get_internals()['fc_weight'])
    net = mx.sym.sum(modified_weight) + mx.sym.sum(fc)
    net.simple_bind(ctx=mx.cpu(), data=data_shape)

def test_simple_bind_gradient_graph_possible_with_cycle():
    """This is a special case that results in a cycle in the gradient graph
    before this bug was fixed. With the following symbol, the node entries
    passed into function AggregateGradient(std::vector<nnvm::NodeEntry>&& v)
    are the outputs of the same node. Therefore, adding a node to the
    control_deps of itself must be skipped.
    See GitHub issue:
    https://github.com/apache/incubator-mxnet/issues/8029
    for more details."""
    data = mx.symbol.Variable('data')
    res = data + data + data + data + data + data + data + data
    res.simple_bind(ctx=mx.cpu(), data=(1,))

def test_children_same_name():
    a = mx.sym.Variable('data')
    b = a + a
    for c in b.get_children():
        pass

def test_transpose_nullop():
    for dim in range(1, 7):
        a = mx.sym.Variable('a')
        b = mx.sym.transpose(a, axes=tuple(np.random.permutation(dim)))
        c = mx.sym.zeros_like(b)

        shape = rand_shape_nd(dim)
        nd_a = mx.nd.random.normal(shape=shape)
        c_out = c.eval(ctx=mx.cpu(), a=nd_a)
        b_out = b.eval(ctx=mx.cpu(), a=nd_a)

        assert mx.test_utils.same(c_out[0].asnumpy(),
                                  np.zeros_like(b_out[0].asnumpy()))

def test_gen_atomic_symbol_multiple_outputs():
    data=mx.sym.Variable('data')
    p = mx.sym.Variable('param')
    h0 = mx.sym.Variable('h0')
    h1 = mx.sym.Variable('h1')
    s = mx.sym.RNN(data, p, h0, h1, state_size=10, num_layers=2,
                   bidirectional=True, state_outputs=True, mode='lstm')
    atomic_sym = s._gen_atomic_symbol()

def test_eliminate_common_expr():
    if not sys.platform.startswith('linux'):
        logging.info("Bypass the CSE test on non-Linux OS as setting env variables during test does not work on Windows")
        return
    def set_back_env_var(var_name, old_env_var):
        if old_env_var is None:
            os.environ.pop(var_name)
        else:
            os.environ[var_name] = old_env_var

    # helper function to test a single model
    def check_cse_on_symbol(sym, expected_savings, check_data, **kwargs):
        inputs = sym.list_inputs()
        shapes = {inp : kwargs[inp].shape for inp in inputs}
        rtol = {'float16' : 1e-2,
                'float32' : 1.5e-6,
                'float64' : 1.5e-6,
                }
        atol = {'float16' : 1e-3,
                'float32' : 1e-7,
                'float64' : 1e-7,
                }
        env_var_name = 'MXNET_ELIMINATE_COMMON_EXPR'
        old_env_var = os.environ.get(env_var_name, None)
        try:
            for dtype in ['float16', 'float32', 'float64']:
                data = {inp : kwargs[inp].astype(dtype) for inp in inputs}
                for grad_req in ['write', 'add']:
                    type_dict = {inp : dtype for inp in inputs}
                    os.environ[env_var_name] = '0'
                    orig_exec = sym.simple_bind(ctx=mx.cpu(0), grad_req=grad_req,
                                                type_dict=type_dict, **shapes)
                    os.environ[env_var_name] = '1'
                    cse_exec = sym.simple_bind(ctx=mx.cpu(0), grad_req=grad_req,
                                               type_dict=type_dict, **shapes)
                    fwd_orig = orig_exec.forward(is_train=True, **data)
                    out_grads = [mx.nd.ones_like(arr) for arr in fwd_orig]
                    orig_exec.backward(out_grads=out_grads)
                    fwd_cse = cse_exec.forward(is_train=True, **data)
                    cse_exec.backward(out_grads=out_grads)
                    if check_data:
                        for orig, cse in zip(fwd_orig, fwd_cse):
                            np.testing.assert_allclose(orig.asnumpy(), cse.asnumpy(),
                                                       rtol=rtol[dtype], atol=atol[dtype])
                        for orig, cse in zip(orig_exec.grad_arrays, cse_exec.grad_arrays):
                            if orig is None and cse is None:
                                continue
                            assert orig is not None
                            assert cse is not None
                            np.testing.assert_allclose(orig.asnumpy(), cse.asnumpy(),
                                                       rtol=rtol[dtype], atol=atol[dtype])
                    orig_sym_internals = orig_exec.get_optimized_symbol().get_internals()
                    cse_sym_internals = cse_exec.get_optimized_symbol().get_internals()
                    # test that the graph has been simplified as expected
                    assert (len(cse_sym_internals) + expected_savings) == len(orig_sym_internals)
        finally:
            set_back_env_var(env_var_name, old_env_var)

    a = mx.sym.Variable('a')
    b = mx.sym.Variable('b')
    c = mx.sym.Variable('c')
    shape = rand_shape_nd(2)
    arr1 = mx.random.uniform(shape=shape)
    arr2 = mx.random.uniform(shape=shape)
    arr3 = mx.random.uniform(shape=shape)

    check_cse_on_symbol((a+5) + (a+5), expected_savings=1, check_data=True, a=arr1, b=arr2)
    check_cse_on_symbol((a+1) + (a+2), expected_savings=0, check_data=True, a=arr1, b=arr2)
    check_cse_on_symbol((1+a) + (a+1), expected_savings=1, check_data=True, a=arr1, b=arr2)
    check_cse_on_symbol((a+b) + (a+b), expected_savings=1, check_data=True, a=arr1, b=arr2)
    check_cse_on_symbol(((a+b)+c) +((a+b)+c), expected_savings=2, check_data=True,
                                                                  a=arr1, b=arr2, c=arr3)
    d = a + 1

    # a*d node gets eliminated, but then a copy is inserted to isolate the outputs, so no net gain.
    check_cse_on_symbol(mx.sym.Group([a*d, a*d]), expected_savings=0, check_data=True, a=arr1)

    # a*d node gets eliminated, then the duplicated add-of-b, but then a copy is added for net of 1.
    check_cse_on_symbol(mx.sym.Group([a*d+b, a*d+b]), expected_savings=1, check_data=True,
                                                                          a=arr1, b=arr2)

    # dropout uses a resource that precludes any optimization
    check_cse_on_symbol(mx.sym.Dropout(a) +
                        mx.sym.Dropout(a), expected_savings=0, check_data=False, a=arr1)

def test_load_save_symbol():
    batch_size = 10
    num_hdidden = 128
    num_features = 784

    def get_net():
        data = mx.sym.var('data')
        weight = mx.sym.var('weight', shape=(num_hdidden, 0))
        return mx.sym.FullyConnected(data, weight, num_hidden=num_hdidden)

    for flag1 in [False, True]:
        with np_shape(flag1):
            net_json_str = get_net().tojson()
            net_data = json.loads(net_json_str)
            assert "attrs" in net_data
            if flag1:
                assert "is_np_shape" in net_data["attrs"]
            else:
                assert "is_np_shape" not in net_data["attrs"]

        with TemporaryDirectory() as work_dir:
            fname = os.path.join(work_dir, 'test_sym.json')
            with open(fname, 'w') as fp:
                json.dump(net_data, fp)

            # test loading 1.5.0 symbol file since 1.6.0
            # w/ or w/o np_shape semantics
            for flag2 in [False, True]:
                if flag1:  # Do not need to test this case since 0 indicates zero-size dim
                    continue
                with np_shape(flag2):
                    net = mx.sym.load(fname)
                    arg_shapes, out_shapes, aux_shapes = net.infer_shape(data=(batch_size, num_features))
                    assert arg_shapes[0] == (batch_size, num_features)  # data
                    assert arg_shapes[1] == (num_hdidden, num_features)  # weight
                    assert arg_shapes[2] == (num_hdidden,)  # bias
                    assert out_shapes[0] == (batch_size, num_hdidden)  # output
                    assert len(aux_shapes) == 0

def test_infershape_happens_for_all_ops_in_graph():
    v = mx.sym.Variable('V')
    s = mx.sym.transpose(v)
    x = mx.sym.Variable('x')
    s2 = x + v
    s3 = s + s2
    with discard_stderr():
        try:
            # This should throw an exception as you cannot add arrays
            # with shapes [2,3] and [3,2]
            e = s3.simple_bind(ctx=mx.cpu(), x=(2,3), grad_req='null')
        except:
            return

    assert False

if __name__ == '__main__':
    import nose
    nose.runmodule()


text:
package com.zimbra.cs.server;

import com.google.common.base.CharMatcher;
import com.zimbra.common.util.Log;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.filterchain.IoFilterAdapter;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.core.write.WriteRequest;
import org.apache.mina.filter.codec.ProtocolDecoderException;

import java.io.IOException;
import java.nio.ByteBuffer;

/**
 * Optionally logs all MINA protocol events to the server log.
 */
final class NioLoggingFilter extends IoFilterAdapter {
    private final Log log;
    private final boolean hexDump;

    NioLoggingFilter(NioServer server, boolean hexDump) {
        log = server.getLog();
        this.hexDump = hexDump;
    }

    @Override
    public void exceptionCaught(NextFilter next, IoSession session, Throwable cause) {
        NioHandlerDispatcher.getHandler(session).setLoggingContext();
        if (cause instanceof IOException || cause instanceof ProtocolDecoderException) {
            // intend to ignore "Connection reset by peer" and "Broken pipe"
            log.debug(cause, cause);
        } else {
            log.error(cause, cause);
        }
        next.exceptionCaught(session, cause);
    }

    @Override
    public void messageReceived(NextFilter nextFilter, IoSession session, Object message) {
        NioHandlerDispatcher.getHandler(session).setLoggingContext();
        if (log.isTraceEnabled()) {
            log.trace("C: %s", pp(message));
        }
        nextFilter.messageReceived(session, message);
    }

    @Override
    public void filterWrite(NextFilter next, IoSession session, WriteRequest req) {
        if (log.isTraceEnabled()) {
            log.trace("S: %s", pp(req));
        }
        next.filterWrite(session, req);
    }

    private Object pp(Object msg) {
        if (msg instanceof WriteRequest) {
            return pp(((WriteRequest) msg).getMessage());
        }
        if (msg instanceof String) {
            return msg;
        }
        ByteBuffer bb;
        if (msg instanceof ByteBuffer) {
            bb = (ByteBuffer) msg;
        } else if (msg instanceof IoBuffer) {
            bb = ((IoBuffer) msg).buf();
        } else if (msg instanceof byte[]) {
            bb = ByteBuffer.wrap((byte[]) msg);
        } else {
            return msg;
        }
        return isPrintable(bb) ? pp(bb) : msg;
    }

    private boolean isPrintable(ByteBuffer bb) {
        int limit = bb.limit();
        for (int i = bb.position(); i < limit; i++) {
            if (!isPrintable(bb.get(i))) return false;
        }
        return true;
    }

    private static boolean isPrintable(byte b) {
        switch (b) {
        case '\r': case '\n': case '\t':
            return true;
        default:
            return b > 31 && b < 127;
        }
    }

    private String pp(ByteBuffer bb) {
        StringBuilder sb = new StringBuilder(bb.remaining());
        if (hexDump) {
            sb = NioUtil.appendHex(sb.append('('), bb).append(") ");
        }
        int limit = bb.limit();
        for (int i = bb.position(); i < limit; i++) {
            sb.append((char) (bb.get(i) & 0xff));
        }
        return CharMatcher.anyOf("\r\n").trimTrailingFrom(sb);
    }

}

redpajama_set_name: RedPajamaGithub


text:
title: XML to JSON Converter | Developer Tools
layout: post
---

    {% include common-meta %}
    <title>{{ page.title }}</title>

    <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
    <meta name="description" content="This is easy to use open source tool convert XML to JSON online. You can also use this to convert JSON to XML." />
    <meta name="keywords" content="online,tool,XML,json,convert,converter,web,opensource" />

    {% include theme-css %}

    {% include ie-fixes %}

        {% include theme-header %}

        {% include theme-sidebar %}

Convert XML Data To JSON Format

                                <form role="form">

                                        XML Data
                                        <textarea class="form-control" rows="10" id="xml" placeholder="Enter your XML data here" autofocus></textarea>

                                </form>

                                        <button type="button" class="btn btn-info" id="convert2json">Convert to JSON </button>

Copy Your JSON Data From Here

                                  JSON Data
                                    <textarea class="form-control" id="json" rows="10" placeholder="Enter your JSON data here"></textarea>

                                        <button type="button" class="btn btn-info" id="convert2xml"> Convert to XML</button>

About XML to JSON Converter Tool

This is a free online tool to convert a XML format data into a JavaScript JSON object. You can also use the same tool to convert it back from JSON to XML. The XML input needs to be valid otherwise JSON translation will not happen.

What is a XML?

XML or eXtended Markup Language is a popular format to store and transfer data. Many web services provide data in XML format. A popular format of XML is RSS feeds. Almost all blogs and website offer RSS feeds that are xml format data.

What Is JSON Format?

JSON (JavaScript Object Notation) is way to represent data in JavaScript object format. It is popular for programming purposes. Many application programs interact using JSON format data. Most of REST API development is preferred
                            in this format.

Can I Convert a RSS Feed Data To JSON?

Yes, RSS feed is a valid xml format and this tool can convert rss feed data to a JSON format data. You just need to copy/paste the RSS Feed content into our XML input box and it can convert it.

Can I Convert a ATOM Feed Data To JSON?

Yes, ATOM feed is a valid xml format and this tool can convert ATOM feed data to a JSON format data. You just need to copy/paste the ATOM Feed content into our XML input box and it can convert it.

Why Convert From XML to JSON?

XML data can be easy to read for human, however JSON data format can be used by JavaScript and other software easily. Many tools may support JSON format and you can import your data by simply converting from XML to JSON.

            {% include addthis %}

        {% include theme-footer %}

    {% include theme-bottom-js %}


text:
angular.module('myApp')// our controller for the form
// =============================================================================
.controller('formController', ['$scope', '$state', '$http', '$cookies', 'CostService', 'EmailService', 'schoolYearFilter', function($scope, $state, $http, $cookies, costService, emailService, schoolYearFilter) {

	$http.get('json/states.json').success(function(data) {
    	$scope.states = data;
	});
	$scope.$state = $state;
	$scope.cost = costService.cost;

	$scope.date = new Date();
	$scope.subjects = {'Math' :true, 'Science':true, 'Reading':true, 'English':true, 'Writing':true};
	$scope.summative = {
		'administrationWindow' : '',
		'calendarYear' : ''
	};
	$scope.periodic = {
		'schoolYear' : ''
	};

	/**
	//Save Draft
	$scope.saveDraft = function(){
		localStorage.setItem('formData', angular.toJson($scope.formData));
		localStorage.setItem('summative', angular.toJson($scope.orders.summative));
		localStorage.setItem('periodic', angular.toJson($scope.orders.periodic));
	};**/

	$scope.printPage = function(){
		window.print();
	}

	$scope.notZero = function(type) {
	  return function(order) { return order[type].total; }
	};

	// we will store all of our form data in this object
	$scope.formData = {
		customer: {},
		summary:{
			discount:{}
		}
	};
	$scope.orders = {
		summative: {
			orders: []
		},
		periodic: {
			orders: []
		}
	}

/*	//Load saved draft if available
	var cookieFormData = localStorage.getItem('formData');
	if(cookieFormData){
		$scope.formData = angular.fromJson(cookieFormData);
	}

	var summativeData = localStorage.getItem('summative');
	if(summativeData){
		$scope.orders.summative = angular.fromJson(summativeData);
	}

	var periodicData = localStorage.getItem('periodic');
	if(periodicData){
		$scope.orders.periodic = angular.fromJson(periodicData);
	}*/

	$scope.updateTotals = function(){
		$scope.formData.summary.total = 0.0;
		angular.forEach($scope.orders.summative.orders, function(order, key) {
			$scope.formData.summary.total += order.online.balance + order.paper.balance;
			if(order.cost.lateFee){
				$scope.formData.summary.total += order.cost.lateFee;
			}
		});

		angular.forEach($scope.orders.periodic.orders, function(order, key) {
			$scope.formData.summary.total += order.balance;
		});

		$scope.formData.summary.tax = 0.0;

		//TODO: Uncomment this code when ready to include sales tax
		/*if($scope.formData.billing && !$scope.formData.billing.taxExempt && $scope.cost.salesTax){
			var taxRate = $scope.cost.salesTax[$scope.formData.billing.address.zip];
			if(taxRate){
				$scope.formData.summary.taxRate = taxRate;
				$scope.formData.summary.tax = taxRate * $scope.formData.summary.total;
				$scope.formData.summary.totalWithTax = $scope.formData.summary.tax + $scope.formData.summary.total;
			}
		}*/
	};

	var getCost = function(administrationWindow, calendarYear, pricing){
		var returnCost;
		if(administrationWindow){
			angular.forEach(pricing.summative, function(cost){
				if(cost.year.toString() == calendarYear.toString() && cost.semester == administrationWindow){
					returnCost = cost;
				}
			});
		}
		else{
			returnCost = pricing.periodic[calendarYear];
		}

		return returnCost;
	};

	$scope.addOrder = function(orders, calendarYear){
		var semAndYear = calendarYear.split(" ");
		var administrationWindow;
		if(semAndYear.length == 2){
			calendarYear = semAndYear[1];
			administrationWindow = semAndYear[0];
		}
		var alreadyInList = false;
		angular.forEach(orders, function(order, key) {
			alreadyInList = alreadyInList || (order.administrationWindow == administrationWindow && order.calendarYear == calendarYear);
		});
		if(!alreadyInList){
			var order = { reportsPerStudent:1, scoreLabelsPerStudent: 1 };
			if(administrationWindow){
				order.subjects = {};
				angular.copy($scope.subjects, order.subjects);
			}

			if(orders.length > 0){ //copy in the last order
				var lastOrder = orders[orders.length - 1];
				angular.copy(lastOrder, order);
				order.preferredDate = ''
			}

			order.cost = getCost(administrationWindow, calendarYear, $scope.cost.pricing);

			//set window and year
			order.administrationWindow = administrationWindow;
			order.calendarYear = calendarYear;

			orders.push(order);

			$scope.summative.error = null;
			$scope.periodic.error = null;
		}
		else{
			if(administrationWindow){
				$scope.summative.error = 'You have already placed ' + administrationWindow + ' ' + calendarYear + ' into the cart. Please proceed to the bottom to check-out.';
			}
			else{
				$scope.periodic.error = 'You have already placed ' + schoolYearFilter(calendarYear) + ' into the cart. Please proceed to the bottom to check-out.';
			}
		}
	};

	$scope.removeOrder = function(orders, order){
		var index = orders.indexOf(order);
		if (index > -1) {
				orders.splice(index, 1);
		}
	};

	$scope.updatePeriodicOrders = function(){
		if($scope.cost.pricing){
			angular.forEach($scope.orders.periodic.orders, function(order, key) {
				var onlineTotal = 0;
				angular.forEach(order.grade, function(grade, key) {
					if(grade.online !== null && !isNaN(grade.online)){
						onlineTotal += parseInt(grade.online);
					}
				});
				order.onlineTotal = onlineTotal;

				order.overrideCost = false;
				if($scope.formData.summary.discount.special && $scope.formData.summary.discount.special.override)
				{
					order.cost = $scope.formData.summary.discount.special.pricing.periodic;
					if($scope.orders.summative.orders != null && $scope.orders.summative.orders.length > 0 && $scope.formData.summary.discount.special.pricing.periodicWithSummative){
						order.cost = $scope.formData.summary.discount.special.pricing.periodicWithSummative;
					}
					order.overrideCost = true;
				}

				//Discounts
				order.discounts = {};
				if(!order.overrideCost) {
					order.cost = getCost(order.administrationWindow, order.calendarYear, $scope.cost.pricing);
					if($scope.formData.billing && $scope.formData.billing.address && $scope.formData.billing.address.state){
						order.discounts.state = costService.getStateDiscount($scope.formData.billing.address.state, "periodic", order.calendarYear);
					}
					if($scope.formData.summary.discount.special && $scope.formData.summary.discount.special.periodic){
						order.discounts.special = $scope.formData.summary.discount.special.periodic.discountPer;
					}
				}

				order.price = order.cost;
				order.extendedPrice = order.price * order.onlineTotal;

				order.totalDiscountPerStudent = 0.0;
				for(discountType in order.discounts){
					order.totalDiscountPerStudent += order.discounts[discountType];
				}
				order.totalDiscount = order.totalDiscountPerStudent * order.onlineTotal;

				order.finalPricePerStudent = order.price - order.totalDiscountPerStudent;
				order.balance = order.finalPricePerStudent * order.onlineTotal;
			});

			$scope.updateSummativeOrders();
		}
	};

	$scope.updateSummativeOrders = function(){
		if($scope.cost.pricing){
			angular.forEach($scope.orders.summative.orders, function(order, key) {
				var onlineTotal = 0;
				var gradeCount = 0;
				var paperTotal = 0;
				angular.forEach(order.grade, function(grade, key) {
					var countGrade = false;
					if(grade.online !== null && !isNaN(grade.online) && grade.online > 0){
						onlineTotal += parseInt(grade.online);
						countGrade = true;
					}
					if(grade.paper !== null && !isNaN(grade.paper) && grade.paper > 0){
						paperTotal += parseInt(grade.paper);
						countGrade = true;
					}
					if(countGrade){
						gradeCount++;
					}
				});
				order.online = {};
				order.paper = {};
				order.online.total = onlineTotal;
				order.paper.total = paperTotal;

				var periodicOrder = {};
				angular.forEach($scope.orders.periodic.orders, function(periodic, periodicKey) {
					if((order.administrationWindow == 'Fall' && periodic.calendarYear == order.calendarYear) ||  (order.administrationWindow == 'Spring' && (parseInt(periodic.calendarYear) + 1) == order.calendarYear)){
						periodicOrder = periodic;
					}
				});

				var summativeForSamePeriodic = {online:{}, paper:{}};
				angular.forEach($scope.orders.summative.orders, function(otherSummative, periodicKey) {
					if((order.administrationWindow == 'Fall' && otherSummative.administrationWindow == 'Spring' && parseInt(order.calendarYear) == parseInt(otherSummative.calendarYear) - 1)
						|| (order.administrationWindow == 'Spring' && otherSummative.administrationWindow == 'Fall' && parseInt(order.calendarYear) == parseInt(otherSummative.calendarYear) + 1)){
						summativeForSamePeriodic = otherSummative;
					}
				});

				order.overrideCost = false;
				if($scope.formData.summary.discount.special && $scope.formData.summary.discount.special.override)
				{
					order.cost = {};
					angular.extend(order.cost, $scope.formData.summary.discount.special.pricing.summative);
					order.overrideCost = true;
				}

				//Online portion
				order.online.discounts = {};
				if(!order.overrideCost) {
					order.cost = getCost(order.administrationWindow, order.calendarYear, $scope.cost.pricing);
					order.online.discounts.volume = costService.getVolumeDiscount(order.online.total + order.paper.total);
					order.online.discounts.multiGrade = costService.getMultigradeDiscount(gradeCount);
					if(periodicOrder && periodicOrder.onlineTotal > 0){
						order.online.discounts.periodic = costService.getPeriodicDiscount(order.online.total, periodicOrder.onlineTotal, summativeForSamePeriodic.online.total);
						order.online.periodicNumberApplied = costService.getPeriodicNumberApplied(order.online.total, periodicOrder.onlineTotal, summativeForSamePeriodic.online.total);
					}
					if($scope.formData.billing && $scope.formData.billing.address && $scope.formData.billing.address.state){
						order.online.discounts.state = costService.getStateDiscount($scope.formData.billing.address.state, "summativeOnline", order.calendarYear, order.administrationWindow);
					}
					if($scope.formData.summary.discount.special && $scope.formData.summary.discount.special.summativeOnline){
						order.online.discounts.special = $scope.formData.summary.discount.special.summativeOnline.discountPer;
					}
				}

				order.online.price = order.cost.online
					+ (order.individualReports ? (order.reportsPerStudent * order.cost.isr) : 0.0)
          + (order.scoreLabels ? (order.scoreLabelsPerStudent * order.cost.labels) : 0.0);
				order.online.extendedPrice = order.online.price * order.online.total;

				order.online.totalDiscountPerStudent = 0.0;
				for(discountType in order.online.discounts){
					order.online.totalDiscountPerStudent += order.online.discounts[discountType];
				}

				order.online.totalDiscount = order.online.totalDiscountPerStudent * order.online.total;

				order.online.finalPricePerStudent = order.online.price - order.online.totalDiscountPerStudent;
				order.online.balance = order.online.finalPricePerStudent * order.online.total;

				//paper portion
				order.paper.discounts = {};
				if(!order.overrideCost) {
					order.cost = getCost(order.administrationWindow, order.calendarYear, $scope.cost.pricing);
					order.paper.discounts.volume = costService.getVolumeDiscount(order.paper.total + order.online.total);
					order.paper.discounts.multiGrade = costService.getMultigradeDiscount(gradeCount);
					if(periodicOrder && periodicOrder.onlineTotal > order.online.total){
						//Only apply what's left after the online portion is disounted
						order.paper.discounts.periodic = costService.getPeriodicDiscount(order.paper.total, periodicOrder.onlineTotal - (order.online.total + (summativeForSamePeriodic.online.total ? summativeForSamePeriodic.online.total : 0)), summativeForSamePeriodic.paper.total);
						order.paper.periodicNumberApplied = costService.getPeriodicNumberApplied(order.paper.total, periodicOrder.onlineTotal - (order.online.total + (summativeForSamePeriodic.online.total ? summativeForSamePeriodic.online.total : 0)), summativeForSamePeriodic.paper.total);
					}
					if($scope.formData.billing && $scope.formData.billing.address && $scope.formData.billing.address.state){
						order.paper.discounts.state = costService.getStateDiscount($scope.formData.billing.address.state, "summativePaper", order.calendarYear, order.administrationWindow);
					}
					if($scope.formData.summary.discount.special && $scope.formData.summary.discount.special.summativePaper){
						order.paper.discounts.special = $scope.formData.summary.discount.special.summativePaper.discountPer;
					}
				}

				order.paper.price = order.cost.paper
					+ (order.individualReports ? (order.reportsPerStudent * order.cost.isr) : 0.0)
          + (order.scoreLabels ? (order.scoreLabelsPerStudent * order.cost.labels) : 0.0);
				order.paper.extendedPrice = order.paper.price * order.paper.total;

				order.paper.totalDiscountPerStudent = 0.0;
				for(discountType in order.paper.discounts){
					order.paper.totalDiscountPerStudent += order.paper.discounts[discountType];
				}

				order.paper.totalDiscount = order.paper.totalDiscountPerStudent * order.paper.total;

				order.paper.finalPricePerStudent = order.paper.price - order.paper.totalDiscountPerStudent;
				order.paper.balance = order.paper.finalPricePerStudent * order.paper.total;
			});
			$scope.updateTotals();
		}
	};

	$scope.addDiscountCode = function(code){
		$scope.formData.summary.discount = {
			special: costService.getSpecialDiscount(code)
		};
		$scope.formData.summary.discount.special.code = code.toUpperCase();

		$scope.updatePeriodicOrders();
	}

	// function to process the form
	$scope.processForm = function() {
		emailService.sendConfirmationEmail($scope.formData, $scope.orders, $scope.cost);
	};

	$scope.$watch('orders.summative.orders', function(newValue, oldValue){
		$scope.updatePeriodicOrders();
	}, true);

	$scope.$watch('orders.periodic.orders', function(newValue, oldValue){
		$scope.updatePeriodicOrders();
	}, true);
	//update the orders once the cost resolves
	$scope.$watch('cost', function(newValue, oldValue){
		$scope.updatePeriodicOrders();
	}, true);
	//update the orders when the state changes
	$scope.$watch('formData.billing.address.state', function(newValue, oldValue){
		$scope.updatePeriodicOrders();
	}, true);
	//TODO: uncomment when adding back sales tax
	//Update sales tax when billing zip or taxExempt status changes
	// $scope.$watchCollection('[formData.billing.taxExempt, formData.billing.address.zip]', function(newValue, oldValue){
	// 	$scope.updateTotals();
	// }, true);
}]);


text:
import d3 from "d3"

const MAX_VALUES = 30

// Set the dimensions of the canvas / graph
var margin = {top: 30, right: 20, bottom: 30, left: 50},
    width = 700 - margin.left - margin.right,
    height = 300 - margin.top - margin.bottom;

// Set the ranges
var x = d3.time.scale().range([0, width]);
var y = d3.scale.linear().range([height, 0]);

// Define the axes
var xAxis = d3.svg.axis().scale(x)
    .orient("bottom").ticks(5);

var yAxis = d3.svg.axis().scale(y)
    .orient("left").ticks(5);

// Define the line
var valueline = d3.svg.line().interpolate("basis")
    .x(function(d) { return x(d.date); })
    .y(function(d) { return y(d.value); });

// Adds the svg canvas
var svg = d3.select("#graph")
    .append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
    .append("g")
        .attr("transform",
              "translate(" + margin.left + "," + margin.top + ")");

    // Add the valueline path.
    svg.append("path")
        .attr("class", "line")
        .attr("d", valueline([]));

    // Add the X Axis
    svg.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate(0," + height + ")")
        .call(xAxis);

    // Add the Y Axis
    svg.append("g")
        .attr("class", "y axis")
        .call(yAxis);

// });

// ** Update data section (Called from the onclick)
export default function(data) {
  data.forEach(function(d) {
    d.date = new Date(d.date)
  })

  let nestedData = d3.nest()
    .key(function(d) { return d.label; })
    .entries(data);

  data = d3.nest()
    .key(function(d) { return d.label; })
    .entries(data.slice(-(MAX_VALUES*nestedData.length)));

  // Scale the range of the data again
  let selectedData = d3.merge(data.map(function(d) { return d.values }))
  x.domain(d3.extent(selectedData, function(d) { return d.date; }));
  y.domain([0, d3.max(selectedData, function(d) { return d.value; })]);

  data.forEach(function(d) {
    let timer = null

    if(svg.select("." + d.key).empty()) {
      let color = randomColor();
      svg.append("path")
        .attr("class", d.key)
        .style("stroke", color)
        .attr("d", valueline([]))
        .on('mouseover', function(){
          svg.selectAll(".selected-label").remove()
          svg
            .append("text")
            .attr("class", "selected-label")
            .style("fill", color)
            .text(d.key)
        })
        .on('mouseout', function(){
          clearTimeout(timer)
          timer = setTimeout(function() {
            svg.selectAll(".selected-label").remove()
          }, 1000);
        });
    }

    svg.select("." + d.key)
      .attr("d", valueline(d.values))
  })

  svg.select(".x.axis").call(xAxis);
  svg.select(".y.axis").call(yAxis);
}

function randomColor() {
  return "hsl(" + Math.random() * 360 + ",100%,50%)";
}


text:
This plugin provides support for wordpress. Only define the
APP Id of your website and your wordpress blog is ready to go.

## Installation

* Clone this repository locally:
 * `git clone https://github.com/komentify/integration-libs.git`
* Go into wordpress folder `cd wordpress`
* Copy `komentify` directory into wordpress plugins directory
* Configure APP Id in admin area


text:
package com.amazonaws.services.ec2.model.transform;

import java.util.ArrayList;

import javax.xml.stream.events.XMLEvent;
import javax.annotation.Generated;

import com.amazonaws.services.ec2.model.*;
import com.amazonaws.transform.Unmarshaller;

import com.amazonaws.transform.StaxUnmarshallerContext;
import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*;

/**
 * StaleSecurityGroup StAX Unmarshaller
 */

@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class StaleSecurityGroupStaxUnmarshaller implements Unmarshaller<StaleSecurityGroup, StaxUnmarshallerContext> {

    public StaleSecurityGroup unmarshall(StaxUnmarshallerContext context) throws Exception {
        StaleSecurityGroup staleSecurityGroup = new StaleSecurityGroup();
        int originalDepth = context.getCurrentDepth();
        int targetDepth = originalDepth + 1;

        if (context.isStartOfDocument())
            targetDepth += 1;

        while (true) {
            XMLEvent xmlEvent = context.nextEvent();
            if (xmlEvent.isEndDocument())
                return staleSecurityGroup;

            if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) {

                if (context.testExpression("description", targetDepth)) {
                    staleSecurityGroup.setDescription(StringStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("groupId", targetDepth)) {
                    staleSecurityGroup.setGroupId(StringStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("groupName", targetDepth)) {
                    staleSecurityGroup.setGroupName(StringStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("staleIpPermissions", targetDepth)) {
                    staleSecurityGroup.withStaleIpPermissions(new ArrayList<StaleIpPermission>());
                    continue;
                }

                if (context.testExpression("staleIpPermissions/item", targetDepth)) {
                    staleSecurityGroup.withStaleIpPermissions(StaleIpPermissionStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("staleIpPermissionsEgress", targetDepth)) {
                    staleSecurityGroup.withStaleIpPermissionsEgress(new ArrayList<StaleIpPermission>());
                    continue;
                }

                if (context.testExpression("staleIpPermissionsEgress/item", targetDepth)) {
                    staleSecurityGroup.withStaleIpPermissionsEgress(StaleIpPermissionStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("vpcId", targetDepth)) {
                    staleSecurityGroup.setVpcId(StringStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }
            } else if (xmlEvent.isEndElement()) {
                if (context.getCurrentDepth() < originalDepth) {
                    return staleSecurityGroup;
                }
            }
        }
    }

    private static StaleSecurityGroupStaxUnmarshaller instance;

    public static StaleSecurityGroupStaxUnmarshaller getInstance() {
        if (instance == null)
            instance = new StaleSecurityGroupStaxUnmarshaller();
        return instance;
    }
}


text:
OPENEXR_IMF_INTERNAL_NAMESPACE_HEADER_ENTER

typedef TypedAttribute<OPENEXR_IMF_INTERNAL_NAMESPACE::Compression> CompressionAttribute;
template <> IMF_EXPORT const char *CompressionAttribute::staticTypeName ();
template <> IMF_EXPORT void CompressionAttribute::writeValueTo (OPENEXR_IMF_INTERNAL_NAMESPACE::OStream &,
                                                     int) const;
template <> IMF_EXPORT void CompressionAttribute::readValueFrom (OPENEXR_IMF_INTERNAL_NAMESPACE::IStream &,
                                                      int,
                                                      int);

OPENEXR_IMF_INTERNAL_NAMESPACE_HEADER_EXIT

#endif


text:
"""Collection of all hosts related calls
"""
from deploy_board.webapp.helpers.deployclient import DeployClient

deployclient = DeployClient()

def get_hosts_by_name(request, host_name):
    return deployclient.get("/hosts/%s" % host_name, request.teletraan_user_id.token)


text:
// QtArg include.
#include <QtArg/Arg>
#include <QtArg/CmdLine>

// Qt include.
#include <QtCore/QString>
#include <QtCore/QStringList>

// unit test helper.
#include <test/helper/helper.hpp>

UNIT_TEST_START

	//
	// test_ignore_rest_1
	//

	UNIT_START( test_ignore_rest_1 )

		QStringList arguments;
		arguments << QLatin1String( "test" )
			<< QLatin1String( "-a" ) << QLatin1String( "1" )
			<< QLatin1String( "--bb" ) << QLatin1String( "2" )
			<< QLatin1String( "--" )
			<< QLatin1String( "--cc" ) << QLatin1String( "3" )
			<< QLatin1String( "-d" ) << QLatin1String( "4" )
			<< QLatin1String( "-e" ) << QLatin1String( "-f" )
			<< QLatin1String( "-g" )
			<< QLatin1String( "-i" ) << QLatin1String( "5" );

		QtArgCmdLine cmd( arguments );

		QtArg a( QLatin1Char( 'a' ), QString(), QString(), false, true );
		QtArg b( QLatin1String( "bb" ), QString(), false, true );

		cmd.addArg( a );
		cmd.addArg( b );

		cmd.parse();

		CHECK_CONDITION( a.value().toString() == QLatin1String( "1" ) )
		CHECK_CONDITION( b.value().toString() == QLatin1String( "2" ) )

	UNIT_FINISH( test_ignore_rest_1 )

	//
	// test_ignore_rest_2
	//

	UNIT_START( test_ignore_rest_2 )

	QStringList arguments;
	arguments << QLatin1String( "test" )
		<< QLatin1String( "-a" ) << QLatin1String( "1" )
		<< QLatin1String( "--bb" ) << QLatin1String( "2" )
		<< QLatin1String( "--" )
		<< QLatin1String( "--cc=3" ) << QLatin1String( "-d4" )
		<< QLatin1String( "-ef" ) << QLatin1String( "-gi5" );

	QtArgCmdLine cmd( arguments );

	QtArg a( QLatin1Char( 'a' ), QString(), QString(), false, true );
	QtArg b( QLatin1String( "bb" ), QString(), false, true );
	QtArg c( QLatin1String( "cc" ), QString(), false, true );
	QtArg d( QLatin1Char( 'd' ), QString(), QString(), false, true );
	QtArg e( QLatin1Char( 'e' ), QString(), QString(), false, false );
	QtArg f( QLatin1Char( 'f' ), QString(), QString(), false, false );
	QtArg g( QLatin1Char( 'g' ), QString(), QString(), false, false );
	QtArg i( QLatin1Char( 'i' ), QString(), QString(), false, true );

	cmd.addArg( a );
	cmd.addArg( b );
	cmd.addArg( c );
	cmd.addArg( d );
	cmd.addArg( e );
	cmd.addArg( f );
	cmd.addArg( g );
	cmd.addArg( i );

	cmd.parse( true );

	CHECK_CONDITION( a.value().toString() == QLatin1String( "1" ) )
	CHECK_CONDITION( b.value().toString() == QLatin1String( "2" ) )
	CHECK_CONDITION( c.value().toString() == QLatin1String( "3" ) )
	CHECK_CONDITION( d.value().toString() == QLatin1String( "4" ) )
	CHECK_CONDITION( e.value().toBool() == true )
	CHECK_CONDITION( f.value().toBool() == true )
	CHECK_CONDITION( g.value().toBool() == true )
	CHECK_CONDITION( i.value().toString() == QLatin1String( "5" ) )

	UNIT_FINISH( test_ignore_rest_2 )

UNIT_TEST_FINISH


text:
namespace CohesionAndCoupling.Utilities
{
    using System;

    public static class FileUtils
    {
        public static string GetFileExtension(string fileName)
        {
            int indexOfLastDot = fileName.LastIndexOf(".");

            if (indexOfLastDot == -1)
            {
                throw new ArgumentException("Input file does not have file extension!");
            }

            string extension = fileName.Substring(indexOfLastDot + 1);
            return extension;
        }

        public static string GetFileNameWithoutExtension(string fileName)
        {
            int indexOfLastDot = fileName.LastIndexOf(".");

            if (indexOfLastDot == -1)
            {
                throw new ArgumentException("Input file does not have file extension!");
            }

            string extension = fileName.Substring(0, indexOfLastDot);
            return extension;
        }
    }
}


text:
<?php

require_once('TypeSafe/logging/Logger.php');
require_once('TypeSafe/config/Configuration.php');
require_once('CouchDB.php');
require_once('CouchDBException.php');
require_once('CouchDBObject.php');

/**
 *
 * @author Tobias Sarnowski
 */
class DefaultCouchDB implements CouchDB {

    /**
     * @var Logger
     */
    private $log;

    /**
     * @var string
     */
    private $host;

    /**
     * @var int
     */
    private $port;

    /**
     * @var string
     */
    private $prefix;

    /**
     * @param Configuration $config
     * @param Logger $log
     * @return void
     */
    function __construct(Configuration $config, Logger $log) {
        $this->log = $log;

        $this->host = $config->get('couchdb.host', 'localhost');
        $this->port = $config->get('couchdb.port', 5984);
        $this->prefix = $config->get('couchdb.prefix', '');
    }

    public function get($database, $url) {
        return $this->send('GET', $this->buildUrl($database, $url));
    }

    public function put($database, $url, $data) {
        return $this->send('PUT', $this->buildUrl($database, $url), $data);
    }

    public function del($database, $url) {
        return $this->send('DELETE', $this->buildUrl($database, $url));
    }

    /**
     * @private
     * @param  string $database
     * @param  string $url
     * @return string
     */
    function buildUrl($database, $url) {
        if (substr($url, 0, 1) != '/') {
            $url = "/$url";
        }
        return '/'.$this->prefix.$database.$url;
    }

    /**
     * Based on the example:
     * http://wiki.apache.org/couchdb/Getting_started_with_PHP
     *
     * @private
     * @throws CouchDBException
     * @param  string $method
     * @param  string $url
     * @param  string $post_data
     * @return string
     */
    function send($method, $url, $post_data = NULL) {
        $s = fsockopen($this->host, $this->port, $errno, $errstr);
        if (!$s) {
            throw new CouchDBException('Connection refused ($errno): $errstr');
        }

        $request = "$method $url HTTP/1.0\r\nHost: ".$this->host."\r\n";

        if ($post_data) {
            $request .= "Content-Length: ".strlen($post_data)."\r\n\r\n";
            $request .= "$post_data\r\n";
        } else {
            $request .= "\r\n";
        }

        fwrite($s, $request);
        $response = "";

        while(!feof($s)) {
            $response .= fgets($s);
        }

        fclose($s);

        list($header, $body) = explode("\r\n\r\n", $response);

        $err_str = '{"error":';
        if (substr($body, 0, strlen($err_str)) == $err_str) {
            $error = json_decode($body, true);
            throw new CouchDBException($error['error'].': '.$error['reason']);
        }

        return $body;
    }

    public function read($database, $class, $id) {
        $json = $this->get($database, $id);

        $class = new ReflectionClass($class);
        $object = $class->getMethod('fromJson')->invokeArgs(null, $json);

        return $object;
    }

    public function update($database, CouchDBObject $object) {
        $json = $this->put($database, $object->getId(), $object->toJson());
        $response = json_decode($json);

        if (!$response) {
            throw new CouchDBException("update failed; no response");
        }
        if ($response['ok'] != true) {
            throw new CouchDBException("update failed; returned false");
        }

        $object->setId($response['id']);
        $object->setRev($response['rev']);

        return $object;
    }

    public function delete($database, CouchDBObject $object) {
        $json = $this->del($database, $object->getId().'?rev='.$object->getRev());
        $response = json_decode($json);

        if (!$response) {
            throw new CouchDBException("deletion failed; no response");
        }
        if ($response['ok'] != true) {
            throw new CouchDBException("deletion failed; returned false");
        }
        return $response;
    }

    public function storeDesignDocument($database, $name, $views) {
        $data = array(
            '_id' => '_design/'.$name,
            'language' => 'javascript',
            'views' => array()
        );

        foreach ($views as $view) {
            $data['views'][$view->getName()] = array(
                'map' => $view->getMapFunction()
            );
            $reduce = $view->getReduceFunction();
            if ($reduce != null) {
                $data['views'][$view->getName()]['reduce'] = $reduce;
            }
        }

        return $this->put($database, '/'.$data['_id'], json_encode($data));
    }

    public function view($database, $designDocument, $viewName, $parameters = null, $class = null) {
        if ($parameters == null) {
            $parameters = array();
        }

        $url = "_design/$designDocument/_view/$viewName";

        if (!empty($parameters)) {
            $first = true;
            foreach ($parameters as $key => $value) {
                if ($first) {
                    $url .= '?';
                    $first = false;
                } else {
                    $url .= '&';
                }

                $url .= $key.'='.$value;
            }
        }

        $response = json_decode($this->get($database, $url), true);
        if (!$response) {
            throw new CouchDBException("Cannot parse view response.");
        }

        if ($class == null) {
            $creator = null;
        } else {
            $class = new ReflectionClass($class);
            $creator = $class->getMethod("fromJson");
        }

        $result = array();
        foreach ($response['rows'] as $row) {
            if ($creator == null) {
                $result[] = $row;
            } else {
                $result[] = $creator->invokeArgs(null, array(json_encode($row)));
            }
        }
        return $result;
    }
}


text:
. ./storm_env.sh

printFormat (){
	echo "Format:     ./squall_local.sh MODE CONFIG_PATH"
	echo "             MODE: SQL (default) or PLAN_RUNNER"
}

# Check the number of arguments
if [[ $# -lt 1 || $# -gt 2 ]]; then
	echo "ERROR:: Improper number of arguments!"
	printFormat
	exit 1
fi

# Reading input paramters
MODE=$1
if [[ "$MODE" != "PLAN_RUNNER" && "$MODE" != "SQL" ]]; then
	MODE=SQL
else
   shift
fi

# Main class
if [ "$MODE" == "PLAN_RUNNER" ]; then
	MAIN_CLASS=ch.epfl.data.squall.main.Main
else
	MAIN_CLASS=ch.epfl.data.squall.api.sql.main.ParserMain
fi

# Set config file path and check if it exist
if [[ $# -lt 1 ]]; then
	echo "ERROR:: Missing configuration file path!"
	printFormat
	exit 1
fi
CONFIG_PATH=$1
if ! [ -f $CONFIG_PATH ]; then
	echo "ERROR:: File $CONFIG_PATH does not exist! Please specify a valid configuration file!"
	exit 1
fi

# Running
java -Xmx128m -cp ../squall-core/target/squall-0.2.0.jar:../squall-core/target/squall-dependencies-0.2.0.jar:../$STORMNAME/lib/* $MAIN_CLASS $CONFIG_PATH


text:
@implementation RGDeal

- (NSDictionary *)replacedKeyFromPropertyName
{
    return @{@"desc" : @"description"};
}

- (NSDictionary *)objectClassInArray
{
    return @{@"businesses" : [RGBusiness class]};
}

MJCodingImplementation

- (BOOL)isEqual:(RGDeal *)other
{
    return [self.deal_id isEqual:other.deal_id];
}

@end


text:
[![NPM](https://nodei.co/npm/ngrate.png)](https://nodei.co/npm/ngrate/)

This is a ultra simple, database agnostic, migrations library based on ES6 Promises.

`npm install ngrate --save`

## Creating a new migration

To create a new migration simply run

`ngrate create migration-name`

This will generate a file under 'migrations/' folder with the timestamp and the name.

The file will look like the this code below:

```javascript
const name = 'create-user-table';
const createdAt = 1476651301760;

exports.createdAt = createdAt;
exports.name = name;

exports.up = () => {
    return new Promise((resolve, reject) => {
        //TODO: Write migration code
        resolve();
    });
};

exports.down = () => {
    return new Promise((resolve, reject) => {
        //TODO: Write migration code
        resolve();
    });
};
```

From this, you should require the databases you need and do your operation.

## Running specific migrations

You can run a specific migration by using the command `up` or `down`.

`ngrate up migrations/yourmigrationfile.js`

`ngrate down migrations/yourmigrationfile.js`

## Execute pending migrations

To run pending migrations just type

`ngrate run`

This will get the last migration execution and run the next one forward. Running one by one until all succeed or one fails.

In case one migration fails, the state left will be up to the latest successful migration

## Strategies

ngrate is based on migration strategies which is a interface that can be found [here](https://github.com/grillorafael/ngrate/blob/master/strategies/abstract-strategy.js)

You can write your own strategy by implementing those methods. By default, this library comes with a local file strategy.

## Customizing strategy

You can customize your strategy by creating a file called `.ngrate.js`

This file should look like this

````javascript
module.exports = {
    migrationsDir: 'migrations',
    strategy: require('./strategies/local-strategy')
};
````

Where `strategy` is a new instance of your AbstractStrategy implementation.

## Available Strategies

I'm going to write new strategies for the following databases:
1. MongoDB
1. Redis

If you have any suggestion, just create an issue.

Strategies should not exist within this code base. The implementations should exist as separate modules.


text:
package stscreds

import (
	"testing"
	"time"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/service/sts"
	"github.com/stretchr/testify/assert"
)

type stubSTS struct {
}

func (s *stubSTS) AssumeRole(input *sts.AssumeRoleInput) (*sts.AssumeRoleOutput, error) {
	expiry := time.Now().Add(60 * time.Minute)
	return &sts.AssumeRoleOutput{
		Credentials: &sts.Credentials{
			// Just reflect the role arn to the provider.
			AccessKeyId:     input.RoleArn,
			SecretAccessKey: aws.String("assumedSecretAccessKey"),
			SessionToken:    aws.String("assumedSessionToken"),
			Expiration:      &expiry,
		},
	}, nil
}

func TestAssumeRoleProvider(t *testing.T) {
	stub := &stubSTS{}
	p := &AssumeRoleProvider{
		Client:  stub,
		RoleARN: "roleARN",
	}

	creds, err := p.Retrieve()
	assert.Nil(t, err, "Expect no error")

	assert.Equal(t, "roleARN", creds.AccessKeyID, "Expect access key ID to be reflected role ARN")
	assert.Equal(t, "assumedSecretAccessKey", creds.SecretAccessKey, "Expect secret access key to match")
	assert.Equal(t, "assumedSessionToken", creds.SessionToken, "Expect session token to match")
}

func BenchmarkAssumeRoleProvider(b *testing.B) {
	stub := &stubSTS{}
	p := &AssumeRoleProvider{
		Client:  stub,
		RoleARN: "roleARN",
	}

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		if _, err := p.Retrieve(); err != nil {
			b.Fatal(err)
		}
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<test-data>
    <test-code>
        <description><![CDATA[
failure case
     ]]></description>
        <expected-problems>3</expected-problems>
        <![CDATA[
public class Foo {
 void bar() {
  try {
  } catch (NullPointerException e) {
  } catch (Exception e) {
  } catch (RuntimeException e) {
  }
 }
}
     ]]>
    </test-code>
    <test-code>
        <description><![CDATA[
catching another type, ok
     ]]></description>
        <expected-problems>0</expected-problems>
        <![CDATA[
public class Foo {
 void bar() {
  try {
  } catch (FooException e) {
  }
 }
}
     ]]>
    </test-code>
    <test-code>
        <description><![CDATA[
throwing it, ok
     ]]></description>
        <expected-problems>0</expected-problems>
        <![CDATA[
public class Foo {
 void bar() {
  throw new NullPointerException();
 }
}
     ]]>
    </test-code>
</test-data>


text:
/* this file has been autogenerated by vtkNodeJsWrap */
/* editing this might proof futile */

#define VTK_WRAPPING_CXX
#define VTK_STREAMS_FWD_ONLY
#include <nan.h>

#include "vtkObjectWrap.h"
#include "vtkTDxInteractorStyleWrap.h"
#include "vtkTDxInteractorStyleSettingsWrap.h"
#include "../../plus/plus.h"

using namespace v8;

extern Nan::Persistent<v8::Object> vtkNodeJsNoWrap;
Nan::Persistent<v8::FunctionTemplate> VtkTDxInteractorStyleWrap::ptpl;

VtkTDxInteractorStyleWrap::VtkTDxInteractorStyleWrap()
{ }

VtkTDxInteractorStyleWrap::VtkTDxInteractorStyleWrap(vtkSmartPointer<vtkTDxInteractorStyle> _native)
{ native = _native; }

VtkTDxInteractorStyleWrap::~VtkTDxInteractorStyleWrap()
{ }

void VtkTDxInteractorStyleWrap::Init(v8::Local<v8::Object> exports)
{
	Nan::SetAccessor(exports, Nan::New("vtkTDxInteractorStyle").ToLocalChecked(), ConstructorGetter);
	Nan::SetAccessor(exports, Nan::New("TDxInteractorStyle").ToLocalChecked(), ConstructorGetter);
}

void VtkTDxInteractorStyleWrap::ConstructorGetter(
	v8::Local<v8::String> property,
	const Nan::PropertyCallbackInfo<v8::Value>& info)
{
	InitPtpl();
	info.GetReturnValue().Set(Nan::New(ptpl)->GetFunction());
}

void VtkTDxInteractorStyleWrap::InitPtpl()
{
	if (!ptpl.IsEmpty()) return;
	v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New);
	VtkObjectWrap::InitPtpl( );
	tpl->Inherit(Nan::New<FunctionTemplate>(VtkObjectWrap::ptpl));
	tpl->SetClassName(Nan::New("VtkTDxInteractorStyleWrap").ToLocalChecked());
	tpl->InstanceTemplate()->SetInternalFieldCount(1);

	Nan::SetPrototypeMethod(tpl, "GetClassName", GetClassName);
	Nan::SetPrototypeMethod(tpl, "getClassName", GetClassName);

	Nan::SetPrototypeMethod(tpl, "GetSettings", GetSettings);
	Nan::SetPrototypeMethod(tpl, "getSettings", GetSettings);

	Nan::SetPrototypeMethod(tpl, "IsA", IsA);
	Nan::SetPrototypeMethod(tpl, "isA", IsA);

	Nan::SetPrototypeMethod(tpl, "NewInstance", NewInstance);
	Nan::SetPrototypeMethod(tpl, "newInstance", NewInstance);

	Nan::SetPrototypeMethod(tpl, "OnButtonPressedEvent", OnButtonPressedEvent);
	Nan::SetPrototypeMethod(tpl, "onButtonPressedEvent", OnButtonPressedEvent);

	Nan::SetPrototypeMethod(tpl, "OnButtonReleasedEvent", OnButtonReleasedEvent);
	Nan::SetPrototypeMethod(tpl, "onButtonReleasedEvent", OnButtonReleasedEvent);

	Nan::SetPrototypeMethod(tpl, "SafeDownCast", SafeDownCast);
	Nan::SetPrototypeMethod(tpl, "safeDownCast", SafeDownCast);

	Nan::SetPrototypeMethod(tpl, "SetSettings", SetSettings);
	Nan::SetPrototypeMethod(tpl, "setSettings", SetSettings);

#ifdef VTK_NODE_PLUS_VTKTDXINTERACTORSTYLEWRAP_INITPTPL
	VTK_NODE_PLUS_VTKTDXINTERACTORSTYLEWRAP_INITPTPL
#endif
	ptpl.Reset( tpl );
}

void VtkTDxInteractorStyleWrap::New(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	if(!info.IsConstructCall())
	{
		Nan::ThrowError("Constructor not called in a construct call.");
		return;
	}

	if(info.Length() == 0)
	{
		Nan::ThrowError("Cannot create instance of abstract class.");
		return;
	}
	else
	{
		if(info[0]->ToObject() != vtkNodeJsNoWrap )
		{
			Nan::ThrowError("Parameter Error");
			return;
		}
	}

	info.GetReturnValue().Set(info.This());
}

void VtkTDxInteractorStyleWrap::GetClassName(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkTDxInteractorStyleWrap *wrapper = ObjectWrap::Unwrap<VtkTDxInteractorStyleWrap>(info.Holder());
	vtkTDxInteractorStyle *native = (vtkTDxInteractorStyle *)wrapper->native.GetPointer();
	char const * r;
	if(info.Length() != 0)
	{
		Nan::ThrowError("Too many parameters.");
		return;
	}
	r = native->GetClassName();
	info.GetReturnValue().Set(Nan::New(r).ToLocalChecked());
}

void VtkTDxInteractorStyleWrap::GetSettings(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkTDxInteractorStyleWrap *wrapper = ObjectWrap::Unwrap<VtkTDxInteractorStyleWrap>(info.Holder());
	vtkTDxInteractorStyle *native = (vtkTDxInteractorStyle *)wrapper->native.GetPointer();
	vtkTDxInteractorStyleSettings * r;
	if(info.Length() != 0)
	{
		Nan::ThrowError("Too many parameters.");
		return;
	}
	r = native->GetSettings();
	VtkTDxInteractorStyleSettingsWrap::InitPtpl();
	v8::Local<v8::Value> argv[1] =
		{ Nan::New(vtkNodeJsNoWrap) };
	v8::Local<v8::Function> cons =
		Nan::New<v8::FunctionTemplate>(VtkTDxInteractorStyleSettingsWrap::ptpl)->GetFunction();
	v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
	VtkTDxInteractorStyleSettingsWrap *w = new VtkTDxInteractorStyleSettingsWrap();
	w->native = r;
	w->Wrap(wo);
	info.GetReturnValue().Set(wo);
}

void VtkTDxInteractorStyleWrap::IsA(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkTDxInteractorStyleWrap *wrapper = ObjectWrap::Unwrap<VtkTDxInteractorStyleWrap>(info.Holder());
	vtkTDxInteractorStyle *native = (vtkTDxInteractorStyle *)wrapper->native.GetPointer();
	if(info.Length() > 0 && info[0]->IsString())
	{
		Nan::Utf8String a0(info[0]);
		int r;
		if(info.Length() != 1)
		{
			Nan::ThrowError("Too many parameters.");
			return;
		}
		r = native->IsA(
			*a0
		);
		info.GetReturnValue().Set(Nan::New(r));
		return;
	}
	Nan::ThrowError("Parameter mismatch");
}

void VtkTDxInteractorStyleWrap::NewInstance(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkTDxInteractorStyleWrap *wrapper = ObjectWrap::Unwrap<VtkTDxInteractorStyleWrap>(info.Holder());
	vtkTDxInteractorStyle *native = (vtkTDxInteractorStyle *)wrapper->native.GetPointer();
	vtkTDxInteractorStyle * r;
	if(info.Length() != 0)
	{
		Nan::ThrowError("Too many parameters.");
		return;
	}
	r = native->NewInstance();
	VtkTDxInteractorStyleWrap::InitPtpl();
	v8::Local<v8::Value> argv[1] =
		{ Nan::New(vtkNodeJsNoWrap) };
	v8::Local<v8::Function> cons =
		Nan::New<v8::FunctionTemplate>(VtkTDxInteractorStyleWrap::ptpl)->GetFunction();
	v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
	VtkTDxInteractorStyleWrap *w = new VtkTDxInteractorStyleWrap();
	w->native = r;
	w->Wrap(wo);
	info.GetReturnValue().Set(wo);
}

void VtkTDxInteractorStyleWrap::OnButtonPressedEvent(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkTDxInteractorStyleWrap *wrapper = ObjectWrap::Unwrap<VtkTDxInteractorStyleWrap>(info.Holder());
	vtkTDxInteractorStyle *native = (vtkTDxInteractorStyle *)wrapper->native.GetPointer();
	if(info.Length() > 0 && info[0]->IsInt32())
	{
				if(info.Length() != 1)
		{
			Nan::ThrowError("Too many parameters.");
			return;
		}
		native->OnButtonPressedEvent(
			info[0]->Int32Value()
		);
		return;
	}
	Nan::ThrowError("Parameter mismatch");
}

void VtkTDxInteractorStyleWrap::OnButtonReleasedEvent(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkTDxInteractorStyleWrap *wrapper = ObjectWrap::Unwrap<VtkTDxInteractorStyleWrap>(info.Holder());
	vtkTDxInteractorStyle *native = (vtkTDxInteractorStyle *)wrapper->native.GetPointer();
	if(info.Length() > 0 && info[0]->IsInt32())
	{
				if(info.Length() != 1)
		{
			Nan::ThrowError("Too many parameters.");
			return;
		}
		native->OnButtonReleasedEvent(
			info[0]->Int32Value()
		);
		return;
	}
	Nan::ThrowError("Parameter mismatch");
}

void VtkTDxInteractorStyleWrap::SafeDownCast(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkTDxInteractorStyleWrap *wrapper = ObjectWrap::Unwrap<VtkTDxInteractorStyleWrap>(info.Holder());
	vtkTDxInteractorStyle *native = (vtkTDxInteractorStyle *)wrapper->native.GetPointer();
	if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkObjectWrap::ptpl))->HasInstance(info[0]))
	{
		VtkObjectWrap *a0 = ObjectWrap::Unwrap<VtkObjectWrap>(info[0]->ToObject());
		vtkTDxInteractorStyle * r;
		if(info.Length() != 1)
		{
			Nan::ThrowError("Too many parameters.");
			return;
		}
		r = native->SafeDownCast(
			(vtkObject *) a0->native.GetPointer()
		);
		VtkTDxInteractorStyleWrap::InitPtpl();
		v8::Local<v8::Value> argv[1] =
			{ Nan::New(vtkNodeJsNoWrap) };
		v8::Local<v8::Function> cons =
			Nan::New<v8::FunctionTemplate>(VtkTDxInteractorStyleWrap::ptpl)->GetFunction();
		v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
		VtkTDxInteractorStyleWrap *w = new VtkTDxInteractorStyleWrap();
		w->native = r;
		w->Wrap(wo);
		info.GetReturnValue().Set(wo);
		return;
	}
	Nan::ThrowError("Parameter mismatch");
}

void VtkTDxInteractorStyleWrap::SetSettings(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkTDxInteractorStyleWrap *wrapper = ObjectWrap::Unwrap<VtkTDxInteractorStyleWrap>(info.Holder());
	vtkTDxInteractorStyle *native = (vtkTDxInteractorStyle *)wrapper->native.GetPointer();
	if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkTDxInteractorStyleSettingsWrap::ptpl))->HasInstance(info[0]))
	{
		VtkTDxInteractorStyleSettingsWrap *a0 = ObjectWrap::Unwrap<VtkTDxInteractorStyleSettingsWrap>(info[0]->ToObject());
				if(info.Length() != 1)
		{
			Nan::ThrowError("Too many parameters.");
			return;
		}
		native->SetSettings(
			(vtkTDxInteractorStyleSettings *) a0->native.GetPointer()
		);
		return;
	}
	Nan::ThrowError("Parameter mismatch");
}


text:
@implementation UrlConnection

+(void)startConnection:(NSString *)url parmaters:(NSDictionary *)par connetionBlock:(connectionBlock)block{
    UrlConnection *roots = [[UrlConnection alloc] init];
    [roots connectionWith:url parmaters:par connectionBlock:block];
}

-(void)connectionWith:(NSString *)url parmaters:(NSDictionary *)par connectionBlock:(connectionBlock)block{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json", @"text/plain", @"text/html", nil];
    manager.securityPolicy.allowInvalidCertificates = YES;
    [manager GET:url parameters:par success:^(AFHTTPRequestOperation *operation, id responseObject) {
        block(responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
    }];
}

@end


text:
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="16dp"
    android:height="16dp"
    android:viewportWidth="16"
    android:viewportHeight="16">
  <path
      android:pathData="M8,8m-7,0a7,7 0,1 1,14 0a7,7 0,1 1,-14 0"
      android:strokeWidth="2"
      android:fillColor="#FFF"
      android:strokeColor="#1E67CE"
      android:fillType="evenOdd"/>
  <path
      android:pathData="M5,5h6v6H5z"
      android:fillColor="#1E67CE"
      android:fillType="evenOdd"/>
</vector>


text:
using Microsoft.Extensions.Localization;

namespace Microsoft.AspNetCore.Mvc.Localization;

/// <summary>
/// An <see cref="IHtmlLocalizerFactory"/> that creates instances of <see cref="HtmlLocalizer"/> using the
/// registered <see cref="IStringLocalizerFactory"/>.
/// </summary>
public class HtmlLocalizerFactory : IHtmlLocalizerFactory
{
    private readonly IStringLocalizerFactory _factory;

    /// <summary>
    /// Creates a new <see cref="HtmlLocalizerFactory"/>.
    /// </summary>
    /// <param name="localizerFactory">The <see cref="IStringLocalizerFactory"/>.</param>
    public HtmlLocalizerFactory(IStringLocalizerFactory localizerFactory)
    {
        if (localizerFactory == null)
        {
            throw new ArgumentNullException(nameof(localizerFactory));
        }

        _factory = localizerFactory;
    }

    /// <summary>
    /// Creates an <see cref="HtmlLocalizer"/> using the specified <see cref="Type"/>.
    /// </summary>
    /// <param name="resourceSource">The <see cref="Type"/> to load resources for.</param>
    /// <returns>The <see cref="HtmlLocalizer"/>.</returns>
    public virtual IHtmlLocalizer Create(Type resourceSource)
    {
        if (resourceSource == null)
        {
            throw new ArgumentNullException(nameof(resourceSource));
        }

        return new HtmlLocalizer(_factory.Create(resourceSource));
    }

    /// <summary>
    /// Creates an <see cref="HtmlLocalizer"/> using the specified base name and location.
    /// </summary>
    /// <param name="baseName">The base name of the resource to load strings from.</param>
    /// <param name="location">The location to load resources from.</param>
    /// <returns>The <see cref="HtmlLocalizer"/>.</returns>
    public virtual IHtmlLocalizer Create(string baseName, string location)
    {
        if (baseName == null)
        {
            throw new ArgumentNullException(nameof(baseName));
        }

        if (location == null)
        {
            throw new ArgumentNullException(nameof(location));
        }

        var localizer = _factory.Create(baseName, location);
        return new HtmlLocalizer(localizer);
    }
}


text:
<?php
namespace Aws\Polly;

use Aws\Api\Serializer\JsonBody;
use Aws\AwsClient;
use Aws\Signature\SignatureV4;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Uri;
use GuzzleHttp\Psr7;

/**
 * This client is used to interact with the **Amazon Polly** service.
 * @method \Aws\Result deleteLexicon(array $args = [])
 * @method \GuzzleHttp\Promise\Promise deleteLexiconAsync(array $args = [])
 * @method \Aws\Result describeVoices(array $args = [])
 * @method \GuzzleHttp\Promise\Promise describeVoicesAsync(array $args = [])
 * @method \Aws\Result getLexicon(array $args = [])
 * @method \GuzzleHttp\Promise\Promise getLexiconAsync(array $args = [])
 * @method \Aws\Result getSpeechSynthesisTask(array $args = [])
 * @method \GuzzleHttp\Promise\Promise getSpeechSynthesisTaskAsync(array $args = [])
 * @method \Aws\Result listLexicons(array $args = [])
 * @method \GuzzleHttp\Promise\Promise listLexiconsAsync(array $args = [])
 * @method \Aws\Result listSpeechSynthesisTasks(array $args = [])
 * @method \GuzzleHttp\Promise\Promise listSpeechSynthesisTasksAsync(array $args = [])
 * @method \Aws\Result putLexicon(array $args = [])
 * @method \GuzzleHttp\Promise\Promise putLexiconAsync(array $args = [])
 * @method \Aws\Result startSpeechSynthesisTask(array $args = [])
 * @method \GuzzleHttp\Promise\Promise startSpeechSynthesisTaskAsync(array $args = [])
 * @method \Aws\Result synthesizeSpeech(array $args = [])
 * @method \GuzzleHttp\Promise\Promise synthesizeSpeechAsync(array $args = [])
 */
class PollyClient extends AwsClient
{
    /** @var JsonBody */
    private $formatter;

    /**
     * Create a pre-signed URL for Polly operation `SynthesizeSpeech`
     *
     * @param array $args parameters array for `SynthesizeSpeech`
     *                    More information @see Aws\Polly\PollyClient::SynthesizeSpeech
     *
     * @return string
     */
    public function createSynthesizeSpeechPreSignedUrl(array $args)
    {
        $uri = new Uri($this->getEndpoint());
        $uri = $uri->withPath('/v1/speech');

        // Formatting parameters follows rest-json protocol
        $this->formatter = $this->formatter ?: new JsonBody($this->getApi());
        $queryArray = json_decode(
            $this->formatter->build(
                $this->getApi()->getOperation('SynthesizeSpeech')->getInput(),
                $args
            ),
            true
        );

        // Mocking a 'GET' request in pre-signing the Url
        $query = Psr7\build_query($queryArray);
        $uri = $uri->withQuery($query);

        $request = new Request('GET', $uri);
        $request = $request->withBody(Psr7\stream_for(''));
        $signer = new SignatureV4('polly', $this->getRegion());
        return (string) $signer->presign(
            $request,
            $this->getCredentials()->wait(),
            '+15 minutes'
        )->getUri();
    }
}