text:
# PyTorch vs Apache MXNet

[PyTorch](https://pytorch.org/) is a popular deep learning framework due to its easy-to-understand API and its completely imperative approach. Apache MXNet includes the Gluon API which gives you the simplicity and flexibility of PyTorch and allows you to hybridize your network to leverage performance optimizations of the symbolic graph. As of April 2019, [NVidia performance benchmarks](https://developer.nvidia.com/deep-learning-performance-training-inference) show that Apache MXNet outperforms PyTorch by ~77% on training ResNet-50: 10,925 images per second vs. 6,175.

In the next 10 minutes, we'll do a quick comparison between the two frameworks and show how small the learning curve can be when switching from PyTorch to Apache MXNet.

## Installation

PyTorch uses conda for installation by default, for example:

```{.python .input}
# !conda install pytorch-cpu -c pytorch
```

For MXNet we use pip:

```{.python .input}
# !pip install mxnet
```

To install Apache MXNet with GPU support, you need to specify CUDA version. For example, the snippet below will install Apache MXNet with CUDA 9.2 support:

```{.python .input}
# !pip install mxnet-cuda92
```

## Data manipulation

Both PyTorch and Apache MXNet relies on multidimensional matrices as a data sources. While PyTorch follows Torch's naming convention and refers to multidimensional matrices as "tensors", Apache MXNet follows NumPy's conventions and refers to them as "NDArrays".

In the code snippets below, we create a two-dimensional matrix where each element is initialized to 1. We show how to add 1 to each element of matrices and print the results.

**PyTorch:**

```{.python .input}
import torch

x = torch.ones(5,3)
y = x + 1
y
```

**MXNet:**

```{.python .input}
from mxnet import nd

x = nd.ones((5,3))
y = x + 1
y
```

The main difference apart from the package name is that the MXNet's shape input parameter needs to be passed as a tuple enclosed in parentheses as in NumPy.

Both frameworks support multiple functions to create and manipulate tensors / NDArrays. You can find more of them in the documentation.

## Model training

After covering the basics of data creation and manipulation, let's dive deep and compare how model training is done in both frameworks. In order to do so, we are going to solve image classification task on MNIST data set using Multilayer Perceptron (MLP) in both frameworks. We divide the task in 4 steps.

### 1. Read data

The first step is to obtain the data. We download the MNIST data set from the web and load it into memory so that we can read batches one by one.

**PyTorch:**

```{.python .input}
from torchvision import datasets, transforms

trans = transforms.Compose([transforms.ToTensor(),
                            transforms.Normalize((0.13,), (0.31,))])
pt_train_data = torch.utils.data.DataLoader(datasets.MNIST(
    root='.', train=True, download=True, transform=trans),
    batch_size=128, shuffle=True, num_workers=4)
```

**MXNet:**

```{.python .input}
from mxnet import gluon
from mxnet.gluon.data.vision import datasets, transforms

trans = transforms.Compose([transforms.ToTensor(),
                            transforms.Normalize(0.13, 0.31)])
mx_train_data = gluon.data.DataLoader(
    datasets.MNIST(train=True).transform_first(trans),
    batch_size=128, shuffle=True, num_workers=4)
```

Both frameworks allows you to download MNIST data set from their sources and specify that only training part of the data set is required.

The main difference between the code snippets is that MXNet uses [transform_first](/api/python/docs/api/gluon/data/index.html#mxnet.gluon.data.Dataset.transform_first) method to indicate that the data transformation is done on the first element of the data batch, the MNIST picture, rather than the second element, the label.

### 2. Creating the model

Below we define a Multilayer Perceptron (MLP) with a single hidden layer
and 10 units in the output layer.

**PyTorch:**

```{.python .input}
import torch.nn as pt_nn

pt_net = pt_nn.Sequential(
    pt_nn.Linear(28*28, 256),
    pt_nn.ReLU(),
    pt_nn.Linear(256, 10))
```

**MXNet:**

```{.python .input}
import mxnet.gluon.nn as mx_nn

mx_net = mx_nn.Sequential()
mx_net.add(mx_nn.Dense(256, activation='relu'),
           mx_nn.Dense(10))
mx_net.initialize()
```

We used the Sequential container to stack layers one after the other in order to construct the neural network. Apache MXNet differs from PyTorch in the following ways:

* In PyTorch you have to specify the input size as the first argument of the `Linear` object. Apache MXNet provides an extra flexibility to network structure by automatically inferring the input size after the first forward pass.

* In Apache MXNet you can specify activation functions directly in fully connected and convolutional layers.

* After the model structure is defined, Apache MXNet requires you to explicitly call the model initialization function.

With a Sequential block, layers are executed one after the other. To have a different execution model, with PyTorch you can inherit from `nn.Module` and then customize how the `.forward()` function is executed. Similarly, in Apache MXNet you can inherit from [nn.Block](/api/python/docs/api/gluon/nn/index.html#mxnet.gluon.nn.Block) to achieve similar results.

### 3. Loss function and optimization algorithm

The next step is to define the loss function and pick an optimization algorithm. Both PyTorch and Apache MXNet provide multiple options to chose from, and for our particular case we are going to use the cross-entropy loss function and the Stochastic Gradient Descent (SGD) optimization algorithm.

**PyTorch:**

```{.python .input}
pt_loss_fn = pt_nn.CrossEntropyLoss()
pt_trainer = torch.optim.SGD(pt_net.parameters(), lr=0.1)
```

**MXNet:**

```{.python .input}
mx_loss_fn = gluon.loss.SoftmaxCrossEntropyLoss()
mx_trainer = gluon.Trainer(mx_net.collect_params(),
                           'sgd', {'learning_rate': 0.1})
```

The code difference between frameworks is small. The main difference is that in Apache MXNet we use [Trainer](/api/python/docs/api/gluon/trainer.html) class, which accepts optimization algorithm as an argument. We also use [.collect_params()](/api/python/docs/api/gluon/block.html#mxnet.gluon.Block.collect_params) method to get parameters of the network.

### 4. Training

Finally, we implement the training algorithm. Note that the results for each run
may vary because the weights will get different initialization values and the
data will be read in a different order due to shuffling.

**PyTorch:**

```{.python .input}
import time

for epoch in range(5):
    total_loss = .0
    tic = time.time()
    for X, y in pt_train_data:
        pt_trainer.zero_grad()
        loss = pt_loss_fn(pt_net(X.view(-1, 28*28)), y)
        loss.backward()
        pt_trainer.step()
        total_loss += loss.mean()
    print('epoch %d, avg loss %.4f, time %.2f' % (
        epoch, total_loss/len(pt_train_data), time.time()-tic))
```

**MXNet:**

```{.python .input}
from mxnet import autograd

for epoch in range(5):
    total_loss = .0
    tic = time.time()
    for X, y in mx_train_data:
        with autograd.record():
            loss = mx_loss_fn(mx_net(X), y)
        loss.backward()
        mx_trainer.step(batch_size=128)
        total_loss += loss.mean().asscalar()
    print('epoch %d, avg loss %.4f, time %.2f' % (
        epoch, total_loss/len(mx_train_data), time.time()-tic))
```

Some of the differences in Apache MXNet when compared to PyTorch are as follows:

* In Apache MXNet, you don't need to flatten the 4-D input into 2-D when feeding the data into forward pass.

* In Apache MXNet, you need to perform the calculation within the [autograd.record()](/api/python/docs/api/autograd/index.html?autograd%20record#mxnet.autograd.record) scope so that it can be automatically differentiated in the backward pass.

* It is not necessary to clear the gradient every time as with PyTorch's `trainer.zero_grad()` because by default the new gradient is written in, not accumulated.

* You need to specify the update step size (usually batch size) when performing [step()](/api/python/docs/api/gluon/trainer.html?#mxnet.gluon.Trainer.step) on the trainer.

* You need to call [.asscalar()](/api/python/docs/api/ndarray/ndarray.html?#mxnet.ndarray.NDArray.asscalar) to turn a multidimensional array into a scalar.

* In this sample, Apache MXNet is twice as fast as PyTorch. Though you need to be cautious with such toy comparisons.

## Conclusion

As we saw above, Apache MXNet Gluon API and PyTorch have many similarities. The main difference lies in terminology (Tensor vs. NDArray) and behavior of accumulating gradients: gradients are accumulated in PyTorch and overwritten in Apache MXNet. The rest of the code is very similar, and it is quite straightforward to move code from one framework to the other.

## Recommended Next Steps

While Apache MXNet Gluon API is very similar to PyTorch, there are some extra functionality that can make your code even faster.

* Check out [Hybridize tutorial](/api/python/docs/tutorials/packages/gluon/blocks/hybridize.html) to learn how to write imperative code which can be converted to symbolic one.

* Also, check out how to extend Apache MXNet with your own [custom layers](/api/python/docs/tutorials/packages/gluon/blocks/custom-layer.html?custom_layers).

## Appendix

Below you can find a detailed comparison of various PyTorch functions and their equivalent in Gluon API of Apache MXNet.

### Tensor operation

Here is the list of function names in PyTorch Tensor that are different from Apache MXNet NDArray.

| Function                      | PyTorch                                   | MXNet Gluon                                               |
|-------------------------------|-------------------------------------------|-----------------------------------------------------------|
| Element-wise inverse cosine   | `x.acos()` or `torch.acos(x)`             | `nd.arccos(x)`                                            |
| Batch Matrix product and accumulation| `torch.addbmm(M, batch1, batch2)`  | `nd.linalg_gemm(M, batch1, batch2)` Leading n-2 dim are reduced |
| Element-wise division of t1, t2, multiply v, and add t | `torch.addcdiv(t, v, t1, t2)` | `t + v*(t1/t2)`                              |
| Matrix product and accumulation| `torch.addmm(M, mat1, mat2)`             | `nd.linalg_gemm(M, mat1, mat2)`                           |
| Outer-product of two vector add a matrix | `m.addr(vec1, vec2)`           | Not available                                             |
| Element-wise applies function | `x.apply_(calllable)`                     | Not available, but there is `nd.custom(x, 'op')`          |
| Element-wise inverse sine     | `x.asin()` or `torch.asin(x)`             | `nd.arcsin(x)`                                            |
| Element-wise inverse tangent  | `x.atan()` or `torch.atan(x)`             | `nd.arctan(x)`                                            |
| Tangent of two tensor         | `x.atan2(y)` or `torch.atan2(x, y)`       | Not available                                             |
| batch matrix product          | `x.bmm(y)` or `torch.bmm(x, x)`           | `nd.linalg_gemm2(x, y)`                                   |
| Draws a sample from bernoulli distribution | `x.bernoulli()`              | Not available                                             |
| Fills a tensor with number drawn from Cauchy distribution | `x.cauchy_()` | Not available                                             |
| Splits a tensor in a given dim| `x.chunk(num_of_chunk)`                   | `nd.split(x, num_outputs=num_of_chunk)`                   |
| Limits the values of a tensor to between min and max | `x.clamp(min, max)`| `nd.clip(x, min, max)`                                    |
| Returns a copy of the tensor  | `x.clone()`                               | `x.copy()`                                                |
| Cross product                 | `x.cross(y)`                              | Not available                                             |
| Cumulative product along an axis| `x.cumprod(1)`                          | Not available                                             |
| Cumulative sum along an axis  | `x.cumsum(1)`                             | Not available                                             |
| Address of the first element  | `x.data_ptr()`                            | Not available                                             |
| Creates a diagonal tensor     | `x.diag()`                                | Not available                                             |
| Computes norm of a tensor     | `x.dist()`                                | `nd.norm(x)` Only calculate L2 norm                       |
| Computes Gauss error function | `x.erf()`                                 | Not available                                             |
| Broadcasts/Expands tensor to new shape | `x.expand(3,4)`                  | `x.broadcast_to([3, 4])`                                  |
| Fills a tensor with samples drawn from exponential distribution | `x.exponential_()` | `nd.random_exponential()`                      |
| Element-wise mod              | `x.fmod(3)`                               | `nd.module(x, 3)`                                         |
| Fractional portion of a tensor| `x.frac()`                                | `x - nd.trunc(x)`                                         |
| Gathers values along an axis specified by dim | `torch.gather(x, 1,  torch.LongTensor([[0,0],[1,0]]))` | `nd.gather_nd(x, nd.array([[[0,0],[1,1]],[[0,0],[1,0]]]))`  |
| Solves least square & least norm | `B.gels(A)`                            | Not available                                             |
| Draws from geometirc distribution | `x.geometric_(p)`                     | Not available                                             |
| Device context of a tensor    | `print(x)` will print which device x is on| `x.context`                                               |
| Repeats tensor                | `x.repeat(4,2)`                           | `x.tile(4,2)`                                             |
| Data type of a tensor         | `x.type()`                                | `x.dtype`                                                 |
| Scatter                       | `torch.zeros(2, 4).scatter_(1, torch.LongTensor([[2], [3]]), 1.23)` | `nd.scatter_nd(nd.array([1.23,1.23]), nd.array([[0,1],[2,3]]), (2,4))` |
| Returns the shape of a tensor | `x.size()`                                | `x.shape`                                                 |
| Number of elements in a tensor| `x.numel()`                               | `x.size`                                                  |
| Returns this tensor as a NumPy ndarray | `x.numpy()`                      | `x.asnumpy()`                                             |
| Eigendecomposition for symmetric matrix | `e, v = a.symeig()`             | `v, e = nd.linalg.syevd(a)`                               |
| Transpose                     | `x.t()`                                   | `x.T`                                                     |
| Sample uniformly              | `torch.uniform_()`                        | `nd.sample_uniform()`                                     |
| Inserts a new dimesion        | `x.unsqueeze()`                           | `nd.expand_dims(x)`                                       |
| Reshape                       | `x.view(16)`                              | `x.reshape((16,))`                                          |
| Veiw as a specified tensor    | `x.view_as(y)`                            | `x.reshape_like(y)`                                       |
| Returns a copy of the tensor after casting to a specified type | `x.type(type)` | `x.astype(dtype)`                                   |
| Copies the value of one tensor to another | `dst.copy_(src)`              | `src.copyto(dst)`                                         |
| Returns a zero tensor with specified shape | `x = torch.zeros(2,3)`       | `x = nd.zeros((2,3))`                                     |
| Returns a one tensor with specified shape | `x = torch.ones(2,3)`         | `x = nd.ones((2,3)`                                       |
| Returns a Tensor filled with the scalar value 1, with the same size as input | `y = torch.ones_like(x)` | `y = nd.ones_like(x)`       |

### Functional

### GPU

Just like Tensor, MXNet NDArray can be copied to and operated on GPU. This is done by specifying context.

| Function               | PyTorch                           | MXNet Gluon                                                                |
|------------------------|-----------------------------------|----------------------------------------------------------------------------|
| Copy to GPU            | `y = torch.FloatTensor(1).cuda()` | `y = mx.nd.ones((1,), ctx=mx.gpu(0))`                                      |
| Convert to numpy array | `x = y.cpu().numpy()`             | `x = y.asnumpy()`                                                          |
| Context scope          | `with torch.cuda.device(1):`
    `y= torch.cuda.FloatTensor(1)`                    | `with mx.gpu(1):`
    `y = mx.nd.ones((3,5))`      |

### Cross-device

Just like Tensor, MXNet NDArray can be copied across multiple GPUs.

| Function               | PyTorch                           | MXNet Gluon                                                                |
|------------------------|-----------------------------------|----------------------------------------------------------------------------|
| Copy from GPU 0 to GPU 1           | `x = torch.cuda.FloatTensor(1)`
`y=x.cuda(1)`| `x = mx.nd.ones((1,), ctx=mx.gpu(0))`
`y=x.as_in_context(mx.gpu(1))`                                      |
| Copy Tensor/NDArray on different GPUs | `y.copy_(x)`             | `x.copyto(y)`                                                          |

## Autograd

### Variable wrapper vs autograd scope

Autograd package of PyTorch/MXNet enables automatic differentiation of Tensor/NDArray.

| Function               | PyTorch                           | MXNet Gluon                                                                |
|------------------------|-----------------------------------|----------------------------------------------------------------------------|
| Recording computation       | `x = Variable(torch.FloatTensor(1), requires_grad=True)`
`y = x * 2`
`y.backward()`  | `x = mx.nd.ones((1,))`
`x.attach_grad()`
`with mx.autograd.record():`
    `y = x * 2`
`y.backward()`                                   |

### Scope override (pause, train_mode, predict_mode)

Some operators (Dropout, BatchNorm, etc) behave differently in training and making predictions. This can be controlled with `train_mode` and `predict_mode` scope in MXNet.
Pause scope is for code that does not need gradients to be calculated.

| Function               | PyTorch                           | MXNet Gluon                                                                |
|------------------------|-----------------------------------|----------------------------------------------------------------------------|
| Scope override   | Not available | `x = mx.nd.ones((1,))`
`with autograd.train_mode():`
    `y = mx.nd.Dropout(x)`
    `with autograd.predict_mode():`
        `z = mx.nd.Dropout(y)`

`w = mx.nd.ones((1,))`
`w.attach_grad()`
`with autograd.record():`
    `y = x * w`
    `y.backward()`
    `with autograd.pause():`
        `w += w.grad`   |

### Batch-end synchronization is needed

Apache MXNet uses lazy evaluation to achieve superior performance. The Python thread just pushes the operations into the backend engine and then returns. In training phase batch-end synchronization is needed, e.g, `asnumpy()`, `wait_to_read()`, `metric.update(...)`.

| Function               | PyTorch                           | MXNet Gluon                                                                |
|------------------------|-----------------------------------|----------------------------------------------------------------------------|
| Batch-end synchronization    |  Not available  | `for (data, label) in train_data:`
    `with autograd.record():`
        `output = net(data)`
        `L = loss(output, label)`
        `L.backward()`
    `trainer.step(data.shape[0])`
    `metric.update([label], [output])` |

## PyTorch module and Gluon blocks

### For new block definition, gluon is similar to PyTorch

| Function               | PyTorch                           | MXNet Gluon                                                                |
|------------------------|-----------------------------------|----------------------------------------------------------------------------|
| New block definition   | `class Net(torch.nn.Module):`
    `def __init__(self, D_in, D_out):`
        `super(Net, self).__init__()`
        `self.linear = torch.nn.Linear(D_in, D_out)`
    `def forward(self, x):`
        `return self.linear(x)`       |    `class Net(mx.gluon.Block):`
    `def __init__(self, D_in, D_out):`
        `super(Net, self).__init__()`
        `self.dense=mx.gluon.nn.Dense(D_out, in_units=D_in)`
    `def forward(self, x):`
        `return self.dense(x)`      |

### Parameter and Initializer

When creating new layers in PyTorch, you do not need to specify its parameter initializer, and different layers have different default initializer. When you create new layers in Gluon API, you can specify its initializer or just leave it none. The parameters will finish initializing after calling `net.initialize(<init method>)` and all parameters will be initialized in `init method` except those layers whose initializer specified.

| Function       | PyTorch           | MXNet Gluon        |
|----------------|-------------------|--------------------|
| Get all parameters |  `net.parameters()` | `net.collect_params()` |
| Initialize network |  Not Available | `net.initialize(mx.init.Xavier())` |
| Specify layer initializer | `layer = torch.nn.Linear(20, 10)`
 `torch.nn.init.normal(layer.weight, 0, 0.01)` | `layer = mx.gluon.nn.Dense(10, weight_initializer=mx.init.Normal(0.01))` |

### Usage of existing blocks look alike

| Function               | PyTorch                           | MXNet Gluon                                                                |
|------------------------|-----------------------------------|----------------------------------------------------------------------------|
| Usage of existing blocks    |  `y=net(x)`  |  `y=net(x)`   |

### HybridBlock can be hybridized, and allows partial-shape info

HybridBlock supports forwarding with both Symbol and NDArray. After hybridized, HybridBlock will create a symbolic graph representing the forward computation and cache it. Most of the built-in blocks (Dense, Conv2D, MaxPool2D, BatchNorm, etc.) are HybridBlocks.

Instead of explicitly declaring the number of inputs to a layer, we can simply state the number of outputs. The shape will be inferred on the fly once the network is provided with some input.

| Function               | PyTorch                           | MXNet Gluon                                                                |
|------------------------|-----------------------------------|----------------------------------------------------------------------------|
| partial-shape
 hybridized    |  Not Available   |  `net = mx.gluon.nn.HybridSequential()`
`net.add(mx.gluon.nn.Dense(10))`
`net.hybridize()`   |

### SymbolBlock

SymbolBlock can construct block from symbol. This is useful for using pre-trained models as feature extractors.

| Function               | PyTorch                           | MXNet Gluon                                                                |
|------------------------|-----------------------------------|----------------------------------------------------------------------------|
|  SymbolBlock    |  Not Available   |  `alexnet = mx.gluon.model_zoo.vision.alexnet(pretrained=True)`
`out = alexnet(inputs)`
`internals = out.get_internals()`
`outputs = [internals['model_dense0_relu_fwd_output']]`
`feat_model = gluon.SymbolBlock(outputs, inputs, params=alexnet.collect_params())`   |

## PyTorch optimizer vs Gluon Trainer
### For Gluon API calling zero_grad is not necessary most of the time
`zero_grad` in optimizer (PyTorch) or Trainer (Gluon API) clears the gradients of all parameters. In Gluon API, there is no need to clear the gradients every batch if `grad_req = 'write'`(default).

| Function               | PyTorch                           | MXNet Gluon                              |
|------------------------|-----------------------------------|------------------------------------------|
| clear the gradients |   `optm = torch.optim.SGD(model.parameters(), lr=0.1)`
`optm.zero_grad()`
`loss_fn(model(input), target).backward()`
`optm.step()`    | `trainer = gluon.Trainer(net.collect_params(), 'sgd', {'learning_rate': 0.1})`
`with autograd.record():`
    `loss = loss_fn(net(data), label)`
`loss.backward()`
`trainer.step(batch_size)`      |

### Multi-GPU training

| Function               | PyTorch                           | MXNet Gluon                              |
|------------------------|-----------------------------------|------------------------------------------|
| data parallelism |   `net = torch.nn.DataParallel(model, device_ids=[0, 1, 2])`
`output = net(data)`    | `ctx = [mx.gpu(i) for i in range(3)]`
`data = gluon.utils.split_and_load(data, ctx)`
`label = gluon.utils.split_and_load(label, ctx)`
`with autograd.record():`
    `losses = [loss(net(X), Y) for X, Y in zip(data, label)]`
`for l in losses:`
    `l.backward()`      |

### Distributed training

| Function               | Pytorch                           | MXNet Gluon                              |
|------------------------|-----------------------------------|------------------------------------------|
| distributed data parallelism |   `torch.distributed.init_process_group(...)`
`model = torch.nn.parallel.distributedDataParallel(model, ...)`    | `store = kv.create('dist')`
`trainer = gluon.Trainer(net.collect_params(), ..., kvstore=store)`  |

## Monitoring

### Apache MXNet has pre-defined metrics

Gluon provide several predefined metrics which can online evaluate the performance of a learned model.

| Function               | PyTorch                           | MXNet Gluon                              |
|------------------------|-----------------------------------|------------------------------------------|
| metric |  Not available   | `metric = mx.metric.Accuracy()`
`with autograd.record():`
    `output = net(data)`
    `L = loss(ouput, label)`
    `loss(ouput, label).backward()`
`trainer.step(batch_size)`
`metric.update(label, output)`  |

### Data visualization

TensorboardX (PyTorch) and [MXBoard](https://github.com/awslabs/mxboard) (MXNet) can be used to visualize your network and plot quantitative metrics about the execution of your graph.

| PyTorch                                        | MXNet                                          |
| ---------------------------------------------- | ---------------------------------------------- |
| `sw = tensorboardX.SummaryWriter()`            | `sw = mxboard.SummaryWriter()`                 |
| `...`                                          | `...`                                          |
| `for name, param in model.named_parameters():` | `for name, param in net.collect_params():`     |
| `    grad = param.clone().cpu().data.numpy()`  | `    grad = param.grad.asnumpy().flatten()`    |
| `    sw.add_histogram(name, grad, n_iter)`     | `    sw.add_histogram(tag=str(param),`         |
| `...`                                          | `       values=grad,`                          |
| `sw.close()`                                   | `       bins=200,`                             |
|                                                | `       global_step=i)`                        |
|                                                | `...`                                          |
|                                                | `sw.close()`                                   |

## I/O and deploy

### Data loading

`Dataset` and `DataLoader` are the basic components for loading data.

| Class               | PyTorch                           | MXNet Gluon                              |
|------------------------|-----------------------------------|------------------------------------------|
| Dataset holding arrays | `torch.utils.data.TensorDataset(data_tensor, label_tensor)`| `gluon.data.ArrayDataset(data_array, label_array)`                        |
| Data loader | `torch.utils.data.DataLoader(dataset, batch_size=1, shuffle=False, sampler=None, batch_sampler=None, num_workers=0, collate_fn=<function default_collate>, drop_last=False)` | `gluon.data.DataLoader(dataset, batch_size=None, shuffle=False, sampler=None, last_batch='keep', batch_sampler=None, batchify_fn=None, num_workers=0)`|
| Sequentially applied sampler | `torch.utils.data.sampler.SequentialSampler(data_source)` | `gluon.data.SequentialSampler(length)` |
| Random order sampler | `torch.utils.data.sampler.RandomSampler(data_source)` | `gluon.data.RandomSampler(length)`|

Some commonly used datasets for computer vision are provided in `mx.gluon.data.vision` package.

| Class               | PyTorch                           | MXNet Gluon                              |
|------------------------|-----------------------------------|------------------------------------------|
| MNIST handwritten digits dataset. | `torchvision.datasets.MNIST`| `mx.gluon.data.vision.MNIST` |
| CIFAR10 Dataset. | `torchvision.datasets.CIFAR10` | `mx.gluon.data.vision.CIFAR10`|
| CIFAR100 Dataset. | `torchvision.datasets.CIFAR100` | `mx.gluon.data.vision.CIFAR100` |
| A generic data loader where the images are arranged in folders. | `torchvision.datasets.ImageFolder(root, transform=None, target_transform=None, loader=<function default_loader>)` | `mx.gluon.data.vision.ImageFolderDataset(root, flag, transform=None)`|

### Serialization

Serialization and deserialization are achieved by calling `save_parameters` and `load_parameters`.

| Class               | PyTorch                           | MXNet Gluon                              |
|------------------------|-----------------------------------|------------------------------------------|
| Save model parameters | `torch.save(the_model.state_dict(), filename)`| `model.save_parameters(filename)`|
| Load parameters | `the_model.load_state_dict(torch.load(PATH))` | `model.load_parameters(filename, ctx, allow_missing=False, ignore_extra=False)` |


text:
hook reflectionfunction function not found
--SKIPIF--
<?php
$plugin = <<<EOF
RASP.algorithmConfig = {
     webshell_callable: {
        name:   '算法4 - 拦截简单的 PHP array_map/walk/filter 后门',
        action: 'block',
        functions: [
            'system', 'exec'
        ]
    }
}
EOF;
include(__DIR__.'/../skipif.inc');
?>
--INI--
openrasp.root_dir=/tmp/openrasp
--FILE--
<?php
$func = new ReflectionFunction('heyguycanyoufindme');
?>
--EXPECTREGEX--
Fatal error: Uncaught .*ReflectionException.*

redpajama_set_name: RedPajamaGithub


text:
package kuroodo.discordbot.games.battleship;

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

import net.dv8tion.jda.core.entities.Member;

public class BattleShipNewGameSetup {
	private BattleShip battleShipSession;

	private ArrayList<String> availableSlots;

	private EShipClass currentShip;
	private int currentShipSlotCount = 0;
	private String currentShipFirstSlot;
	private String lastSlot;

	private Member member;

	private boolean isSetupComplete = false, isFirstShipSlot = true, horizontal = false, diagonal = false;

	public BattleShipNewGameSetup(Member member, BattleShip battleShipSession) {
		this.battleShipSession = battleShipSession;
		this.member = member;

		availableSlots = new ArrayList<>();

		// for (int index = 1; index <= BSData.CARRIER_HEALTH; index++) {
		// battleShipSession.getPlayerBoard(member).addShip(EShipClass.CARRIER,
		// "A" + index);
		// }
		//
		// for (int index = 1; index <= BSData.BATTLESHIP_HEALTH; index++) {
		// battleShipSession.getPlayerBoard(member).addShip(EShipClass.BATTLESHIP,
		// "B" + index);
		// }
		//
		// for (int index = 1; index <= BSData.SUBMARINE_HEALTH; index++) {
		// battleShipSession.getPlayerBoard(member).addShip(EShipClass.SUBMARIINE,
		// "C" + index);
		// }
		//
		// for (int index = 1; index <= BSData.CRUISER_HEALTH; index++) {
		// battleShipSession.getPlayerBoard(member).addShip(EShipClass.CRUISER,
		// "D" + index);
		// }
		//
		// for (int index = 1; index <= BSData.DESTROYER_HEALTH; index++) {
		// battleShipSession.getPlayerBoard(member).addShip(EShipClass.DESTROYER,
		// "E" + index);
		// }
		//
		// isSetupComplete = true;
		// String message = "**All done! Now waiting for the other player to
		// finish setting up their board**";
		// battleShipSession.sendPrivateMessage(member, message);
		// battleShipSession.setPlayerReady(member);
	}

	public void printOpening() {
		String message = "Welcome to battleship!\nPlease refer to your specified gamesession in the servers text channels.\n\nLet's set up your game board!\n";
		battleShipSession.sendPrivateMessage(member, message);

		currentShip = EShipClass.CARRIER;
		currentShipSlotCount = BSData.CARRIER_HEALTH;
		message = "```\nCurrent Ship: " + currentShip.name() + "\nSlots remaining: " + currentShipSlotCount
				+ "\n```\ntype !game <gridlocation> to enter the next grid location for the ship! (ex: !game B5)";
		battleShipSession.sendPrivateMessage(member, message);
	}

	private void printNextShipInfo() {
		String message = "**Moving On To Next Ship**\n```\nCurrent Ship: " + currentShip.name() + "\nSlots remaining: "
				+ currentShipSlotCount
				+ "\n```\ntype !game <gridlocation> to enter the next grid location for the ship! (ex: !game B5)";

		battleShipSession.sendPrivateMessage(member, message);
	}

	public void recieveInput(String input) {
		String message = "";

		if (!isSetupComplete) {
			if (isValidShipPlacement(input)) {

				addNewSlot(input);

				message = battleShipSession.getPlayerBoard(member).getBoardAsString();
				message = message + "```\nCurrent Ship: " + currentShip.name() + "\nSlots remaining: "
						+ currentShipSlotCount
						+ "\n```\ntype !game <gridlocation> to enter the next grid location for the ship! (ex: !game B5)";
				battleShipSession.sendPrivateMessage(member, message);

				if (currentShipSlotCount == 0) {

					// Check if is final ship
					if (currentShip != EShipClass.DESTROYER) {
						setNextShip();
						isFirstShipSlot = true;
						diagonal = false;
						horizontal = false;
						currentShipSlotCount = getCurrentShipTotalSlots();
						printNextShipInfo();
					} else {
						isSetupComplete = true;
						message = "**All done! Now waiting for the other player to finish setting up their board**";
						battleShipSession.sendPrivateMessage(member, message);
						battleShipSession.setPlayerReady(member);
					}
				}
			} else {
				System.out.println("INVALID SLOT");
			}
		}
	}

	private void addNewSlot(String slot) {
		battleShipSession.getPlayerBoard(member).addShip(currentShip, slot);
		currentShipSlotCount--;
	}

	private boolean isValidShipPlacement(String input) {
		// TODO: Finish this

		if (!battleShipSession.getPlayerBoard(member).isValidSlot(input)) {
			return false;
		}

		if (!battleShipSession.getPlayerBoard(member).isSlotEmpty(input)) {
			return false;
		}

		// If just adding first slot for current ship
		if (isFirstShipSlot) {
			isFirstShipSlot = false;
			currentShipFirstSlot = input;
			lastSlot = input;
			return true;
		}

		// If is second or later ship slot
		if (!isFirstShipSlot) {
			return configureLaterSlots(input);
		}

		return false;

	}

	private boolean configureLaterSlots(String input) {

		List<String> keys = new ArrayList<String>(battleShipSession.getPlayerBoard(member).getBoard().keySet());
		BSGameBoard playersBoard = battleShipSession.getPlayerBoard(member);

		try {
			if (horizontal) {
				return (playersBoard.getBoard().get(keys.indexOf(input) - 10) == BSData.getShipSymbol(currentShip)
						|| playersBoard.getBoard().get(keys.indexOf(input) + 10) == BSData.getShipSymbol(currentShip));

			} else if (diagonal) {
				return (playersBoard.getBoard().get(keys.indexOf(input) + 1) == BSData.getShipSymbol(currentShip)
						|| playersBoard.getBoard().get(keys.indexOf(input) - 1) == BSData.getShipSymbol(currentShip));

			} else {
				if (keys.get(keys.indexOf(input) - 10) == keys.get(keys.indexOf(currentShipFirstSlot))
						|| keys.get(keys.indexOf(input) + 10) == keys.get(keys.indexOf(currentShipFirstSlot))) {
					diagonal = true;
				} else if (keys.get(keys.indexOf(input) - 1) == keys.get(keys.indexOf(currentShipFirstSlot))
						|| keys.get(keys.indexOf(input) + 1) == keys.get(keys.indexOf(currentShipFirstSlot))) {
					horizontal = true;
				}

				lastSlot = input;
				return true;
			}
		} catch (ArrayIndexOutOfBoundsException e) {
			return false;
		}

		// List<String> keys = new
		// ArrayList<String>(battleShipSession.getPlayerBoard(member).getBoard().keySet());
		//
		// if (horizontal) {
		// if(battleShipSession.getPlayerBoard(member).isValidSlot(keys.indexOf(input)))
		// } else if (diagonal) {
		//
		// } else {
		// if (keys.get(keys.indexOf(input) - 10) ==
		// keys.get(keys.indexOf(currentShipFirstSlot))
		// || keys.get(keys.indexOf(input) + 10) ==
		// keys.get(keys.indexOf(currentShipFirstSlot))) {
		// diagonal = true;
		// horizontal = false;
		// configureLaterSlots(input);
		// } else if (keys.get(keys.indexOf(input) - 1) ==
		// keys.get(keys.indexOf(currentShipFirstSlot))
		// || keys.get(keys.indexOf(input) + 1) ==
		// keys.get(keys.indexOf(currentShipFirstSlot))) {
		// horizontal = true;
		// diagonal = false;
		// configureLaterSlots(input);
		// }
		// }
	}

	private void setFirstSlots(String input) {

		// List<String> keys = new
		// ArrayList<String>(battleShipSession.getPlayerBoard(member).getBoard().keySet());

		//
		// availableSlots.clear();
		//
		// // Left
		// if
		// (battleShipSession.getPlayerBoard(member).isValidSlot(keys.get(keys.indexOf(input)
		// - 1))) {
		// System.out.println("Left slot is valid");
		// System.out.println("Key: " + keys.get(keys.indexOf(input) - 1));
		//
		// availableSlots.add(keys.get(keys.indexOf(input) - 1));
		// }
		//
		// // Right
		// if
		// (battleShipSession.getPlayerBoard(member).isValidSlot(keys.get(keys.indexOf(input)
		// + 1))) {
		// System.out.println("Right slot is valid");
		// System.out.println("Key: " + keys.get(keys.indexOf(input) + 1));
		//
		// availableSlots.add(keys.get(keys.indexOf(input) + 1));
		// }
		//
		// // Up
		// if
		// (battleShipSession.getPlayerBoard(member).isValidSlot(keys.get(keys.indexOf(input)
		// - 10))) {
		// System.out.println("Up slot is valid");
		// System.out.println("Key: " + keys.get(keys.indexOf(input) - 10));
		//
		// availableSlots.add(keys.get(keys.indexOf(input) - 10));
		// }
		//
		// // Down
		// if
		// (battleShipSession.getPlayerBoard(member).isValidSlot(keys.get(keys.indexOf(input)
		// + 10))) {
		// System.out.println("Down slot is valid");
		// System.out.println("Key: " + keys.get(keys.indexOf(input) + 10));
		//
		// availableSlots.add(keys.get(keys.indexOf(input) + 10));
		// }
	}

	private Integer getCurrentShipTotalSlots() {
		switch (currentShip) {
		case CARRIER:
			return BSData.CARRIER_HEALTH;
		case BATTLESHIP:
			return BSData.BATTLESHIP_HEALTH;
		case SUBMARIINE:
			return BSData.SUBMARINE_HEALTH;
		case CRUISER:
			return BSData.CRUISER_HEALTH;
		case DESTROYER:
			return BSData.DESTROYER_HEALTH;
		default:
			return -1;
		}
	}

	private void setNextShip() {
		switch (currentShip) {
		case CARRIER:
			currentShip = EShipClass.BATTLESHIP;
			break;
		case BATTLESHIP:
			currentShip = EShipClass.SUBMARIINE;
			break;
		case SUBMARIINE:
			currentShip = EShipClass.CRUISER;
			break;
		case CRUISER:
			currentShip = EShipClass.DESTROYER;
			break;
		default:
			break;
		}
	}

}


text:
import time
from JumpScale import j

j.application.start("jumpscale:portalclientest")
j.application.initGrid()

import JumpScale.portal

client = j.core.a.portal.getPortalClient("127.0.0.1", port=81, "1234")
system = client.getActor("system", "master", instance=0)

j.application.stop()


text:
  <title>REWYNDR</title>
    <meta charset="UTF-8">
    <meta name="description" content="Rewyndr Company Website">
    <meta name="keywords" content="Rewyndr" />

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/css/materialize.min.css">
    <link type="text/css" rel="stylesheet" href="css/style.css"  >

    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>

          REWYNDR

About

InSite

BigEvent

Contact

Blog

        We create image solutions that connect people to hidden information.

Our Philosophy

Rewyndr was founded on the belief that a picture is worth a thousand words, and when those words are connected to objects in a photo, a story is told, a problem is solved, a connection is made.  All of our products leverage proprietary image-based technologies to create this enlightenment.  For our consumer products, the value is measured in more meaningful personal communications, connections, and memories; for our business products the ROI is proven through better and more timely solutions to difficult problems.

           Engaging Usability

            Our solutions here at Rewyndr are here to help you not only solve your business problems but also engage the customer in an immersive yet helpful solution.

           Image-based Technologies

            We harness sophisticated technology to create innovative image-based mobile apps that solve perplexing business problems

           High Value Solutionfs

            Usability is our top priority here at Rewyndr when it comes to designing our solutions. We strive for the best user experience for customers

What We Make

Here at Rewyndr, we focus on creating image-based mobile apps that solve perplexing business problems.  Our products deliver sustained user engagement and increased business value through spontaneous, on-the-spot information into current business process and data stores.

Introducing InSite

InSite is a mobile application that uses image analytics to enable field operators to dynamically collaborate with management and experts in remote locates to efficiently solve problems.

            Learn More
            Check Out BigEvent!

Get in Touch!

            <form method= "POST" name="contactform" action="contact-form-handler.php">

              <input id="first_name" type="text" class="validate white-text" name = "firstname">
              First Name

              <input id="last_name" type="text" class="validate white-text" name = "lastname">
              Last Name

              <input id="email" type="email" class="validate white-text">
            Email

          <textarea class="materialize-textarea" placeholder = "write us something!" cols="30" rows="6" id ="message" name = "message"></textarea>
          Message

              <input class = "waves-effect lighten-1 btn-flat col s4 offset-s4 green center" type="submit" value="Submit">

            </form>

REWYNDR

Work

People

Careers

CONTACT

PHONE | 412-288-4257

EMAIL | email@rwyndr.com

1303 OLD MEADOW ROAD
PITTSBURGH, PA 15241

            © 2016 REWYNDR | All Rights Reserved


text:
package com.u2ware.springfield.controller;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.u2ware.springfield.domain.EntityInformation;
import com.u2ware.springfield.domain.Pagination;
import com.u2ware.springfield.service.EntityService;
import com.u2ware.springfield.validation.EntityValidator;
import com.u2ware.springfield.validation.RejectableException;

/**
 *                        /{topLevelMapping}/{methodLevelMapping}
 * 		Home:         GET /{path}/
 * 		List        : GET /{path}
 * 		Create Form : GET /{path}/new
 * 		Create     : POST /{path}/new
 * 		Read        : GET /{path}/{id}
 * 		Update Form : GET /{path}/{id}/edit
 * 		Update      : PUT /{path}/{id}/edit
 * 		Delete   : DELETE /{path}/{id}/edit
 *
 * @author admin
 *
 * @param <T>
 * @param <Q>
 */
public abstract class AbstractEntityController<T,Q> implements EntityController<T,Q> {

	protected final Logger logger = LoggerFactory.getLogger(getClass());

	protected abstract EntityInformation<T, Q> getInformation();
	protected abstract EntityService<T,Q> getService();
	protected abstract EntityValidator<T,Q> getValidator();

	/////////////////////////////////////////
	//
	////////////////////////////////////////
	@ModelAttribute(MODEL_ENTITY)
	public T createEntityObject(){
		try {
			T command = getInformation().getEntityClass().newInstance();
			return command;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	@ModelAttribute(MODEL_QUERY)
	public Q createQueryObject(){
		try {
			Q command = getInformation().getQueryClass().newInstance();
			return command;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/////////////////////////////////////////
	//
	////////////////////////////////////////
	protected void validate(BindingResult errors, RejectableException e){

		String field = e.getField();
		String errorCode = e.getErrorCode();
		Object[] errorArgs = e.getErrorArgs();
		String defaultMessage = e.getDefaultMessage();

		if(field == null){
			errors.reject(errorCode, errorArgs, defaultMessage);
		}else{
			errors.rejectValue(field, errorCode, errorArgs, defaultMessage);
		}
	}

	protected String resolveViewName(Model model, BindingResult errors, String commandMethod,  Object entity, Object query, Pageable pageable, Object queryResult)throws Exception{

		if(errors.hasErrors()){
			for(ObjectError objectError : errors.getAllErrors()){
				logger.warn("validator error: \n"+objectError.toString());
			}
		}
		if(entity == null && query == null)
			throw new HttpClientErrorException(HttpStatus.NOT_FOUND);

		model.addAttribute(MODEL_INFORMATION, getInformation());
		model.addAttribute(MODEL_ENTITY, entity);
		model.addAttribute(MODEL_QUERY, query);
		model.addAttribute(MODEL_QUERY_PAGEABLE, pageable);
		model.addAttribute(MODEL_QUERY_RESULT, queryResult);

		/*
		if(queryResult != null && ClassUtils.isAssignableValue(PageImpl.class, queryResult)){
			PageImpl<?> p = (PageImpl<?>)queryResult;
			logger.warn("getNumber : "+p.getNumber());
			logger.warn("getSize : "+p.getSize());
			logger.warn("getTotalElements : "+p.getTotalElements());
			logger.warn("getTotalPages "+p.getTotalPages());

			logger.warn("getCurrentIndex "+p.getCurrentIndex());
			logger.warn("getBeginIndex "+p.getBeginIndex());
			logger.warn("getEndIndex "+p.getEndIndex());
		}
*/

		ServletRequestAttributes attrs = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = attrs.getRequest();

		String commandMethodAppend = "";
///		//change view name by User agent
////		String userAgent = request.getHeader("User-Agent");
////		logger.debug(userAgent);
////		if(userAgent == null){
////			commandMethodAppend = "-mobile";
////		}

		String identityPath = entity != null ? getInformation().getEntityPath(entity) : "";
		String requestUri = request.getRequestURI();
		String extension = StringUtils.getFilenameExtension(requestUri);

		//String path = ClassUtils.convertClassNameToResourcePath(className)

		String viewName = //getInformation().getBasePackage().replace('.', '/')+
				 getInformation().getTopLevelMapping()+"/"
				+commandMethod+commandMethodAppend
				+(StringUtils.hasText(extension) ? "."+extension : "");

		if(StringUtils.hasText(getInformation().getAttributesCSV())){
			viewName = viewName + "?" + getInformation().getAttributesCSV();
		}

		logger.warn("response model: "+COMMAND_ID_PATH+"="+identityPath);
		logger.warn("response model: "+COMMAND_METHOD+"="+commandMethod);
		logger.warn("response model: "+COMMAND_EXTENSION+"="+(extension ==  null ? "" : "."+extension));
		logger.warn("response model: "+COMMAND_VIEW+"="+viewName);

		model.addAttribute(COMMAND_ID_PATH , identityPath);
		model.addAttribute(COMMAND_METHOD , commandMethod);
		model.addAttribute(COMMAND_EXTENSION , extension ==  null ? "" : "."+extension);
		model.addAttribute(COMMAND_VIEW , viewName);

		return viewName;
	}

	@RequestMapping(method={RequestMethod.GET, RequestMethod.POST}, value="")
	public String find(
			@RequestParam(required=false,value=ENABLE_PARAMETER_NAME,defaultValue="true")Boolean pageEnable,
			Model model, Pageable pageable, @ModelAttribute(MODEL_QUERY)Q query, BindingResult errors) throws Exception{

		logger.warn("request method: find()");
		logger.warn("request model : "+query);

		Pageable p = pageEnable ? pageable : null;
		logger.warn("request model : pageable="+p);

		getValidator().find(query, errors);
		if(errors.hasErrors()){
			return resolveViewName(model, errors, "find", null, query, p, new Pagination<T>());
		}

		try{
			Iterable<?> result = getService().find(query, p);
			if(result == null)
				result = new Pagination<T>();

			return resolveViewName(model, errors, "find", null, query, p, result);
		}catch(RejectableException e){
			validate(errors, e);
			return resolveViewName(model, errors, "find", null, query, p, new Pagination<T>());
		}
	}

	@RequestMapping(method=RequestMethod.GET, value="/"+COMMAND_ID_PATH+"")
	public String read(Model model, @ModelAttribute(MODEL_ENTITY)T entity,BindingResult errors) throws Exception{

		logger.warn("request method: read()");
		logger.warn("request model : "+entity);

		getValidator().read(entity, errors);
		if(errors.hasErrors()){
			return resolveViewName(model, errors, "read", entity, null, null, null);
		}

		try{
			T newEntity = getService().read(entity);
			if(newEntity == null)
				throw new HttpClientErrorException(HttpStatus.NOT_FOUND);

			return resolveViewName(model, errors, "read", newEntity, null, null, null);

		}catch(RejectableException e){
			validate(errors, e);
			return resolveViewName(model, errors, "read", entity, null, null, null);
		}
	}

	@RequestMapping(method=RequestMethod.GET, value="/new")
	public String createForm(Model model, @ModelAttribute(MODEL_ENTITY)T entity, BindingResult errors) throws Exception{

		logger.warn("request method: createForm()");
		logger.warn("request model : "+entity);

		getValidator().createForm(entity, errors);
		if(errors.hasErrors()){
			return resolveViewName(model, errors, "createForm", entity, null, null, null);
		}

		try{
			T newEntity = getService().createForm(entity);
			return resolveViewName(model, errors, "createForm", newEntity, null, null, null);

		}catch(RejectableException e){
			validate(errors, e);
			return resolveViewName(model, errors, "createForm", entity, null, null, null);
		}
	}

	@RequestMapping(method=RequestMethod.POST, value="/new")
	public String create(Model model, @ModelAttribute(MODEL_ENTITY) T entity, BindingResult errors) throws Exception{

		logger.warn("request method: create()");
		logger.warn("request model : "+entity);

		getValidator().create(entity, errors);
		if(errors.hasErrors()){
			return resolveViewName(model, errors, "createForm", entity, null, null, null);
		}

		try{
			T newEntity = getService().create(entity);
			return resolveViewName(model, errors,"create", newEntity, null, null, null);

		}catch(RejectableException e){
			validate(errors, e);
			return resolveViewName(model, errors, "createForm", entity, null, null, null);
		}
	}

	@RequestMapping(method=RequestMethod.GET, value="/"+COMMAND_ID_PATH+"/edit")
	public String updateForm(Model model, @ModelAttribute(MODEL_ENTITY)T entity, BindingResult errors) throws Exception{

		logger.warn("request method: updateForm()");
		logger.warn("request model : "+entity);

		getValidator().updateForm(entity, errors);
		if(errors.hasErrors()){
			return resolveViewName(model, errors, "updateForm", entity, null, null, null);
		}

		try{
			T newEntity = getService().updateForm(entity);
			return resolveViewName(model, errors, "updateForm", newEntity, null, null, null);

		}catch(RejectableException e){
			validate(errors, e);
			return resolveViewName(model, errors, "updateForm", entity, null, null, null);
		}
	}

	@RequestMapping(method=RequestMethod.PUT, value="/"+COMMAND_ID_PATH+"/edit")
	public String update(Model model, @ModelAttribute(MODEL_ENTITY) T entity,BindingResult errors) throws Exception{

		logger.warn("request method: update()");
		logger.warn("request model : "+entity);

		getValidator().update(entity, errors);
		if(errors.hasErrors()){
			return resolveViewName(model, errors, "updateForm", entity, null, null, null);
		}

		try{
			T newEntity = getService().update(entity);
			return resolveViewName(model, errors, "update", newEntity, null, null, null);

		}catch(RejectableException e){
			validate(errors, e);
			return resolveViewName(model, errors, "updateForm", entity, null, null, null);
		}
	}

	@RequestMapping(method=RequestMethod.DELETE, value="/"+COMMAND_ID_PATH+"/edit")
	public String delete(Model model, @ModelAttribute(MODEL_ENTITY)T entity, BindingResult errors) throws Exception{

		logger.warn("request method: delete()");
		logger.warn("request model : "+entity);

		getValidator().delete(entity, errors);
		if(errors.hasErrors()){
			return resolveViewName(model, errors, "read", entity, null, null, null);
		}

		try{
			T newEntity = getService().delete(entity);
			return resolveViewName(model, errors, "delete", newEntity, null, null, null);
		}catch(RejectableException e){
			validate(errors, e);
			return resolveViewName(model, errors, "read", entity, null, null, null);
		}
	}

}


text:
var qiniu=require('qiniu');
var domain="yhaoao.qiniudn.com";

qiniu.conf.ACCESS_KEY = 'ON7aeHTBckn-wboFrWhtpzITkzvjqUbveBQb3qhg';
qiniu.conf.SECRET_KEY = 'Ph8PSr0_e22A918pEXqq45Y5gzabu1Sqtl44YRJ4';

function uptoken(bucketname) {
	var putPolicy = new qiniu.rs.PutPolicy(bucketname);
	putPolicy.returnBody = 'key=$(etag)';

	return putPolicy.token();
}

function downloadUrl(domain, key) {
  var baseUrl = qiniu.rs.makeBaseUrl(domain, key);
  var policy = new qiniu.rs.GetPolicy();
  return policy.makeRequest(baseUrl);
}

exports.getToken=function(req,res){
	res.json({
		token:uptoken('yhaoao')
	});
}

exports.bucketUrl="http://yhaoao.qiniudn.com/";


text:
from flask import Markup
try:
    from markdown2 import markdown as md2
except ImportError:
    from markdown import markdown as md2
# Jinja

def date(value):
    """Formats datetime object to a yyyy-mm-dd string."""
    return value.strftime('%Y-%m-%d')

def date_pretty(value):
    """Formats datetime object to a Month dd, yyyy string."""
    return value.strftime('%B %d, %Y')

def datetime(value):
    """Formats datetime object to a yyyy-mm-dd hh:mm string."""
    return value.strftime('%Y-%m-%d %H:%M')

def pluralize(value, one='', many='s'):
    """Returns the plural suffix when needed."""
    return one if abs(value) == 1 else many

def month_name(value):
    """Return month name for a month number."""
    from calendar import month_name
    return month_name[value]

def markdown(value):
    """Convert plain text to HTML."""
    extras = ['fenced-code-blocks', 'wiki-tables']
    return Markup(md2(value, extras=extras))


text:
<?php

namespace Drupal\site_send_message\TwigExtension;

/**
 * Twig extension that adds a custom function and a custom filter.
 */
class SendMessageTwigExtension extends \Twig_Extension {

    /**
     * Generates a list of all Twig functions that this extension defines.
     *
     * @return array
     *   A key/value array that defines custom Twig functions. The key denotes the
     *   function name used in the tag, e.g.:
     *   @code
     *   {{ testfunc() }}
     *   @endcode
     *
     *   The value is a standard PHP callback that defines what the function does.
     */
    public function getFunctions() {
        return array(
            'getSendMessageForm' => new \Twig_Function_Function(array('Drupal\site_send_message\TwigExtension\SendMessageTwigExtension', 'getSendMessageForm')),
        );
    }

    /**
     * Gets a unique identifier for this Twig extension.
     *
     * @return string
     *   A unique identifier for this Twig extension.
     */
    public function getName() {
        return 'site_send_message.twig_extension';
    }

    /**
    * Формирует путь до папки с файлами по умолчанию.
    */
    public static function getSendMessageForm($name = TRUE, $phone = TRUE, $mail = TRUE, $text = TRUE, $submit_label = 'Send') {
        $form = \Drupal::formBuilder()->getForm('Drupal\site_send_message\Form\SendMessageForm', $name, $phone, $mail, $text, $submit_label);
        return \Drupal::service('renderer')->render($form, FALSE);
    }
}


text:
package org.apache.geode.cache.asyncqueue;

import static org.apache.geode.distributed.ConfigurationProperties.MCAST_PORT;
import static org.apache.geode.test.awaitility.GeodeAwaitility.await;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;

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

import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.rules.TestName;

import org.apache.geode.cache.Cache;
import org.apache.geode.cache.CacheFactory;
import org.apache.geode.cache.EvictionAction;
import org.apache.geode.cache.EvictionAttributes;
import org.apache.geode.cache.ExpirationAction;
import org.apache.geode.cache.ExpirationAttributes;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.RegionFactory;
import org.apache.geode.cache.RegionShortcut;
import org.apache.geode.cache.asyncqueue.internal.AsyncEventQueueImpl;
import org.apache.geode.internal.cache.LocalRegion;
import org.apache.geode.internal.cache.PartitionedRegion;
import org.apache.geode.internal.cache.wan.AbstractGatewaySender;
import org.apache.geode.test.junit.categories.AEQTest;

@Category({AEQTest.class})
public class AsyncEventQueueEvictionAndExpirationJUnitTest {

  private AsyncEventQueue aeq;
  private Cache cache;
  private Region region;
  String aeqId;
  List<AsyncEvent> events = new ArrayList<>();

  @Rule
  public TestName name = new TestName();

  @Before
  public void setup() {
    events.clear();
    try {
      cache = CacheFactory.getAnyInstance();
    } catch (Exception e) {
      // ignore
    }
    if (null == cache) {
      cache = new CacheFactory().set(MCAST_PORT, "0").create();
    }
    aeqId = name.getMethodName();
  }

  @After
  public void tearDown() {
    if (cache != null && !cache.isClosed()) {
      cache.close();
      cache = null;
    }
  }

  @Test
  public void isForwardExpirationDestroyAttributeFalseByDefault() {
    AsyncEventListener al = mock(AsyncEventListener.class);
    aeq = cache.createAsyncEventQueueFactory().create("aeq", al);
    // Test for default value of isIgnoreEvictionAndExpiration setting.
    assertFalse(aeq.isForwardExpirationDestroy());
  }

  @Test
  public void canSetTrueForForwardExpirationDestroy() {
    AsyncEventListener al = mock(AsyncEventListener.class);
    aeq = cache.createAsyncEventQueueFactory().setForwardExpirationDestroy(true).create("aeq", al);
    // Test for default value of isIgnoreEvictionAndExpiration setting.
    assertTrue(aeq.isForwardExpirationDestroy());
  }

  @Test
  public void evictionDestroyOpEventsNotPropogatedByDefault() {
    // For Replicated Region with eviction-destroy op.
    // Number of expected events 2. Two for create and none for eviction destroy.
    createRegionAeqAndPopulate(false /* isPR */, false /* forwardExpirationDestroy */,
        true /* eviction */, false /* evictionOverflow */, false /* expirationDestroy */,
        false /* expirationInvalidate */);

    // Wait for region to evict/expire events.
    await()
        .untilAsserted(() -> assertEquals(1, region.size()));

    // Validate events that are not queued.
    // This guarantees that eviction/expiration is performed and events are
    // sent all the way to Gateway.
    await()
        .untilAsserted(() -> assertEquals(1, getEventsNotQueuedSize(aeqId)));

    // The AQListner should get expected events.
    await()
        .untilAsserted(() -> assertEquals(2, events.size()));

  }

  @Test
  public void evictionDestroyOpEventsNotPropogatedByDefaultForPR() {
    // For PR with eviction-destroy op.
    // Number of expected events 2. Two for create and none for eviction destroy.
    createRegionAeqAndPopulate(true /* isPR */, false /* forwardExpirationDestroy */,
        true /* eviction */, false /* evictionOverflow */, false /* expirationDestroy */,
        false /* expirationInvalidate */);

    // Wait for region to evict/expire events.
    await()
        .untilAsserted(() -> assertEquals(1, region.size()));

    // Validate events that are not queued.
    // This guarantees that eviction/expiration is performed and events are
    // sent all the way to Gateway.
    // In case of eviction one event is evicted that should not be queued.
    await()
        .untilAsserted(() -> assertEquals(1, getEventsNotQueuedSize(aeqId)));

    // The AQListner should get expected events.
    await()
        .untilAsserted(() -> assertEquals(2, events.size()));

  }

  @Test
  public void expirationDestroyOpEventsNotPropogatedByDefault() {
    // For Replicated Region with expiration-destroy op.
    // Number of expected events 2. Two for create and none for eviction destroy.
    createRegionAeqAndPopulate(false /* isPR */, false /* forwardExpirationDestroy */,
        false /* eviction */, false /* evictionOverflow */, true /* expirationDestroy */,
        false /* expirationInvalidate */);

    // Wait for region to evict/expire events.
    await()
        .untilAsserted(() -> assertEquals(0, region.size()));

    // Validate events that are not queued.
    // This guarantees that eviction/expiration is performed and events are
    // sent all the way to Gateway.
    await()
        .untilAsserted(() -> assertEquals(2, getEventsNotQueuedSize(aeqId)));

    // The AQListner should get expected events.
    await()
        .untilAsserted(() -> assertEquals(2, events.size()));

  }

  @Test
  public void expirationDestroyOpEventsNotPropogatedByDefaultForPR() {
    // For PR with expiration-destroy op.
    // Number of expected events 2. Two for create and none for eviction destroy.
    createRegionAeqAndPopulate(true /* isPR */, false /* forwardExpirationDestroy */,
        false /* eviction */, false /* evictionOverflow */, true /* expirationDestroy */,
        false /* expirationInvalidate */);

    // Wait for region to evict/expire events.
    await()
        .untilAsserted(() -> assertEquals(0, region.size()));

    // Validate events that are not queued.
    // This guarantees that eviction/expiration is performed and events are
    // sent all the way to Gateway.
    await()
        .untilAsserted(() -> assertEquals(2, getEventsNotQueuedSize(aeqId)));

    // The AQListner should get expected events.
    await()
        .untilAsserted(() -> assertEquals(2, events.size()));

  }

  @Test
  public void expirationInvalidOpEventsNotPropogatedByDefault() {
    // For Replicated Region with expiration-invalid op.
    // Number of expected events 2. Two for create and none for eviction destroy.
    createRegionAeqAndPopulate(false /* isPR */, false /* forwardExpirationDestroy */,
        false /* eviction */, false /* evictionOverflow */, false /* expirationDestroy */,
        true /* expirationInvalidate */);

    LocalRegion lr = (LocalRegion) region;
    // Wait for region to evict/expire events.
    await()
        .untilAsserted(() -> assertEquals(2L, lr.getCachePerfStats().getInvalidates()));
    // The AQListner should get expected events.
    await()
        .untilAsserted(() -> assertEquals(2, events.size()));

  }

  @Test
  public void expirationInvalidOpEventsNotPropogatedByDefaultForPR() {
    // For Replicated Region with expiration-invalid op.
    // Number of expected events 2. Two for create and none for eviction destroy.
    createRegionAeqAndPopulate(true /* isPR */, false /* forwardExpirationDestroy */,
        false /* eviction */, false /* evictionOverflow */, false /* expirationDestroy */,
        true /* expirationInvalidate */);

    LocalRegion lr = (LocalRegion) region;
    // Wait for region to evict/expire events.
    await()
        .untilAsserted(() -> assertEquals(2L, lr.getCachePerfStats().getInvalidates()));
    // The AQListner should get expected events.
    await()
        .untilAsserted(() -> assertEquals(2, events.size()));
  }

  @Test
  public void evictionNotPropogatedUsingForwardExpirationDestroyAttribute() {
    // For Replicated Region with eviction-destroy op.
    // Number of expected events 2. Two for create and none for eviction destroy.
    createRegionAeqAndPopulate(false /* isPR */, true /* forwardExpirationDestroy */,
        true /* eviction */, false /* evictionOverflow */, false /* expirationDestroy */,
        false /* expirationInvalidate */);

    // Wait for region to evict/expire events.
    await()
        .untilAsserted(() -> assertEquals(1, region.size()));

    // Validate events that are not queued.
    // This guarantees that eviction/expiration is performed and events are
    // sent all the way to Gateway.
    await()
        .untilAsserted(() -> assertEquals(1, getEventsNotQueuedSize(aeqId)));

    // The AQListner should get expected events.
    await()
        .untilAsserted(() -> assertEquals(2, events.size()));

  }

  @Test
  public void evictionNotPropogatedUsingForwardExpirationDestroyAttributeForPR() {
    // For PR with eviction-destroy op.
    // Number of expected events 3. Two for create and none for eviction destroy.
    createRegionAeqAndPopulate(true /* isPR */, true /* forwardExpirationDestroy */,
        true /* eviction */, false /* evictionOverflow */, false /* expirationDestroy */,
        false /* expirationInvalidate */);

    // Wait for region to evict/expire events.
    await()
        .untilAsserted(() -> assertEquals(1, region.size()));

    // Validate events that are not queued.
    // This guarantees that eviction/expiration is performed and events are
    // sent all the way to Gateway.
    await()
        .untilAsserted(() -> assertEquals(1, getEventsNotQueuedSize(aeqId)));

    // The AQListner should get expected events.
    await()
        .untilAsserted(() -> assertEquals(2, events.size()));

  }

  @Test
  public void overflowNotPropogatedUsingForwardExpirationDestroyAttribute() {
    // For Replicated Region with eviction-overflow op.
    // Number of expected events 2. Two for create and non for eviction overflow.
    createRegionAeqAndPopulate(false /* isPR */, true /* forwardExpirationDestroy */,
        false /* eviction */, true /* evictionOverflow */, false /* expirationDestroy */,
        false /* expirationInvalidate */);

    // Wait for region to evict/expire events.
    LocalRegion lr = (LocalRegion) region;
    await()
        .untilAsserted(() -> assertEquals(1, lr.getDiskRegion().getStats().getNumOverflowOnDisk()));
    // The AQListner should get expected events.
    await()
        .untilAsserted(() -> assertEquals(2, events.size()));
  }

  @Test
  public void overflowNotPropogatedUsingForwardExpirationDestroyAttributeForPR() {
    // For PR with eviction-overflow op.
    // Number of expected events 2. Two for create and non for eviction overflow.
    createRegionAeqAndPopulate(true /* isPR */, true /* forwardExpirationDestroy */,
        false /* eviction */, true /* evictionOverflow */, false /* expirationDestroy */,
        false /* expirationInvalidate */);

    // Wait for region to evict/expire events.
    PartitionedRegion pr = (PartitionedRegion) region;
    await()
        .untilAsserted(() -> assertEquals(1, pr.getDiskRegionStats().getNumOverflowOnDisk()));
    // The AQListner should get expected events.
    await()
        .untilAsserted(() -> assertEquals(2, events.size()));

  }

  @Test
  public void expirationDestroyPropogatedUsingForwardExpirationDestroyAttribute() {
    // For Replicated Region with expiration-destroy op.
    // Number of expected events 4. Two for create and Two for expiration destroy.
    createRegionAeqAndPopulate(false /* isPR */, true /* forwardExpirationDestroy */,
        false /* eviction */, false /* evictionOverflow */, true /* expirationDestroy */,
        false /* expirationInvalidate */);

    // Wait for region to evict/expire events.
    await()
        .untilAsserted(() -> assertEquals(0, region.size()));

    await()
        .untilAsserted(() -> assertEquals(4, getEventsReceived(aeqId)));

    // The AQListner should get expected events.
    await()
        .untilAsserted(() -> assertEquals(4, events.size()));

    assertTrue("Expiration event not arrived", checkForOperation(events, false, true));

  }

  @Test
  public void expirationDestroyPropogatedUsingForwardExpirationDestroyAttributeForPR() {
    // For PR with expiration-destroy op.
    // Number of expected events 4. Two for create and Two for expiration destroy.
    createRegionAeqAndPopulate(true /* isPR */, true /* forwardExpirationDestroy */,
        false /* eviction */, false /* evictionOverflow */, true /* expirationDestroy */,
        false /* expirationInvalidate */);

    // Wait for region to evict/expire events.
    await()
        .untilAsserted(() -> assertEquals(0, region.size()));

    await()
        .untilAsserted(() -> assertEquals(4, getEventsReceived(aeqId)));

    // The AQListner should get expected events.
    await()
        .untilAsserted(() -> assertEquals(4, events.size()));

    assertTrue("Expiration event not arrived", checkForOperation(events, false, true));

  }

  @Test
  public void expirationInvalidateNotPropogatedUsingForwardExpirationDestroyAttribute() {
    // For Replicated Region with expiration-invalidate op.
    // Currently invalidate event callbacks are not made to GateWay sender.
    // Invalidates are not sent to AEQ.
    // Number of expected events 2. None for expiration invalidate.
    createRegionAeqAndPopulate(false /* isPR */, true /* forwardExpirationDestroy */,
        false /* eviction */, false /* evictionOverflow */, false /* expirationDestroy */,
        true /* expirationInvalidate */);

    // Wait for region to evict/expire events.
    LocalRegion lr = (LocalRegion) region;
    await()
        .untilAsserted(() -> assertEquals(2L, lr.getCachePerfStats().getInvalidates()));

    // The AQListner should get expected events.
    await()
        .untilAsserted(() -> assertEquals(2, events.size()));

  }

  @Test
  public void expirationInvalidateNotPropogatedUsingForwardExpirationDestroyAttributeForPR() {
    // For PR with expiration-invalidate op.
    // Currently invalidate event callbacks are not made to GateWay sender.
    // Invalidates are not sent to AEQ.
    // Number of expected events 2. None for expiration invalidate.
    createRegionAeqAndPopulate(true /* isPR */, true /* forwardExpirationDestroy */,
        false /* eviction */, false /* evictionOverflow */, false /* expirationDestroy */,
        true /* expirationInvalidate */);

    // Wait for region to evict/expire events.
    LocalRegion lr = (LocalRegion) region;
    await()
        .untilAsserted(() -> assertEquals(2L, lr.getCachePerfStats().getInvalidates()));

    // The AQListner should get expected events.
    await()
        .untilAsserted(() -> assertEquals(2, events.size()));

  }

  private void createRegionAeqAndPopulate(boolean isPR, boolean forwardExpirationDestroy,
      boolean eviction, boolean evictionOverflow, boolean expirationDestroy,
      boolean expirationInvalidate) {
    // String aeqId = "AEQTest";
    String aeqId = name.getMethodName();

    // Create AEQ
    createAsyncEventQueue(aeqId, forwardExpirationDestroy, events);

    region = createRegion("ReplicatedRegionForAEQ", isPR, aeqId, eviction, evictionOverflow,
        expirationDestroy, expirationInvalidate);

    // Populate region with two entries.
    region.put("Key-1", "Value-1");
    region.put("Key-2", "Value-2");

  }

  private void waitForAEQEventsNotQueued() {
    await().until(() -> {
      return (getEventsNotQueuedSize(aeqId) >= 1);
    });
  }

  private boolean checkForOperation(List<AsyncEvent> events, boolean invalidate, boolean destroy) {
    boolean found = false;
    for (AsyncEvent e : events) {
      if (invalidate && e.getOperation().isInvalidate()) {
        found = true;
        break;
      }
      if (destroy && e.getOperation().isDestroy()) {
        found = true;
        break;
      }
    }
    return found;
  }

  public int getEventsNotQueuedSize(String aeqId) {
    AsyncEventQueueImpl aeq = (AsyncEventQueueImpl) cache.getAsyncEventQueue(aeqId);
    AbstractGatewaySender sender = (AbstractGatewaySender) aeq.getSender();
    return sender.getStatistics().getEventsNotQueued();
  }

  public int getEventsReceived(String aeqId) {
    AsyncEventQueueImpl aeq = (AsyncEventQueueImpl) cache.getAsyncEventQueue(aeqId);
    AbstractGatewaySender sender = (AbstractGatewaySender) aeq.getSender();
    return sender.getStatistics().getEventsReceived();
  }

  private void createAsyncEventQueue(String id, boolean forwardExpirationDestroy,
      List<AsyncEvent> storeEvents) {
    AsyncEventListener al = createAsyncListener(storeEvents);
    aeq = cache.createAsyncEventQueueFactory().setParallel(false)
        .setForwardExpirationDestroy(forwardExpirationDestroy).setBatchSize(1)
        .setBatchTimeInterval(1).create(id, al);
  }

  private Region createRegion(String name, boolean isPR, String aeqId, boolean evictionDestroy,
      boolean evictionOverflow, boolean expirationDestroy, boolean expirationInvalidate) {
    RegionFactory rf;
    if (isPR) {
      rf = cache.createRegionFactory(RegionShortcut.PARTITION);
    } else {
      rf = cache.createRegionFactory(RegionShortcut.REPLICATE);
    }
    // Set AsyncQueue.
    rf.addAsyncEventQueueId(aeqId);
    if (evictionDestroy) {
      rf.setEvictionAttributes(
          EvictionAttributes.createLIFOEntryAttributes(1, EvictionAction.LOCAL_DESTROY));
    }
    if (evictionOverflow) {
      rf.setEvictionAttributes(
          EvictionAttributes.createLIFOEntryAttributes(1, EvictionAction.OVERFLOW_TO_DISK));
    }
    if (expirationDestroy) {
      rf.setEntryTimeToLive(new ExpirationAttributes(1, ExpirationAction.DESTROY));
    }
    if (expirationInvalidate) {
      rf.setEntryTimeToLive(new ExpirationAttributes(1, ExpirationAction.INVALIDATE));
    }

    return rf.create(name);
  }

  private AsyncEventListener createAsyncListener(List<AsyncEvent> list) {
    AsyncEventListener listener = new AsyncEventListener() {
      private final List<AsyncEvent> aeList = list;

      @Override
      public void close() {}

      @Override
      public boolean processEvents(List<AsyncEvent> arg0) {
        try {
          synchronized (aeList) {
            aeList.add(arg0.get(0));
          }
        } catch (Exception ignored) {
        }
        return true;
      }
    };
    return listener;
  }

}


text:
<!DOCTYPE html>

		<meta charset="utf-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
		<title></title>
		<meta name="description" content="">
		<meta name="viewport" content="width=device-width">
        <link rel="stylesheet" type="text/css" href="../js/jquery-ui-1.12.1/jquery-ui.min.css" />
        <link rel="stylesheet" type="text/css" href="../libraries/bootstrap-3.3.7-dist/css/bootstrap.min.css" />
        <link rel="stylesheet" type="text/css" href="../css/app.css" />

		<button id="BURGER" class="c-hamburger c-hamburger--htx">
			toggle menu
		</button>

											 Español

											 English

											 Français

											 Italiano

											 Deustch

											 Pусский

											 汉语

											 Español

											 English

											 Français

											 Italiano

											 Deustch

											 Pусский

											 汉语

											 Español

											 English

											 Français

											 Italiano

											 Deustch

											 Pусский

											 汉语

											 Español

											 English

											 Français

											 Italiano

											 Deustch

											 Pусский

											 Español

											 English

											 Français

											 Italiano

											 Deustch

											 Español

											 English

											 Français

											 Italiano

											 Deustch

											 Pусский

											 汉语

											 Español

											 English

											 Français

											 Italiano

											 Deustch

											 Pусский

											 汉语

							Esta aplicación contiene más imágenes de las que descargadas por defecto en la instalación básica de la misma.
Si las desea puede descargarlas haciendo click en el botón descargar.

						<button class="btn btn-lg btn-success" id="startMainDownload">
							Descargar
						</button>


text:
#import <Onyx2D/Win32Font.h>

#ifndef CLEARTYPE_QUALITY
#define CLEARTYPE_QUALITY 5
#endif
#ifndef CLEARTYPE_NATURAL_QUALITY
#define CLEARTYPE_NATURAL_QUALITY 6
#endif

@implementation Win32Font

-initWithName:(NSString *)name height:(int)height antialias:(BOOL)antialias angle:(CGFloat)angle
{
	NSUInteger length=[name length];
	unichar    buffer[length+1];

	[name getCharacters:buffer];
	buffer[length]=0x0000;

	long quality = antialias?CLEARTYPE_QUALITY:DEFAULT_QUALITY;

	angle = 180.*angle/M_PI*10; // Tenth of degrees
	_handle=CreateFontW(height,0,angle,angle,FW_NORMAL,
						FALSE,FALSE,FALSE,
						DEFAULT_CHARSET,OUT_DEFAULT_PRECIS,CLIP_DEFAULT_PRECIS,
						quality,DEFAULT_PITCH|FF_DONTCARE,buffer);

	return self;
}

-initWithName:(NSString *)name height:(int)height antialias:(BOOL)antialias
{
	return [self initWithName:name height:height antialias:antialias angle: 0.f];
}

-(void)dealloc {
   DeleteObject(_handle);
   NSDeallocateObject(self);
   return;
   [super dealloc];
}

-(HFONT)fontHandle {
   return _handle;
}

@end


text:
<?php

defined('_JEXEC') or die();

class ZtPortfolioTableItem extends FOFTable {

    public function check() {

        $result = true;

        //Alias
        if (empty($this->alias)) {
            // Auto-fetch a alias
            $this->alias = JFilterOutput::stringURLSafe($this->title);
        } else {
            // Make sure nobody adds crap characters to the alias
            $this->alias = JFilterOutput::stringURLSafe($this->alias);
        }

        $existingAlias = FOFModel::getTmpInstance('Items', 'ZtPortfolioModel')
                ->alias($this->alias)
                ->getList(true);

        if (!empty($existingAlias)) {
            $count = 0;
            $k = $this->getKeyName();
            foreach ($existingAlias as $item) {
                if ($item->$k != $this->$k)
                    $count++;
            }
            if ($count) {
                $this->setError(JText::_('COM_ZTPORTFOLIO_ALIAS_ERR_SLUGUNIQUE'));
                $result = false;
            }
        }

        //Tags
        if (is_array($this->ztportfolio_tag_id)) {
            if (!empty($this->ztportfolio_tag_id)) {
                $this->ztportfolio_tag_id = json_encode($this->ztportfolio_tag_id);
            }
        }
        if (is_null($this->ztportfolio_tag_id) || empty($this->ztportfolio_tag_id)) {
            $this->ztportfolio_tag_id = '';
        }

        //Generate Thumbnails
        if ($result) {

            $params = JComponentHelper::getParams('com_ztportfolio');
            $square = strtolower($params->get('square', '600x600'));
            $rectangle = strtolower($params->get('rectangle', '600x400'));
            $tower = strtolower($params->get('tower', '600x800'));
            $cropratio = $params->get('cropratio', 4);

            if (!is_null($this->image)) {
                jimport('joomla.filesystem.file');
                jimport('joomla.filesystem.folder');
                jimport('joomla.image.image');

                $image = JPATH_ROOT . '/' . $this->image;
                $path = JPATH_ROOT . '/images/ztportfolio/' . $this->alias;

                if (!file_exists($path)) {
                    JFolder::create($path, 0755);
                }

                $sizes = array($square, $rectangle, $tower);
                $image = new JImage($image);
                $image->createThumbs($sizes, $cropratio, $path);
            }
        }

        return $result;
    }

    public function onAfterLoad(&$result) {

        if (!is_array($this->ztportfolio_tag_id)) {
            if (!empty($this->ztportfolio_tag_id)) {
                $this->ztportfolio_tag_id = json_decode($this->ztportfolio_tag_id, true);
            }
        }

        if (is_null($this->ztportfolio_tag_id) || empty($this->ztportfolio_tag_id)) {
            $this->ztportfolio_tag_id = array();
        }

        return parent::onAfterLoad($result);
    }

}


text:
<?xml version="1.0" ?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<link rel="stylesheet" type="text/css" href="../../../../scineplex.css">
<title></title>
<link rel="stylesheet" href="../../../../Active.css" type="text/css" />
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<link rev="made" href="mailto:" />

NAME

SYNOPSIS

DESCRIPTION

REFERENCES

%ReturnTypes

%ReturnValues

TODO

NAME

DBI::Const::GetInfo::ANSI - ISO/IEC SQL/CLI Constants for GetInfo

SYNOPSIS

  The API for this module is private and subject to change.

DESCRIPTION

Information requested by GetInfo().

See: A.1 C header file SQLCLI.H, Page 316, 317.

The API for this module is private and subject to change.

REFERENCES

  ISO/IEC FCD 9075-3:200x Information technology - Database Languages -
  SQL - Part 3: Call-Level Interface (SQL/CLI)

  SC32 N00744 = WG3:VIE-005 = H2-2002-007

  Date: 2002-01-15

%ReturnTypes

See: Codes and data types for implementation information (Table 28), Page 85, 86.

Mapped to ODBC datatype names.

%ReturnValues

See: A.1 C header file SQLCLI.H, Page 317, 318.

TODO

Corrections, e.g.:

  SQL_TRANSACTION_ISOLATION_OPTION vs. SQL_TRANSACTION_ISOLATION


text:
<?php

include 'node--nbablog.tpl.php';


text:
void Ax_fan_mf_cpu_siddon(float *X,float *y,float SO,float OD,float scale,int nx,int ny,int nv,float *sd_phi,int nd,float *y_det,int *id_X);
extern "C" void Ax_fan_mf_gpu_siddon(float *X,float *y,float SO,float OD,float scale,int nx,int ny,int nv,float *sd_phi,int nd,float *y_det,int *id_X,int nt);
// Siddon's method to compute the X-ray transform

void Ax_fan_mf_cpu_new(float *X,float *y,float SO,float OD,float scale,int nx,int ny,int nv,float *sd_phi,int nd,float *y_det,int *id_X);
extern "C" void Ax_fan_mf_gpu_new(float *X,float *y,float SO,float OD,float scale,int nx,int ny,int nv,float *sd_phi,int nd,float *y_det,int *id_X,int nt);
// A new method for computing the X-ray transform (infinitely-narrow beam)
// The algorithm details are available in
// H. Gao. "Fast parallel algorithms for the X-ray transform and its adjoint", Medical Physics (2012).

void Ax_fan_mf_cpu_new_fb(float *X,float *y,float SO,float OD,float scale,int nx,int ny,int nv,float *sd_phi,int nd,float *y_det,int *id_X,float dy_det);
extern "C" void Ax_fan_mf_gpu_new_fb(float *X,float *y,float SO,float OD,float scale,int nx,int ny,int nv,float *sd_phi,int nd,float *y_det,int *id_X,int nt,float dy_det);
// A new method for computing the X-ray transform (finite-size beam)
// The algorithm details are available in
// H. Gao. "Fast parallel algorithms for the X-ray transform and its adjoint", Medical Physics (2012).


text:
require 'spec_helper'

describe V1::SharedAssessmentsController do
  render_views

  describe '#show' do
    let(:facilitator) { FactoryGirl.create :user, :with_facilitator_role }
    let(:rubric) { FactoryGirl.create :rubric }
    let(:district) { FactoryGirl.create :district }
    let(:assessment) { FactoryGirl.create :assessment, rubric: rubric, district: district, user: facilitator }

    context 'with valid token' do
      let(:token) { assessment.share_token }

      before(:each) do
        get :show, params: { token: token }, as: :json
      end

      it do
        expect(response).to have_http_status(:success)
      end

      it do
        expect(assigns(:assessment).id).to eq(assessment.id)
      end
    end

    context 'with invalid token' do
      let(:token) { 'foo-bar-invalid-token' }

      it do
        get :show, params: { token: token }, as: :json
        expect(response).to have_http_status(:not_found)
      end
    end
  end
end


text:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { SharedModule } from '../shared/shared.module';
import { CSTModule } from '../cst/cst.module';
import { KitchenSinkComponent } from './kitchen-sink.component';

@NgModule({
    imports: [CommonModule, SharedModule, CSTModule],
    declarations: [KitchenSinkComponent],
    exports: [KitchenSinkComponent],
    providers: []
})

export class KitchenSinkModule { }


text:
package proguard.evaluation.value;

/**
 * This FloatValue represents a float value that is identified by a unique ID.
 *
 * @author Eric Lafortune
 */
final class IdentifiedFloatValue extends SpecificFloatValue
{
    private final ValueFactory valuefactory;
    private final int          id;

    /**
     * Creates a new float value with the given ID.
     */
    public IdentifiedFloatValue(ValueFactory valuefactory, int id)
    {
        this.valuefactory = valuefactory;
        this.id           = id;
    }

    // Implementations for Object.

    public boolean equals(Object object)
    {
        return this == object ||
               super.equals(object) &&
               this.valuefactory.equals(((IdentifiedFloatValue)object).valuefactory) &&
               this.id == ((IdentifiedFloatValue)object).id;
    }

    public int hashCode()
    {
        return super.hashCode() ^
               valuefactory.hashCode() ^
               id;
    }

    public String toString()
    {
        return "f"+id;
    }
}


text:
import io
import json

from falcon.request import Request
from falcon.response import Response
import six
from ws4py import websocket

class MarconiWebsocket(websocket.WebSocket):

    falcon_app = None

    def received_message(self, message):

        try:
            data = json.loads(unicode(message.data))
        except Exception:
            print(message.data)

        body = data.get('body', '')
        if isinstance(body, six.text_type):
            body = body.encode('utf-8')

        env = self.environ.copy()
        env.update({'PATH_INFO': data['path'],
                    'SERVER_PROTOCOL': 'HTTP/1.1',
                    'REQUEST_METHOD': data['method'],

                    # NOTE(flaper87): Body is optional. If present
                    # it has to be a serialized json.
                    'wsgi.input': io.BytesIO(body),

                    # NOTE(flaper87): Accept is a required
                    # header for the wsgi API. We won't make it
                    # so for the websocket transport.
                    'HTTP_ACCEPT': 'application/json'})

        # NOTE(flaper87): Copy all HTTP headers to
        # the wsgi environment and make the wsgi transport
        # happy.
        headers = data.get('headers', {})
        for header, value in headers.items():
            env['HTTP_' + header.upper()] = value

        req = Request(env)
        resp = Response()

        get_responder = self.falcon_app._get_responder
        responder, params, na_responder = get_responder(req.path, req.method)
        responder(req, resp, **params)

        # NOTE(flaper87): Send the response back to the
        # client.
        self.send(json.dumps({'headers': resp._headers,
                              'status': resp.status,
                              'body': resp.body_encoded}))


text:
package com.chute.sdk.v2.api.upload;

import com.araneaapps.android.libs.asyncrunners.models.RequestOptions;
import com.chute.sdk.v2.api.parsers.ListResponseParser;
import com.chute.sdk.v2.model.AssetModel;
import com.chute.sdk.v2.model.response.ListResponseModel;
import com.chute.sdk.v2.utils.MediaTypes;
import com.dg.libs.rest.callbacks.HttpCallback;
import com.dg.libs.rest.client.RequestMethod;
import com.dg.libs.rest.requests.RestClientRequest;
import com.squareup.okhttp.MultipartBuilder;
import com.squareup.okhttp.RequestBody;

import java.io.File;

public abstract class BaseUploadRequest extends
	RestClientRequest<ListResponseModel<AssetModel>> implements CountingFileRequestBody.ProgressListener {

	private final UploadProgressListener uploadListener;
	private final File file;
	private final CountingFileRequestBody requestBody;

	public BaseUploadRequest(String filePath,
			UploadProgressListener uploadListener,
			HttpCallback<ListResponseModel<AssetModel>> callback) {

		this.uploadListener = uploadListener;
		this.file = new File(filePath);
		this.requestBody = new CountingFileRequestBody(file, MediaTypes.OCTET_STREAM, this);
		RequestBody requestBody = new MultipartBuilder()
			.type(MultipartBuilder.FORM)
			.addFormDataPart(getMultipartEntityKey(), file.getName(), this.requestBody)
			.build();
		setRequestMethod(RequestMethod.POST, requestBody);
		setCallback(callback);
		setParser(new ListResponseParser<AssetModel>(AssetModel.class));
		setRequestOptions(new RequestOptions.RequestOptionsBuilder().setRunInSingleThread(true).build());
	}
	public abstract String getMultipartEntityKey();

	public void cancel() {
		requestBody.cancel();
	}

	@Override
	public void transferred(long num) {
		uploadListener.onProgress(file.length(), num);
	}

	@Override
	protected void doBeforeRunRequestInBackgroundThread() {
		super.doBeforeRunRequestInBackgroundThread();
		if (uploadListener != null) {
			uploadListener.onUploadStarted(file);
		}
	}

	@Override
	public void run() {
		super.run();
		if (uploadListener != null) {
			uploadListener.onUploadFinished(file);
		}
	}

}


text:
class GeneFilter
  include Filter

  def self.filter(relation, values)
    relation.where('genes.name' => values)
  end

  def self.valid_values
    Gene.uniq
    .order(name: :asc)
    .pluck(:name)
  end

  def self.param_name
    :genes
  end

  def self.filter_type
    :multiselect
  end
end


text:
You can grab gulp-wp-theme via npm or download the zip and build your project from scratch, based on gulp-wp-theme.

Per default, the gulp-wp-theme grabs your files from a `src` folder and compiles it to the `dist/wp-content/themes` folder, where it will be stored in a folder taking the name from your package.json.

But you can configure it all yourself. See following sections:

* [Getting Started](https://github.com/whatwedo/gulp-wp-theme/blob/develop/docs/getting-started.md) - How to get going with gulp-wp-theme
* [API documentation](https://github.com/whatwedo/gulp-wp-theme/blob/develop/docs/API.md) - Learn how you configure the tasks

## Questions or problems?
Don't hesitate to open an issue on github to get your questions answered.


text:
layout: post
---

## WHAT COLOR IS THIS DRESS?

![Dress](http://i2.cdn.turner.com/cnnnext/dam/assets/150226215539-black-blue-dress-super-169.jpg)

It's crazy how people view this dress a different color then what its original color.  All over the world people argue is this dress really blue and black or gold and white?  I didn't believe it at first until someone showed me the picture and I tested it out on my family member and friends. Everyone in my house said it was black and blue, but my nephew who is 8 year-old saw the dress gold and white and my two friends I showed as well. They thought I was crazy and did not know my colors. We were going back and forth on the color of the dress that I had to show them proof of the color scheme. My sister thought her son was color blind and he needed to see the doctor. I told her it's okay, not only he that sees this dress as gold and white.

I was so shock how people saw this dress a different color then me. So I went on the internet and started to do research on the dress. Why do the eyes see different color on this Black and blue dress?
[read more...](http://www.dogonews.com/2015/3/6/white-and-gold-or-blue-and-black-the-great-dress-debate)


text:
#include "crypto/s2n_hmac.h"

#include <cbmc_proof/make_common_datastructures.h>

void s2n_hmac_digest_two_compression_rounds_harness()
{
    /* Non-deterministic inputs. */
    struct s2n_hmac_state *state = cbmc_allocate_s2n_hmac_state();
    uint32_t size;
    void* out = malloc(size);

    /* Assumptions. */
    __CPROVER_assume(s2n_result_is_ok(s2n_hmac_state_validate(state)));
    __CPROVER_file_local_s2n_hash_c_s2n_hash_set_impl(&state->inner);
    __CPROVER_file_local_s2n_hash_c_s2n_hash_set_impl(&state->outer);
    __CPROVER_file_local_s2n_hash_c_s2n_hash_set_impl(&state->outer_just_key);

    /* Operation under verification. */
    if (s2n_hmac_digest_two_compression_rounds(state, out, size) == S2N_SUCCESS)
    {
        /* Post-conditions. */
        assert(s2n_result_is_ok(s2n_hmac_state_validate(state)));
        assert(state->inner.hash_impl->digest != NULL);
        assert(state->outer.hash_impl->digest != NULL);
        assert(state->outer.hash_impl->update != NULL);
        assert(state->outer_just_key.hash_impl->copy != NULL);
    }
}