text:
import {Options} from './Options';

/**
 * Functions that flatten/unflatten objects.
 * ---
 * Objects must be flattened into rows in order to write to a spreadsheet, and must be unflattened in order to return
 * them back as objects.
 *
 * **LIMITATIONS**
 * 1. Only strings, numbers, booleans, and arrays of those types may be written and read. Yes really.
 */
export class ObjectUtilities {
  options:Options;

  constructor(options?:Options){
    this.options = options || new Options();
  }

  convertToRows(objects:object[], headers:string[]){
    return objects.map((obj) => this.objectToRow(obj, headers));
  }

  convertToObjects(rows:any[][], headers:string[]):any[]{
    return rows.map((row) => this.rowToObject(row, headers));
  }

  // TODO: Not especially efficient. Getting headers should be seperate from flattening.
  getAllHeaders(objects:object[]){
    const flattenedObjects = objects.map((obj) => this.flatten(obj));
    const allKeys = flattenedObjects.map((flatObj) => Object.keys(flatObj)).flatMap((keys) => keys);
    const uniqueKeys = [...new Set(allKeys)].sort();
    return uniqueKeys;
  }

  /**
   * Takes two lists of headers (one from the sheet and one from new objects to be written) and combines them by
   * de-duping and appending remaining new headers to the end of the list.
   * @param existingHeaders The existing set of headers from the sheet.
   * @param newHeaders New headers you want to accommodate.
   * @returns `existingHeaders` but with unique, new values from `newHeaders` at the end.
   */
  appendMerge(existingHeaders:string[], newHeaders:string[]){
    // If the only item is a blank, we're writing headers for the first time. Don't keep that around.
    if (existingHeaders.length == 1 && existingHeaders[0] == '')
      existingHeaders = [];

    const newValues = newHeaders.filter(header => !existingHeaders.includes(header));
    return existingHeaders.concat(newValues);
  }

  ////////

  objectToRow(obj:object, headers:string[]){
    let result:string[] = [];
    let flatObject = this.flatten(obj);

    for (let i = 0; i < headers.length; i++){
      let header = headers[i];
      let value = flatObject[header];

      if (value == null || value == undefined)
        result.push('');
      else
        result.push(value);
    }

    return result;
  }

  rowToObject(row:any[], headers:string[]):object{
    if (row.length != headers.length)
      throw 'Header and row data length mismatch during rowToObject().';

    const namedFields = row.map((field, index) => {
      let header = headers[index];
      if (field !== '') return {header, field}; // Blanks never come back.
      else return null;
    });

    const flatObject:{[key:string]:any} = {};
    namedFields.forEach((tuple) => {
      if (tuple){
        flatObject[tuple.header] = tuple.field;
      }
    });

    return this.unflatten(flatObject);
  }

  flatten(target:any){
    let accumulator:{[key:string]:any} = {};

    this.innerFlatten(accumulator, target, '', '');

    return accumulator;
  }

  innerFlatten(accumulator:{[key:string]:any}, target:any, ancestry:string, name:string){
    const type = typeof target;

    switch (type) {
      // Drop these outright.  TODO: Or don't.
      case 'undefined':
      case 'function':
      case 'symbol':
        return null;

      // Special processing
      case 'object':
        this.flattenObject(accumulator, target, ancestry, name);
        break;

      // Write to accumulator: bigint, bool, number, or string.
      case 'bigint':
      case 'boolean':
      case 'number':
      case 'string':
        if (target === '') return;
        name = name.replace(/\./g, '/.');
        const key = (ancestry && name) ? ancestry + '.' + name : name;
        accumulator[key] = target;

      default:
        break;
    }
  }

  flattenObject(accumulator:{[key:string]:any}, target:any, ancestry:string, name:string){
    const isArray = Array.isArray(target);
    name = name.replace(/\./g, '/.');
    const key = (ancestry && name) ? ancestry + '.' + name : name;

    // Null: NO NULLs.
    if (target == null) return;

    // Dates: Dates get reduced to UTC timestamps.
    if (Object.prototype.toString.call(target) == '[object Date]'){
      accumulator[key] = target.toString();
    }

    // Arrays and other objects
    let iterable = isArray ? target : Object.keys(target);
    if (isArray){
      for (var i = 0; i < target.length; i++){
        this.innerFlatten(accumulator, target[i], key, i.toString());
      }

    } else {
      for (var localProperty in target) {
        this.innerFlatten(accumulator, target[localProperty], key, localProperty);
      }
    }
  }

  isKeyPartOfArray(key:string, allKeys:string[]){
    let keyParts = key.split('.');
    // Not a number? It's an object.
    if (isNaN(parseInt(keyParts[keyParts.length-1]))) return false;

    // Confirm that all equal depth keys are numbers, else this is an object.
    const siblingKeys = allKeys.filter((candidate) => {
      // All values except the last- in order- should match. That's siblings.
      return JSON.stringify(candidate.split('.').slice(0, -1)) == JSON.stringify(key.split('.').slice(0, -1));
    });

    return siblingKeys.every((key) => {
      let siblingValue = key.split('.').pop() || '';
      return !isNaN(parseInt(siblingValue));
    });
  }

  unflatten(flatObj:{[key:string]:any}):object{
    const keys = Object.keys(flatObj);
    let result:{[key:string]:any} = {};

    keys.forEach((key) => {
      let parent = result;
      let child = '';
      let keyParts = key.split('.');

      for (let i = 0; i < keyParts.length; i++){
        let currentKey = keyParts.slice(0, i + 1).join('.'); // Key to this point.
        let isArray = this.isKeyPartOfArray(currentKey, keys);
        if (!parent[child]) parent[child] = isArray ? [] : {};
        parent = parent[child];
        child = keyParts[i];
      }

      if (flatObj[key] !== '') {
        parent[child] = flatObj[key];
      } else {
        delete parent[child];
      }
    });

    return result[''];
  }

  bundleIndices(indices:number[]){
    indices = indices.sort((a,b) => a - b); // I shouldn't have to do this.
    return indices.reduce((accumulator:number[][], i) => {
      const lastSubArray = accumulator[accumulator.length - 1];

      if(!lastSubArray || lastSubArray[lastSubArray.length - 1] !== i - 1) {
        let newArray:number[] = [];
        accumulator.push(newArray);
      }

      accumulator[accumulator.length - 1].push(i);

      return accumulator;
    }, []);
  }
}


text:
package com.example.springmvc.domain.di.repository.jpa;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.example.springmvc.domain.entity.jpa.TScheduledTaskHistory;

/**
 * Spring Data JPA repository (table: t_scheduledtask_history).
 */
@Repository
//@Scope("prototype")
public interface TScheduledTaskHistoryRepository extends JpaRepository<TScheduledTaskHistory, Integer> {
}

redpajama_set_name: RedPajamaGithub


text:
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.utils import timezone
from django.views import generic
from django.views.generic.edit import CreateView
from django.contrib.auth.models import User
from .models import Choice, Poll
import csv
from django.http import HttpResponse
from .forms import ChoiceForm, PollForm, UserForm, UpdateChoiceForm
from polls.templatetags import polls_helpers

def some_view(request):
    # Create the HttpResponse object with the appropriate CSV header.
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="somefilename.csv"'

    writer = csv.writer(response)
    choices = range(len(Choice.objects.all()))
    for i, choice in zip(choices, Choice.objects.all()):
        writer.writerow([i, choice.user.username, str(choice.dob), polls_helpers.allowed(choice), choice.rumber, polls_helpers.BizzFuzzTag(choice.rumber)])
    return response

def delete_choice(request, pk):

    try:
       instance = Choice.objects.get(id=pk)
    except Choice.DoesNotExist:
        instance = None
    if not instance:
        return HttpResponseRedirect('/polls')

    pom=instance.user
    try:
        instance.delete()
    except polls.models.DoesNotExist:
        pass
    try:
        pom.delete()
    except polls.models.DoesNotExist:
        pass

    return HttpResponseRedirect('/polls')

def create_choice(request):
    # if this is a POST request we need to process the form data
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        user_form = UserForm(request.POST)
        choice_form = ChoiceForm(request.POST)
        # check whether it's valid:
        if user_form.is_valid() and choice_form.is_valid():
            dob = choice_form.cleaned_data['dob']
            new_choice = Choice.objects.create(dob=dob)
            username = user_form.cleaned_data['username']
            new_user = User.objects.create_user(username=username,
                                 email='jlennon@beatles.com',
                                 password='glass onion')
            new_user.save()
            new_choice.user=new_user
            new_choice.age=new_choice.howold()
            new_choice.save()
            return HttpResponseRedirect('/polls')

    # if a GET (or any other method) we'll create a blank form
    else:
        user_form = UserForm()
        choice_form = ChoiceForm()

    return render(request, 'polls/forms.html',  {'user_form': user_form, 'choice_form': choice_form})

def update_choice(request, pk):
    # if this is a POST request we need to process the form data
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        choice_form = UpdateChoiceForm(request.POST)
        # check whether it's valid:
        if choice_form.is_valid():
            choice_instance = Choice.objects.get(id=pk)
            dob = choice_form.cleaned_data['dob']
            choice_instance.dob = dob
            choice_instance.age=choice_instance.howold()
            choice_instance.save()
            return HttpResponseRedirect('/polls')

    # if a GET (or any other method) we'll create a blank form
    else:
        choice_instance = Choice.objects.get(id=pk)
        choice_form = UpdateChoiceForm(instance=choice_instance)

    return render(request, 'polls/forms.html',  {'choice_form': choice_form})

class IndexView(generic.ListView):
    model = Choice
    template_name = 'polls/index.html'
    context_object_name = 'lista_c'

    def get_queryset(self):
        """
        Return the last five published polls (not including those set to be
        published in the future).
        """
        return Choice.objects.all()

class ChoiceDetailView(generic.DetailView):
    model = Choice
    template_name = 'polls/detail.html'
    context_object_name = 'c'

    def get_context_data(self, **kwargs):
        context = super(ChoiceDetailView, self).get_context_data(**kwargs)
        return context

class ResultsView(generic.DetailView):
    model = Poll
    template_name = 'polls/results.html'


text:
<?php

namespace App\MainBundle\Document;

use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\Serializer\Annotation\Groups;

/**
 * @MongoDB\Document(collection="file",repositoryClass="App\Repository\FileDocumentRepository")
 * @MongoDB\HasLifecycleCallbacks()
 */
class FileDocument
{
    const OWNER_CATEGORY = 'category';
    const OWNER_DOCUMENT = 'document';
    const OWNER_TEMPORARY = 'temporary';
    const OWNER_ORDER_TEMPORARY = 'order_temporary';
    const OWNER_ORDER_PRODUCT = 'order_product';

    /**
     * @MongoDB\Id(type="int", strategy="INCREMENT")
     * @Groups({"details", "list"})
     * @var int
     */
    protected $id;

    /**
     * @MongoDB\Field(type="string")
     * @Groups({"details", "list"})
     * @var string
     */
    protected $title;

    /**
     * @MongoDB\Field(type="string")
     * @Groups({"details", "list"})
     * @var string
     */
    protected $fileName;

    /**
     * @MongoDB\Field(type="string")
     * @Groups({"details", "list"})
     * @var string
     */
    protected $originalFileName;

    /**
     * @MongoDB\Field(type="string")
     * @Groups({"details", "list"})
     * @var string
     */
    protected $extension;

    /**
     * @MongoDB\Field(type="string")
     * @Groups({"details", "list"})
     * @var string
     */
    protected $mimeType;

    /**
     * @MongoDB\Field(type="int")
     * @Groups({"details", "list"})
     * @var int
     */
    protected $size;

    /**
     * @MongoDB\Field(type="int")
     * @Groups({"details", "list"})
     * @var int
     */
    protected $downloads;

    /**
     * @MongoDB\Field(type="int")
     * @Groups({"details", "list"})
     * @var int
     */
    protected $userId;

    /**
     * @MongoDB\Field(type="string")
     * @Groups({"details"})
     * @var string
     */
    protected $ownerType;

    /**
     * @MongoDB\Field(type="string")
     * @Groups({"details"})
     * @var string
     */
    protected $ownerId;

    /**
     * @MongoDB\Field(type="int")
     * @Groups({"details"})
     * @var string
     */
    protected $ownerDocId;

    /**
     * @MongoDB\Field(type="date")
     * @Groups({"details", "list"})
     * @var \DateTime
     */
    protected $createdDate;

    /**
     * @MongoDB\ReferenceOne(targetDocument="App\MainBundle\Document\Order", storeAs="id")
     * @var Order
     */
    protected $order;

    /** @var string */
    private $uploadRootDir = '';
    /** @var  UploadedFile */
    private $file;

    /**
     * Get id
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set title
     *
     * @param string $title
     * @return $this
     */
    public function setTitle($title)
    {
        $this->title = $title;
        return $this;
    }

    /**
     * Get title
     *
     * @return string
     */
    public function getTitle()
    {
        return $this->title;
    }

    /**
     * Set extension
     *
     * @param string $extension
     * @return $this
     */
    public function setExtension($extension)
    {
        $this->extension = $extension;
        return $this;
    }

    /**
     * Get extension
     *
     * @return string
     */
    public function getExtension()
    {
        return $this->extension;
    }

    /**
     * Set mimeType
     *
     * @param string $mimeType
     * @return $this
     */
    public function setMimeType($mimeType)
    {
        $this->mimeType = $mimeType;
        return $this;
    }

    /**
     * Get mimeType
     *
     * @return string
     */
    public function getMimeType()
    {
        return $this->mimeType;
    }

    /**
     * Set ownerType
     *
     * @param string $ownerType
     * @return $this
     */
    public function setOwnerType($ownerType)
    {
        $this->ownerType = $ownerType;
        return $this;
    }

    /**
     * Get ownerType
     *
     * @return string
     */
    public function getOwnerType()
    {
        return $this->ownerType;
    }

    /**
     * Set size
     *
     * @param integer $size
     * @return $this
     */
    public function setSize($size)
    {
        $this->size = $size;
        return $this;
    }

    /**
     * Get size
     *
     * @return integer
     */
    public function getSize()
    {
        return $this->size;
    }

    /**
     * Set downloads
     *
     * @param $downloads
     * @return $this
     */
    public function setDownloads($downloads)
    {
        $this->downloads = $downloads;
        return $this;
    }

    /**
     * Get downloads
     *
     * @return integer
     */
    public function getDownloads()
    {
        return $this->downloads;
    }

    /**
     * Downloads number increment
     *
     * @param int $number
     * @return $this
     */
    public function incrementDownloads($number = 1)
    {
        if (!$this->downloads) {
            $this->downloads = 0;
        }
        $this->downloads += $number;
        return $this;
    }

    /**
     * Set userId
     *
     * @param integer $userId
     * @return $this
     */
    public function setUserId($userId)
    {
        $this->userId = $userId;
        return $this;
    }

    /**
     * Get userId
     *
     * @return integer
     */
    public function getUserId()
    {
        return $this->userId;
    }

    /**
     * Set ownerId
     *
     * @param string $ownerId
     * @return $this
     */
    public function setOwnerId($ownerId)
    {
        $this->ownerId = $ownerId;
        return $this;
    }

    /**
     * Get ownerId
     *
     * @return string
     */
    public function getOwnerId()
    {
        return $this->ownerId;
    }

    /**
     * Set ownerDocId
     *
     * @param int $ownerDocId
     * @return $this
     */
    public function setOwnerDocId($ownerDocId)
    {
        $this->ownerDocId = $ownerDocId;
        return $this;
    }

    /**
     * Get ownerDocId
     *
     * @return int
     */
    public function getOwnerDocId()
    {
        return $this->ownerDocId;
    }

    /**
     * Set fileName
     *
     * @param string $fileName
     * @return $this
     */
    public function setFileName($fileName)
    {
        $this->fileName = $fileName;
        return $this;
    }

    /**
     * Get fileName
     *
     * @return string
     */
    public function getFileName()
    {
        return $this->fileName;
    }

    /**
     * Set originalFileName
     *
     * @param string $originalFileName
     * @return $this
     */
    public function setOriginalFileName($originalFileName)
    {
        $this->originalFileName = $originalFileName;
        return $this;
    }

    /**
     * Get originalFileName
     *
     * @return string
     */
    public function getOriginalFileName()
    {
        return $this->originalFileName;
    }

    /**
     * Set createdDate
     *
     * @param \DateTime $createdDate
     * @return $this
     */
    public function setCreatedDate($createdDate)
    {
        $this->createdDate = $createdDate;
        return $this;
    }

    /**
     * Get createdDate
     *
     * @return \DateTime
     */
    public function getCreatedDate()
    {
        return $this->createdDate;
    }

    /**
     * Sets file
     * @param UploadedFile|null $file
     * @return $this
     */
    public function setFile(UploadedFile $file = null)
    {
        $this->file = $file;
        return $this;
    }

    /**
     * Get file.
     *
     * @return UploadedFile
     */
    public function getFile()
    {
        return $this->file;
    }

    /**
     * @return string
     */
    public function getFullFileName()
    {
        return $this->getFileName() . '.' . $this->getExtension();
    }

    /**
     * @return $this
     */
    public function setUniqueFileName(){
        $filename = time() . '_' . uniqid(true);
        $this->setFileName($filename);
        return $this;
    }

    /**
     * @param $uploadRootDir
     * @return $this
     */
    public function setUploadRootDir($uploadRootDir)
    {
        $this->uploadRootDir = $uploadRootDir;
        return $this;
    }

    /**
     * @return string
     */
    public function getUploadRootDir()
    {
        return $this->uploadRootDir;
    }

    public function getDirBasePath()
    {
        return $this->getCreatedDate()->format('Y/m/d');
    }

    /**
     * @return bool|null|string
     */
    public function getUploadDir()
    {
        if (!$this->getCreatedDate()) {
            $this->setCreatedDate(new \DateTime());
        }
        $uploadRootDirPath = $this->getUploadRootDir();
        if (!$uploadRootDirPath) {
            return null;
        }
        if(!is_dir($uploadRootDirPath)){
            mkdir($uploadRootDirPath);
            chmod($uploadRootDirPath, 0777);
        }
        $uploadRootDirPath = realpath($uploadRootDirPath);
        $dateArr = explode('/', $this->getDirBasePath());

        foreach ($dateArr as $num) {
            $uploadRootDirPath .= DIRECTORY_SEPARATOR . $num;
            if (!is_dir($uploadRootDirPath)) {
                mkdir($uploadRootDirPath);
                chmod($uploadRootDirPath, 0777);
            }
        }
        return $uploadRootDirPath;
    }

    /**
     * @return null|string
     */
    public function getUploadedPath()
    {
        if (!$this->getUploadDir()) {
            return null;
        }
        return $this->getUploadDir() . '/' . $this->getFullFileName();
    }

    /**
     * @return string
     */
    public function getFileUrl()
    {
        return '/uploads/' . $this->getDirBasePath() . '/' . $this->getFullFileName();
    }

    /**
     * @MongoDB\PrePersist()
     * @MongoDB\PreUpdate()
     */
    public function preUpload()
    {
        if (null !== $this->getFile()) {
            $this
                ->setUniqueFileName()
                ->setExtension(strtolower($this->getFile()->getClientOriginalExtension()))
                ->setMimeType($this->getFile()->getMimeType())
                ->setSize($this->getFile()->getSize());

            if (!$this->getTitle()) {
                $originalName = $this->getFile()->getClientOriginalName();
                $title = mb_substr($originalName, 0, mb_strrpos($originalName, '.'));
                $this->setTitle($title);
            }
            if (!$this->getOriginalFileName()) {
                $this->setOriginalFileName($this->getFile()->getClientOriginalName());
            }
        }
        $filePath = $this->getUploadedPath();
        if ($filePath && file_exists($filePath)) {
            $this->setSize(filesize($filePath));
        }
    }

    /**
     * @MongoDB\PostPersist()
     * @MongoDB\PostUpdate()
     * @return bool
     */
    public function upload()
    {
        if (null === $this->getFile()) {
            return false;
        }
        if(!$this->getFileName()){
            $this
                ->setUniqueFileName()
                ->setExtension(strtolower($this->getFile()->getClientOriginalExtension()));
        }

        $uploadDirPath = $this->getUploadDir();
        if (!is_dir($uploadDirPath)) {
            return false;
        }

        $fullFileName = $this->getFullFileName();
        $this->getFile()->move($uploadDirPath, $fullFileName);

        chmod($this->getUploadedPath(), 0775);

        $this->file = null;
        return true;
    }

    /**
     * @MongoDB\PreRemove()
     * @return bool
     */
    public function removeFile()
    {
        $fileUploadedPath = $this->getUploadedPath();
        if ($fileUploadedPath && file_exists($fileUploadedPath)) {
            unlink($fileUploadedPath);
            return true;
        }
        return false;
    }

    /**
     * Set order
     *
     * @param Order $order
     * @return $this
     */
    public function setOrder(Order $order)
    {
        $this->order = $order;
        return $this;
    }

    /**
     * Get order
     *
     * @return Order
     */
    public function getOrder()
    {
        return $this->order;
    }

    /**
     * @return array
     */
    public function toArray()
    {
        return [
            'id' => $this->getId(),
            'title' => $this->getTitle(),
            'name' => $this->getFileName(),
            'size' => $this->getSize(),
            'extension' => $this->getExtension(),
            'mimeType' => $this->getMimeType(),
            'ownerType' => $this->getOwnerType(),
            'ownerId' => $this->getOwnerId(),
            'createdDate' => $this->getCreatedDate()
        ];
    }

    /**
     * @return array
     */
    public function getRecordData()
    {
        return [
            'fileId' => $this->getId(),
            'title' => $this->getTitle(),
            'fileName' => $this->getFileName(),
            'extension' => $this->getExtension(),
            'dirPath' => $this->getDirBasePath(),
            'size' => $this->getSize()
        ];
    }
}


text:
<tool id="EMBOSS: cirdna11" name="cirdna" version="@VERSION@">
  <description>Draws circular maps of DNA constructs</description>
  <macros>
    <import>macros.xml</import>
  </macros>
  <expand macro="requirements" />
  <command>perl '$__tool_directory__/emboss_single_outputfile_wrapper.pl' cirdna -infile '$input1' -graphout png -goutfile '$out_file1' -auto</command>
  <inputs>
    <param name="input1" type="data" format="data" label="On query" />
  </inputs>
  <outputs>
    <data name="out_file1" format="png" />
  </outputs>
  <!--    <tests>
    <test>
         puts name of file into the png
    </test>
  </tests> -->
  <help>
    You can view the original documentation here_.

    .. _here: http://galaxy-iuc.github.io/emboss-5.0-docs/cirdna.html
  </help>
  <expand macro="citations" />
</tool>


text:
package org.apache.pulsar.io.kafka;

import lombok.extern.slf4j.Slf4j;
import org.testng.annotations.Test;

import java.nio.ByteBuffer;

import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotSame;
import static org.testng.Assert.assertSame;
import static org.testng.internal.junit.ArrayAsserts.assertArrayEquals;

@Slf4j
public class ByteBufferSchemaWrapperTest {

    @Test
    public void testGetBytesNoCopy() throws Exception {
        byte[] originalArray = {1, 2, 3};
        ByteBuffer wrapped = ByteBuffer.wrap(originalArray);
        assertEquals(0, wrapped.arrayOffset());
        assertEquals(3, wrapped.remaining());
        assertSame(ByteBufferSchemaWrapper.getBytes(wrapped), originalArray);
    }

    @Test
    public void testGetBytesOffsetZeroDifferentLen() throws Exception {
        byte[] originalArray = {1, 2, 3};
        ByteBuffer wrapped = ByteBuffer.wrap(originalArray, 1, 2);
        assertEquals(0, wrapped.arrayOffset());
        assertEquals(2, wrapped.remaining());
        byte[] result = ByteBufferSchemaWrapper.getBytes(wrapped);
        assertNotSame(result, originalArray);
        assertArrayEquals(result, new byte[] {2,3});
    }

    @Test
    public void testGetBytesOffsetNonZero() throws Exception {
        byte[] originalArray = {1, 2, 3};
        ByteBuffer wrapped = ByteBuffer.wrap(originalArray);
        wrapped.position(1);
        assertEquals(1, wrapped.position());
        wrapped = wrapped.slice();
        assertEquals(1, wrapped.arrayOffset());
        assertEquals(2, wrapped.remaining());
        byte[] result = ByteBufferSchemaWrapper.getBytes(wrapped);
        assertNotSame(result, originalArray);
        assertArrayEquals(result, new byte[] {2,3});
    }

    @Test
    public void testGetBytesOffsetZero() throws Exception {
        byte[] originalArray = {1, 2, 3};
        ByteBuffer wrapped = ByteBuffer.wrap(originalArray, 0, 2);
        assertEquals(0, wrapped.arrayOffset());
        assertEquals(2, wrapped.remaining());
        byte[] result = ByteBufferSchemaWrapper.getBytes(wrapped);
        assertNotSame(result, originalArray);
        assertArrayEquals(result, new byte[] {1,2});
    }

}


text:
using java.lang;

public class AutoboxingAssignLocal3 {
	public static Short test(short s) {
		Short var;
		var = s;
		return var;
	}
}


text:
package com.bazaarvoice.emodb.sdk;

import org.apache.maven.execution.MavenSession;
import org.apache.maven.model.Plugin;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.BuildPluginManager;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
import org.eclipse.aether.RepositorySystem;
import org.eclipse.aether.RepositorySystemSession;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import static org.twdata.maven.mojoexecutor.MojoExecutor.artifactId;
import static org.twdata.maven.mojoexecutor.MojoExecutor.groupId;
import static org.twdata.maven.mojoexecutor.MojoExecutor.plugin;
import static org.twdata.maven.mojoexecutor.MojoExecutor.version;

public abstract class AbstractEmoMojo extends AbstractMojo {

    @Component
    protected RepositorySystem repositorySystem;

    @Parameter(property = "session.repositorySession", required = true, readonly = true)
    protected RepositorySystemSession repositorySystemSession;

    @Parameter( defaultValue = "${project}", required = true, readonly = true )
    protected MavenProject project;

    @Parameter( defaultValue = "${session}", required = true, readonly = true )
    protected MavenSession session;

    @Component
    protected BuildPluginManager pluginManager;

    @Parameter(defaultValue = "false")
    protected boolean skip;

    @Parameter(defaultValue = "false", property = "emo.waitForInterrupt")
    protected boolean waitForInterrupt;

    @Parameter(defaultValue = "true", property = "emo.autoStartEmo")
    protected boolean autoStartEmo;

    @Parameter(defaultValue = "true", property = "emo.autoStartCassandra")
    protected boolean autoStartCassandra;

    @Parameter(defaultValue = "false", property = "emo.autoStartZookeeper")
    protected boolean autoStartZookeeper;

    @Parameter(property = "emo.zookeeperPort", defaultValue = "2181")
    protected int zookeeperPort;

    /** From this port we will compute the other ports. */
    @Parameter(property = "emo.cassandraRpcPort", defaultValue = "9160")
    protected int cassandraRpcPort;

    @Parameter(defaultValue = "8061", property = "emo.healthCheckPort")
    protected int healthCheckPort;

    @Parameter(property = "emo.cassandraMavenVersion")
    protected String cassandraMavenVersion;

    @Parameter(property = "emo.cassandraMaxMemory", defaultValue = "1000")
    protected int cassandraMaxMemory; // megabytes

    @Parameter(property = "emo.cassandraDir")
    protected String cassandraDir;

    @Parameter(property = "emo.emoDir", defaultValue = "emodb")
    protected String emoDir;

    @Parameter
    protected String emoConfigurationFile;

    @Parameter
    protected String ddlConfigurationFile;

    @Parameter(property = "emo.maxMemory", defaultValue = "1000")
    protected int emoMaxMemory; // megabytes

    @Parameter(property = "emo.debugPort", defaultValue = "-1")
    protected int emoDebugPort;

    @Parameter
    protected RoleParameter[] roles;

    @Parameter
    protected ApiKeyParameter[] apiKeys;

    @Parameter(property = "debug.suspend")
    protected boolean suspendDebugOnStartup = false;

    @Parameter(required = false)
    protected String emoLogFile;

    /** We'll expect to find a resource in *this* package that tells us the cassandra maven version to use. */
    private static final String EMO_MAVEN_PLUGIN_PROPERTIES_RESOURCE = "/emo-maven-plugin.properties";

    private static final Properties EMO_MAVEN_PLUGIN_PROPERTIES = loadEmoMavenPluginProperties();

    protected static final Plugin CASSANDRA_PLUGIN = plugin(
            groupId("com.bazaarvoice.maven.plugins"),
            artifactId("cassandra-maven-plugin"),
            version(requireEmoMavenPluginProperty("cassandra-maven-plugin.version"))
    );

    protected static File ensureDirectory(File dir) {
        if (!dir.mkdirs() && !dir.isDirectory()) {
            throw new RuntimeException("couldn't create directories: " + dir);
        }
        return dir;
    }

    private static Properties loadEmoMavenPluginProperties() {
        final Properties properties = new Properties();
        try {
            final InputStream ourPluginProperties = AbstractEmoMojo.class.getResourceAsStream(EMO_MAVEN_PLUGIN_PROPERTIES_RESOURCE);
            if (ourPluginProperties == null) {
                throw new IllegalStateException("couldn't find " + EMO_MAVEN_PLUGIN_PROPERTIES_RESOURCE + "on the classpath");
            }
            properties.load(ourPluginProperties);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return properties;
    }

    private static String requireEmoMavenPluginProperty(String key) {
        final String value = EMO_MAVEN_PLUGIN_PROPERTIES.getProperty(key);
        if (value == null || "".equals(value.trim())) {
            throw new IllegalStateException("expected to find '" + key + "' in " + EMO_MAVEN_PLUGIN_PROPERTIES_RESOURCE);
        }
        return value;
    }

}


text:
import django.dispatch

# Сигнализирует о добавлении новой сущности.
sig_entity_new = django.dispatch.Signal(providing_args=['entity'])

# Сигнализирует о публикации новой сущности.
sig_entity_published = django.dispatch.Signal(providing_args=['entity'])

# Сигнализирует о том, что пользователь проголосовал
# за материал или отозвал голос.
sig_support_changed = django.dispatch.Signal()

# Сигнализирует о поиске без результатов.
sig_search_failed = django.dispatch.Signal(providing_args=['search_term'])

# Сигнализирует о неисправности в процессах интеграции со внешними сервисами.
sig_integration_failed = django.dispatch.Signal(providing_args=['description'])


text:
using System;
using Newtonsoft.Json;
using System.Text;

namespace aaLogReader
{
    public class LogHeader : ILogHeader
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        public string LogFilePath { get; set; }

        public ulong StartMsgNumber { get; set; }

        public ulong MsgCount { get; set; }

        public ulong EndMsgNumber
        {
            get
            {
                return (ulong)(checked(this.StartMsgNumber + this.MsgCount) - 1);
            }
        }

        private ulong _startFileTime;
        private DateTimeOffset _startDateTime;

        public ulong StartFileTime
        {
            get { return _startFileTime; }
            set
            {
                _startFileTime = value;
                _startDateTime = DateTimeOffset.FromFileTime((long)value);
            }
        }

        public DateTimeOffset StartDateTime
        {
            get { return _startDateTime; }
        }

        [JsonIgnore]
        public DateTime StartDateTimeLocal
        {
            get { return _startDateTime.LocalDateTime; }
        }

        [JsonIgnore]
        public DateTime StartDateTimeUtc
        {
            get { return _startDateTime.UtcDateTime; }
        }

        private ulong _endFileTime;
        private DateTimeOffset _endDateTime;

        public ulong EndFileTime
        {
            get { return _endFileTime; }
            set
            {
                _endFileTime = value;
                _endDateTime = DateTimeOffset.FromFileTime((long)value);
            }
        }

        public DateTimeOffset EndDateTime
        {
            get { return _endDateTime; }
        }

        [JsonIgnore]
        public DateTime EndDateTimeLocal
        {
            get { return _endDateTime.LocalDateTime; }
        }

        [JsonIgnore]
        public DateTime EndDateTimeUtc
        {
            get { return _endDateTime.UtcDateTime; }
        }

        public int OffsetFirstRecord { get; set; }

        public int OffsetLastRecord { get; set; }

        public string ComputerName { get; set; }

        public string Session { get; set; }

        public string PrevFileName { get; set; }

        public string HostFQDN { get; set; }

        [JsonIgnore]
        public ReturnCodeStruct ReturnCode { get; set; }

        public string ToJSON()
        {
            return JsonConvert.SerializeObject(this);
        }

        /// <summary>
        /// Return the log header data in the form of a Key-Value Pair
        /// </summary>
        /// <param name="format">Full or Minimal</param>
        /// <returns></returns>
        public string ToKVP()
        {
            string returnValue;
            StringBuilder localSB = new StringBuilder();

            try
            {

                localSB.AppendFormat("MsgStartingNumber=\"{0}\"", this.StartMsgNumber.ToString("yyyy-MM-dd HH:mm:ss.fff"));
                localSB.AppendFormat(", MsgCount=\"{0}\"", this.MsgCount);
                localSB.AppendFormat(", MsgLastNumber=\"{0}\"", this.EndMsgNumber);
                localSB.AppendFormat(", StartDateTime=\"{0}\"", this.StartDateTime);
                localSB.AppendFormat(", EndDateTime=\"{0}\"", this.EndDateTime);
                localSB.AppendFormat(", OffsetFirstRecord=\"{0}\"", this.OffsetFirstRecord);
                localSB.AppendFormat(", OffsetLastRecord=\"{0}\"", this.OffsetLastRecord);
                localSB.AppendFormat(", ComputerName=\"{0}\"", this.ComputerName);
                localSB.AppendFormat(", Session=\"{0}\"", this.Session);
                localSB.AppendFormat(", PrevFileName=\"{0}\"", this.PrevFileName);
                localSB.AppendFormat(", HostFQDN=\"{0}\"", this.HostFQDN);

                returnValue = localSB.ToString();
            }
            catch (Exception ex)
            {
                LogException(ex);
                returnValue = "";
            }

            return returnValue;
        }

        /// <summary>
        /// Get a header for a series of log records with a delimiter
        /// </summary>
        /// <param name="Delimiter"></param>
        /// <param name="format"></param>
        /// <returns></returns>
        private string localHeader(char Delimiter = ',')
        {
            string returnValue;
            StringBuilder localSB = new StringBuilder();

            try
            {
                localSB.Append("LogFilePath");
                localSB.Append(Delimiter + "MsgStartingNumber");
                localSB.Append(Delimiter + "MsgCount");
                localSB.Append(Delimiter + "MsgLastNumber");
                localSB.Append(Delimiter + "StartDateTime");
                localSB.Append(Delimiter + "StartFileTime");
                localSB.Append(Delimiter + "EndDateTime");
                localSB.Append(Delimiter + "EndFileTime");
                localSB.Append(Delimiter + "OffsetFirstRecord");
                localSB.Append(Delimiter + "OffsetLastRecord");
                localSB.Append(Delimiter + "ComputerName");
                localSB.Append(Delimiter + "Session");
                localSB.Append(Delimiter + "PrevFileName");
                localSB.Append(Delimiter + "HostFQDN");

                returnValue = localSB.ToString();
            }
            catch (Exception ex)
            {
                LogException(ex);
                returnValue = "";
            }

            return returnValue;
        }

        public static string Header(char Delimiter = ',')
        {
            LogHeader lh = new LogHeader();
            return lh.localHeader(Delimiter);
        }

        public static string HeaderCSV()
        {
            return LogHeader.Header(',');
        }

        public static string HeaderTSV()
        {
            return LogHeader.Header('\t');
        }

        /// <summary>
        ///  Get the lastRecordRead in the form of a delimited string
        /// </summary>
        /// <param name="Delimiter">Delimiter to Use</param>
        /// <param name="format">Full or Minimal</param>
        /// <returns></returns>
        public string ToDelimitedString(char Delimiter = ',')
        {

            string returnValue;
            StringBuilder localSB = new StringBuilder();

            try
            {
                localSB.Append("\"" + this.LogFilePath + "\"");
                localSB.Append(Delimiter + this.StartMsgNumber.ToString());
                localSB.Append(Delimiter + this.MsgCount.ToString());
                localSB.Append(Delimiter + this.EndMsgNumber.ToString());
                localSB.Append(Delimiter + "\"" + this.StartDateTime.ToString("yyyy-MM-dd HH:mm:ss.fff") + "\"");
                localSB.Append(Delimiter + this.StartFileTime.ToString());
                localSB.Append(Delimiter + "\"" + this.EndDateTime.ToString("yyyy-MM-dd HH:mm:ss.fff") + "\"");
                localSB.Append(Delimiter + this.EndFileTime.ToString());
                localSB.Append(Delimiter + this.OffsetFirstRecord.ToString());
                localSB.Append(Delimiter + this.OffsetLastRecord.ToString());
                localSB.Append(Delimiter + "\"" + this.ComputerName + "\"");
                localSB.Append(Delimiter + this.Session);
                localSB.Append(Delimiter + "\"" + this.PrevFileName + "\"");
                localSB.Append(Delimiter + "\"" + this.HostFQDN + "\"");

                returnValue = localSB.ToString();
            }
            catch (Exception ex)
            {
                LogException(ex);
                returnValue = "";
            }

            return returnValue;
        }

        public string ToCSV()
        {
            return this.ToDelimitedString(',');
        }

        public string ToTSV()
        {
            return this.ToDelimitedString('\t');
        }

#if NET45_OR_GREATER
        private void LogException(Exception ex, [CallerMemberName]string methodName = "")
        {
#else
        [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
        private void LogException(Exception ex)
        {
            string methodName = new System.Diagnostics.StackFrame(1, false).GetMethod().Name;
#endif
            log.Error(string.Format("{0}: {1} - {2}", methodName, ex.GetType().Name, ex.Message), ex);
        }
    }
}


text:
@interface INTF
- (id) foo __attribute__((warn_unused_result));
- (void) garf __attribute__((warn_unused_result)); // expected-warning {{attribute 'warn_unused_result' cannot be applied to Objective-C method without return value}}
- (int) fee __attribute__((warn_unused_result));
+ (int) c __attribute__((warn_unused_result));
@end

void foo(INTF *a) {
  [a garf];
  [a fee]; // expected-warning {{ignoring return value of function declared with 'warn_unused_result' attribute}}
  [INTF c]; // expected-warning {{ignoring return value of function declared with 'warn_unused_result' attribute}}
}


text:
using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using MasterDetailApp.ViewModels;
using MasterDetailApp.Models;
using ReactiveProperty.XamarinAndroid;
using ReactiveProperty.XamarinAndroid.Extensions;

namespace MasterDetailApp.Views
{
    [Activity(Label = "MasterDetailApp", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : ListActivity
    {
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            var viewModel = new MainActivityViewModel(this, AppContext.Instance);
            this.ListAdapter = viewModel.People.ToAdapter(
                (_, __) => LayoutInflater.FromContext(this).Inflate(Android.Resource.Layout.SimpleListItem1, null),
                (_, x, v) => v.FindViewById<TextView>(Android.Resource.Id.Text1).SetBinding(y => y.Text, x.Name),
                (_, x) => x.Person.Id);
        }
    }
}


text:
/**
    @author Benjamin Livshits <livshits@cs.stanford.edu>

    $Id: Inter2.java,v 1.4 2006/04/04 20:00:40 livshits Exp $
 */
package securibench.micro.inter;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import securibench.micro.BasicTestCase;
import securibench.micro.MicroTestCase;

/**
 *  @servlet description="simple id method call"
 *  @servlet vuln_count = "2"
 *  */
public class Inter2 extends BasicTestCase implements MicroTestCase {
    private static final String FIELD_NAME = "name";

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String s1 = req.getParameter(FIELD_NAME);

        PrintWriter writer = resp.getWriter();
        String s2 = id(s1, writer);
        String s3 = id("abc", writer);
        writer.println(s2);         /* BAD */   // Is this double-reporting?..
        writer.println(s3);         /* OK */
    }

    private String id(String string, PrintWriter writer) {
        writer.println(string); /* BAD */

        return string;
    }

    public String getDescription() {
        return "simple id method call";
    }

    public int getVulnerabilityCount() {
        return 2;
    }
}


text:
from flask import Flask, render_template, request

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/menu-link')
def menu_link():
    return 'Menu Link Clicked'

@app.route('/contact', methods=['POST'])
def submit():
    return '{name} sent {message}'.format(
            name=request.form['name'],
            message=request.form['message'])

if __name__ == '__main__':
    app.run(debug=True)


text:
@class WDLayer;

@interface WDAddImage : WDSimpleDocumentChange

@property (nonatomic) NSUInteger layerIndex;
@property (nonatomic) NSString *mediaType;
@property (nonatomic, assign) BOOL mergeDown;
@property (nonatomic) NSData *imageData;
@property (nonatomic) NSString *imageHash;
@property (nonatomic) NSString *layerUUID;
@property (nonatomic, assign) CGAffineTransform transform;

+ (WDAddImage *) addImage:(UIImage *)image atIndex:(NSUInteger)index mergeDown:(BOOL)mergeDown transform:(CGAffineTransform)transform;

@end


text:
package urchin.cli.user;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import urchin.cli.BasicCommand;
import urchin.cli.Command;
import urchin.model.user.LinuxUser;

import java.util.Arrays;

@Component
public class GetShadowCommand extends BasicCommand {

    private static final String GET_SHADOW = "get-shadow";
    private static final String USERNAME = "%username%";

    private final Command command;

    @Autowired
    public GetShadowCommand(Runtime runtime, Command command) {
        super(runtime);
        this.command = command;
    }

    public String execute(LinuxUser linuxUser) {
        return executeCommand(command.getUserCommand(GET_SHADOW).replace(USERNAME, linuxUser.getUsername().getValue()))
                .map(shadow -> parseResponse(linuxUser, shadow))
                .orElseThrow(RuntimeException::new);
    }

    private String parseResponse(LinuxUser linuxUser, String response) {
        return Arrays.stream(response.split(System.lineSeparator()))
                .filter(line -> line.startsWith(linuxUser.getUsername().getValue()))
                .findFirst()
                .map(s -> s.replaceFirst(String.format("%s:", linuxUser.getUsername().getValue()), ""))
                .orElseThrow(RuntimeException::new);
    }
}


text:
EALANG:=erlc

local:
	${EALANG} prog.erl
	#erl -noshell -s sample main -s init stop

wandbox:
	make -C . local --no-print-directory EALANG="wandbox-erlc run"


text:
package org.camunda.bpm.engine.impl.cmd;

import org.camunda.bpm.engine.impl.interceptor.CommandContext;
import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity;
import org.camunda.bpm.engine.impl.util.ModificationUtil;

/**
 * @author Thorben Lindhauer
 *
 */
public abstract class AbstractInstanceCancellationCmd extends AbstractProcessInstanceModificationCommand {

  protected String cancellationReason;

  public AbstractInstanceCancellationCmd(String processInstanceId) {
    super(processInstanceId);
    this.cancellationReason = "Cancellation due to process instance modifcation";
  }

  public AbstractInstanceCancellationCmd(String processInstanceId, String cancellationReason) {
    super(processInstanceId);
    this.cancellationReason = cancellationReason;
  }

  public Void execute(CommandContext commandContext) {
    ExecutionEntity sourceInstanceExecution = determineSourceInstanceExecution(commandContext);

    // Outline:
    // 1. find topmost scope execution beginning at scopeExecution that has exactly
    //    one child (this is the topmost scope we can cancel)
    // 2. cancel all children of the topmost execution
    // 3. cancel the activity of the topmost execution itself (if applicable)
    // 4. remove topmost execution (and concurrent parent) if topmostExecution is not the process instance

    ExecutionEntity topmostCancellableExecution = sourceInstanceExecution;
    ExecutionEntity parentScopeExecution = (ExecutionEntity) topmostCancellableExecution.getParentScopeExecution(false);

    // if topmostCancellableExecution's scope execution has no other non-event-scope children,
    // we have reached the correct execution
    while (parentScopeExecution != null && (parentScopeExecution.getNonEventScopeExecutions().size() <= 1)) {
        topmostCancellableExecution = parentScopeExecution;
        parentScopeExecution = (ExecutionEntity) topmostCancellableExecution.getParentScopeExecution(false);
    }

    if (topmostCancellableExecution.isPreserveScope()) {
      topmostCancellableExecution.interrupt(cancellationReason, skipCustomListeners, skipIoMappings, externallyTerminated);
      topmostCancellableExecution.leaveActivityInstance();
      topmostCancellableExecution.setActivity(null);
    } else {
      topmostCancellableExecution.deleteCascade(cancellationReason, skipCustomListeners, skipIoMappings, externallyTerminated, false);
      ModificationUtil.handleChildRemovalInScope(topmostCancellableExecution);
    }

    return null;
  }

  protected abstract ExecutionEntity determineSourceInstanceExecution(CommandContext commandContext);

  protected ExecutionEntity findSuperExecution(ExecutionEntity parentScopeExecution, ExecutionEntity topmostCancellableExecution){
    ExecutionEntity superExecution = null;
    if(parentScopeExecution == null) {
      superExecution = topmostCancellableExecution.getSuperExecution();

    }
    return superExecution;
  }

}


text:
const isNeeded = require('./isNeeded');
const initializeInheritance = require('./initializeInheritance');
const addToRules = require('./addToRules');
const merge = require('./merge');
const getAppliedConditions = require('./getAppliedConditions');
const getArguments = require('./getArguments');

class Inheritance {
  constructor(parameters){
    this.throwError = this.throwError.bind(this);
    this.apply = this.apply.bind(this);
    this.applyHierarchy = this.applyHierarchy.bind(this);
    this.incrementSourceTally = this.incrementSourceTally.bind(this);
    this.initializeInheritance( parameters );
  }

  incrementSourceTally(id){
    if( !this.sourceTally[ id ] ){
      this.sourceTally[ id ] = 0;
    }
    this.sourceTally[ id ]++;
  }

  throwError( message ){
    this.error = message;
    throw new Error( message );
  }

  apply(){
    if( this.documents ){
      this.applyHierarchy();
    }
    return this;
  }

  applyHierarchy(){

    const ahjsByRootType = this.documents.reduce((result, ahj) => {
      const addToResult = (type, doc) => {
        if( !result[type] ){
          result[type] = [ doc ];
        } else {
          result[type].push( doc );
        }
      };
      const isRoot = !(ahj.inheritance && ahj.inheritance.ancestors);
      if(isRoot){
        if(this.isNeeded(ahj)){
          addToResult(ahj.type, ahj);
          const descendants = (ahj.inheritance||{}).descendants;
          if( descendants ) descendants.map( docId => {
            addToResult(ahj.type, this.documentMap[docId]);
          });
        }
      }
      return result;
    }, {});

    this.order = this.hierarchy.reduce( (results, ahjType) => {
      // organzize by hierarchy level and root hierarchy level for inherited/linked ahjs
      if( ahjsByRootType[ ahjType ] ) {
        ahjsByRootType[ ahjType ].map( ahj => {
          //filter out same type unless inherited/linked to same type
          if( !this.neededTypes.includes(ahj.type) || ahjType === ahj.type ){
            this.neededTypes.push(ahj.type);
            results.push( ahj.id );
          }
        });
      }
      return results;
    }, []);

    return this;
  }
}

Inheritance.prototype.getAppliedConditions = getAppliedConditions;
Inheritance.prototype.isNeeded = isNeeded;
Inheritance.prototype.initializeInheritance = initializeInheritance;
Inheritance.prototype.addToRules = addToRules;
Inheritance.prototype.merge = merge;
Inheritance.prototype.getArguments = getArguments;

module.exports = Inheritance;


text:
@interface PodsDummy_Pods_EVTTabPageScrollView_Example : NSObject
@end
@implementation PodsDummy_Pods_EVTTabPageScrollView_Example
@end


text:
require 'helper'

describe 'Sasl' do

  # https://github.com/seattlerb/minitest/issues/298
  def self.xit(msg, &block)
  end

  describe 'a server requiring authentication' do
    before do
      @server = mock()
      @server.stubs(:request).returns(true)
      @server.stubs(:weight).returns(1)
      @server.stubs(:hostname).returns("localhost")
      @server.stubs(:port).returns("19124")
    end

    describe 'without authentication credentials' do
      before do
        ENV['MEMCACHE_USERNAME'] = 'foo'
        ENV['MEMCACHE_PASSWORD'] = 'wrongpwd'
      end

      after do
        ENV['MEMCACHE_USERNAME'] = nil
        ENV['MEMCACHE_PASSWORD'] = nil
      end

      it 'provide one test that passes' do
        assert true
      end

      it 'gracefully handle authentication failures' do
        memcached(19124, '-S') do |dc|
          assert_error Dalli::DalliError, /32/ do
            dc.set('abc', 123)
          end
        end
      end
    end

    it 'fail SASL authentication with wrong options' do
      memcached(19124, '-S') do |dc|
        dc = Dalli::Client.new('localhost:19124', :username => 'foo', :password => 'wrongpwd')
        assert_error Dalli::DalliError, /32/ do
          dc.set('abc', 123)
        end
      end
    end

    # OSX: Create a SASL user for the memcached application like so:
    #
    # saslpasswd2 -a memcached -c testuser
    #
    # with password 'testtest'
    describe 'in an authenticated environment' do
      before do
        ENV['MEMCACHE_USERNAME'] = 'testuser'
        ENV['MEMCACHE_PASSWORD'] = 'testtest'
      end

      after do
        ENV['MEMCACHE_USERNAME'] = nil
        ENV['MEMCACHE_PASSWORD'] = nil
      end

      xit 'pass SASL authentication' do
        memcached(19124, '-S') do |dc|
          # I get "Dalli::DalliError: Error authenticating: 32" in OSX
          # but SASL works on Heroku servers. YMMV.
          assert_equal true, dc.set('abc', 123)
          assert_equal 123, dc.get('abc')
          results = dc.stats
          assert_equal 1, results.size
          assert_equal 38, results.values.first.size
        end
      end
    end

    xit 'pass SASL authentication with options' do
      memcached(19124, '-S') do |dc|
        dc = Dalli::Client.new('localhost:19124', :username => 'testuser', :password => 'testtest')
        # I get "Dalli::DalliError: Error authenticating: 32" in OSX
        # but SASL works on Heroku servers. YMMV.
        assert_equal true, dc.set('abc', 123)
        assert_equal 123, dc.get('abc')
        results = dc.stats
        assert_equal 1, results.size
        assert_equal 38, results.values.first.size
      end
    end

    it 'pass SASL as URI' do
      Dalli::Server.expects(:new).with("localhost:19124",
        :username => "testuser", :password => "testtest").returns(@server)
      dc = Dalli::Client.new('memcached://testuser:testtest@localhost:19124')
      dc.flush_all
    end

    it 'pass SASL as ring of URIs' do
      Dalli::Server.expects(:new).with("localhost:19124",
        :username => "testuser", :password => "testtest").returns(@server)
      Dalli::Server.expects(:new).with("otherhost:19125",
        :username => "testuser2", :password => "testtest2").returns(@server)
      dc = Dalli::Client.new(['memcached://testuser:testtest@localhost:19124',
      'memcached://testuser2:testtest2@otherhost:19125'])
      dc.flush_all
    end
  end
end


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="pdsd.systems.cs.pub.ro.practicaltest01var01.PracticalTest01Var01SecondaryActivity">

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editText"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Ok"
        android:id="@+id/ok_button"
        android:layout_below="@+id/editText"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="43dp" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Cancel"
        android:id="@+id/cancel_button"
        android:layout_alignTop="@+id/ok_button"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />
</RelativeLayout>


text:
.. _developing_testing:

***************
Testing Ansible
***************

.. contents:: Topics
   :local:

Why test your Ansible contributions?
====================================

If you're a developer, one of the most valuable things you can do is to look at GitHub issues and help fix bugs, since bug-fixing is almost always prioritized over feature development.  Even for non-developers, helping to test pull requests for bug fixes and features is still immensely valuable.

Ansible users who understand how to write playbooks and roles should be able to test their work.  GitHub pull requests will automatically run a variety of tests (e.g., Shippable) that show bugs in action.  However, contributors must also test their work outside of the automated GitHub checks and show evidence of these tests in the PR to ensure that their work will be more likely to be reviewed and merged.

Read on to learn how Ansible is tested, how to test your contributions locally, and how to extend testing capabilities.

Types of tests
==============

At a high level we have the following classifications of tests:

:compile:
  * :ref:`testing_compile`
  * Test python code against a variety of Python versions.
:sanity:
  * :ref:`testing_sanity`
  * Sanity tests are made up of scripts and tools used to perform static code analysis.
  * The primary purpose of these tests is to enforce Ansible coding standards and requirements.
:integration:
  * :ref:`testing_integration`
  * Functional tests of modules and Ansible core functionality.
:units:
  * :ref:`testing_units`
  * Tests directly against individual parts of the code base.

If you're a developer, one of the most valuable things you can do is look at the GitHub
issues list and help fix bugs.  We almost always prioritize bug fixing over feature
development.

Even for non developers, helping to test pull requests for bug fixes and features is still
immensely valuable.  Ansible users who understand writing playbooks and roles should be
able to add integration tests and so GitHub pull requests with integration tests that show
bugs in action will also be a great way to help.

Testing within GitHub & Shippable
=================================

Organization
------------

When Pull Requests (PRs) are created they are tested using Shippable, a Continuous Integration (CI) tool. Results are shown at the end of every PR.

When Shippable detects an error and it can be linked back to a file that has been modified in the PR then the relevant lines will be added as a GitHub comment. For example::

   The test `ansible-test sanity --test pep8` failed with the following errors:

   lib/ansible/modules/network/foo/bar.py:509:17: E265 block comment should start with '# '

   The test `ansible-test sanity --test validate-modules` failed with the following errors:
   lib/ansible/modules/network/foo/bar.py:0:0: E307 version_added should be 2.4. Currently 2.3
   lib/ansible/modules/network/foo/bar.py:0:0: E316 ANSIBLE_METADATA.metadata_version: required key not provided @ data['metadata_version']. Got None

From the above example we can see that ``--test pep8`` and ``--test validate-modules`` have identified issues. The commands given allow you to run the same tests locally to ensure you've fixed the issues without having to push your changed to GitHub and wait for Shippable, for example:

If you haven't already got Ansible available, use the local checkout by running::

  source hacking/env-setup

Then run the tests detailed in the GitHub comment::

  ansible-test sanity --test pep8
  ansible-test sanity --test validate-modules

If there isn't a GitHub comment stating what's failed you can inspect the results by clicking on the "Details" button under the "checks have failed" message at the end of the PR.

Rerunning a failing CI job
--------------------------

Occasionally you may find your PR fails due to a reason unrelated to your change. This could happen for several reasons, including:

* a temporary issue accessing an external resource, such as a yum or git repo
* a timeout creating a virtual machine to run the tests on

If either of these issues appear to be the case, you can rerun the Shippable test by:

* closing and re-opening the PR
* making another change to the PR and pushing to GitHub

If the issue persists, please contact us in ``#ansible-devel`` on Freenode IRC.

How to test a PR
================

Ideally, code should add tests that prove that the code works. That's not always possible and tests are not always comprehensive, especially when a user doesn't have access to a wide variety of platforms, or is using an API or web service. In these cases, live testing against real equipment can be more valuable than automation that runs against simulated interfaces. In any case, things should always be tested manually the first time as well.

Thankfully, helping to test Ansible is pretty straightforward, assuming you are familiar with how Ansible works.

Setup: Checking out a Pull Request
----------------------------------

You can do this by:

* checking out Ansible
* making a test branch off the main branch
* merging a GitHub issue
* testing
* commenting on that particular issue on GitHub

Here's how:

.. warning::
   Testing source code from GitHub pull requests sent to us does have some inherent risk, as the source code
   sent may have mistakes or malicious code that could have a negative impact on your system. We recommend
   doing all testing on a virtual machine, whether a cloud instance, or locally.  Some users like Vagrant
   or Docker for this, but they are optional. It is also useful to have virtual machines of different Linux or
   other flavors, since some features (apt vs. yum, for example) are specific to those OS versions.

Create a fresh area to work::

   git clone https://github.com/ansible/ansible.git ansible-pr-testing
   cd ansible-pr-testing

Next, find the pull request you'd like to test and make note of the line at the top which describes the source
and destination repositories. It will look something like this::

   Someuser wants to merge 1 commit into ansible:devel from someuser:feature_branch_name

.. note:: Only test ``ansible:devel``

   It is important that the PR request target be ``ansible:devel``, as we do not accept pull requests into any other branch. Dot releases are cherry-picked manually by Ansible staff.

The username and branch at the end are the important parts, which will be turned into git commands as follows::

   git checkout -b testing_PRXXXX devel
   git pull https://github.com/someuser/ansible.git feature_branch_name

The first command creates and switches to a new branch named ``testing_PRXXXX``, where the XXXX is the actual issue number associated with the pull request (for example, 1234). This branch is based on the ``devel`` branch. The second command pulls the new code from the users feature branch into the newly created branch.

.. note::
   If the GitHub user interface shows that the pull request will not merge cleanly, we do not recommend proceeding if you are not somewhat familiar with git and coding, as you will have to resolve a merge conflict. This is the responsibility of the original pull request contributor.

.. note::
   Some users do not create feature branches, which can cause problems when they have multiple, unrelated commits in their version of ``devel``. If the source looks like ``someuser:devel``, make sure there is only one commit listed on the pull request.

The Ansible source includes a script that allows you to use Ansible directly from source without requiring a
full installation that is frequently used by developers on Ansible.

Simply source it (to use the Linux/Unix terminology) to begin using it immediately::

   source ./hacking/env-setup

This script modifies the ``PYTHONPATH`` environment variables (along with a few other things), which will be temporarily
set as long as your shell session is open.

Testing the Pull Request
------------------------

At this point, you should be ready to begin testing!

Some ideas of what to test are:

* Create a test Playbook with the examples in and check if they function correctly
* Test to see if any Python backtraces returned (that's a bug)
* Test on different operating systems, or against different library versions

Any potential issues should be added as comments on the pull request (and it's acceptable to comment if the feature works as well), remembering to include the output of ``ansible --version``

Example::

   Works for me! Tested on `Ansible 2.3.0`.  I verified this on CentOS 6.5 and also Ubuntu 14.04.

If the PR does not resolve the issue, or if you see any failures from the unit/integration tests, just include that output instead:

   | This doesn't work for me.
   |
   | When I ran this Ubuntu 16.04 it failed with the following:
   |
   |   \```
   |   some output
   |   StackTrace
   |   some other output
   |   \```

Code Coverage Online
````````````````````

`The online code coverage reports <https://codecov.io/gh/ansible/ansible>`_ are a good way
to identify areas for testing improvement in Ansible.  By following red colors you can
drill down through the reports to find files which have no tests at all.  Adding both
integration and unit tests which show clearly how code should work, verify important
Ansible functions and increase testing coverage in areas where there is none is a valuable
way to help improve Ansible.

The code coverage reports only cover the ``devel`` branch of Ansible where new feature
development takes place.  Pull requests and new code will be missing from the codecov.io
coverage reports so local reporting is needed.  Most ``ansible-test`` commands allow you
to collect code coverage, this is particularly useful to indicate where to extend
testing. See :ref:`testing_running_locally` for more information.

Want to know more about testing?
================================

If you'd like to know more about the plans for improving testing Ansible then why not join the
`Testing Working Group <https://github.com/ansible/community/blob/master/meetings/README.md>`_.


text:
SQuangLe
========

Overview
--------

SQuangLe is a C++ MySQL client library built on top of
[WebScaleSQL](http://webscalesql.org/)'s C client library. It does not require
a WebScaleSQL server - WebScaleSQL, MySQL, MariaDB, and Percona Server should
all work fine.

Current Status
--------------

**THIS IS AN EARLY PREVIEW RELEASE**

 - Expect the API to change
 - Documentation is not ready for release
 - Automated tests are not included - they exist, however they require Facebook
   infrastructure to run, so releasing them seemed more confusing than useful

In particular, we plan to move everything from the various namespaces to
'squangle'.

We have released it at this early stage as it is a dependency of other Facebook
projects.

Features
--------

 - Object-oriented API
 - Query builder with automatic escaping
 - Asynchronous query execution

License
-------

SQuangLe is BSD-licensed. We also provide an additional patent grant. Please
see the LICENSE and PATENTS files.

Contributing
------------

Please see CONTRIBUTING.md