// modify from
// https://github.com/chengdazhi/Deformable-Convolution-V2-PyTorch/blob/mmdetection/mmdet/ops/dcn/src/deform_conv_cuda.c

#include <ATen/ATen.h>
#include <ATen/cuda/CUDAContext.h>

#include <THC/THC.h>
#include <THC/THCDeviceUtils.cuh>

#include <vector>
#include <iostream>
#include <cmath>

void deformable_im2col(const at::Tensor data_im, const at::Tensor data_offset,
                       const int channels, const int height, const int width,
                       const int ksize_h, const int ksize_w, const int pad_h,
                       const int pad_w, const int stride_h, const int stride_w,
                       const int dilation_h, const int dilation_w,
                       const int parallel_imgs, const int deformable_group,
                       at::Tensor data_col);

void deformable_col2im(const at::Tensor data_col, const at::Tensor data_offset,
                       const int channels, const int height, const int width,
                       const int ksize_h, const int ksize_w, const int pad_h,
                       const int pad_w, const int stride_h, const int stride_w,
                       const int dilation_h, const int dilation_w,
                       const int parallel_imgs, const int deformable_group,
                       at::Tensor grad_im);

void deformable_col2im_coord(
    const at::Tensor data_col, const at::Tensor data_im,
    const at::Tensor data_offset, const int channels, const int height,
    const int width, const int ksize_h, const int ksize_w, const int pad_h,
    const int pad_w, const int stride_h, const int stride_w,
    const int dilation_h, const int dilation_w, const int parallel_imgs,
    const int deformable_group, at::Tensor grad_offset);

void modulated_deformable_im2col_cuda(
    const at::Tensor data_im, const at::Tensor data_offset,
    const at::Tensor data_mask, const int batch_size, const int channels,
    const int height_im, const int width_im, const int height_col,
    const int width_col, const int kernel_h, const int kenerl_w,
    const int pad_h, const int pad_w, const int stride_h, const int stride_w,
    const int dilation_h, const int dilation_w, const int deformable_group,
    at::Tensor data_col);

void modulated_deformable_col2im_cuda(
    const at::Tensor data_col, const at::Tensor data_offset,
    const at::Tensor data_mask, const int batch_size, const int channels,
    const int height_im, const int width_im, const int height_col,
    const int width_col, const int kernel_h, const int kenerl_w,
    const int pad_h, const int pad_w, const int stride_h, const int stride_w,
    const int dilation_h, const int dilation_w, const int deformable_group,
    at::Tensor grad_im);

void modulated_deformable_col2im_coord_cuda(
    const at::Tensor data_col, const at::Tensor data_im,
    const at::Tensor data_offset, const at::Tensor data_mask,
    const int batch_size, const int channels, const int height_im,
    const int width_im, const int height_col, const int width_col,
    const int kernel_h, const int kenerl_w, const int pad_h, const int pad_w,
    const int stride_h, const int stride_w, const int dilation_h,
    const int dilation_w, const int deformable_group, at::Tensor grad_offset,
    at::Tensor grad_mask);

void shape_check(at::Tensor input, at::Tensor offset, at::Tensor *gradOutput,
                 at::Tensor weight, int kH, int kW, int dH, int dW, int padH,
                 int padW, int dilationH, int dilationW, int group,
                 int deformable_group)
{
  AT_CHECK(weight.ndimension() == 4,
           "4D weight tensor (nOutputPlane,nInputPlane,kH,kW) expected, "
           "but got: %s",
           weight.ndimension());

  AT_CHECK(weight.is_contiguous(), "weight tensor has to be contiguous");

  AT_CHECK(kW > 0 && kH > 0,
           "kernel size should be greater than zero, but got kH: %d kW: %d", kH,
           kW);

  AT_CHECK((weight.size(2) == kH && weight.size(3) == kW),
           "kernel size should be consistent with weight, ",
           "but got kH: %d kW: %d weight.size(2): %d, weight.size(3): %d", kH,
           kW, weight.size(2), weight.size(3));

  AT_CHECK(dW > 0 && dH > 0,
           "stride should be greater than zero, but got dH: %d dW: %d", dH, dW);

  AT_CHECK(
      dilationW > 0 && dilationH > 0,
      "dilation should be greater than 0, but got dilationH: %d dilationW: %d",
      dilationH, dilationW);

  int ndim = input.ndimension();
  int dimf = 0;
  int dimh = 1;
  int dimw = 2;

  if (ndim == 4) {
    dimf++;
    dimh++;
    dimw++;
  }

  AT_CHECK(ndim == 3 || ndim == 4, "3D or 4D input tensor expected but got: %s",
           ndim);

  long nInputPlane = weight.size(1) * group;
  long inputHeight = input.size(dimh);
  long inputWidth = input.size(dimw);
  long nOutputPlane = weight.size(0);
  long outputHeight =
      (inputHeight + 2 * padH - (dilationH * (kH - 1) + 1)) / dH + 1;
  long outputWidth =
      (inputWidth + 2 * padW - (dilationW * (kW - 1) + 1)) / dW + 1;

  AT_CHECK(nInputPlane % deformable_group == 0,
           "input channels must divide deformable group size");

  if (outputWidth < 1 || outputHeight < 1)
    AT_ERROR(
        "Given input size: (%ld x %ld x %ld). "
        "Calculated output size: (%ld x %ld x %ld). Output size is too small",
        nInputPlane, inputHeight, inputWidth, nOutputPlane, outputHeight,
        outputWidth);

  AT_CHECK(input.size(1) == nInputPlane,
           "invalid number of input planes, expected: %d, but got: %d",
           nInputPlane, input.size(1));

  AT_CHECK((inputHeight >= kH && inputWidth >= kW),
           "input image is smaller than kernel");

  AT_CHECK((offset.size(2) == outputHeight && offset.size(3) == outputWidth),
           "invalid spatial size of offset, expected height: %d width: %d, but "
           "got height: %d width: %d",
           outputHeight, outputWidth, offset.size(2), offset.size(3));

  AT_CHECK((offset.size(1) == deformable_group * 2 * kH * kW),
           "invalid number of channels of offset");

  if (gradOutput != NULL) {
    AT_CHECK(gradOutput->size(dimf) == nOutputPlane,
             "invalid number of gradOutput planes, expected: %d, but got: %d",
             nOutputPlane, gradOutput->size(dimf));

    AT_CHECK((gradOutput->size(dimh) == outputHeight &&
              gradOutput->size(dimw) == outputWidth),
             "invalid size of gradOutput, expected height: %d width: %d , but "
             "got height: %d width: %d",
             outputHeight, outputWidth, gradOutput->size(dimh),
             gradOutput->size(dimw));
  }
}

int deform_conv_forward_cuda(at::Tensor input, at::Tensor weight,
                             at::Tensor offset, at::Tensor output,
                             at::Tensor columns, at::Tensor ones, int kW,
                             int kH, int dW, int dH, int padW, int padH,
                             int dilationW, int dilationH, int group,
                             int deformable_group, int im2col_step)
{
  // todo: resize columns to include im2col: done
  // todo: add im2col_step as input
  // todo: add new output buffer and transpose it to output (or directly
  // transpose output) todo: possibly change data indexing because of
  // parallel_imgs

  shape_check(input, offset, NULL, weight, kH, kW, dH, dW, padH, padW,
              dilationH, dilationW, group, deformable_group);

  input = input.contiguous();
  offset = offset.contiguous();
  weight = weight.contiguous();

  int batch = 1;
  if (input.ndimension() == 3) {
    // Force batch
    batch = 0;
    input.unsqueeze_(0);
    offset.unsqueeze_(0);
  }

  // todo: assert batchsize dividable by im2col_step

  long batchSize = input.size(0);
  long nInputPlane = input.size(1);
  long inputHeight = input.size(2);
  long inputWidth = input.size(3);

  long nOutputPlane = weight.size(0);

  long outputWidth =
      (inputWidth + 2 * padW - (dilationW * (kW - 1) + 1)) / dW + 1;
  long outputHeight =
      (inputHeight + 2 * padH - (dilationH * (kH - 1) + 1)) / dH + 1;

  AT_CHECK((offset.size(0) == batchSize), "invalid batch size of offset");

  output = output.view({batchSize / im2col_step, im2col_step, nOutputPlane,
                        outputHeight, outputWidth});
  columns = at::zeros(
      {nInputPlane * kW * kH, im2col_step * outputHeight * outputWidth},
      input.options());

  if (ones.ndimension() != 2 ||
      ones.size(0) * ones.size(1) < outputHeight * outputWidth) {
    ones = at::ones({outputHeight, outputWidth}, input.options());
  }

  input = input.view({batchSize / im2col_step, im2col_step, nInputPlane,
                      inputHeight, inputWidth});
  offset =
      offset.view({batchSize / im2col_step, im2col_step,
                   deformable_group * 2 * kH * kW, outputHeight, outputWidth});

  at::Tensor output_buffer =
      at::zeros({batchSize / im2col_step, nOutputPlane,
                 im2col_step * outputHeight, outputWidth},
                output.options());

  output_buffer = output_buffer.view(
      {output_buffer.size(0), group, output_buffer.size(1) / group,
       output_buffer.size(2), output_buffer.size(3)});

  for (int elt = 0; elt < batchSize / im2col_step; elt++) {
    deformable_im2col(input[elt], offset[elt], nInputPlane, inputHeight,
                      inputWidth, kH, kW, padH, padW, dH, dW, dilationH,
                      dilationW, im2col_step, deformable_group, columns);

    columns = columns.view({group, columns.size(0) / group, columns.size(1)});
    weight = weight.view({group, weight.size(0) / group, weight.size(1),
                          weight.size(2), weight.size(3)});

    for (int g = 0; g < group; g++) {
      output_buffer[elt][g] = output_buffer[elt][g]
                                  .flatten(1)
                                  .addmm_(weight[g].flatten(1), columns[g])
                                  .view_as(output_buffer[elt][g]);
    }
  }

  output_buffer = output_buffer.view(
      {output_buffer.size(0), output_buffer.size(1) * output_buffer.size(2),
       output_buffer.size(3), output_buffer.size(4)});

  output_buffer = output_buffer.view({batchSize / im2col_step, nOutputPlane,
                                      im2col_step, outputHeight, outputWidth});
  output_buffer.transpose_(1, 2);
  output.copy_(output_buffer);
  output = output.view({batchSize, nOutputPlane, outputHeight, outputWidth});

  input = input.view({batchSize, nInputPlane, inputHeight, inputWidth});
  offset = offset.view(
      {batchSize, deformable_group * 2 * kH * kW, outputHeight, outputWidth});

  if (batch == 0) {
    output = output.view({nOutputPlane, outputHeight, outputWidth});
    input = input.view({nInputPlane, inputHeight, inputWidth});
    offset = offset.view({offset.size(1), offset.size(2), offset.size(3)});
  }

  return 1;
}

int deform_conv_backward_input_cuda(at::Tensor input, at::Tensor offset,
                                    at::Tensor gradOutput, at::Tensor gradInput,
                                    at::Tensor gradOffset, at::Tensor weight,
                                    at::Tensor columns, int kW, int kH, int dW,
                                    int dH, int padW, int padH, int dilationW,
                                    int dilationH, int group,
                                    int deformable_group, int im2col_step)
{
  shape_check(input, offset, &gradOutput, weight, kH, kW, dH, dW, padH, padW,
              dilationH, dilationW, group, deformable_group);

  input = input.contiguous();
  offset = offset.contiguous();
  gradOutput = gradOutput.contiguous();
  weight = weight.contiguous();

  int batch = 1;

  if (input.ndimension() == 3) {
    // Force batch
    batch = 0;
    input = input.view({1, input.size(0), input.size(1), input.size(2)});
    offset = offset.view({1, offset.size(0), offset.size(1), offset.size(2)});
    gradOutput = gradOutput.view(
        {1, gradOutput.size(0), gradOutput.size(1), gradOutput.size(2)});
  }

  long batchSize = input.size(0);
  long nInputPlane = input.size(1);
  long inputHeight = input.size(2);
  long inputWidth = input.size(3);

  long nOutputPlane = weight.size(0);

  long outputWidth =
      (inputWidth + 2 * padW - (dilationW * (kW - 1) + 1)) / dW + 1;
  long outputHeight =
      (inputHeight + 2 * padH - (dilationH * (kH - 1) + 1)) / dH + 1;

  AT_CHECK((offset.size(0) == batchSize), 3, "invalid batch size of offset");
  gradInput = gradInput.view({batchSize, nInputPlane, inputHeight, inputWidth});
  columns = at::zeros(
      {nInputPlane * kW * kH, im2col_step * outputHeight * outputWidth},
      input.options());

  // change order of grad output
  gradOutput = gradOutput.view({batchSize / im2col_step, im2col_step,
                                nOutputPlane, outputHeight, outputWidth});
  gradOutput.transpose_(1, 2);

  gradInput = gradInput.view({batchSize / im2col_step, im2col_step, nInputPlane,
                              inputHeight, inputWidth});
  input = input.view({batchSize / im2col_step, im2col_step, nInputPlane,
                      inputHeight, inputWidth});
  gradOffset = gradOffset.view({batchSize / im2col_step, im2col_step,
                                deformable_group * 2 * kH * kW, outputHeight,
                                outputWidth});
  offset =
      offset.view({batchSize / im2col_step, im2col_step,
                   deformable_group * 2 * kH * kW, outputHeight, outputWidth});

  for (int elt = 0; elt < batchSize / im2col_step; elt++) {
    // divide into groups
    columns = columns.view({group, columns.size(0) / group, columns.size(1)});
    weight = weight.view({group, weight.size(0) / group, weight.size(1),
                          weight.size(2), weight.size(3)});
    gradOutput = gradOutput.view(
        {gradOutput.size(0), group, gradOutput.size(1) / group,
         gradOutput.size(2), gradOutput.size(3), gradOutput.size(4)});

    for (int g = 0; g < group; g++) {
      columns[g] = columns[g].addmm_(weight[g].flatten(1).transpose(0, 1),
                                     gradOutput[elt][g].flatten(1), 0.0f, 1.0f);
    }

    columns =
        columns.view({columns.size(0) * columns.size(1), columns.size(2)});
    gradOutput = gradOutput.view(
        {gradOutput.size(0), gradOutput.size(1) * gradOutput.size(2),
         gradOutput.size(3), gradOutput.size(4), gradOutput.size(5)});

    deformable_col2im_coord(columns, input[elt], offset[elt], nInputPlane,
                            inputHeight, inputWidth, kH, kW, padH, padW, dH, dW,
                            dilationH, dilationW, im2col_step, deformable_group,
                            gradOffset[elt]);

    deformable_col2im(columns, offset[elt], nInputPlane, inputHeight,
                      inputWidth, kH, kW, padH, padW, dH, dW, dilationH,
                      dilationW, im2col_step, deformable_group, gradInput[elt]);
  }

  gradOutput.transpose_(1, 2);
  gradOutput =
      gradOutput.view({batchSize, nOutputPlane, outputHeight, outputWidth});

  gradInput = gradInput.view({batchSize, nInputPlane, inputHeight, inputWidth});
  input = input.view({batchSize, nInputPlane, inputHeight, inputWidth});
  gradOffset = gradOffset.view(
      {batchSize, deformable_group * 2 * kH * kW, outputHeight, outputWidth});
  offset = offset.view(
      {batchSize, deformable_group * 2 * kH * kW, outputHeight, outputWidth});

  if (batch == 0) {
    gradOutput = gradOutput.view({nOutputPlane, outputHeight, outputWidth});
    input = input.view({nInputPlane, inputHeight, inputWidth});
    gradInput = gradInput.view({nInputPlane, inputHeight, inputWidth});
    offset = offset.view({offset.size(1), offset.size(2), offset.size(3)});
    gradOffset =
        gradOffset.view({offset.size(1), offset.size(2), offset.size(3)});
  }

  return 1;
}

int deform_conv_backward_parameters_cuda(
    at::Tensor input, at::Tensor offset, at::Tensor gradOutput,
    at::Tensor gradWeight,  // at::Tensor gradBias,
    at::Tensor columns, at::Tensor ones, int kW, int kH, int dW, int dH,
    int padW, int padH, int dilationW, int dilationH, int group,
    int deformable_group, float scale, int im2col_step)
{
  // todo: transpose and reshape outGrad
  // todo: reshape columns
  // todo: add im2col_step as input

  shape_check(input, offset, &gradOutput, gradWeight, kH, kW, dH, dW, padH,
              padW, dilationH, dilationW, group, deformable_group);

  input = input.contiguous();
  offset = offset.contiguous();
  gradOutput = gradOutput.contiguous();

  int batch = 1;

  if (input.ndimension() == 3) {
    // Force batch
    batch = 0;
    input = input.view(
        at::IntList({1, input.size(0), input.size(1), input.size(2)}));
    gradOutput = gradOutput.view(
        {1, gradOutput.size(0), gradOutput.size(1), gradOutput.size(2)});
  }

  long batchSize = input.size(0);
  long nInputPlane = input.size(1);
  long inputHeight = input.size(2);
  long inputWidth = input.size(3);

  long nOutputPlane = gradWeight.size(0);

  long outputWidth =
      (inputWidth + 2 * padW - (dilationW * (kW - 1) + 1)) / dW + 1;
  long outputHeight =
      (inputHeight + 2 * padH - (dilationH * (kH - 1) + 1)) / dH + 1;

  AT_CHECK((offset.size(0) == batchSize), "invalid batch size of offset");

  columns = at::zeros(
      {nInputPlane * kW * kH, im2col_step * outputHeight * outputWidth},
      input.options());

  gradOutput = gradOutput.view({batchSize / im2col_step, im2col_step,
                                nOutputPlane, outputHeight, outputWidth});
  gradOutput.transpose_(1, 2);

  at::Tensor gradOutputBuffer = at::zeros_like(gradOutput);
  gradOutputBuffer =
      gradOutputBuffer.view({batchSize / im2col_step, nOutputPlane, im2col_step,
                             outputHeight, outputWidth});
  gradOutputBuffer.copy_(gradOutput);
  gradOutputBuffer =
      gradOutputBuffer.view({batchSize / im2col_step, nOutputPlane,
                             im2col_step * outputHeight, outputWidth});

  gradOutput.transpose_(1, 2);
  gradOutput =
      gradOutput.view({batchSize, nOutputPlane, outputHeight, outputWidth});

  input = input.view({batchSize / im2col_step, im2col_step, nInputPlane,
                      inputHeight, inputWidth});
  offset =
      offset.view({batchSize / im2col_step, im2col_step,
                   deformable_group * 2 * kH * kW, outputHeight, outputWidth});

  for (int elt = 0; elt < batchSize / im2col_step; elt++) {
    deformable_im2col(input[elt], offset[elt], nInputPlane, inputHeight,
                      inputWidth, kH, kW, padH, padW, dH, dW, dilationH,
                      dilationW, im2col_step, deformable_group, columns);

    // divide into group
    gradOutputBuffer = gradOutputBuffer.view(
        {gradOutputBuffer.size(0), group, gradOutputBuffer.size(1) / group,
         gradOutputBuffer.size(2), gradOutputBuffer.size(3)});
    columns = columns.view({group, columns.size(0) / group, columns.size(1)});
    gradWeight =
        gradWeight.view({group, gradWeight.size(0) / group, gradWeight.size(1),
                         gradWeight.size(2), gradWeight.size(3)});

    for (int g = 0; g < group; g++) {
      gradWeight[g] = gradWeight[g]
                          .flatten(1)
                          .addmm_(gradOutputBuffer[elt][g].flatten(1),
                                  columns[g].transpose(1, 0), 1.0, scale)
                          .view_as(gradWeight[g]);
    }
    gradOutputBuffer = gradOutputBuffer.view(
        {gradOutputBuffer.size(0),
         gradOutputBuffer.size(1) * gradOutputBuffer.size(2),
         gradOutputBuffer.size(3), gradOutputBuffer.size(4)});
    columns =
        columns.view({columns.size(0) * columns.size(1), columns.size(2)});
    gradWeight = gradWeight.view({gradWeight.size(0) * gradWeight.size(1),
                                  gradWeight.size(2), gradWeight.size(3),
                                  gradWeight.size(4)});
  }

  input = input.view({batchSize, nInputPlane, inputHeight, inputWidth});
  offset = offset.view(
      {batchSize, deformable_group * 2 * kH * kW, outputHeight, outputWidth});

  if (batch == 0) {
    gradOutput = gradOutput.view({nOutputPlane, outputHeight, outputWidth});
    input = input.view({nInputPlane, inputHeight, inputWidth});
  }

  return 1;
}

void modulated_deform_conv_cuda_forward(
    at::Tensor input, at::Tensor weight, at::Tensor bias, at::Tensor ones,
    at::Tensor offset, at::Tensor mask, at::Tensor output, at::Tensor columns,
    int kernel_h, int kernel_w, const int stride_h, const int stride_w,
    const int pad_h, const int pad_w, const int dilation_h,
    const int dilation_w, const int group, const int deformable_group,
    const bool with_bias)
{
  AT_CHECK(input.is_contiguous(), "input tensor has to be contiguous");
  AT_CHECK(weight.is_contiguous(), "weight tensor has to be contiguous");

  const int batch = input.size(0);
  const int channels = input.size(1);
  const int height = input.size(2);
  const int width = input.size(3);

  const int channels_out = weight.size(0);
  const int channels_kernel = weight.size(1);
  const int kernel_h_ = weight.size(2);
  const int kernel_w_ = weight.size(3);

  if (kernel_h_ != kernel_h || kernel_w_ != kernel_w)
    AT_ERROR("Input shape and kernel shape wont match: (%d x %d vs %d x %d).",
             kernel_h_, kernel_w, kernel_h_, kernel_w_);
  if (channels != channels_kernel * group)
    AT_ERROR("Input shape and kernel channels wont match: (%d vs %d).",
             channels, channels_kernel * group);

  const int height_out =
      (height + 2 * pad_h - (dilation_h * (kernel_h - 1) + 1)) / stride_h + 1;
  const int width_out =
      (width + 2 * pad_w - (dilation_w * (kernel_w - 1) + 1)) / stride_w + 1;

  if (ones.ndimension() != 2 ||
      ones.size(0) * ones.size(1) < height_out * width_out) {
    // Resize plane and fill with ones...
    ones = at::ones({height_out, width_out}, input.options());
  }

  // resize output
  output = output.view({batch, channels_out, height_out, width_out}).zero_();
  // resize temporary columns
  columns =
      at::zeros({channels * kernel_h * kernel_w, 1 * height_out * width_out},
                input.options());

  output = output.view({output.size(0), group, output.size(1) / group,
                        output.size(2), output.size(3)});

  for (int b = 0; b < batch; b++) {
    modulated_deformable_im2col_cuda(
        input[b], offset[b], mask[b], 1, channels, height, width, height_out,
        width_out, kernel_h, kernel_w, pad_h, pad_w, stride_h, stride_w,
        dilation_h, dilation_w, deformable_group, columns);

    // divide into group
    weight = weight.view({group, weight.size(0) / group, weight.size(1),
                          weight.size(2), weight.size(3)});
    columns = columns.view({group, columns.size(0) / group, columns.size(1)});

    for (int g = 0; g < group; g++) {
      output[b][g] = output[b][g]
                         .flatten(1)
                         .addmm_(weight[g].flatten(1), columns[g])
                         .view_as(output[b][g]);
    }

    weight = weight.view({weight.size(0) * weight.size(1), weight.size(2),
                          weight.size(3), weight.size(4)});
    columns =
        columns.view({columns.size(0) * columns.size(1), columns.size(2)});
  }

  output = output.view({output.size(0), output.size(1) * output.size(2),
                        output.size(3), output.size(4)});

  if (with_bias) {
    output += bias.view({1, bias.size(0), 1, 1});
  }
}

void modulated_deform_conv_cuda_backward(
    at::Tensor input, at::Tensor weight, at::Tensor bias, at::Tensor ones,
    at::Tensor offset, at::Tensor mask, at::Tensor columns,
    at::Tensor grad_input, at::Tensor grad_weight, at::Tensor grad_bias,
    at::Tensor grad_offset, at::Tensor grad_mask, at::Tensor grad_output,
    int kernel_h, int kernel_w, int stride_h, int stride_w, int pad_h,
    int pad_w, int dilation_h, int dilation_w, int group, int deformable_group,
    const bool with_bias)
{
  AT_CHECK(input.is_contiguous(), "input tensor has to be contiguous");
  AT_CHECK(weight.is_contiguous(), "weight tensor has to be contiguous");

  const int batch = input.size(0);
  const int channels = input.size(1);
  const int height = input.size(2);
  const int width = input.size(3);

  const int channels_kernel = weight.size(1);
  const int kernel_h_ = weight.size(2);
  const int kernel_w_ = weight.size(3);
  if (kernel_h_ != kernel_h || kernel_w_ != kernel_w)
    AT_ERROR("Input shape and kernel shape wont match: (%d x %d vs %d x %d).",
             kernel_h_, kernel_w, kernel_h_, kernel_w_);
  if (channels != channels_kernel * group)
    AT_ERROR("Input shape and kernel channels wont match: (%d vs %d).",
             channels, channels_kernel * group);

  const int height_out =
      (height + 2 * pad_h - (dilation_h * (kernel_h - 1) + 1)) / stride_h + 1;
  const int width_out =
      (width + 2 * pad_w - (dilation_w * (kernel_w - 1) + 1)) / stride_w + 1;

  if (ones.ndimension() != 2 ||
      ones.size(0) * ones.size(1) < height_out * width_out) {
    // Resize plane and fill with ones...
    ones = at::ones({height_out, width_out}, input.options());
  }

  grad_input = grad_input.view({batch, channels, height, width});
  columns = at::zeros({channels * kernel_h * kernel_w, height_out * width_out},
                      input.options());

  grad_output =
      grad_output.view({grad_output.size(0), group, grad_output.size(1) / group,
                        grad_output.size(2), grad_output.size(3)});

  for (int b = 0; b < batch; b++) {
    // divide int group
    columns = columns.view({group, columns.size(0) / group, columns.size(1)});
    weight = weight.view({group, weight.size(0) / group, weight.size(1),
                          weight.size(2), weight.size(3)});

    for (int g = 0; g < group; g++) {
      columns[g].addmm_(weight[g].flatten(1).transpose(0, 1),
                        grad_output[b][g].flatten(1), 0.0f, 1.0f);
    }

    columns =
        columns.view({columns.size(0) * columns.size(1), columns.size(2)});
    weight = weight.view({weight.size(0) * weight.size(1), weight.size(2),
                          weight.size(3), weight.size(4)});

    // gradient w.r.t. input coordinate data
    modulated_deformable_col2im_coord_cuda(
        columns, input[b], offset[b], mask[b], 1, channels, height, width,
        height_out, width_out, kernel_h, kernel_w, pad_h, pad_w, stride_h,
        stride_w, dilation_h, dilation_w, deformable_group, grad_offset[b],
        grad_mask[b]);
    // gradient w.r.t. input data
    modulated_deformable_col2im_cuda(
        columns, offset[b], mask[b], 1, channels, height, width, height_out,
        width_out, kernel_h, kernel_w, pad_h, pad_w, stride_h, stride_w,
        dilation_h, dilation_w, deformable_group, grad_input[b]);

    // gradient w.r.t. weight, dWeight should accumulate across the batch and
    // group
    modulated_deformable_im2col_cuda(
        input[b], offset[b], mask[b], 1, channels, height, width, height_out,
        width_out, kernel_h, kernel_w, pad_h, pad_w, stride_h, stride_w,
        dilation_h, dilation_w, deformable_group, columns);

    columns = columns.view({group, columns.size(0) / group, columns.size(1)});
    grad_weight = grad_weight.view({group, grad_weight.size(0) / group,
                                    grad_weight.size(1), grad_weight.size(2),
                                    grad_weight.size(3)});
    if (with_bias)
      grad_bias = grad_bias.view({group, grad_bias.size(0) / group});

    for (int g = 0; g < group; g++) {
      grad_weight[g] =
          grad_weight[g]
              .flatten(1)
              .addmm_(grad_output[b][g].flatten(1), columns[g].transpose(0, 1))
              .view_as(grad_weight[g]);
      if (with_bias) {
        grad_bias[g] =
            grad_bias[g]
                .view({-1, 1})
                .addmm_(grad_output[b][g].flatten(1), ones.view({-1, 1}))
                .view(-1);
      }
    }

    columns =
        columns.view({columns.size(0) * columns.size(1), columns.size(2)});
    grad_weight = grad_weight.view({grad_weight.size(0) * grad_weight.size(1),
                                    grad_weight.size(2), grad_weight.size(3),
                                    grad_weight.size(4)});
    if (with_bias)
      grad_bias = grad_bias.view({grad_bias.size(0) * grad_bias.size(1)});
  }
  grad_output = grad_output.view({grad_output.size(0) * grad_output.size(1),
                                  grad_output.size(2), grad_output.size(3),
                                  grad_output.size(4)});
}

{'repo_name': 'Wangt-CN/VC-R-CNN', 'stars': '131', 'repo_language': 'Python', 'file_name': 'small_model.yml', 'mime_type': 'text/plain', 'hash': 7368927247602763734, 'source_dataset': 'data'}


<launch>

	<include file="$(find learning_launch)/launch/simple.launch" />

    <node pkg="turtlesim" type="turtlesim_node" name="turtlesim_node">
		<remap from="/turtle1/cmd_vel" to="/cmd_vel"/>
	</node>

</launch>

{'repo_name': 'huchunxu/ros_21_tutorials', 'stars': '335', 'repo_language': 'CMake', 'file_name': 'c++_for.cpp', 'mime_type': 'text/x-c++', 'hash': -9147637476947738523, 'source_dataset': 'data'}


/*!
 * Bootstrap Table of Contents v1.0.1 (http://afeld.github.io/bootstrap-toc/)
 * Copyright 2015 Aidan Feldman
 * Licensed under MIT (https://github.com/afeld/bootstrap-toc/blob/gh-pages/LICENSE.md) */

/* modified from https://github.com/twbs/bootstrap/blob/94b4076dd2efba9af71f0b18d4ee4b163aa9e0dd/docs/assets/css/src/docs.css#L548-L601 */

/* All levels of nav */
nav[data-toggle="toc"] .nav > li > a {
  display: block;
  padding: 4px 20px;
  font-size: 13px;
  font-weight: 500;
  color: #aaaaaa;
}
nav[data-toggle="toc"] .nav > li > a:hover,
nav[data-toggle="toc"] .nav > li > a:focus {
  padding-left: 19px;
  color: #666666;
  text-decoration: none;
  background-color: transparent;
  border-left: 1px solid #666666;
}
nav[data-toggle="toc"] .nav-link.active,
nav[data-toggle="toc"] .nav-link.active:hover,
nav[data-toggle="toc"] .nav-link.active:focus {
  padding-left: 18px;
  font-weight: bold;
  color: #666666;
  background-color: transparent;
  border-left: 2px solid #666666;
}

/* Nav: second level (shown on .active) */
nav[data-toggle="toc"] .nav-link + ul {
  display: none; /* Hide by default, but at >768px, show it */
  padding-bottom: 10px;
}

nav[data-toggle="toc"] .nav .nav > li > a {
  padding-top: 1px;
  padding-bottom: 1px;
  padding-left: 30px;
  font-size: 12px;
  font-weight: normal;
}
nav[data-toggle="toc"] .nav .nav > li > a:hover,
nav[data-toggle="toc"] .nav .nav > li > a:focus {
  padding-left: 29px;
}
nav[data-toggle="toc"] .nav .nav > li > .active,
nav[data-toggle="toc"] .nav .nav > li > .active:hover,
nav[data-toggle="toc"] .nav .nav > li > .active:focus {
  padding-left: 28px;
  font-weight: 500;
}

nav[data-toggle="toc"] .nav-link.active + ul {
  display: block;
}

{'repo_name': 'Shuttle/shuttle-esb', 'stars': '118', 'repo_language': 'HTML', 'file_name': 'api.html', 'mime_type': 'text/html', 'hash': -4517995817050994995, 'source_dataset': 'data'}


# -*- coding: utf-8 -*-
# # Copyright DataStax, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import six
from cassandra.auth import PlainTextAuthenticator

try:
    import unittest2 as unittest
except ImportError:
    import unittest  # noqa

class TestPlainTextAuthenticator(unittest.TestCase):

    def test_evaluate_challenge_with_unicode_data(self):
        authenticator = PlainTextAuthenticator("johnӁ", "doeӁ")
        self.assertEqual(
            authenticator.evaluate_challenge(six.ensure_binary('PLAIN-START')),
            six.ensure_binary("\x00johnӁ\x00doeӁ")
        )

{'repo_name': 'datastax/python-driver', 'stars': '1156', 'repo_language': 'Python', 'file_name': 'statements.py', 'mime_type': 'text/x-python', 'hash': -1487255389776558149, 'source_dataset': 'data'}


package com.openrsc.server.plugins.authentic.npcs.varrock;

import com.openrsc.server.constants.ItemId;
import com.openrsc.server.constants.NpcId;
import com.openrsc.server.model.Shop;
import com.openrsc.server.model.container.Item;
import com.openrsc.server.model.entity.npc.Npc;
import com.openrsc.server.model.entity.player.Player;
import com.openrsc.server.model.world.World;
import com.openrsc.server.net.rsc.ActionSender;
import com.openrsc.server.plugins.AbstractShop;

import static com.openrsc.server.plugins.Functions.*;

public final class LowesArchery extends AbstractShop {

	private final Shop shop = new Shop(false, 3000, 100, 55, 1, new Item(ItemId.BRONZE_ARROWS.id(),
		200), new Item(ItemId.CROSSBOW_BOLTS.id(), 150), new Item(ItemId.SHORTBOW.id(), 4), new Item(
		ItemId.LONGBOW.id(), 2), new Item(ItemId.CROSSBOW.id(), 2));

	@Override
	public boolean blockTalkNpc(final Player player, final Npc n) {
		return n.getID() == NpcId.LOWE.id();
	}

	@Override
	public Shop[] getShops(World world) {
		return new Shop[]{shop};
	}

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

	@Override
	public Shop getShop() {
		return shop;
	}

	@Override
	public void onTalkNpc(final Player player, final Npc n) {
		npcsay(player, n, "Welcome to Lowe's Archery Store",
			"Do you want to see my wares?");

		int option = multi(player, n, false, //do not send over
			"Yes please", "No, I prefer to bash things close up");

		if (option == 0) {
			say(player, n, "Yes Please");
			player.setAccessingShop(shop);
			ActionSender.showShop(player, shop);
		} else if (option == 1) {
			say(player, n, "No, I prefer to bash things close up");
		}
	}

}

{'repo_name': 'Open-RSC/Core-Framework', 'stars': '118', 'repo_language': 'Java', 'file_name': 'TeleportStone.java', 'mime_type': 'text/x-java', 'hash': 456362672011390627, 'source_dataset': 'data'}


import hail as hl

def densify(sparse_mt):
    """Convert sparse matrix table to a dense VCF-like representation by expanding reference blocks.

    Parameters
    ----------
    sparse_mt : :class:`.MatrixTable`
        Sparse MatrixTable to densify.  The first row key field must
        be named ``locus`` and have type ``locus``.  Must have an
        ``END`` entry field of type ``int32``.

    Returns
    -------
    :class:`.MatrixTable`
        The densified MatrixTable.  The ``END`` entry field is dropped.

    While computationally expensive, this
    operation is necessary for many downstream analyses, and should be thought of as
    roughly costing as much as reading a matrix table created by importing a dense
    project VCF.
    """
    if list(sparse_mt.row_key)[0] != 'locus' or not isinstance(sparse_mt.locus.dtype, hl.tlocus):
        raise ValueError("first row key field must be named 'locus' and have type 'locus'")
    if 'END' not in sparse_mt.entry or sparse_mt.END.dtype != hl.tint32:
        raise ValueError("'densify' requires 'END' entry field of type 'int32'")
    col_key_fields = list(sparse_mt.col_key)

    contigs = sparse_mt.locus.dtype.reference_genome.contigs
    contig_idx_map = hl.literal({contigs[i]: i for i in range(len(contigs))}, 'dict<str, int32>')
    mt = sparse_mt.annotate_rows(__contig_idx=contig_idx_map[sparse_mt.locus.contig])
    mt = mt.annotate_entries(__contig=mt.__contig_idx)

    t = mt._localize_entries('__entries', '__cols')
    t = t.annotate(
        __entries=hl.rbind(
            hl.scan.array_agg(
                lambda entry: hl.scan._prev_nonnull(hl.or_missing(hl.is_defined(entry.END), entry)),
                t.__entries),
            lambda prev_entries: hl.map(
                lambda i:
                hl.rbind(
                    prev_entries[i], t.__entries[i],
                    lambda prev_entry, entry:
                    hl.cond(
                        (~hl.is_defined(entry)
                         & (prev_entry.END >= t.locus.position)
                         & (prev_entry.__contig == t.__contig_idx)),
                        prev_entry,
                        entry)),
                hl.range(0, hl.len(t.__entries)))))
    mt = t._unlocalize_entries('__entries', '__cols', col_key_fields)
    mt = mt.drop('__contig_idx', '__contig', 'END')
    return mt

{'repo_name': 'hail-is/hail', 'stars': '640', 'repo_language': 'Scala', 'file_name': 'billing.html', 'mime_type': 'text/html', 'hash': 4413394323566083470, 'source_dataset': 'data'}


import random

class GoodChip:
    def good(self):
        return True

    def check(self, other):
        return other.good()

class BadChip:
    def good(self):
        return False

    def check(self, other):
        return [True, False][random.randint(0, 1)]

def jig(a, b):
    return [a.check(b), b.check(a)]

def diogenes(chips, verbose = False):
    def find_single(chips):
        if len(chips) <= 2:
            return chips[0]
        else:
            halfpoint = len(chips) // 2
            pairs     = zip(chips[0:halfpoint], chips[halfpoint:halfpoint * 2])
            kept      = [a for (a, b) in pairs if jig(a, b) == [True, True]]

            if len(chips) % 2 == 1:
                kept.append(chips[-1])

            return find_single(kept)

    good = find_single(chips)
    return [chip for chip in chips if jig(good, chip) == [True, True]]

{'repo_name': 'skanev/playground', 'stars': '157', 'repo_language': 'Scheme', 'file_name': '03.c', 'mime_type': 'text/x-c', 'hash': -3845646575785828833, 'source_dataset': 'data'}


Vsi koledarji niso popolnoma predpomnjeni

Videti je, da so vsi predmeti predpomnjeni

Ni ustreznih dovoljenj za urejanje tega dogodka.

Datoteka ni vsebovala dogodkov, ali pa so vsi že shranjeni v koledarju.

v novi koledar so bili shranjeni dogodki

%n dogodek je bil shranjen v nov koledar %s.

%n dogodka sta bila shranjena v nov koledar %s.

%n dogodki so bili shranjeni v nov koledar %s.

%n dogodkov je bilo shranjenih v nov koledar %s.

%n dogodkov je bilo shranjenih v koledar.

ddd, d. MMMM [ yyyy]{ - [ddd, d.] MMMM yyyy}

ddd. d. MMMM[ yyyy] HH:mm{ - [ ddd. d. MMMM yyyy] HH:mm}

Naslov

Določilo časovnega razmika ni veljavno. Vrednost mora biti pozitivno celo število..

V souporabi z vami in skupino {group}. Lastnik je {owner}.

Souporaba z uporabniki ali s skupinami ...

Souporaba z uporabniki, skupinami ali oddaljenimi uporabniki ...

Souporaba z uporabniki drugih oblakov ownCloud je mogoča s povezavo uporabnik@domena.si/owncloud

Javna povezava bo potekla {days} dni po ustvarjanju.

V souporabi v {item} z uporabnikom {user}

Ni ustreznih dovoljenj za posodobitev tega koledarja.

Ni ustreznih dovoljenj za izbris tega koledarja.

Ni ustreznih dovoljenj za dodajanje tega koledarja.

Ni ustreznih dovoljenj za dodajanje dogodkov v ta koledar.

V koledar v souporabi ni mogoče dodati zasebnih dogodkov.

Ni ustreznih dovoljenj za izbris tega dogodka.

Počisti predpomnilnik ponavljajočih se dogodkov

Naslov koledarja CalDAV rojstnih dni stika

Opis

Koledar s tem imenom že obstaja. Z nadaljevanjem bosta vsebini koledarjev združeni.

Odstrani vse dogodke iz izbranega koledarja

Omogoči souporabo s skupino ali z uporabnikom

{'repo_name': 'owncloudarchive/calendar', 'stars': '184', 'repo_language': 'PHP', 'file_name': 'geo.js', 'mime_type': 'text/plain', 'hash': -5962059470682222831, 'source_dataset': 'data'}


load("@io_bazel_rules_go//go:def.bzl", "go_library")

go_library(
    name = "go_default_library",
    srcs = [
        "network.go",
        "plugins.go",
    ],
    importpath = "k8s.io/kubernetes/pkg/kubelet/dockershim/network",
    visibility = ["//visibility:public"],
    deps = [
        "//pkg/features:go_default_library",
        "//pkg/kubelet/apis/config:go_default_library",
        "//pkg/kubelet/container:go_default_library",
        "//pkg/kubelet/dockershim/network/hostport:go_default_library",
        "//pkg/kubelet/dockershim/network/metrics:go_default_library",
        "//pkg/util/sysctl:go_default_library",
        "//staging/src/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library",
        "//staging/src/k8s.io/apimachinery/pkg/util/errors:go_default_library",
        "//staging/src/k8s.io/apimachinery/pkg/util/sets:go_default_library",
        "//staging/src/k8s.io/apimachinery/pkg/util/validation:go_default_library",
        "//staging/src/k8s.io/apiserver/pkg/util/feature:go_default_library",
        "//vendor/k8s.io/klog:go_default_library",
        "//vendor/k8s.io/utils/exec:go_default_library",
    ],
)

filegroup(
    name = "package-srcs",
    srcs = glob(["**"]),
    tags = ["automanaged"],
    visibility = ["//visibility:private"],
)

filegroup(
    name = "all-srcs",
    srcs = [
        ":package-srcs",
        "//pkg/kubelet/dockershim/network/cni:all-srcs",
        "//pkg/kubelet/dockershim/network/hairpin:all-srcs",
        "//pkg/kubelet/dockershim/network/hostport:all-srcs",
        "//pkg/kubelet/dockershim/network/kubenet:all-srcs",
        "//pkg/kubelet/dockershim/network/metrics:all-srcs",
        "//pkg/kubelet/dockershim/network/testing:all-srcs",
    ],
    tags = ["automanaged"],
    visibility = ["//visibility:public"],
)

{'repo_name': 'kubeedge/kubeedge', 'stars': '2686', 'repo_language': 'Go', 'file_name': 'options.go', 'mime_type': 'text/plain', 'hash': 361362659326847308, 'source_dataset': 'data'}


>>>
GET /?p=%20 HTTP/1.0
User-Agent: Mozilla

<<<
HTTP/1.0 200 OK
Date: Mon, 31 Aug 2009 20:25:50 GMT
Server: Apache
Connection: close
Content-Type: text/html
Content-Length: 12

Hello
<<<
 World!

{'repo_name': 'OISF/libhtp', 'stars': '210', 'repo_language': 'C++', 'file_name': 'HTP.c', 'mime_type': 'text/x-c', 'hash': 3001094573200287162, 'source_dataset': 'data'}


#include "f.h"
DUPLICATETYPEPARAMETER
extern "C" int puts(const char *s);
int main() {
  puts("duplicate-type-parameter");
}

{'repo_name': 'yrnkrn/zapcc', 'stars': '1045', 'repo_language': 'C++', 'file_name': 'file1.cpp', 'mime_type': 'text/x-c', 'hash': -1962617284363029450, 'source_dataset': 'data'}


---
title: Post Types
description: Reference for the schema API
---

# Post Types

You can create new post types for use creating advanced functionality like blogs, forums, job listings, etc. In this guide, we'll walk through the basic steps.

## Base Post Type

All post types are built on a base post type schema called simply `post`.

This post type includes functionality that is common to most post use cases. For example, it adds `title`, `content`, `tag`, and `category` fields.

It also adds [indexes](https://mongoosejs.com/docs/guide.html#indexes) for common queries. Examples of default indexes are:

- Text search on `title` and `content` fields
- Unique index on `permalink`
- Index on `postType`

Here is the [schema definition](https://github.com/fiction-com/factor/blob/development/%40factor/post/post-type.ts).

## Adding A Post Type

To add a post type, all that is needed is the `addPostType` function:

```js
import { addPostType } from "@factor/api"

addPostType({
  postType: "myPostType",
  // ... other options
})
```

For all post type features to work correctly this function needs to be run in both the app and server environments. So make sure to address this with your [main files](./main-files); for example a load configuration of `load: ['app', 'server']`.

## Configuring the Post Type

There are many available options available when creating new post types, let's walk through them.

## Post Type Management Options

You can control the dashboard management features with the following options:

```js
import { addPostType } from "@factor/api"

import icon from "./my-icon.svg"

addPostType({
  postType: "myPostType",
  managePosts: true, // Enable dashboard menu
  icon, // Dashboard icon
  nameIndex: "Users", // Contextual references
  nameSingle: "User",
  namePlural: "Users",
  accessLevel: 500, // accessLevel needed to see dashboard menu
  noAddNew: true, // hide "add new"
  addNewText: "Create User", // change add new text
  listTemplate: () => import("./v-list.vue"), // override post listing component
  editTemplate: () => import("./v-edit.vue"), // override post edit component
})
```

## Post Type Permalinks

You can control the post type permalinks when you set up the post type.

This doesn't create the route however it just allows you to use `postLink` ([doc](./links)) and get the desired link. You'll also need to[ create the routes and handling](./routes) to make the post show correctly on that page.

```js
import { addPostType, slugify } from "@factor/api"

addPostType({
  postType: "myPostType",
  permalink: (post) => {
    return `/my-post-type/${post._id}/${slugify(post.title)}`
  },
})
```

If you want to allow permalinks to be set in the dashboard:

```js
import { addPostType } from "@factor/api"

addPostType({
  postType: "myPostType",
  customPermalink: true, // Allow permalink option on post edit
  permalink: (post) => {
    return `/my-post-type/${post.permalink}`
  },
})
```

## Create Structure with Post Schema Options

### Schema Definition

Schemas are to help organize the handling of post data on your server. Create a custom schema to add new properties or to change the base post definition.

The `schemaDefinition` options are used to add a [Mongoose schema](https://mongoosejs.com/docs/guide.html) definition to your post type and extend the base post schema.

Post type creation also supports three additional options related to schemas:

- `schemaMiddleware` - Callback function for adding [Mongoose middleware](https://mongoosejs.com/docs/middleware.html) functions
- `schemaOptions` - Add Mongoose [options](https://mongoosejs.com/docs/guide.html#options) to the schema
- `schemaPopulated` - An array of fields that consist of references to other posts and need to be populated on query (e.g. `author`).

```js
import { addPostType, ObjectId } from "@factor/api"

addPostType({
  schemaDefinition: {
    foo: String,
    bar: Buffer,
    baz: Number,
    buz: {ref: "anotherPostType", type: ObjectId}
  },
  schemaMiddleware: Schema => {
    Schema.pre('save', function(){
      // add middleware
    })
  }
  schemaPopulated: ['buz'], // populate the buz field with its post
  schemaOptions: {}
  // ...other post type options
})

```

#### Notes

- Populated fields are fields consisting of just `_id`'s or `objectId` that populate based on data in the original post (like a SQL join)
- `ObjectId` is needed for Mongoose to property type check reference to other posts

## Security Permissions

For database operations, you need permissions to control access. Factor offers a basic system to control standard CRUD input and output.

The base post permissions schema looks like this:

```js
addPostType({
  permissions: {
    create: { accessLevel: 100 },
    retrieve: {
      accessLevel: 100,
      accessPublished: 0,
      accessAuthor: true,
    },
    update: { accessLevel: 100, accessAuthor: true },
    delete: { accessLevel: 200, accessAuthor: true },
    embedded: {
      create: { accessLevel: 1 },
      retrieve: { accessLevel: 0 },
      update: { accessLevel: 100, accessAuthor: true },
      delete: { accessLevel: 100, accessAuthor: true },
    },
  },
})
```

In your extending schema you can override this. For example with contact form submissions, we want it to be possible for anyone to create them (`accessLevel: 0`) but you have to be a moderator or the post author to read them (`accessLevel: 300`). In your schema that looks like this:

```js
export default {
  name: "contact-form",
  permissions: {
    create: { accessLevel: 0 },
    retrieve: {
      accessLevel: 300,
      accessAuthor: true,
    },
  },
}
```

## Template Settings

If you would like to allow users to set meta-information on each post, there is a way to add template options in post types using [template settings](./template-settings).

```js
addPostType({
  postType: "portfolioItems",
  templateSettings: [
    {
      _id: "items",
      input: "sortable",
      label: "Additional Work Info",
      description: "Additional information about this project",
      _default: [
        { __title: "Client", value: "Client Name" },
        { __title: "Role", value: "Role" },
        { __title: "Year", value: new Date().getFullYear() },
        { __title: "Platforms", value: "Web" },
        { __title: "URL", value: "https://www.example.com" },
      ],
      settings: [
        {
          input: "text",
          label: "Value",
          _id: "value",
        },
      ],
    },
  ],
})
```

## Public Sitemap

Some post types are meant to be public, e.g. blog posts, while others are meant to be private, e.g. contact form submissions.

If you would like to indicate that posts are public and meant to be added to the public sitemap then use `addSitemap`.

```js
addPostType({
  postType: "portfolioItems",
  addSitemap: true,
})
```

Enabling this option will add the post type to public tools like the `sitemap.xml` file and search utilities.

## Changing Post Types with Filters

You can edit or add to existing post types using standard filters.

- `schema-definition-[post type]` - Is a filter to adjust the schema definition of a post type
- `schema-hooks-[post type]` - Add additional Mongoose middleware to a schema

```js
import { randomToken } from "@factor/api"
addFilter({
  key: "addApiKey",
  hook: "schema-definition-user",
  callback: (definition) => {
    definition.apiKey = {
      type: String,
      default: randomToken(50),
    }
    return definition
  },
})
```

{'repo_name': 'fiction-com/factor', 'stars': '912', 'repo_language': 'Vue', 'file_name': 'widget-meta.vue', 'mime_type': 'text/html', 'hash': 1444635536505878006, 'source_dataset': 'data'}


.assembly-type-curated_links {
  &.nav-menu {
    border-top: 1px solid #e9e9e9;
    border-bottom: 1px solid #e9e9e9;
    margin-bottom: 15px;
  }
}
.curated-links {
  @extend .container;
  padding: 40px 15px;
  .nav-menu & {
    padding: 15px 15px 0 15px;
  }
}

.curated-links__list {
  border-top: 1px solid #e9e9e9;
  border-bottom: 1px solid #e9e9e9;
  padding: 20px 0;
  list-style: none;
  .nav-menu & {
    border-top: none;
    border-bottom: none;
    display: flex;
    padding: 0;
    margin: 0 0 15px 0;
    text-align: left;
    @include desktop-extra-small-and-down {
      flex-direction: column;
    }
  }
}

.curated-links__list-item {
  line-height: 40px;
  padding-left: 12px;
  .nav-menu & {
    padding-left: 0;
    padding-right: 30px;
    display: inline-block;
    max-width: 15rem;
    line-height: 1.3;
    a {
      font-size: 14px;
    }
    @include desktop-extra-small-and-down {
      display: block;
      max-width: 100%;
      line-height: 24px;
      margin-bottom: 8px;
    }
  }

  @include desktop-small-and-down {
    line-height: 24px;
    margin-bottom: 8px;
  }
}

.curated-links__list-item .fa-arrow-alt-circle-right {
  color: #999;
  height: 100%;
  font-size: 8px;
}

.curated-links__list-item > a {
  font-size: 20px;

  @include desktop-small-and-down {
    font-size: 14px;
  }
}

{'repo_name': 'redhat-developer/developers.redhat.com', 'stars': '134', 'repo_language': 'CSS', 'file_name': 'wdio.conf.browserstack.js', 'mime_type': 'text/plain', 'hash': 7757519888582292555, 'source_dataset': 'data'}


# Copyright 2017-2020 The Verible Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Build rule for generating C or C++ sources with Flex.

IMPORTANT: we _strongly recommend_ that you include a unique and project-
specific `%option prefix="myproject"` directive in your scanner spec to avoid
very hard-to-debug symbol name conflict problems if two scanners are linked
into the same dynamically-linked executable.

By default, flex includes the definition of a static function `yyunput` in its
output. If you never use the lex `unput` function in your lex rules, however,
`yyunput` will never be called. This causes problems building the output file,
as llvm issues warnings about static functions that are never called. To avoid
this problem, use `%option nounput` in the declarations section if your lex
rules never use `unput`.

Note that if you use the c++ mode of flex, you will need to include the
boilerplate header `FlexLexer.h` file in any `cc_library` which includes the
generated flex scanner directly.  This is typically done by
`#include <FlexLexer.h>` which typically is installed in /usr/include
when flex is installed.

Examples
--------

This is a simple example.
```
genlex(
    name = "html_lex_lex",
    src = "html.lex",
    out = "html_lexer.c",
)
```

This example uses a `.tab.hh` file.
```
genlex(
    name = "rules_l",
    src = "rules.lex",
    includes = [
        "rules.tab.hh",
    ],
    out = "rules.yy.cc",
)
```
"""

def _genlex_impl(ctx):
    """Implementation for genlex rule."""

    # Compute the prefix, if not specified.
    if ctx.attr.prefix:
        prefix = ctx.attr.prefix
    else:
        prefix = ctx.file.src.basename.partition(".")[0]

    # Construct the arguments.
    args = ctx.actions.args()
    args.add("-o", ctx.outputs.out)
    args.add("-P", prefix)
    args.add_all(ctx.attr.lexopts)
    args.add(ctx.file.src)

    ctx.actions.run(
        executable = ctx.executable._flex,
        env = {
            "M4": ctx.executable._m4.path,
        },
        arguments = [args],
        inputs = ctx.files.src + ctx.files.includes,
        tools = [ctx.executable._m4],
        outputs = [ctx.outputs.out],
        mnemonic = "Flex",
        progress_message = "Generating %s from %s" % (
            ctx.outputs.out.short_path,
            ctx.file.src.short_path,
        ),
    )

genlex = rule(
    attrs = {
        "src": attr.label(
            mandatory = True,
            allow_single_file = [
                ".l",
                ".ll",
                ".lex",
                ".lpp",
            ],
            doc = "The .lex source file for this rule",
        ),
        "includes": attr.label_list(
            allow_files = True,
            doc = "A list of headers that are included by the .lex file",
        ),
        "out": attr.output(
            mandatory = True,
            doc = "The generated source file",
        ),
        "prefix": attr.string(
            doc = "External symbol prefix for Flex. This string is " +
                  "passed to flex as the -P option, causing the resulting C " +
                  "file to define external functions named 'prefix'text, " +
                  "'prefix'in, etc.  The default is the basename of the source" +
                  "file without the .lex extension.",
        ),
        "lexopts": attr.string_list(
            doc = "A list of options to be added to the flex command line.",
        ),
        "_flex": attr.label(
            default = Label("//bazel:flex_bin"),
            executable = True,
            cfg = "host",
        ),
        "_m4": attr.label(
            default = Label("//bazel:m4_bin"),
            executable = True,
            cfg = "host",
        ),
    },
    doc = "Generate C/C++-language sources from a lex file using Flex.",
    output_to_genfiles = True,
    implementation = _genlex_impl,
)

{'repo_name': 'google/verible', 'stars': '229', 'repo_language': 'C++', 'file_name': 'development.md', 'mime_type': 'text/plain', 'hash': -173052272830232877, 'source_dataset': 'data'}


assert-plus

Extra assertions on top of node's assert module

{'repo_name': 'hua1995116/musiccloudWebapp', 'stars': '692', 'repo_language': 'Vue', 'file_name': 'webpack.test.conf.js', 'mime_type': 'text/plain', 'hash': 1896213850803863513, 'source_dataset': 'data'}


# Licensed to Elasticsearch B.V. under one or more contributor
# license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright
# ownership. Elasticsearch B.V. licenses this file to you under
# the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.

require 'spec_helper'

describe 'client.cluster#put_template' do

  let(:expected_args) do
    [
        'PUT',
        url,
        params,
        body,
        {}
    ]
  end

  let(:url) do
    '_template/foo'
  end

  let(:body) do
    { template: 'bar' }
  end

  let(:params) do
    {}
  end

  it 'performs the request' do
    expect(client_double.indices.put_template(name: 'foo', body: { template: 'bar' })).to eq({})
  end

  context 'when there is no name specified' do

    let(:client) do
      Class.new { include Elasticsearch::API }.new
    end

    it 'raises an exception' do
      expect {
        client.indices.put_template(body: {})
      }.to raise_exception(ArgumentError)
    end
  end

  context 'when there is no body specified' do

    let(:client) do
      Class.new { include Elasticsearch::API }.new
    end

    it 'raises an exception' do
      expect {
        client.indices.put_template(name: 'foo')
      }.to raise_exception(ArgumentError)
    end
  end

  context 'when parameters are specified' do

    let(:params) do
      { order: 3 }
    end

    let(:url) do
      '_template/foo'
    end

    let(:body) do
      {}
    end

    it 'performs the request' do
      expect(client_double.indices.put_template(name: 'foo', order: 3, body: {})).to eq({})
    end
  end

  context 'when the path needs to be URL-escaped' do

    let(:url) do
      '_template/foo%5Ebar'
    end

    let(:body) do
      {}
    end

    it 'performs the request' do
      expect(client_double.indices.put_template(name: 'foo^bar', body: {})).to eq({})
    end
  end
end

{'repo_name': 'elastic/elasticsearch-ruby', 'stars': '1752', 'repo_language': 'Ruby', 'file_name': 'search_suggest_test.rb', 'mime_type': 'text/x-ruby', 'hash': -2582980171217970394, 'source_dataset': 'data'}


{{with .PDoc}}

	{{if $.IsMain}}
		{{/* command documentation */}}
		{{comment_html .Doc}}
	{{else}}
		{{/* package documentation */}}

import "{{html .ImportPath}}"

Overview

Index

			{{if $.Examples}}

Examples

			{{end}}
			{{if $.Dirs}}

Subdirectories

			{{end}}

Overview ▹

Overview ▾

				{{comment_html .Doc}}

		{{example_html $ ""}}

Index ▹

Index ▾

			{{if .Consts}}

Constants

			{{end}}
			{{if .Vars}}

Variables

			{{end}}
			{{range .Funcs}}
				{{$name_html := html .Name}}

{{node_html $ .Decl false | sanitize}}

			{{end}}
			{{range .Types}}
				{{$tname_html := html .Name}}

type {{$tname_html}}

				{{range .Funcs}}
					{{$name_html := html .Name}}

    {{node_html $ .Decl false | sanitize}}

				{{end}}
				{{range .Methods}}
					{{$name_html := html .Name}}

    {{node_html $ .Decl false | sanitize}}

				{{end}}
			{{end}}
			{{if $.Notes}}
				{{range $marker, $item := $.Notes}}

{{noteTitle $marker | html}}s

				{{end}}
			{{end}}

		{{if $.Examples}}

Examples

			{{range $.Examples}}

{{example_name .Name}}

			{{end}}

		{{end}}

		{{with .Filenames}}

Package files

			{{range .}}
				{{.|filename|html}}
			{{end}}

		{{end}}

Internal call graph ▹

Internal call graph ▾

			  In the call graph viewer below, each node
			  is a function belonging to this package
			  and its children are the functions it
			  calls—perhaps dynamically.

			  The root nodes are the entry points of the
			  package: functions that may be called from
			  outside the package.
			  There may be non-exported or anonymous
			  functions among them if they are called
			  dynamically from another package.

			  Click a node to visit that function's source code.
			  From there you can visit its callers by
			  clicking its declaring func
			  token.

			  Functions may be omitted if they were
			  determined to be unreachable in the
			  particular programs or tests that were
			  analyzed.

		{{with .Consts}}

Constants

			{{range .}}

{{node_html $ .Decl true}}

				{{comment_html .Doc}}
			{{end}}
		{{end}}
		{{with .Vars}}

Variables

			{{range .}}

{{node_html $ .Decl true}}

				{{comment_html .Doc}}
			{{end}}
		{{end}}
		{{range .Funcs}}
			{{/* Name is a string - no need for FSet */}}
			{{$name_html := html .Name}}

func {{$name_html}}

{{node_html $ .Decl true}}

			{{comment_html .Doc}}
			{{example_html $ .Name}}
			{{callgraph_html $ "" .Name}}

		{{end}}
		{{range .Types}}
			{{$tname := .Name}}
			{{$tname_html := html .Name}}

type {{$tname_html}}

{{node_html $ .Decl true}}

			{{comment_html .Doc}}

			{{range .Consts}}

{{node_html $ .Decl true}}

				{{comment_html .Doc}}
			{{end}}

			{{range .Vars}}

{{node_html $ .Decl true}}

				{{comment_html .Doc}}
			{{end}}

			{{example_html $ $tname}}
			{{implements_html $ $tname}}
			{{methodset_html $ $tname}}

			{{range .Funcs}}
				{{$name_html := html .Name}}

func {{$name_html}}

{{node_html $ .Decl true}}

				{{comment_html .Doc}}
				{{example_html $ .Name}}
				{{callgraph_html $ "" .Name}}
			{{end}}

			{{range .Methods}}
				{{$name_html := html .Name}}

func ({{html .Recv}}) {{$name_html}}

{{node_html $ .Decl true}}

				{{comment_html .Doc}}
				{{$name := printf "%s_%s" $tname .Name}}
				{{example_html $ $name}}
				{{callgraph_html $ .Recv .Name}}
			{{end}}
		{{end}}
	{{end}}

	{{with $.Notes}}
		{{range $marker, $content := .}}

{{noteTitle $marker | html}}s

			{{range .}}

☞ {{html .Body}}

			{{end}}

		{{end}}
	{{end}}
{{end}}

{{with .PAst}}
	{{range $filename, $ast := .}}
		{{$filename|filename|html}}:
{{node_html $ $ast false}}

	{{end}}
{{end}}

{{with .Dirs}}
	{{/* DirList entries are numbers and strings - no need for FSet */}}
	{{if $.PDoc}}

Subdirectories

	{{end}}
	{{if eq $.Dirname "/src"}}

Standard library

Other packages

Sub-repositories

Community

Standard library

	{{end}}

	Name

	Synopsis

	{{if not (or (eq $.Dirname "/src") (eq $.Dirname "/src/cmd") $.DirFlat)}}

		..

	{{end}}
	{{range .List}}
		{{if $.DirFlat}}
			{{if .HasPkg}}

				{{html .Path}}

				{{html .Synopsis}}

			{{end}}
		{{else}}

			{{repeat `     ` .Depth}}{{html .Name}}

			{{html .Synopsis}}

		{{end}}
	{{end}}

	{{if eq $.Dirname "/src"}}

Other packages

Sub-repositories

	These packages are part of the Go Project but outside the main Go tree.
	They are developed under looser compatibility requirements than the Go core.
	Install them with "go get".

crypto — additional cryptography packages.

image — additional imaging packages.

net — additional networking packages.

sys — packages for making system calls.

text — packages for working with text.

tools — godoc, vet, cover, and other tools.

exp — experimental code (handle with care; may change without warning).

Community

	These services can help you find Open Source packages provided by the community.

GoDoc - a package index and search engine.

Go Search - a code search engine.

Projects at the Go Wiki - a curated list of Go projects.

	{{end}}
{{end}}

{'repo_name': 'evergreen-ci/evergreen', 'stars': '234', 'repo_language': 'Go', 'file_name': 'split_command.go', 'mime_type': 'text/plain', 'hash': 9221017408502594913, 'source_dataset': 'data'}


<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2015 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: yunwuxin <448901948@qq.com>
// +----------------------------------------------------------------------

namespace think\process\exception;

use think\Process;

class Timeout extends \RuntimeException
{

    const TYPE_GENERAL = 1;
    const TYPE_IDLE    = 2;

    private $process;
    private $timeoutType;

    public function __construct(Process $process, $timeoutType)
    {
        $this->process     = $process;
        $this->timeoutType = $timeoutType;

        parent::__construct(sprintf('The process "%s" exceeded the timeout of %s seconds.', $process->getCommandLine(), $this->getExceededTimeout()));
    }

    public function getProcess()
    {
        return $this->process;
    }

    public function isGeneralTimeout()
    {
        return $this->timeoutType === self::TYPE_GENERAL;
    }

    public function isIdleTimeout()
    {
        return $this->timeoutType === self::TYPE_IDLE;
    }

    public function getExceededTimeout()
    {
        switch ($this->timeoutType) {
            case self::TYPE_GENERAL:
                return $this->process->getTimeout();

            case self::TYPE_IDLE:
                return $this->process->getIdleTimeout();

            default:
                throw new \LogicException(sprintf('Unknown timeout type "%d".', $this->timeoutType));
        }
    }
}

{'repo_name': 'apanly/mooc', 'stars': '246', 'repo_language': 'PHP', 'file_name': 'yii2.conf', 'mime_type': 'text/plain', 'hash': -4614919817597961695, 'source_dataset': 'data'}


# frozen_string_literal: true

source ENV['GEM_SOURCE'] || 'https://rubygems.org'

# Disable analytics when running in development
ENV['BOLT_DISABLE_ANALYTICS'] = 'true'

# Disable warning that Bolt may be installed as a gem
ENV['BOLT_GEM'] = 'true'

gemspec

group(:bolt_server) do
  # Bolt server gems are managed here not in the gemspec
  gem "hocon", '>= 1.2.5'
  gem "json-schema", '>= 2.8.0'
  gem "puma", '>= 3.12.0'
  gem "rack", '>= 2.0.5'
  gem "rails-auth", '>= 2.1.4'
  gem "sinatra", '>= 2.0.4'
end

# Optional paint gem for rainbow outputter
gem "paint", "~> 2.2"

group(:test) do
  gem "beaker-hostgenerator"
  gem "mocha", '~> 1.4.0'
  gem "rack-test", '~> 1.0'
  gem "rubocop", '~> 0.61', require: false
end

group(:packaging) do
  gem 'packaging', '~> 0.99.35'
end

local_gemfile = File.join(__dir__, 'Gemfile.local')
if File.exist? local_gemfile
  eval_gemfile local_gemfile
end

{'repo_name': 'puppetlabs/bolt', 'stars': '326', 'repo_language': 'Ruby', 'file_name': 'pwsh_bolt.tests.ps1.erb', 'mime_type': 'text/plain', 'hash': 3890193399270299474, 'source_dataset': 'data'}


{ buildPythonPackage, fetchPypi, isPy3k, stdenv }:

buildPythonPackage rec {
  pname = "lmtpd";
  version = "6.2.0";

  disabled = !isPy3k;

  src = fetchPypi {
    inherit pname version;
    sha256 = "2c6825d2ffa1de099440411a742f58e1b3e8deeb3345adcfd4c2c38d4baf62b3";
  };

  meta = with stdenv.lib; {
    homepage = "https://github.com/moggers87/lmtpd";
    description = "LMTP counterpart to smtpd in the Python standard library";
    license = licenses.mit;
    maintainers = with maintainers; [ jluttine ];
  };
}

{'repo_name': 'NixOS/nixpkgs', 'stars': '5317', 'repo_language': 'Nix', 'file_name': 'default.nix', 'mime_type': 'text/plain', 'hash': -8818758400413841683, 'source_dataset': 'data'}


/* Monkey HTTP Daemon
 * ------------------
 * Copyright (C) 2012, Lauri Kasanen <cand@gmx.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Library General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */

#include <libmonkey.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>

/*
 * This example shows how to start the server, and point it to /tmp.
 * It also creates /tmp/index.html.
*/

static void write_index() {

	const char *path = "/tmp/index.html";

	FILE *f = fopen(path, "w");
	if (!f) exit(1);

	fprintf(f, "
Hello Monkey
");

	fclose(f);
}

int main() {

	int ret;

	write_index();

	// All defaults. Bind to all interfaces, port 2001, default plugins, /tmp.
	// No callbacks are used.
	mklib_ctx ctx = mklib_init(NULL, 0, 0, "/tmp");
	if (!ctx) return 1;

	// The default has no index files, let's set index.html as one.
	ret = mklib_config(ctx, MKC_INDEXFILE, "index.html", NULL);
	if (!ret) return 1;

	// Start the server.
	mklib_start(ctx);

	// I'm now free to do my own things. I'm just going to wait for a keypress.
	printf("All set and running! Visit me, I default to localhost:2001.\n");
	printf("Press a key to exit.\n");
	getchar();

	mklib_stop(ctx);

	return 0;
}

{'repo_name': 'monkey/monkey', 'stars': '517', 'repo_language': 'C', 'file_name': 'sys_siglist.h', 'mime_type': 'text/x-c', 'hash': -7746814982924333035, 'source_dataset': 'data'}


<title>hc_nodtdstaff</title>

  EMP0001
  Margaret Martin
  Accountant
  56,000
  <var>Female</var>
  <acronym title="Yes">1230 North Ave. Dallas, Texas 98551</acronym>

{'repo_name': 'jsdom/jsdom', 'stars': '14372', 'repo_language': 'JavaScript', 'file_name': 'utils.js', 'mime_type': 'text/plain', 'hash': -8020759389929339170, 'source_dataset': 'data'}


const Sequelize = require('sequelize')
const sequelize = new Sequelize('nodejs_login1', 'root', '', {
  host: 'localhost',
  dialect: 'mysql',
  operatorsAliases: false,
})

module.exports = sequelize

{'repo_name': 'ArjunAranetaCodes/MoreCodes-Youtube', 'stars': '226', 'repo_language': 'JavaScript', 'file_name': 'Task.js', 'mime_type': 'text/plain', 'hash': 6934788253087996930, 'source_dataset': 'data'}


/*
 *  Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

/******************************************************************

 iLBC Speech Coder ANSI-C Source Code

 WebRtcIlbcfix_Vq4.c

******************************************************************/

#include "modules/audio_coding/codecs/ilbc/vq4.h"
#include "modules/audio_coding/codecs/ilbc/constants.h"

/*----------------------------------------------------------------*
 *  vector quantization
 *---------------------------------------------------------------*/

void WebRtcIlbcfix_Vq4(
    int16_t *Xq, /* quantized vector (Q13) */
    int16_t *index,
    int16_t *CB, /* codebook in Q13 */
    int16_t *X,  /* vector to quantize (Q13) */
    int16_t n_cb
                       ){
  int16_t i, j;
  int16_t pos, minindex=0;
  int16_t tmp;
  int32_t dist, mindist;

  pos = 0;
  mindist = WEBRTC_SPL_WORD32_MAX; /* start value */

  /* Find the codebook with the lowest square distance */
  for (j = 0; j < n_cb; j++) {
    tmp = X[0] - CB[pos];
    dist = tmp * tmp;
    for (i = 1; i < 4; i++) {
      tmp = X[i] - CB[pos + i];
      dist += tmp * tmp;
    }

    if (dist < mindist) {
      mindist = dist;
      minindex = j;
    }
    pos += 4;
  }

  /* Store the quantized codebook and the index */
  for (i = 0; i < 4; i++) {
    Xq[i] = CB[minindex*4 + i];
  }
  *index = minindex;
}

{'repo_name': 'Telegram-FOSS-Team/Telegram-FOSS', 'stars': '824', 'repo_language': 'Java', 'file_name': 'EmojiTextureMaker.m', 'mime_type': 'text/x-objective-c', 'hash': -4776876551632749262, 'source_dataset': 'data'}


Start new transport

    <tabset>

        <tab heading="Irc">

                Irc bot nick:
                <input type="text" ng-model="nick"/>
                Irc bot password:
                <input type="text" ng-model="password"/>
                Irc channel:
                <input type="text" ng-model="channel"/>
                Irc channel key:
                <input type="text" ng-model="channel_key"/>
                Irc server host:
                <input type="text" ng-model="host"/>
                Irc server port:
                <input type="text" ng-model="port"/>
                Use ssl:
                <input type="checkbox" ng-model="ssl"/>
                Recconnect timeout:
                <input type="text" ng-model="timeout"/>

                <button ng-click="start_irc(nick, password, channel, channel_key, host, port, ssl, timeout)"
                        class="btn">Start</button>

        </tab>

        <tab heading="XMPP">

                Bot login:
                <input type="text" ng-model="jabber_login"/>
                Bot password:
                <input type="text" ng-model="jabber_password"/>
                Jabber room:
                <input type="text" ng-model="jabber_room"/>
                Nick in room:
                <input type="text" ng-model="jabber_nick"/>
                Jabber server:
                <input type="text" ng-model="jabber_server"/>
                Jabber resource:
                <input type="text" ng-model="jabber_resource"/>
                Server port:
                <input type="text" ng-model="jabber_port"/>
                Use ssl:
                <input type="checkbox" ng-model="jabber_ssl"/>
                Recconnect timeout:
                <input type="text" ng-model="jabber_reconnect_timeout"/>

                <button ng-click="start_xmpp(jabber_nick, jabber_password, jabber_room, jabber_server, jabber_resource, jabber_port,
                jabber_ssl, jabber_reconnect_timeout)" class="btn">Start</button>

        </tab>

        <tab heading="Campfire">

                Bot nick:
                <input type="text" ng-model="campfire_nick"/>
                Campfire token:
                <input type="text" ng-model="campfire_token"/>
                Campfire room id:
                <input type="text" ng-model="campfire_room_id"/>
                Campfire subdomain:
                <input type="text" ng-model="campfire_subdomain"/>
                Reconnect timeout:
                <input type="text" ng-model="campfire_reconnect_timeout"/>

                <button ng-click="start_campfire(campfire_nick, campfire_token, campfire_room_id, campfire_subdomain, campfire_reconnect_timeout)" class="btn">Start</button>

        </tab>

        <tab heading="HipChat">

                Bot jid:
                <input type="text" ng-model="hipchat_jid"/>
                Bot password:
                <input type="text" ng-model="hipchat_password"/>
                Hipchat room:
                <input type="text" ng-model="hipchat_room"/>
                Hipchat bot nick:
                <input type="text" ng-model="hipchat_nick"/>
                Reconnect timeout:
                <input type="text" ng-model="hipchat_reconnect_timeout"/>

                <button ng-click="start_hipchat(hipchat_jid, hipchat_password, hipchat_room, hipchat_nick, hipchat_reconnect_timeout)" class="btn">Start</button>

        </tab>

        <tab heading="Skype">

                Ybot http backend host:
                <input type="text" ng-model="skype_http_host"/>
                Ybot http backend port:
                <input type="text" ng-model="skype_http_port"/>

                <button ng-click="start_skype(skype_http_host, skype_http_port)" class="btn">Start</button>

        </tab>

        <tab heading="HTTP">
            HTTP host:
            <input type="text" ng-model="http_host"/>
            HTTP port:
            <input type="text" ng-model="http_port"/>
            Bot nick:
            <input type="text" ng-model="http_bot_nick"/>

            <button ng-click="start_http(http_host, http_port, http_bot_nick)" class="btn">Start</button>
        </tab>

        <tab heading="Flowdock">
            Bot chat nick:
            <input type="text" ng-model="flowdock_nick"/>
            Bot flowdock login:
            <input type="text" ng-model="flowdock_login"/>
            Bot password:
            <input type="text" ng-model="flowdock_password"/>
            flowdock organization:
            <input type="text" ng-model="flowdock_org"/>
            flowdock flow:
            <input type="text" ng-model="flowdock_flow"/>

            <button ng-click="start_flowdock(flowdock_nick, flowdock_login, flowdock_password, flowdock_org, flowdock_flow)" class="btn">Start</button>
        </tab>

        <tab heading="TalkerApp">
            Bot chat nick:
            <input type="text" ng-model="talkerapp_nick"/>
            Bot talkerapp room:
            <input type="text" ng-model="talkerapp_room"/>
            Talkerapp token:
            <input type="text" ng-model="talkerapp_token"/>

            <button ng-click="start_talkerapp(talkerapp_nick, talkerapp_room, talkerapp_token)" class="btn">Start</button>
        </tab>
    </tabset>

{'repo_name': 'OtpChatBot/Ybot', 'stars': '197', 'repo_language': 'Erlang', 'file_name': 'ackbar.rb', 'mime_type': 'text/x-ruby', 'hash': 7304790798251594045, 'source_dataset': 'data'}


package com.b44t.messenger;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

public class DcContext {

    public final static int DC_PREF_DEFAULT_MDNS_ENABLED = 1;
    public final static int DC_PREF_DEFAULT_TRIM_ENABLED = 0;
    public final static int DC_PREF_DEFAULT_TRIM_LENGTH  = 500;

    public final static int DC_EVENT_INFO                        = 100;
    public final static int DC_EVENT_WARNING                     = 300;
    public final static int DC_EVENT_ERROR                       = 400;
    public final static int DC_EVENT_ERROR_NETWORK               = 401;
    public final static int DC_EVENT_ERROR_SELF_NOT_IN_GROUP     = 410;
    public final static int DC_EVENT_MSGS_CHANGED                = 2000;
    public final static int DC_EVENT_INCOMING_MSG                = 2005;
    public final static int DC_EVENT_MSGS_NOTICED                = 2008;
    public final static int DC_EVENT_MSG_DELIVERED               = 2010;
    public final static int DC_EVENT_MSG_FAILED                  = 2012;
    public final static int DC_EVENT_MSG_READ                    = 2015;
    public final static int DC_EVENT_CHAT_MODIFIED               = 2020;
    public final static int DC_EVENT_CHAT_EPHEMERAL_TIMER_MODIFIED = 2021;
    public final static int DC_EVENT_CONTACTS_CHANGED            = 2030;
    public final static int DC_EVENT_LOCATION_CHANGED            = 2035;
    public final static int DC_EVENT_CONFIGURE_PROGRESS          = 2041;
    public final static int DC_EVENT_IMEX_PROGRESS               = 2051;
    public final static int DC_EVENT_IMEX_FILE_WRITTEN           = 2052;
    public final static int DC_EVENT_SECUREJOIN_INVITER_PROGRESS = 2060;
    public final static int DC_EVENT_SECUREJOIN_JOINER_PROGRESS  = 2061;

    public final static int DC_IMEX_EXPORT_SELF_KEYS = 1;
    public final static int DC_IMEX_IMPORT_SELF_KEYS = 2;
    public final static int DC_IMEX_EXPORT_BACKUP    = 11;
    public final static int DC_IMEX_IMPORT_BACKUP    = 12;

    public final static int DC_GCL_VERIFIED_ONLY    = 1;
    public final static int DC_GCL_ADD_SELF         = 2;
    public final static int DC_GCL_ARCHIVED_ONLY    = 0x01;
    public final static int DC_GCL_NO_SPECIALS      = 0x02;
    public final static int DC_GCL_ADD_ALLDONE_HINT = 0x04;
    public final static int DC_GCL_FOR_FORWARDING   = 0x08;

    public final static int DC_GCM_ADDDAYMARKER = 0x01;

    public final static int DC_QR_ASK_VERIFYCONTACT = 200;
    public final static int DC_QR_ASK_VERIFYGROUP   = 202;
    public final static int DC_QR_FPR_OK            = 210;
    public final static int DC_QR_FPR_MISMATCH      = 220;
    public final static int DC_QR_FPR_WITHOUT_ADDR  = 230;
    public final static int DC_QR_ACCOUNT           = 250;
    public final static int DC_QR_WEBRTC            = 260;
    public final static int DC_QR_ADDR              = 320;
    public final static int DC_QR_TEXT              = 330;
    public final static int DC_QR_URL               = 332;
    public final static int DC_QR_ERROR             = 400;

    public final static int DC_LP_AUTH_OAUTH2          =     0x2;
    public final static int DC_LP_AUTH_NORMAL          =     0x4;

    public final static int DC_SOCKET_AUTO     = 0;
    public final static int DC_SOCKET_SSL      = 1;
    public final static int DC_SOCKET_STARTTLS = 2;
    public final static int DC_SOCKET_PLAIN    = 3;

    public final static int DC_SHOW_EMAILS_OFF               = 0;
    public final static int DC_SHOW_EMAILS_ACCEPTED_CONTACTS = 1;
    public final static int DC_SHOW_EMAILS_ALL               = 2;

    public final static int DC_MEDIA_QUALITY_BALANCED = 0;
    public final static int DC_MEDIA_QUALITY_WORSE    = 1;

    public DcContext(String osName, String dbfile) {
        contextCPtr = createContextCPtr(osName, dbfile);
    }

    public boolean isOk() {
        return contextCPtr != 0;
    }

    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        unref();
    }

    public void unref() {
        if (contextCPtr != 0) {
            unrefContextCPtr();
            contextCPtr = 0;
        }
    }

    public DcEventEmitter      getEventEmitter      () { return new DcEventEmitter(getEventEmitterCPtr()); }
    public native void         setStockTranslation  (int stockId, String translation);
    public native String       getBlobdir           ();
    public native void         configure            ();
    public native void         stopOngoingProcess   ();
    public native int          isConfigured         ();

    public native void         startIo              ();
    public native void         stopIo               ();
    public native boolean      isIoRunning          ();

    public native void         maybeNetwork         ();
    public native void         setConfig            (String key, String value);
    public void                setConfigInt         (String key, int value) { setConfig(key, Integer.toString(value)); }
    public native boolean      setConfigFromQr      (String qr);
    public native String       getConfig            (String key);
    public int                 getConfigInt         (String key) { try{return Integer.parseInt(getConfig(key));} catch(Exception e) {} return 0; }
    @Deprecated public String  getConfig            (String key, String def) { return getConfig(key); }
    @Deprecated public int     getConfigInt         (String key, int def) { return getConfigInt(key); }
    public native String       getInfo              ();
    public native String       getOauth2Url         (String addr, String redirectUrl);
    public native String       initiateKeyTransfer  ();
    public native boolean      continueKeyTransfer  (int msg_id, String setup_code);
    public native void         imex                 (int what, String dir);
    public native String       imexHasBackup        (String dir);
    public native boolean      mayBeValidAddr       (String addr);
    public native int          lookupContactIdByAddr(String addr);
    public native int[]        getContacts          (int flags, String query);
    public native int          getBlockedCount      ();
    public native int[]        getBlockedContacts   ();
    public @NonNull DcContact  getContact           (int contact_id) { return new DcContact(getContactCPtr(contact_id)); }
    public native int          createContact        (String name, String addr);
    public native void         blockContact         (int id, int block);
    public native String       getContactEncrInfo   (int contact_id);
    public native boolean      deleteContact        (int id);
    public native int          addAddressBook       (String adrbook);
    public @NonNull DcChatlist getChatlist          (int listflags, String query, int queryId) { return new DcChatlist(getChatlistCPtr(listflags, query, queryId)); }
    public @NonNull DcChat     getChat              (int chat_id) { return new DcChat(getChatCPtr(chat_id)); }
    public native void         markseenMsgs         (int msg_ids[]);
    public native void         marknoticedChat      (int chat_id);
    public native void         marknoticedContact   (int contact_id);
    public native void         setChatVisibility    (int chat_id, int visibility);
    public native int          getChatIdByContactId (int contact_id);
    public native int          createChatByContactId(int contact_id);
    public native int          createChatByMsgId    (int msg_id);
    public native int          createGroupChat      (boolean verified, String name);
    public native boolean      isContactInChat      (int chat_id, int contact_id);
    public native int          addContactToChat     (int chat_id, int contact_id);
    public native int          removeContactFromChat(int chat_id, int contact_id);
    public native void         setDraft             (int chat_id, DcMsg msg/*null=delete*/);
    public @Nullable DcMsg     getDraft             (int chat_id) { return new DcMsg(getDraftCPtr(chat_id)); }
    public native int          setChatName          (int chat_id, String name);
    public native int          setChatProfileImage  (int chat_id, String name);
    public native int[]        getChatMsgs          (int chat_id, int flags, int marker1before);
    public native int[]        searchMsgs           (int chat_id, String query);
    public native int[]        getFreshMsgs         ();
    public native int[]        getChatMedia         (int chat_id, int type1, int type2, int type3);
    public native int          getNextMedia         (int msg_id, int dir, int type1, int type2, int type3);
    public native int[]        getChatContacts      (int chat_id);
    public native int          getChatEphemeralTimer (int chat_id);
    public native boolean      setChatEphemeralTimer (int chat_id, int timer);
    public native boolean      setChatMuteDuration  (int chat_id, long duration);
    public native void         deleteChat           (int chat_id);
    public @NonNull DcMsg      getMsg               (int msg_id) { return new DcMsg(getMsgCPtr(msg_id)); }
    public native String       getMsgInfo           (int id);
    public native int          getFreshMsgCount     (int chat_id);
    public native int          estimateDeletionCount(boolean from_server, long seconds);
    public native void         deleteMsgs           (int msg_ids[]);
    public native void         forwardMsgs          (int msg_ids[], int chat_id);
    public native int          prepareMsg           (int chat_id, DcMsg msg);
    public native int          sendMsg              (int chat_id, DcMsg msg);
    public native int          sendTextMsg          (int chat_id, String text);
    public native int          sendVideochatInvitation(int chat_id);
    public native int          addDeviceMsg         (String label, DcMsg msg);
    public native boolean      wasDeviceMsgEverAdded(String label);
    public native void         updateDeviceChats    ();
    public @NonNull DcLot      checkQr              (String qr) { return new DcLot(checkQrCPtr(qr)); }
    public native String       getSecurejoinQr      (int chat_id);
    public native int          joinSecurejoin       (String qr);
    public native void         sendLocationsToChat  (int chat_id, int seconds);
    public native boolean      isSendingLocationsToChat(int chat_id);
    public @NonNull DcArray    getLocations         (int chat_id, int contact_id, long timestamp_start, long timestamp_end) { return new DcArray(getLocationsCPtr(chat_id, contact_id, timestamp_start, timestamp_end)); }
    public native void         deleteAllLocations   ();
    public @Nullable DcProvider getProviderFromEmail (String email) { long cptr = getProviderFromEmailCPtr(email); return cptr!=0 ? new DcProvider(cptr) : null; }

    /**
     * @return true if at least one chat has location streaming enabled
     */
    public native boolean      setLocation          (float latitude, float longitude, float accuracy);

    // helper to get/return strings from/to handleEvent()
    public native static boolean data2IsString(int event);

    // working with raw c-data
    private long        contextCPtr;     // CAVE: the name is referenced in the JNI
    private native long createContextCPtr(String osName, String dbfile);
    private native void unrefContextCPtr ();
    private native long getEventEmitterCPtr();
    public  native long createMsgCPtr    (int viewtype);
    private native long getChatlistCPtr  (int listflags, String query, int queryId);
    private native long getChatCPtr      (int chat_id);
    private native long getMsgCPtr       (int id);
    private native long getDraftCPtr    (int id);
    private native long getContactCPtr   (int id);
    private native long getLocationsCPtr (int chat_id, int contact_id, long timestamp_start, long timestamp_end);
    private native long checkQrCPtr      (String qr);
    private native long getProviderFromEmailCPtr  (String addr);
}

{'repo_name': 'deltachat/deltachat-android', 'stars': '549', 'repo_language': 'Java', 'file_name': 'config', 'mime_type': 'text/plain', 'hash': 8696381366733588019, 'source_dataset': 'data'}


import amqpstorm
from amqpstorm.tests.functional.utility import TestFunctionalFramework
from amqpstorm.tests.functional.utility import setup

class ExchangeFunctionalTests(TestFunctionalFramework):
    @setup(exchange=True)
    def test_functional_exchange_declare(self):
        self.channel.exchange.declare(self.exchange_name,
                                      passive=False,
                                      durable=True, auto_delete=True)
        self.assertEqual({}, self.channel.exchange.declare(self.exchange_name,
                                                           passive=True))

    @setup(exchange=True)
    def test_functional_exchange_delete(self):
        self.channel.exchange.declare(self.exchange_name)
        self.channel.exchange.delete(self.exchange_name,
                                     if_unused=True)
        self.assertRaises(amqpstorm.AMQPChannelError,
                          self.channel.exchange.declare,
                          self.exchange_name, passive=True)

    @setup(exchange=True, override_names=['exchange1', 'exchange2'])
    def test_functional_exchange_bind(self):
        self.channel.exchange.declare('exchange1')
        self.channel.exchange.declare('exchange2')

        self.assertEqual(self.channel.exchange.bind('exchange1',
                                                    'exchange2',
                                                    'routing_key'), {})

    @setup(exchange=True, override_names=['exchange1', 'exchange2'])
    def test_functional_exchange_unbind(self):
        self.channel.exchange.declare('exchange1')
        self.channel.exchange.declare('exchange2')
        self.channel.exchange.bind('exchange1', 'exchange2', 'routing_key')

        self.assertEqual(self.channel.exchange.unbind('exchange1', 'exchange2',
                                                      'routing_key'), {})

{'repo_name': 'eandersson/amqpstorm', 'stars': '116', 'repo_language': 'Python', 'file_name': 'channel.rst', 'mime_type': 'text/plain', 'hash': -3147780201870214816, 'source_dataset': 'data'}