text:
package com.flockinger.spongeblogSP.security;

import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup;

import java.nio.charset.Charset;

import org.flywaydb.test.annotation.FlywayTest;
import org.flywaydb.test.junit.FlywayTestExecutionListener;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener;
import org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener;
import org.springframework.http.MediaType;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.security.test.context.support.WithSecurityContextTestExecutionListener;
import org.springframework.security.web.FilterChainProxy;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.context.WebApplicationContext;

@RunWith(SpringRunner.class)
@SpringBootTest
@WebAppConfiguration
@ActiveProfiles(profiles = {"default", "test"})
@TestExecutionListeners({DependencyInjectionTestExecutionListener.class,
    FlywayTestExecutionListener.class, MockitoTestExecutionListener.class,
    ResetMocksTestExecutionListener.class, WithSecurityContextTestExecutionListener.class})
@FlywayTest(invokeCleanDB = true, locationsForMigrate = {"/db/migration","/db/testfill/"})
public class SecurityConfigTest {

  private MockMvc mockMvc;

  protected MediaType jsonContentType = new MediaType(MediaType.APPLICATION_JSON.getType(),
      MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));

  @Autowired
  private WebApplicationContext webApplicationContext;

  @Autowired
  private FilterChainProxy filterChain;

  @Before
  public void setup() throws Exception {
    this.mockMvc = webAppContextSetup(webApplicationContext)
        .apply(springSecurity())
        .addFilters(filterChain).build();

    SecurityContextHolder.clearContext();
  }

  @Test
  public void testRoot_withUnauthorized_shouldBeRedirectedToSwaggerPage() throws Exception {
    mockMvc.perform(get("/").contentType(jsonContentType)).andExpect(status().is3xxRedirection());
  }

  @Test
  @WithMockUser(authorities = {"AUTHOR"})
  public void testRoot_withBasicUser_shouldBeRedirectedToSwaggerPage() throws Exception {
    mockMvc.perform(get("/").contentType(jsonContentType) )
        .andExpect(status().is3xxRedirection());
  }

  @Test
  @WithMockUser(authorities = {"ADMIN"})
  public void testRoot_withAdmin_shouldReturnCorrect() throws Exception {
    mockMvc.perform(get("/").contentType(jsonContentType))
        .andExpect(status().is3xxRedirection());
  }

  @Test
  public void testSwagger_withUnauthorized_shouldReturn401() throws Exception {
    mockMvc.perform(get("/swagger-ui.html").contentType(jsonContentType))
        .andExpect(status().isForbidden());
  }

  @Test
  @WithMockUser(authorities = {"AUTHOR"})
  public void testSwagger_withBasicUser_shouldReturn403() throws Exception {
    mockMvc
        .perform(
            get("/swagger-ui.html").contentType(jsonContentType) )
        .andExpect(status().isForbidden());
  }

  @Test
  @WithMockUser(authorities = {"ADMIN"})
  public void testSwagger_withAdmin_shouldReturnCorrect() throws Exception {
    mockMvc
        .perform(
            get("/swagger-ui.html").contentType(jsonContentType)  )
        .andExpect(status().isOk());
  }

  @Test
  public void testGetBlog_withAnonymous_shouldReturnCorrect() throws Exception {
    mockMvc.perform(get("/api/v1/blog").contentType(jsonContentType)).andExpect(status().isOk());
  }

  @Test
  public void testGetCategories_withAnonymous_shouldReturnCorrect() throws Exception {
    mockMvc.perform(get("/api/v1/categories").contentType(jsonContentType))
        .andExpect(status().isOk());
  }

  @Test
  public void testGetCategory_withAnonymous_shouldReturnCorrect() throws Exception {
    mockMvc.perform(get("/api/v1/categories/1").contentType(jsonContentType))
        .andExpect(status().isOk());
  }

  @Test
  public void testGetCagegoryChildren_withAnonymous_shouldReturnCorrect() throws Exception {
    mockMvc.perform(get("/api/v1/categories/children/1").contentType(jsonContentType))
        .andExpect(status().isOk());
  }

  // TODO activate when implementedd
  /*
   * @Test public void testGetImages_withAnonymous_shouldReturnCorrect() throws Exception {
   * mockMvc.perform(get("/api/v1/images") .contentType(jsonContentType))
   * .andExpect(status().isOk()); }
   *
   * @Test public void testGetImagesWithKey_withAnonymous_shouldReturnCorrect() throws Exception {
   * mockMvc.perform(get("/api/v1/images/1_bla.jpg") .contentType(jsonContentType))
   * .andExpect(status().isOk()); }
   *
   * @Test public void testGetImageLink_withAnonymous_shouldReturnCorrect() throws Exception {
   * mockMvc.perform(get("/api/v1/images/link/1_bla.jpg") .contentType(jsonContentType))
   * .andExpect(status().isOk()); }
   */

  @Test
  public void testGetPosts_withAnonymous_shouldReturnCorrect() throws Exception {
    mockMvc.perform(get("/api/v1/posts").contentType(jsonContentType)).andExpect(status().isOk());
  }

  @Test
  public void testGetPost_withAnonymous_shouldReturnCorrect() throws Exception {
    mockMvc.perform(get("/api/v1/posts/1").contentType(jsonContentType)).andExpect(status().isOk());
  }

  @Test
  public void testGetPostsStatus_withAnonymous_shouldReturnCorrect() throws Exception {
    mockMvc.perform(get("/api/v1/posts/status/PUBLIC").contentType(jsonContentType))
        .andExpect(status().isOk());
  }

  @Test
  public void testGetPostsTag_withAnonymous_shouldReturnCorrect() throws Exception {
    mockMvc.perform(get("/api/v1/posts/tag/1").contentType(jsonContentType))
        .andExpect(status().isOk());
  }

  @Test
  public void testGetPostsTagStatus_withAnonymous_shouldReturnCorrect() throws Exception {
    mockMvc.perform(get("/api/v1/posts/tag/1/PUBLIC").contentType(jsonContentType))
        .andExpect(status().isOk());
  }

  @Test
  public void testGetPostsCategory_withAnonymous_shouldReturnCorrect() throws Exception {
    mockMvc.perform(get("/api/v1/posts/category/1").contentType(jsonContentType))
        .andExpect(status().isOk());
  }

  @Test
  public void testGetPostsCategoryStatus_withAnonymous_shouldReturnCorrect() throws Exception {
    mockMvc.perform(get("/api/v1/posts/category/1/PUBLIC").contentType(jsonContentType))
        .andExpect(status().isOk());
  }

  @Test
  public void testGetTags_withAnonymous_shouldReturnCorrect() throws Exception {
    mockMvc.perform(get("/api/v1/tags").contentType(jsonContentType)).andExpect(status().isOk());
  }

  @Test
  public void testGetTag_withAnonymous_shouldReturnCorrect() throws Exception {
    mockMvc.perform(get("/api/v1/tags/1").contentType(jsonContentType)).andExpect(status().isOk());
  }

  @Test
  public void testGetUserInfo_withAnonymous_shouldReturnCorrect() throws Exception {
    mockMvc.perform(get("/api/v1/users/info/1").contentType(jsonContentType))
        .andExpect(status().isOk());
  }

  @Test
  public void testChangeBlog_withAnonymous_shouldReturn401() throws Exception {
    mockMvc.perform(post("/api/v1/blog").contentType(jsonContentType))
        .andExpect(status().isForbidden());

    mockMvc.perform(delete("/api/v1/blog").contentType(jsonContentType))
        .andExpect(status().isForbidden());

    mockMvc.perform(put("/api/v1/blog").contentType(jsonContentType))
        .andExpect(status().isForbidden());

    mockMvc.perform(put("/api/v1/blog/rewind").contentType(jsonContentType))
        .andExpect(status().isForbidden());
  }

  @Test
  @WithMockUser(authorities = {"AUTHOR"})
  public void testChangeBlog_withUser_shouldReturn403() throws Exception {
    mockMvc
        .perform(post("/api/v1/blog").contentType(jsonContentType) )
        .andExpect(status().isForbidden());

    mockMvc
        .perform(
            delete("/api/v1/blog").contentType(jsonContentType) )
        .andExpect(status().isForbidden());

    mockMvc
        .perform(put("/api/v1/blog").contentType(jsonContentType) )
        .andExpect(status().isForbidden());

    mockMvc
        .perform(
            put("/api/v1/blog/rewind").contentType(jsonContentType) )
        .andExpect(status().isForbidden());
  }

  @Test
  @WithMockUser(authorities = {"ADMIN"})
  @FlywayTest(locationsForMigrate = {"/db/testfill/"})
  public void testChangeBlog_withAdmin_shouldReturnWork() throws Exception {
    mockMvc
        .perform(post("/api/v1/blog").contentType(jsonContentType)  )
        .andExpect(status().isBadRequest());

    mockMvc
        .perform(
            delete("/api/v1/blog").contentType(jsonContentType)  )
        .andExpect(status().isOk());

    mockMvc
        .perform(put("/api/v1/blog").contentType(jsonContentType)  )
        .andExpect(status().isBadRequest());

    mockMvc
        .perform(put("/api/v1/blog/rewind")
            .contentType(jsonContentType)  )
        .andExpect(status().isOk());
  }

  @Test
  public void testChangeCategory_withAnonymous_shouldReturn401() throws Exception {
    mockMvc.perform(post("/api/v1/categories").contentType(jsonContentType))
        .andExpect(status().isForbidden());

    mockMvc.perform(delete("/api/v1/categories/1").contentType(jsonContentType))
        .andExpect(status().isForbidden());

    mockMvc.perform(put("/api/v1/categories").contentType(jsonContentType))
        .andExpect(status().isForbidden());

    mockMvc.perform(put("/api/v1/categories/rewind/1").contentType(jsonContentType))
        .andExpect(status().isForbidden());
  }

  @Test
  @WithMockUser(authorities = {"AUTHOR"})
  public void testChangeCategory_withUser_shouldReturn403() throws Exception {
    mockMvc
        .perform(
            post("/api/v1/categories").contentType(jsonContentType) )
        .andExpect(status().isForbidden());

    mockMvc
        .perform(delete("/api/v1/categories/1")
            .contentType(jsonContentType) )
        .andExpect(status().isForbidden());

    mockMvc
        .perform(
            put("/api/v1/categories").contentType(jsonContentType) )
        .andExpect(status().isForbidden());

    mockMvc
        .perform(put("/api/v1/categories/rewind/1")
            .contentType(jsonContentType) )
        .andExpect(status().isForbidden());
  }

  @Test
  @WithMockUser(authorities = {"ADMIN"})
  @FlywayTest(locationsForMigrate = {"/db/testfill/"})
  public void testChangeCategory_withAdmin_shouldReturnWork() throws Exception {
    mockMvc
        .perform(post("/api/v1/categories")
            .contentType(jsonContentType)  )
        .andExpect(status().isBadRequest());

    mockMvc
        .perform(delete("/api/v1/categories/1")
            .contentType(jsonContentType)  )
        .andExpect(status().isConflict());

    mockMvc
        .perform(
            put("/api/v1/categories").contentType(jsonContentType)  )
        .andExpect(status().isBadRequest());

    mockMvc
        .perform(put("/api/v1/categorie/rewind/1")
            .contentType(jsonContentType)  )
        .andExpect(status().isNotFound());
  }

  // TODO activate when images implemented
  /*
   * @Test public void testChangeImage_withAnonymous_shouldReturn401() throws Exception {
   * mockMvc.perform(post("/api/v1/images") .contentType(jsonContentType))
   * .andExpect(status().isUnauthorized());
   *
   * mockMvc.perform(delete("/api/v1/images/1_bla.jpg") .contentType(jsonContentType))
   * .andExpect(status().isUnauthorized()); }
   *
   * @Test public void testChangeImage_withUser_shouldReturn403() throws Exception {
   * mockMvc.perform(post("/api/v1/images") .contentType(jsonContentType).headers(getUserHeaders()))
   * .andExpect(status().isForbidden());
   *
   * mockMvc.perform(delete("/api/v1/images/1_bla.jpg")
   * .contentType(jsonContentType).headers(getUserHeaders())) .andExpect(status().isForbidden()); }
   *
   * @Test
   *
   * @FlywayTest(locationsForMigrate = { "/db/testfill/" }) public void
   * testChangeImage_withAdmin_shouldReturnWork() throws Exception {
   * mockMvc.perform(post("/api/v1/images")
   * .contentType(jsonContentType)) .andExpect(status().isBadRequest());
   *
   * mockMvc.perform(delete("/api/v1/images/1_bla.jpg")
   * .contentType(jsonContentType)) .andExpect(status().isOk()); }
   */

  @Test
  public void testChangeOrWeirdAccessPost_withAnonymous_shouldReturn401() throws Exception {
    mockMvc.perform(post("/api/v1/posts").contentType(jsonContentType))
        .andExpect(status().isForbidden());

    mockMvc.perform(delete("/api/v1/posts/1").contentType(jsonContentType))
        .andExpect(status().isForbidden());

    mockMvc.perform(put("/api/v1/posts").contentType(jsonContentType))
        .andExpect(status().isForbidden());

    mockMvc.perform(put("/api/v1/posts/rewind/1").contentType(jsonContentType))
        .andExpect(status().isForbidden());
  }

  @Test
  @WithMockUser(authorities = {"AUTHOR"})
  @FlywayTest(locationsForMigrate = {"/db/testfill/"})
  public void testChangeOrWeirdAccessPost_withUser_shouldReturnWork() throws Exception {
    mockMvc
        .perform(get("/api/v1/posts/author/1")
            .contentType(jsonContentType) )
        .andExpect(status().isOk());

    mockMvc
        .perform(get("/api/v1/posts/author/1/PUBLIC")
            .contentType(jsonContentType) )
        .andExpect(status().isOk());

    mockMvc
        .perform(post("/api/v1/posts").contentType(jsonContentType) )
        .andExpect(status().isBadRequest());

    mockMvc
        .perform(
            delete("/api/v1/posts/1").contentType(jsonContentType) )
        .andExpect(status().isOk());

    mockMvc
        .perform(put("/api/v1/posts").contentType(jsonContentType) )
        .andExpect(status().isBadRequest());

    mockMvc
        .perform(put("/api/v1/posts/rewind/1")
            .contentType(jsonContentType) )
        .andExpect(status().isConflict());
  }

  @Test
  @WithMockUser(authorities = {"ADMIN"})
  @FlywayTest(locationsForMigrate = {"/db/testfill/"})
  public void testChangeOrWeirdAccessPost_withAdmin_shouldReturnWork() throws Exception {
    mockMvc
        .perform(get("/api/v1/posts/author/1")
            .contentType(jsonContentType)  )
        .andExpect(status().isOk());

    mockMvc.perform(get("/api/v1/posts/author/1/PUBLIC").contentType(jsonContentType)
      ).andExpect(status().isOk());

    mockMvc
        .perform(
            post("/api/v1/posts").contentType(jsonContentType)  )
        .andExpect(status().isBadRequest());

    mockMvc
        .perform(
            delete("/api/v1/posts/1").contentType(jsonContentType)  )
        .andExpect(status().isOk());

    mockMvc
        .perform(put("/api/v1/posts").contentType(jsonContentType)  )
        .andExpect(status().isBadRequest());

    mockMvc
        .perform(put("/api/v1/posts/rewind/1")
            .contentType(jsonContentType)  )
        .andExpect(status().isConflict());
  }

  @Test
  public void testChangeTags_withAnonymous_shouldReturn401() throws Exception {

    mockMvc.perform(post("/api/v1/tags").contentType(jsonContentType))
        .andExpect(status().isForbidden());

    mockMvc.perform(delete("/api/v1/tags/1").contentType(jsonContentType))
        .andExpect(status().isForbidden());

    mockMvc.perform(put("/api/v1/tags").contentType(jsonContentType))
        .andExpect(status().isForbidden());

    mockMvc.perform(put("/api/v1/tags/rewind/1").contentType(jsonContentType))
        .andExpect(status().isForbidden());
  }

  @Test
  @WithMockUser(authorities = {"AUTHOR"})
  public void testChangeTags_withUser_shouldReturnWork() throws Exception {

    mockMvc
        .perform(post("/api/v1/tags").contentType(jsonContentType) )
        .andExpect(status().isForbidden());

    mockMvc
        .perform(
            delete("/api/v1/tags/1").contentType(jsonContentType) )
        .andExpect(status().isForbidden());

    mockMvc
        .perform(put("/api/v1/tags").contentType(jsonContentType) )
        .andExpect(status().isForbidden());

    mockMvc
        .perform(put("/api/v1/tags/rewind/1")
            .contentType(jsonContentType) )
        .andExpect(status().isForbidden());
  }

  @Test
  @WithMockUser(authorities = {"ADMIN"})
  @FlywayTest(locationsForMigrate = {"/db/testfill/"})
  public void testChangeTags_withAdmin_shouldReturnWork() throws Exception {

    mockMvc
        .perform(post("/api/v1/tags").contentType(jsonContentType)  )
        .andExpect(status().isBadRequest());

    mockMvc
        .perform(
            delete("/api/v1/tags/1").contentType(jsonContentType)  )
        .andExpect(status().isOk());

    mockMvc
        .perform(put("/api/v1/tags").contentType(jsonContentType)  )
        .andExpect(status().isBadRequest());

    mockMvc
        .perform(put("/api/v1/tags/rewind/1")
            .contentType(jsonContentType)  )
        .andExpect(status().isConflict());
  }

  @Test
  public void testChangeUser_withAnonymous_shouldReturn401() throws Exception {

    mockMvc.perform(get("/api/v1/users").contentType(jsonContentType))
        .andExpect(status().isForbidden());

    mockMvc.perform(get("/api/v1/users/1").contentType(jsonContentType))
        .andExpect(status().isForbidden());

    mockMvc.perform(post("/api/v1/users").contentType(jsonContentType))
        .andExpect(status().isForbidden());

    mockMvc.perform(delete("/api/v1/users/1").contentType(jsonContentType))
        .andExpect(status().isForbidden());

    mockMvc.perform(put("/api/v1/users").contentType(jsonContentType))
        .andExpect(status().isForbidden());

    mockMvc.perform(put("/api/v1/users/rewind/1").contentType(jsonContentType))
        .andExpect(status().isForbidden());
  }

  @Test
  @WithMockUser(authorities = {"AUTHOR"})
  @FlywayTest(locationsForMigrate = {"/db/testfill/"})
  public void testChangeUser_withUser_shouldReturnWork() throws Exception {

    mockMvc
        .perform(get("/api/v1/users").contentType(jsonContentType) )
        .andExpect(status().isForbidden());

    mockMvc
        .perform(
            get("/api/v1/users/1").contentType(jsonContentType) )
        .andExpect(status().isForbidden());

    mockMvc
        .perform(post("/api/v1/users").contentType(jsonContentType) )
        .andExpect(status().isForbidden());

    mockMvc
        .perform(
            delete("/api/v1/users/1").contentType(jsonContentType) )
        .andExpect(status().isForbidden());

    mockMvc
        .perform(put("/api/v1/users").contentType(jsonContentType) )
        .andExpect(status().isForbidden());

    mockMvc
        .perform(put("/api/v1/users/rewind/1")
            .contentType(jsonContentType) )
        .andExpect(status().isForbidden());
  }

  @Test
  @WithMockUser(authorities = {"ADMIN"})
  @FlywayTest(locationsForMigrate = {"/db/testfill/"})
  public void testChangeUser_withAdmin_shouldReturnWork() throws Exception {

    mockMvc
        .perform(get("/api/v1/users").contentType(jsonContentType)  )
        .andExpect(status().isOk());

    mockMvc
        .perform(
            get("/api/v1/users/1").contentType(jsonContentType)  )
        .andExpect(status().isOk());

    mockMvc
        .perform(
            post("/api/v1/users").contentType(jsonContentType)  )
        .andExpect(status().isBadRequest());

    mockMvc
        .perform(
            delete("/api/v1/users/2").contentType(jsonContentType)  )
        .andExpect(status().isOk());

    mockMvc
        .perform(put("/api/v1/users").contentType(jsonContentType)  )
        .andExpect(status().isBadRequest());

    mockMvc
        .perform(put("/api/v1/users/rewind/2")
            .contentType(jsonContentType)  )
        .andExpect(status().isConflict());
  }
}

redpajama_set_name: RedPajamaGithub


text:
package org.jesterj.ingest.model;

import org.jesterj.ingest.logging.Markers;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

/*
 * Created with IntelliJ IDEA.
 * User: gus
 * Date: 10/19/16
 */
public class StatusTest {

  @Test
  public void testStatusMarkers() {
    assertEquals(Status.BATCHED.getMarker(), Markers.SET_READY);
    assertEquals(Status.DIRTY.getMarker(), Markers.SET_DIRTY);
    assertEquals(Status.DEAD.getMarker(), Markers.SET_DEAD);
    assertEquals(Status.DROPPED.getMarker(), Markers.SET_DROPPED);
    assertEquals(Status.ERROR.getMarker(), Markers.SET_ERROR);
    assertEquals(Status.INDEXED.getMarker(), Markers.SET_INDEXED);
    assertEquals(Status.PROCESSING.getMarker(), Markers.SET_PROCESSING);
    assertEquals(Status.SEARCHABLE.getMarker(), Markers.SET_SEARCHABLE);
  }
}


text:
<?php

namespace Stripe;

class TransferTest extends TestCase
{
    // The resource that was traditionally called "transfer" became a "payout"
    // in API version 2017-04-06. We're testing traditional transfers here, so
    // we force the API version just prior anywhere that we need to.
    private $opts = array('stripe_version' => '2017-02-14');

    public function testCreate()
    {
        $transfer = self::createTestTransfer(array(), $this->opts);
        $this->assertSame('transfer', $transfer->object);
    }

    public function testRetrieve()
    {
        $transfer = self::createTestTransfer(array(), $this->opts);
        $reloaded = Transfer::retrieve($transfer->id, $this->opts);
        $this->assertSame($reloaded->id, $transfer->id);
    }

    public function testTransferUpdateMetadata()
    {
        $transfer = self::createTestTransfer(array(), $this->opts);

        $transfer->metadata['test'] = 'foo bar';
        $transfer->save();

        $updatedTransfer = Transfer::retrieve($transfer->id, $this->opts);
        $this->assertSame('foo bar', $updatedTransfer->metadata['test']);
    }

    public function testTransferUpdateMetadataAll()
    {
        $transfer = self::createTestTransfer(array(), $this->opts);

        $transfer->metadata = array('test' => 'foo bar');
        $transfer->save();

        $updatedTransfer = Transfer::retrieve($transfer->id, $this->opts);
        $this->assertSame('foo bar', $updatedTransfer->metadata['test']);
    }
}


text:
<?php

namespace Oro\Bundle\WorkflowBundle\Form;

use Doctrine\Common\Persistence\ManagerRegistry;
use Doctrine\Common\Persistence\Mapping\ClassMetadata;
use Doctrine\ORM\ORMException;
use Oro\Bundle\WorkflowBundle\Model\Variable;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\PropertyAccess\PropertyAccess;

class WorkflowVariableDataTransformer implements DataTransformerInterface
{
    /** @var ManagerRegistry */
    protected $managerRegistry;

    /** @var Variable|null */
    protected $variable;

    /**
     * @param ManagerRegistry $managerRegistry
     * @param Variable $variable
     */
    public function __construct(ManagerRegistry $managerRegistry, Variable $variable = null)
    {
        $this->managerRegistry = $managerRegistry;
        $this->variable = $variable;
    }

    /**
     * @param mixed $entity
     *
     * @return mixed
     */
    public function transform($entity)
    {
        return $entity;
    }

    /**
     * @param mixed $entity
     *
     * @return string
     */
    public function reverseTransform($entity)
    {
        $class = is_object($entity) ? get_class($entity) : null;
        $metadata = $this->getMetadataForClass($class);
        if (!$metadata) {
            return '';
        }

        $identifier = null;
        if ($this->variable instanceof Variable) {
            $identifier = $this->variable->getOption('identifier');
        }

        if (!$identifier) {
            $identifierFields = $metadata->getIdentifierFieldNames();
            if (!isset($identifierFields[0])) {
                return '';
            }
            $identifier = $identifierFields[0];
        }

        $accessor = PropertyAccess::createPropertyAccessor();
        try {
            return $accessor->getValue($entity, $identifier);
        } catch (\RuntimeException $e) {
            return '';
        }
    }

    /**
     * @param null|string $class
     * @return null|ClassMetadata
     */
    protected function getMetadataForClass($class)
    {
        try {
            $entityManager = $this->managerRegistry->getManagerForClass($class);
        } catch (ORMException $e) {
            return null;
        }

        return $entityManager ? $entityManager->getClassMetadata($class) : null;
    }
}


text:
<!DOCTYPE html>

    <meta charset="UTF-8"/>
    <link href="https://fonts.googleapis.com/css?family=Space+Mono" rel="stylesheet">
    <link rel="stylesheet" type="text/css" href="css/picture-puzzle.css"/>
    <title>Tetris</title>

Game Over

<button class="rotate-right" id="rotateRight"> ↺</button>
<button class="rotate-left" id="rotateLeft">↻</button>
<button class="rotate-left" id="moveLeft">↻</button>

        Move # :

        <button id="backStateButton" class="move-left-button" tabindex="10">←</button>
        <button id="dropShapeButton" class="drop-shape-button" tabindex="11">Drop Shape</button>
        <button id="forwardStateButton" class="move-right-button" tabindex="12">→</button>

                <button id="resetStateButton" class="reset-state-button" tabindex="11">New Game</button>


text:
<?php

namespace Igorw\Silex;

use Symfony\Component\Yaml\Yaml;

class YamlConfigDriver implements ConfigDriver
{
    public function load($filename)
    {
        if (!class_exists('Symfony\\Component\\Yaml\\Yaml')) {
            throw new \RuntimeException('Unable to read yaml as the Symfony Yaml Component is not installed.');
        }
        $config = Yaml::parse($filename);
        return $config ?: array();
    }

    public function supports($filename)
    {
        return (bool) preg_match('#\.ya?ml(\.dist)?$#', $filename);
    }
}


text:
using System;
using Umbraco.Cms.Core.Events;
using Umbraco.Cms.Core.Models.Entities;
using Umbraco.Cms.Core.Notifications;
using Umbraco.Cms.Core.Sync;

namespace Umbraco.Cms.Core.Cache
{
    /// <summary>
    /// A base class for cache refreshers that handles events.
    /// </summary>
    /// <typeparam name="TInstanceType">The actual cache refresher type.</typeparam>
    /// <remarks>The actual cache refresher type is used for strongly typed events.</remarks>
    public abstract class CacheRefresherBase<TNotification> : ICacheRefresher
        where TNotification : CacheRefresherNotification
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="CacheRefresherBase{TInstanceType}"/>.
        /// </summary>
        /// <param name="appCaches">A cache helper.</param>
        protected CacheRefresherBase(AppCaches appCaches, IEventAggregator eventAggregator, ICacheRefresherNotificationFactory factory)
        {
            AppCaches = appCaches;
            EventAggregator = eventAggregator;
            NotificationFactory = factory;
        }

        #region Define

        /// <summary>
        /// Gets the unique identifier of the refresher.
        /// </summary>
        public abstract Guid RefresherUniqueId { get; }

        /// <summary>
        /// Gets the name of the refresher.
        /// </summary>
        public abstract string Name { get; }

        /// <summary>
        /// Gets the <see cref="TNotificationFactory"/> for <see cref="TNotification"/>
        /// </summary>
        protected ICacheRefresherNotificationFactory NotificationFactory { get; }

        #endregion

        #region Refresher

        /// <summary>
        /// Refreshes all entities.
        /// </summary>
        public virtual void RefreshAll()
        {
            // NOTE: We pass in string.Empty here because if we pass in NULL this causes problems with
            // the underlying ActivatorUtilities.CreateInstance which doesn't seem to support passing in
            // null to an 'object' parameter and we end up with "A suitable constructor for type 'ZYZ' could not be located."
            // In this case, all cache refreshers should be checking for the type first before checking for a msg value
            // so this shouldn't cause any issues.
            OnCacheUpdated(NotificationFactory.Create<TNotification>(string.Empty, MessageType.RefreshAll));
        }

        /// <summary>
        /// Refreshes an entity.
        /// </summary>
        /// <param name="id">The entity's identifier.</param>
        public virtual void Refresh(int id)
        {
            OnCacheUpdated(NotificationFactory.Create<TNotification>(id, MessageType.RefreshById));
        }

        /// <summary>
        /// Refreshes an entity.
        /// </summary>
        /// <param name="id">The entity's identifier.</param>
        public virtual void Refresh(Guid id)
        {
            OnCacheUpdated(NotificationFactory.Create<TNotification>(id, MessageType.RefreshById));
        }

        /// <summary>
        /// Removes an entity.
        /// </summary>
        /// <param name="id">The entity's identifier.</param>
        public virtual void Remove(int id)
        {
            OnCacheUpdated(NotificationFactory.Create<TNotification>(id, MessageType.RemoveById));
        }

        #endregion

        #region Protected

        /// <summary>
        /// Gets the cache helper.
        /// </summary>
        protected AppCaches AppCaches { get; }

        protected IEventAggregator EventAggregator { get; }

        /// <summary>
        /// Clears the cache for all repository entities of a specified type.
        /// </summary>
        /// <typeparam name="TEntity">The type of the entities.</typeparam>
        protected void ClearAllIsolatedCacheByEntityType<TEntity>()
            where TEntity : class, IEntity
        {
            AppCaches.IsolatedCaches.ClearCache<TEntity>();
        }

        /// <summary>
        /// Raises the CacheUpdated event.
        /// </summary>
        /// <param name="sender">The event sender.</param>
        /// <param name="args">The event arguments.</param>
        protected void OnCacheUpdated(CacheRefresherNotification notification)
        {
            EventAggregator.Publish(notification);
        }

        #endregion
    }
}


text:
/**
 * Module dependencies
 */
var Hapi = require('hapi')
  , allowCrossDomain = require('./cors')
  , amqp = require('amqp')
  , path = require('path')
  , tskl = require('../../../lib')
  , tokenManager  = require('../../../lib/sec/token')
  , http = require("http")
  , debug = require('debug')('tskl:demoapp')

var proServers = [
   { name:'Cloud1', host: 'ec2-54-247-13-87.eu-west-1.compute.amazonaws.com' }
 , { name:'Cloud2', host: 'ec2-54-228-126-145.eu-west-1.compute.amazonaws.com' }
 , { name:'Cloud3', host: 'ec2-79-125-102-226.eu-west-1.compute.amazonaws.com' }
];

var devServers = [
   { name:'Cloud1', host: '192.168.1.33' }
 , { name:'Cloud2', host: '192.168.1.37' }
 , { name:'Cloud3', host: '192.168.1.36' }
];

const DEFAULT_SERVER_PROTOCOL = 'http';
const DEFAULT_SERVER_PORT = 8080;

/**
 * RabbitMQ queue name to share private keys between the servers
 */
const EXCHANGE_NAME = 'tskl-key-exchange';
const QUEUE_NAME_PREFIX = 'tskl-key-queue_';

var started = false, exchange, mqConnections = [];

/**
 * Creates and initializes the server according to the settings.
 *
 * Example:
 *
 *  appBase.init({port: "8080"});
 */
module.exports.init = function (settings) {

  if ( !settings.serverName ) { throw "The 'serverName' is required parameter"; }

  var server = Hapi.createServer('0.0.0.0', DEFAULT_SERVER_PORT, { cors: {exposedHeaders: ['Authorization']}, files: { relativeTo: 'routes' } });

  server.route({
    method: 'GET',
    path: '/{path*}',
    handler:{
        directory: {
            path: './public',
            listing: true
        }
    }
  });

  // App routes
  server.route({
    method: 'GET',
    path: '/status',
    handler: function () {
      var status = {
        keys : tskl.serverKeys(),
        remainingToRenew : tskl.remainingToRenew(),
        started: started
      };
      this.reply(status);
    }
  });

  server.route({
    method: 'GET',
    path: '/start',
    handler: function () {
      var servers;
      if ( this.info.referrer ) {
        servers = ( this.info.referrer.indexOf('localhost') == -1 ) ? proServers : devServers;
      } else {
        servers = proServers;
      }

      settings.host = this.info.host.split(":")[0];

      for ( var f = 0, F = servers.length; f < F; f++ ) {
        var server = servers[f];
        rabbitConnect(server);
      }

      tskl.init({serverName: settings.serverName, port: settings.port, onNewKey: onNewKey});

      started = true;

      this.reply(settings.host + " started.");

    }
  });

  server.route({
    method: 'GET',
    path: '/login',
    handler: function () {
      if ( !this.query.hasOwnProperty("email") && !this.query.hasOwnProperty("pass") && !this.query.hasOwnProperty("origin") ) {
        return this.reply(400);
      }

      var user = {
        email : this.query.email,
        pass : this.query.pass,
        origin : this.query.origin
      };

      var expiresIn, scope = "scope1 scope2";
      if ( this.query.hasOwnProperty("expires_in") ) {
        expiresIn = Number(this.query.expires_in);
      } else {
        expiresIn = 0;
      }

      if ( this.query.hasOwnProperty("scope") ) {
        scope = this.query.scope;
      }

      var json = { access_token : tskl.token.create(user.origin, user.email, scope, expiresIn), expires_in : expiresIn };
      this.reply(json);
    }
  });

  // Protected API

  server.route({
    method: 'GET',
    path: '/protected_resource',
    handler: function () {
      var authHeader = this.raw.req.headers['authorization'];
      if ( !authHeader ) {
        return this.reply( Hapi.error.unauthorized() );
      }

      var encryptedToken = /TSKL (.*)/.exec(authHeader)[1];
      if ( !encryptedToken ) {
        debug("Invalid auth header: ", authHeader);
        return this.reply( Hapi.error.unauthorized() );
      }

      var token = tokenManager.decrypt(encryptedToken);

      if ( token == null ) {
        debug("Invalid encrypted token: ", encryptedToken);
        return this.reply( Hapi.error.unauthorized() );
      }

      // Renew access token
      if ( token.expiresIn != 0  && (token.creation + token.expiresIn) * 1000 <= new Date().getTime() ) {
        debug("Expired token: ", encryptedToken);
        return this.reply( Hapi.error.unauthorized() );
      }

      debug("Valid token: ", token);

      var response = this.reply(JSON.stringify(token, undefined, 2));

      if ( token.expiresIn == 0 ) {

        var newToken = tokenManager.renew(token);
        response.header('Authorization', 'TSKL ' + newToken);

        debug("New token: ", newToken);

      }
    }
  });

  server.route({
    method: 'GET',
    path: '/stop',
    handler: function () {
      debug(" [x] Stopping tskl renew interval...")
      tskl.end();

      var f, F;
      for ( f = 0, F = mqConnections.length; f < F; f++ ) {
        debug(" [x] Closing connection...")
        mqConnections[f].end();
      }
      debug(" [x] All connection has been closed.");

      mqConnections = [];
      exchange = undefined;
      started = false;

      this.reply('OK');
    }
  });

  server.route({
    method: 'GET',
    path: '/propage-keys',
    handler: function () {
      if ( !this.query.origin || !this.query.newKey ) { return this.reply(Hapi.error.badRequest()) }

      tskl.addKey(this.query.origin, this.query.newKey);

      if ( exchange ) {
        debug("Propage the server keys");
        var serverKeys = tskl.serverKeys();
        for ( var f = 0, F = serverKeys.length; f < F; f++ ) {
          var server = serverKeys[f];
          var g;
          if ( server.name != this.query.origin ) {
            for ( g = server.keys.length - 1; g >= 0; g-- ) {
              exchange.publish('#', { key: server.keys[g], origin: server.name });
            }
          }
        }
      }

      this.reply({keys: tskl.serverKeys(this.query.origin)});
    }
  });

  server.route({
    method: 'GET',
    path: '/get-servers',
    handler: function () {
      var servers;
      if ( this.info.host ) {
        servers = ( this.info.host.indexOf('localhost') == -1 ) ? proServers : devServers;
      } else {
        servers = proServers;
      }

      var json = {
        servers : servers,
        protocol : DEFAULT_SERVER_PROTOCOL,
        port : DEFAULT_SERVER_PORT
      };
      this.reply(json);
    }
  });

  function rabbitConnect (server) {
    debug("Rabbit trying connect to: " + server.name + ' (' + server.host + ')');

    var connection = amqp.createConnection({ host: server.host }, {reconnect: false});

    connection.on('error', function(err){
      debug("Rabbit[" + server.name + "] error: ", err.message);
    });

    connection.on('close',function () {
      debug("Rabbit[" + server.name + "] Connection Closed!")
    });

    // Wait for connection to become established.
    connection.on('ready',function () {
      debug('Rabbit connected to ' + server.name);
      mqConnections.push(connection);

      // An exchange of type fanout, send message to all known queues
      connection.exchange(EXCHANGE_NAME, {type:'fanout'}, function(ex) {

        if ( server.name !== settings.serverName ) {
            var queueName = QUEUE_NAME_PREFIX + settings.serverName;
            connection.queue(queueName, function(q){

            // # == Catch all messages
            q.bind(ex, '#');
            debug('Rabbit queue[' + queueName + '] binded on server[' + server.name + ']');

            q.subscribe(function (message) {
              debug("Rabbit message: ", message);
              tskl.addKey(message.origin, message.key);
            });

            // Get current server keys
            var propageUrl = DEFAULT_SERVER_PROTOCOL + '://' + server.host;

            // Add port if the current environment is dev
            if ( devServers.indexOf(server) != -1 ) {
              propageUrl += ':' + DEFAULT_SERVER_PORT;
            }

            propageUrl += '/propage-keys?origin=' + settings.serverName + '&newKey=' + tskl.currentKey();
            debug("Request " + server.name + "'s keys, propageUrl: ", propageUrl);

            http.get(propageUrl, function(res) {
              var body = '';

              res.on('data', function(chunk) {
                  body += chunk;
              });

              res.on('end', function() {
                  var json = JSON.parse(body);
                  tskl.serverKeys(settings.serverName, json.keys);
              });
            }).on('error', function(e) {
              debug('Propage keys fails: The application ' + server.name + ' is down: ', e)
            });
          });

        } else {
          exchange = ex;
        }

      });
    });
  }

  /**
   * TSKL
   */
  function onNewKey (newKey) {
    if ( exchange ) {
      debug("Propage new key: " + newKey);
      exchange.publish('#', { key: newKey, origin: settings.serverName });
    }
  }

  server.start();
  debug("Running " + settings.serverName + " on port: " + DEFAULT_SERVER_PORT);

}


text:
import Prefixer from 'inline-style-prefixer';
import plugin from './vendorPrefixer';

export default function vendorPrefixer(prefixer = new Prefixer()) {
  return plugin(prefixer.prefix.bind(prefixer));
}


text:
package org.apache.stratos.messaging.message.processor.topology;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.stratos.messaging.domain.topology.Cluster;
import org.apache.stratos.messaging.domain.topology.Member;
import org.apache.stratos.messaging.domain.topology.Service;
import org.apache.stratos.messaging.domain.topology.Topology;
import org.apache.stratos.messaging.event.topology.MemberCreatedEvent;
import org.apache.stratos.messaging.message.filter.topology.TopologyApplicationFilter;
import org.apache.stratos.messaging.message.filter.topology.TopologyClusterFilter;
import org.apache.stratos.messaging.message.filter.topology.TopologyServiceFilter;
import org.apache.stratos.messaging.message.processor.MessageProcessor;
import org.apache.stratos.messaging.message.processor.topology.updater.TopologyUpdater;
import org.apache.stratos.messaging.message.receiver.topology.TopologyManager;
import org.apache.stratos.messaging.util.MessagingUtil;

public class MemberCreatedMessageProcessor extends MessageProcessor {

    private static final Log log = LogFactory.getLog(MemberCreatedMessageProcessor.class);
    private MessageProcessor nextProcessor;

    @Override
    public void setNext(MessageProcessor nextProcessor) {
        this.nextProcessor = nextProcessor;
    }

    @Override
    public boolean process(String type, String message, Object object) {
        Topology topology = (Topology) object;

        if (MemberCreatedEvent.class.getName().equals(type)) {
            // Return if topology has not been initialized
            if (!TopologyManager.isInitialized())
                return false;

            // Parse complete message and build event
            MemberCreatedEvent event = (MemberCreatedEvent) MessagingUtil.jsonToObject(message, MemberCreatedEvent.class);

            TopologyUpdater.acquireWriteLockForCluster(event.getServiceName(), event.getClusterId());
            try {
                return doProcess(event, topology);

            } finally {
                TopologyUpdater.releaseWriteLockForCluster(event.getServiceName(), event.getClusterId());
            }

        } else {
            if (nextProcessor != null) {
                // ask the next processor to take care of the message.
                return nextProcessor.process(type, message, topology);
            } else {
                throw new RuntimeException(String.format("Failed to process message using available message processors: [type] %s [body] %s", type, message));
            }
        }
    }

    private boolean doProcess(MemberCreatedEvent event, Topology topology) {

        String serviceName = event.getServiceName();
        String clusterId = event.getClusterId();

        // Apply service filter
        if (TopologyServiceFilter.apply(serviceName)) {
            return false;
        }

        // Apply cluster filter
        if (TopologyClusterFilter.apply(clusterId)) {
            return false;
        }

        // Validate event against the existing topology
        Service service = topology.getService(event.getServiceName());
        if (service == null) {
            if (log.isWarnEnabled()) {
                log.warn(String.format("Service does not exist: [service] %s",
                        event.getServiceName()));
            }
            return false;
        }
        Cluster cluster = service.getCluster(event.getClusterId());
        if (cluster == null) {
            if (log.isWarnEnabled()) {
                log.warn(String.format("Cluster does not exist: [service] %s [cluster] %s",
                        event.getServiceName(), event.getClusterId()));
            }
            return false;
        }

        // Apply application filter
        if(TopologyApplicationFilter.apply(cluster.getAppId())) {
            return false;
        }

        if (cluster.memberExists(event.getMemberId())) {
            if (log.isDebugEnabled()) {
                log.debug(String.format("Member already exists: [service] %s [cluster] %s [member] %s",
                        event.getServiceName(),
                        event.getClusterId(),
                        event.getMemberId()));
            }
        } else {

            // Apply changes to the topology
            Member member = new Member(event.getServiceName(), event.getClusterId(), event.getMemberId(),
                    event.getClusterInstanceId(), event.getNetworkPartitionId(),
                    event.getPartitionId(), event.getLoadBalancingIPType(), event.getInitTime());
            member.setProperties(event.getProperties());
            cluster.addMember(member);

            if (log.isInfoEnabled()) {
                log.info(String.format("Member created: [service-name] %s [cluster-id] %s [member-id] %s " +
                                "[cluster-instance-id] %s",
                        event.getServiceName(),
                        event.getClusterId(),
                        event.getMemberId(),
                        event.getClusterInstanceId()));
            }
        }

        // Notify event listeners
        notifyEventListeners(event);
        return true;
    }
}


text:
package io.jvoid.test.configuration;

import java.util.Properties;

import org.junit.Assert;
import org.junit.Test;

import io.jvoid.configuration.PropertyBasedConfiguration;

public class PropertyBasedConfigurationTest {

    private static final String TEST_VALUE = "test_value";

    @Test
    public void testInvalidProperties() {
        Properties properties = new Properties();
        properties.setProperty("db.location", TEST_VALUE);
        try {
            new PropertyBasedConfiguration(null);
            Assert.fail();
        } catch (IllegalArgumentException e) {
        }
    }

    @Test
    public void testDbUrl() {
        Properties properties = new Properties();
        properties.setProperty("db.url", TEST_VALUE);
        PropertyBasedConfiguration config = new PropertyBasedConfiguration(properties);
        Assert.assertEquals(TEST_VALUE, config.dbUrl());
    }

    @Test
    public void testDbUsername() {
        Properties properties = new Properties();
        properties.setProperty("db.username", TEST_VALUE);
        PropertyBasedConfiguration config = new PropertyBasedConfiguration(properties);
        Assert.assertEquals(TEST_VALUE, config.dbUsername());
    }

    @Test
    public void testDbPassword() {
        Properties properties = new Properties();
        properties.setProperty("db.password", TEST_VALUE);
        PropertyBasedConfiguration config = new PropertyBasedConfiguration(properties);
        Assert.assertEquals(TEST_VALUE, config.dbPassword());
    }

    @Test
    public void testBasePackage() {
        Properties properties = new Properties();
        properties.setProperty("app.package", TEST_VALUE);
        PropertyBasedConfiguration config = new PropertyBasedConfiguration(properties);
        Assert.assertEquals(TEST_VALUE, config.basePackage());
    }

    @Test
    public void testIncludes() {
        Properties properties = new Properties();
        properties.setProperty("app.includes", TEST_VALUE);
        PropertyBasedConfiguration config = new PropertyBasedConfiguration(properties);
        Assert.assertEquals(TEST_VALUE, config.includes());
    }

    @Test
    public void testExcludes() {
        Properties properties = new Properties();
        properties.setProperty("app.excludes", TEST_VALUE);
        PropertyBasedConfiguration config = new PropertyBasedConfiguration(properties);
        Assert.assertEquals(TEST_VALUE, config.excludes());
    }

}


text:
#pragma once
#include "CWindowCommander.h"

#define	kRosterStringListID	130
#define	kNetInfoTimeOut		120		// 2 seconds

#define	kChatMessageWidth	336
#define	kMaxChatLines		13

enum
{	kTopBox,
	kCardBox,
	kCardContentBox,
	kTabBox,

	kChatBufferBox,
	kChatBufferLineBox,
	kChatEntryBox,
	kChatDivisorBox,

	kOnePlayerBox,
	kFullMapBox,
	kSmallMapBox,
	kMugShotBox,

	kMapInfoBox,	//	Location coordinates and maybe more
	kNetInfoBox,	//	Information on networking stuff
	kOneColorBox,
	kOneNameBox,	//	Player name and status
	kOneScoreBox,	//	Latest player result
	kOneMessageBox,	//

	kResultsBox,
	kCustomResultsBox,

	kScoreInformationBox,

	kBottomBox,
	kBottomLeftBox,
	kBottomRightBox,
	kWaterMarkBox,
	kRosterRowBox,
	kNumberBox,
	kUserBox,
	kUserBoxTopLine,
	kUserBoxBottomLine,
	kRealNameBox
};

class	CRosterWindow : public CWindowCommander
{
public:
			PicHandle			waterMarkPic;
			Rect				waterMarkFrame;

			PicHandle			mapPic;
	class	CTabCards			*tabs;
			Str255				chatLine;
			StringPtr			chatBuffers[kMaxChatLines];
			Str255				chatSpace[kMaxChatLines];

			Handle				leftNetInfo;
			Handle				rightNetInfo;
			short				tabNetInfo;
			short				slotInfo;
			long				infoStamp;

			void				TruncatePlayerName(StringPtr theName);

	virtual	void				IWindowCommander(CCommander *theCommander,
												CWindowCommander **theList);
	virtual	void				Dispose();

	virtual	void				GetMapPicture();

	virtual	CloseRequestResult	CloseRequest(Boolean isQuitting);

	virtual	void				PointToAnchor(Point *thePoint);
	virtual	void				ChatClick(Point where);
	virtual	void				ContentClick(EventRecord *theEvent, Point where);

	virtual	Boolean				CheckNetInfo(short slot);

	virtual	void				GotEvent();

	virtual	void				DrawAngleString(short angle, short positive, short negative);

	virtual	void				DrawChatPage();
	virtual	void				DrawPlayersPage();
	virtual	void				DrawOnePlayerPage();
	virtual	void				DrawPlayerPicts();
	virtual	void				DrawResultsPage();
	virtual	void				DrawCustomPage();

	virtual	void				DrawContents();

	//	CCommander methods:
	virtual	void				AdjustMenus(CEventHandler *master);
	virtual	void				DoCommand(long theCommand);

	virtual	void				KeyEvent(EventRecord *theEvent);

	virtual	Boolean				DoEvent(CEventHandler *master, EventRecord *theEvent);

	//	Utility:
	virtual	Boolean				GetRosterRect(Rect *theRect, short part, short index);
	virtual	void				DragUserBox(EventRecord *theEvent, Point where, short index);
	virtual	void				ClickUserColor(EventRecord *theEvent, Point where, short index);
	virtual	void				InvalidateColorBox(short ind);
	virtual	void				InvalidateArea(short areaCode, short i);

	virtual	void				SetChatLine(StringPtr theLine);
	virtual	void				NewChatLine(StringPtr theLine);

	virtual	Boolean				AvoidReopen(FSSpec *theFile, Boolean doSelect);
};


text:
<!doctype html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>Montage • TodoMVC</title>

        <link rel="stylesheet" href="node_modules/todomvc-common/base.css">
        <link rel="stylesheet" href="node_modules/todomvc-app-css/index.css">
        <link rel="stylesheet" href="assets/app.css">


text:
/*	$NetBSD: genfbvar.h,v 1.24 2014/07/24 21:35:13 riastradh Exp $ */

/*-
 * Copyright (c) 2007 Michael Lorenz
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#ifndef GENFBVAR_H
#define GENFBVAR_H

#ifdef _KERNEL_OPT
#include "opt_splash.h"
#endif

#include <sys/param.h>
#include <sys/buf.h>
#include <sys/conf.h>
#include <sys/device.h>

#include <sys/bus.h>

#include <dev/wscons/wsconsio.h>
#include <dev/wscons/wsdisplayvar.h>
#include <dev/rasops/rasops.h>

#include <dev/wscons/wsdisplay_vconsvar.h>
#ifdef _KERNEL_OPT
#include "opt_genfb.h"
#endif

#ifdef SPLASHSCREEN
#define GENFB_DISABLE_TEXT
#include <dev/splash/splash.h>
#endif

struct genfb_softc;

struct genfb_ops {
	int (*genfb_ioctl)(void *, void *, u_long, void *, int, struct lwp *);
	paddr_t	(*genfb_mmap)(void *, void *, off_t, int);
	int (*genfb_borrow)(void *, bus_addr_t, bus_space_handle_t *);
	int (*genfb_enable_polling)(void *);
	int (*genfb_disable_polling)(void *);
};

struct genfb_colormap_callback {
	void *gcc_cookie;
	void (*gcc_set_mapreg)(void *, int, int, int, int);
};

/*
 * Integer parameter provider.  Each callback shall return 0 on success,
 * and an error(2) number on failure.  The gpc_upd_parameter callback is
 * optional (i.e. it can be NULL).
 *
 * This structure is used for backlight and brightness control.  The
 * expected parameter range is:
 *
 *	[0, 1]		for backlight
 *	[0, 255]	for brightness
 */
struct genfb_parameter_callback {
	void *gpc_cookie;
	int (*gpc_get_parameter)(void *, int *);
	int (*gpc_set_parameter)(void *, int);
	int (*gpc_upd_parameter)(void *, int);
};

struct genfb_pmf_callback {
	bool (*gpc_suspend)(device_t, const pmf_qual_t *);
	bool (*gpc_resume)(device_t, const pmf_qual_t *);
};

struct genfb_mode_callback {
	bool (*gmc_setmode)(struct genfb_softc *, int);
};

struct genfb_softc {
	device_t sc_dev;
	struct vcons_data vd;
	struct genfb_ops sc_ops;
	struct vcons_screen sc_console_screen;
	struct wsscreen_descr sc_defaultscreen_descr;
	const struct wsscreen_descr *sc_screens[1];
	struct wsscreen_list sc_screenlist;
	struct genfb_colormap_callback *sc_cmcb;
	struct genfb_pmf_callback *sc_pmfcb;
	struct genfb_parameter_callback *sc_backlight;
	struct genfb_parameter_callback *sc_brightness;
	struct genfb_mode_callback *sc_modecb;
	int sc_backlight_level, sc_backlight_on;
	void *sc_fbaddr;	/* kva */
#ifdef GENFB_SHADOWFB
	void *sc_shadowfb;
#endif
	bus_addr_t sc_fboffset;	/* bus address */
	int sc_width, sc_height, sc_stride, sc_depth;
	size_t sc_fbsize;
	int sc_mode;
	u_char sc_cmap_red[256];
	u_char sc_cmap_green[256];
	u_char sc_cmap_blue[256];
	bool sc_want_clear;
#ifdef SPLASHSCREEN
	struct splash_info sc_splash;
#endif
	struct wsdisplay_accessops sc_accessops;
};

void	genfb_cnattach(void);
void	genfb_disable(void);
int	genfb_is_console(void);
int	genfb_is_enabled(void);
void	genfb_init(struct genfb_softc *);
int	genfb_attach(struct genfb_softc *, struct genfb_ops *);
int	genfb_borrow(bus_addr_t, bus_space_handle_t *);
void	genfb_restore_palette(struct genfb_softc *);
void	genfb_enable_polling(device_t);
void	genfb_disable_polling(device_t);

#endif /* GENFBVAR_H */


text:
@interface SimpleTalkTableViewCell ()

@property (weak, nonatomic) IBOutlet UILabel *timeLabel;
@property (weak, nonatomic) IBOutlet UIImageView *talkImage;
@property (weak, nonatomic) IBOutlet UILabel *contentLabel;
@property (weak, nonatomic) IBOutlet UILabel *picNumLabel;
@end

@implementation SimpleTalkTableViewCell

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}

- (void)setModel:(SimpleTalkModel *)model
{
    _model = model;
    _timeLabel.text = model.displaytime;
    NSArray *imageArr = [self getImageIdArr:model.imageids];
    [_talkImage sd_setImageWithURL:[NSURL URLWithString:[NSString getS4ImageUri:[imageArr firstObject]]]];
    _contentLabel.text = model.text;
    _picNumLabel.text = [NSString stringWithFormat:@"共%ld张",(long)imageArr.count];
}

- (NSArray *)getImageIdArr:(NSString *)imageids
{
    NSRange range = [imageids rangeOfString:@","];
    // 一张图片
    if (range.length == 0) {
        return @[imageids];
    }
    else
    {
        NSArray *array = [imageids componentsSeparatedByString:@","];
        return array;
    }
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end


text:
package com.fhc25.percepcion.osiris.mapviewer.data;

import com.fhc25.percepcion.osiris.mapviewer.common.ICallback;
import com.fhc25.percepcion.osiris.mapviewer.common.ICancellableTask;
import com.fhc25.percepcion.osiris.mapviewer.common.data.IBackendCaller;
import com.fhc25.percepcion.osiris.mapviewer.common.data.RequestConfiguration;
import com.fhc25.percepcion.osiris.mapviewer.common.errors.Failure;

import java.io.InputStream;

public class Repository {

    private String appId;
    private int defaultPageSize = 20;

    private IBackendCaller backendCaller;

    public void setDefaultPageSize(int defaultPageSize) {
        this.defaultPageSize = defaultPageSize;
    }

    public Repository(IBackendCaller backendCaller, String appId) {
        this.appId = appId;
        this.backendCaller = backendCaller;
    }

    public ICancellableTask request(RequestConfiguration configuration, ICallback<String> callback) {

        addHeaders(configuration);
        return backendCaller.request(configuration, callback);
    }

    public ICancellableTask requestStream(RequestConfiguration configuration, ICallback<InputStream> callback) {
        addHeaders(configuration);
        return backendCaller.requestStream(configuration, callback);
    }

    private void addHeaders(RequestConfiguration configuration) {

        if (!configuration.containsHeaderKey("api_key")) {
            configuration.addHeader("api_key", appId);
        }

        if (!configuration.containsHeaderKey("Cache-Control")) {
            configuration.addHeader("Cache-Control", "no-cache");
        }

        if (!configuration.containsHeaderKey("Pragma")) {
            configuration.addHeader("Pragma", "no-cache");
        }

    }

    public ICancellableTask requestWithPagination(RequestConfiguration configuration, PaginationCallback callback) {

        PaginationCancellableTask cancellableTask = new PaginationCancellableTask();
        recursiveRequestWithPagination(cancellableTask, configuration, callback, defaultPageSize, 0);

        return cancellableTask;
    }

    private void recursiveRequestWithPagination(final PaginationCancellableTask cancellableTask, final RequestConfiguration configuration,
                                                final PaginationCallback callback, final int pageSize, final int pageIndex) {

        String originalPathParams = configuration.getPathParams();
        String pathParams = originalPathParams + "?pageSize=" + pageSize + "&pageIndex=" + pageIndex;
        configuration.setPathParams(pathParams);

        ICancellableTask task = request(configuration, new ICallback<String>() {
            @Override
            public void onFinish(Failure error, String data) {
                if (error != null) {
                    callback.onFinish(error, null);
                } else {
                    if (callback.pageQueryReturned(data)) {
                        recursiveRequestWithPagination(cancellableTask, configuration, callback, pageSize, pageIndex + 1);
                    } else {
                        callback.onFinish(null, null);
                    }
                }
            }
        });

        cancellableTask.setCancellableTask(task);
        configuration.setPathParams(originalPathParams);
    }

    public class PaginationCancellableTask implements ICancellableTask {

        private ICancellableTask cancellableTask;

        public void setCancellableTask(ICancellableTask cancellableTask) {
            this.cancellableTask = cancellableTask;
        }

        @Override
        public boolean cancel() {
            if (cancellableTask != null) {
                return cancellableTask.cancel();
            }

            return true;
        }
    }

    public interface PaginationCallback extends ICallback<Void> {

        /**
         * Returns if the pagination queries sould continue
         *
         * @param response
         * @return
         */
        boolean pageQueryReturned(String response);
    }
}


text:
require 'repr'

local function monsterFromXML(node)
  return xml.attrs(node)
end

-- Master table of all monsters, indexed by monster name.
local monsters = {}

local function loadMonsters(path)
  local dom = xml.load(path)
  local count = 0
  for mondef in xml.walk(dom.root, 'monster') do
    if monsters[mondef.attr.name] then
      log.debug("skipping duplicate monster definition %s", mondef.attr.name)
    else
      count = count+1
      local monster = monsterFromXML(mondef)
      monsters[monster.name] = monster
    end
  end
  log.debug("Loaded %d monsters from %s", count, path)
end

function dredmor.loadMonsters()
  loadMonsters(flags.parsed.dredmor_dir..'/game/monDB.xml')
  loadMonsters(flags.parsed.dredmor_dir..'/expansion/game/monDB.xml')
  loadMonsters(flags.parsed.dredmor_dir..'/expansion2/game/monDB.xml')
  loadMonsters(flags.parsed.dredmor_dir..'/expansion3/game/monDB.xml')
end

function dredmor.monsters(filter)
  local R = {}
  filter = filter or f' => true'
  for _,monster in pairs(monsters) do
    if filter(monster) then
      R[monster.name] = monster
      table.insert(R, monster)
    end
  end
  log.debug("Returning filtered list of %d monsters", #R)
  return R
end

function dredmor.monster(name)
  return monsters[name]
end


text:
<?php declare(strict_types=1);

namespace PhpParser;

/**
 * @codeCoverageIgnore
 */
class Autoloader
{
    /** @var bool Whether the autoloader has been registered. */
    private static $registered = false;

    /**
     * Registers PhpParser\Autoloader as an SPL autoloader.
     *
     * @param bool $prepend Whether to prepend the autoloader instead of appending
     */
    static public function register(bool $prepend = false) {
        if (self::$registered === true) {
            return;
        }

        spl_autoload_register([__CLASS__, 'autoload'], true, $prepend);
        self::$registered = true;
    }

    /**
     * Handles autoloading of classes.
     *
     * @param string $class A class name.
     */
    static public function autoload(string $class) {
        if (0 === strpos($class, 'PhpParser\\')) {
            $fileName = __DIR__ . strtr(substr($class, 9), '\\', '/') . '.php';
            if (file_exists($fileName)) {
                require $fileName;
            }
        } elseif (0 === strpos($class, 'Rascal\\')) {
            $fileName = dirname(__DIR__) . '/' . strtr($class, '\\', '/') . '.php';
            if (file_exists($fileName)) {
                require $fileName;
            }
        }
    }
}


text:
table.confluenceTable {
    margin: 5px;
    border-collapse: collapse;
}

td.confluenceTd, table.confluenceTable td.confluenceTd {
    border-width: 1px;
    border-style: solid;
    border-color: #ccc;
    padding: 5px;
    vertical-align: top;
}

th.confluenceTh, table.confluenceTable th.confluenceTh {
    border-width: 1px;
    border-style: solid;
    border-color: #ccc;
    padding: 5px;
    background-color: #f0f0f0;
    text-align: left;
    vertical-align: top;
}


text:
The Userinterface of the Tagrefinery project.

## Deployment
Clone the repository and install the npm and bower dependencies.

```bash
    npm install
    bower install

    grunt serve
```

You need a running [server](https://github.com/Christoph/tagrefinery-core) to use the interface. The easiest way is to download the latest [release](https://github.com/Christoph/tagrefinery-releases) and start the included server.jar file.


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//using System.Threading.Tasks;

namespace Landis.Library.Metadata
{
    public enum OutputType
    {
        Map = 0,
        Table = 1,
    }
}


text:
SET @eoi_competition_type = (SELECT id FROM competition_type ct WHERE ct.name='Expression of interest');

UPDATE section s
    SET s.description = 'You are agreeing to these by submitting your application.'
WHERE
        s.section_type = 'TERMS_AND_CONDITIONS' AND
        s.competition_id IN (
            SELECT c.id
            FROM competition c
            WHERE
                    c.competition_type_id = @eoi_competition_type OR
                    c.template AND c.name = 'Template for the Expression of interest competition type'
    );


text:
<!-- mdformat off(b/169948621#comment2) -->

As of June 1, 2021, the TFLM codebase has moved to a [stand-alone github
repository](https://github.com/tensorflow/tflite-micro). The code in the current
location is in a read-only state until June 30, 2021 at which point in time it
will be deleted.


text:
var app = new Vue({
    el: '#card',
    data: {
        img: 'http://c7.nrostatic.com/sites/default/files/uploaded/donald-trump-bankruptcy-lies-r.jpg',
        items: [
            { label: 'Price', value: '10.000 €', selected: false },
            { label: 'Mileage', value: '100.000 KM', selected: false },
            { label: 'Registration', value: '01.10.2010', selected: false },
            { label: 'Power', value: '100 kW / 140 HP', selected: false },
            { label: 'Displacement', value: '3799', selected: false }
        ]
    },
    methods: {
        toggleSelected: function(item) {
            this.items.forEach(function (item) {
                item.selected = false;
            });

            item.selected = !item.selected;
        }
    }
});


text:
<?php

?>

<?php
class ReporterTableKeysController extends AppController {

	var $name = 'ReporterTableKeys';

	function index() {

		debug($this->ReporterTableKey->reporter_list_keys());

		$this->ReporterTableKey->recursive = 0;
		$this->set('reporterTableKeys', $this->paginate());
	}

	function view($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid reporter table key', true));
			$this->redirect(array('action' => 'index'));
		}
		$this->set('reporterTableKey', $this->ReporterTableKey->read(null, $id));
	}

	function add() {
		if (!empty($this->data)) {
			$this->ReporterTableKey->create();
			if ($this->ReporterTableKey->save($this->data)) {
				$this->Session->setFlash(__('The reporter table key has been saved', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The reporter table key could not be saved. Please, try again.', true));
			}
		}
	}

	function edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid reporter table key', true));
			$this->redirect(array('action' => 'index'));
		}
		if (!empty($this->data)) {
			if ($this->ReporterTableKey->save($this->data)) {
				$this->Session->setFlash(__('The reporter table key has been saved', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The reporter table key could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->ReporterTableKey->read(null, $id);
		}
	}

	function delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for reporter table key', true));
			$this->redirect(array('action'=>'index'));
		}
		if ($this->ReporterTableKey->delete($id)) {
			$this->Session->setFlash(__('Reporter table key deleted', true));
			$this->redirect(array('action'=>'index'));
		}
		$this->Session->setFlash(__('Reporter table key was not deleted', true));
		$this->redirect(array('action' => 'index'));
	}
}


text:
package com.xiaoyu;

/**
 * Created by gxytk on 2016/10/31.
 */
public class HappyHourStrategy implements BillStrategy {
    @Override
    public double getActPrice(double rawPrice) {
        return rawPrice * 0.5;
    }
}


text:
package cmd

import (
	"fmt"
	"os"
	"os/exec"
	"path"
	"path/filepath"
	"strconv"
	"strings"

	"github.com/codegangsta/cli"

	"github.com/gogits/gogs/models"
	"github.com/gogits/gogs/modules/log"
	"github.com/gogits/gogs/modules/setting"
	"github.com/gogits/gogs/modules/uuid"
)

var CmdServ = cli.Command{
	Name:        "serv",
	Usage:       "This command should only be called by SSH shell",
	Description: `Serv provide access auth for repositories`,
	Action:      runServ,
	Flags:       []cli.Flag{},
}

func setup(logPath string) {
	setting.NewConfigContext()
	log.NewGitLogger(filepath.Join(setting.LogRootPath, logPath))
	models.LoadModelsConfig()

	if models.UseSQLite3 {
		workDir, _ := setting.WorkDir()
		os.Chdir(workDir)
	}

	models.SetEngine()
}

func parseCmd(cmd string) (string, string) {
	ss := strings.SplitN(cmd, " ", 2)
	if len(ss) != 2 {
		return "", ""
	}

	verb, args := ss[0], ss[1]
	if verb == "git" {
		ss = strings.SplitN(args, " ", 2)
		args = ss[1]
		verb = fmt.Sprintf("%s %s", verb, ss[0])
	}
	return verb, strings.Replace(args, "'/", "'", 1)
}

var (
	COMMANDS_READONLY = map[string]models.AccessType{
		"git-upload-pack":    models.WRITABLE,
		"git upload-pack":    models.WRITABLE,
		"git-upload-archive": models.WRITABLE,
	}

	COMMANDS_WRITE = map[string]models.AccessType{
		"git-receive-pack": models.READABLE,
		"git receive-pack": models.READABLE,
	}
)

func In(b string, sl map[string]models.AccessType) bool {
	_, e := sl[b]
	return e
}

func runServ(k *cli.Context) {
	setup("serv.log")

	keys := strings.Split(os.Args[2], "-")
	if len(keys) != 2 {
		println("Gogs: auth file format error")
		log.GitLogger.Fatal("Invalid auth file format: %s", os.Args[2])
	}

	keyId, err := strconv.ParseInt(keys[1], 10, 64)
	if err != nil {
		println("Gogs: auth file format error")
		log.GitLogger.Fatal("Invalid auth file format: %v", err)
	}
	user, err := models.GetUserByKeyId(keyId)
	if err != nil {
		if err == models.ErrUserNotKeyOwner {
			println("Gogs: you are not the owner of SSH key")
			log.GitLogger.Fatal("Invalid owner of SSH key: %d", keyId)
		}
		println("Gogs: internal error:", err)
		log.GitLogger.Fatal("Fail to get user by key ID(%d): %v", keyId, err)
	}

	cmd := os.Getenv("SSH_ORIGINAL_COMMAND")
	if cmd == "" {
		println("Hi", user.Name, "! You've successfully authenticated, but Gogs does not provide shell access.")
		return
	}

	verb, args := parseCmd(cmd)
	repoPath := strings.Trim(args, "'")
	rr := strings.SplitN(repoPath, "/", 2)
	if len(rr) != 2 {
		println("Gogs: unavailable repository", args)
		log.GitLogger.Fatal("Unavailable repository: %v", args)
	}
	repoUserName := rr[0]
	repoName := strings.TrimSuffix(rr[1], ".git")

	isWrite := In(verb, COMMANDS_WRITE)
	isRead := In(verb, COMMANDS_READONLY)

	repoUser, err := models.GetUserByName(repoUserName)
	if err != nil {
		if err == models.ErrUserNotExist {
			println("Gogs: given repository owner are not registered")
			log.GitLogger.Fatal("Unregistered owner: %s", repoUserName)
		}
		println("Gogs: internal error:", err)
		log.GitLogger.Fatal("Fail to get repository owner(%s): %v", repoUserName, err)
	}

	// Access check.
	switch {
	case isWrite:
		has, err := models.HasAccess(user.Name, path.Join(repoUserName, repoName), models.WRITABLE)
		if err != nil {
			println("Gogs: internal error:", err)
			log.GitLogger.Fatal("Fail to check write access:", err)
		} else if !has {
			println("You have no right to write this repository")
			log.GitLogger.Fatal("User %s has no right to write repository %s", user.Name, repoPath)
		}
	case isRead:
		repo, err := models.GetRepositoryByName(repoUser.Id, repoName)
		if err != nil {
			if err == models.ErrRepoNotExist {
				println("Gogs: given repository does not exist")
				log.GitLogger.Fatal("Repository does not exist: %s/%s", repoUser.Name, repoName)
			}
			println("Gogs: internal error:", err)
			log.GitLogger.Fatal("Fail to get repository: %v", err)
		}

		if !repo.IsPrivate {
			break
		}

		has, err := models.HasAccess(user.Name, path.Join(repoUserName, repoName), models.READABLE)
		if err != nil {
			println("Gogs: internal error:", err)
			log.GitLogger.Fatal("Fail to check read access:", err)
		} else if !has {
			println("You have no right to access this repository")
			log.GitLogger.Fatal("User %s has no right to read repository %s", user.Name, repoPath)
		}
	default:
		println("Unknown command")
		return
	}

	uuid := uuid.NewV4().String()
	os.Setenv("uuid", uuid)

	gitcmd := exec.Command(verb, repoPath)
	gitcmd.Dir = setting.RepoRootPath
	gitcmd.Stdout = os.Stdout
	gitcmd.Stdin = os.Stdin
	gitcmd.Stderr = os.Stderr
	err = gitcmd.Run()
	if err != nil {
		println("Gogs: internal error:", err)
		log.GitLogger.Fatal("Fail to execute git command: %v", err)
	}

	if isWrite {
		tasks, err := models.GetUpdateTasksByUuid(uuid)
		if err != nil {
			log.GitLogger.Fatal("Fail to get update task: %v", err)
		}

		for _, task := range tasks {
			err = models.Update(task.RefName, task.OldCommitId, task.NewCommitId,
				user.Name, repoUserName, repoName, user.Id)
			if err != nil {
				log.GitLogger.Fatal("Fail to update: %v", err)
			}
		}

		err = models.DelUpdateTasksByUuid(uuid)
		if err != nil {
			log.GitLogger.Fatal("Fail to del update task: %v", err)
		}
	}
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: feras
 * Date: 9/27/17
 * Time: 9:06 AM
 */
defined('BASEPATH') OR exit('No direct script access allowed');
class Post extends CI_Controller
{
    public function __construct()
    {
        /*-------------including all needed models*/
        parent::__construct();
        $this->load->library('Jsonlib');
        $this->load->model('post_model');
        $this->load->model('vote_model');
        $this->load->model('user_model');
    }

    public function index()                                 //simple interfes for test add post with Ajax and Json
    {

        $data['title'] = 'Task for Zont';
        $this->load->view('templates/header', $data);
        $this->load->view('post/index');
        $this->load->view('templates/footer');
    }
    public function get_top()                   //simple interfes for test top n post with Ajax and Json
    {

        $data['title'] = 'Task for Zont';
        $this->load->view('templates/header', $data);
        $this->load->view('post/top');
        $this->load->view('templates/footer');
    }
    public function add()
    {
        $data = $_REQUEST;
        if (! isset($data['user']) || $data['user'] == '')
            $this->jsonlib->return_error('empty user name');                            // check empty value user
        else{
            if (! isset($data['content']) || $data['content'] == '')                    // check empty value content
                $this->jsonlib->return_error('empty content post');
            else {
                if (! isset($data['title']) || $data['title'] == '')                    // check empty value title
                    $this->jsonlib->return_error('empty title post');
                else {
                    $user = $this->user_model->get_by_name($data['user']);              // check if user exist
                    if ($user == null)                                                  // if not user creating new
                        $user = $this->user_model->set_user($data['user']);
                    if ($user == null)
                        $this->jsonlib->return_error('cannot add new user');            // check added new user or not
                    else {
                        $data['user'] = $user;
                        $post = $this->post_model->set_post($data);                     // add new post
                        if ($post['id'] == null)
                            $this->jsonlib->return_error('cannot add new post');        // check if added post
                        else
                            $this->jsonlib->return_normal($post);
                    }
                }
            }
        }
    }
    public function gettop() {
        $n = $_REQUEST['count'];
        if ($n > 0 ){                                                           //check empty values
            $data = $this->post_model->get_top_n($n);
            if ($data['error'])
                $this->jsonlib->return_error($data['error']);                        // check if added vote
            else
                $this->jsonlib->return_normal($data);
        }else {
            $this->jsonlib->return_error('Nomber have to be greater than 0');
        }
    }
    public function generatedbposts()                                           //Function for generate 200000 post whit 100 user and 50 ip
    {
        $ipsArray = array();
        for ($i = 0; $i < 50; $i++) {
            $ipsArray[] = mt_rand(0,255).".".mt_rand(0,255).".".mt_rand(0,255).".".mt_rand(0,255);
        }
        $usersArray = array();
        $names = array(
            'feras',
            'test',
            'Christopher',
            'Ryan',
            'Ethan',
            'John',
            'Zoey',
            'Sarah',
            'Michelle',
            'Samantha',
        );
        $surnames = array(
            'Walker',
            'Thompson',
            'Anderson',
            'Johnson',
            'Tremblay',
            'Peltier',
            'Cunningham',
            'Simpson',
            'Mercado',
            'Sellers'
        );
        foreach ($names as $name){
            foreach ($surnames as $surname){
                $usersArray[] = $name.$surname ;
            }
        }
        $title = 'this title is for all post' ;
        $content = 'this title is for all post' ;
        $arrayposts = array();
        for ($i = 0; $i < 200000; $i++) {
            $arrayposts[] = array(
                'post_user_ip' => $ipsArray[mt_rand(0,50)] ,
                'user_id' => mt_rand(1,100),
                'title'=>$title,
                'content' => $content ,
            );
        }
        $this->user_model->set_users($usersArray);
        $this->post_model->set_posts($arrayposts);
        $this->jsonlib->return_normal(array("result"=>'DB GENERATED 200K post 50 ip 100 user'));
    }
}
?>


text:
package keynuker_go_common

import "time"

// Note: this package should not have any dependencies to any other keynuker-go sub-packages,
// since they will probably create circular dependencies

const (
	DefaultKeyNukerOrg = "default"

	DocIdPrefixGithubUsers = "github_users"

	DocIdPrefixAwsKeys = "aws_keys"

	DocIdPrefixGithubEventCheckpoints = "github_event_checkpoints"
)

// Environment Variable Names
const (
	EnvVarKeyNukerTestGithubAccessToken = "KEYNUKER_INTEGRATION_TEST_GITHUB_ACCESS_TOKEN"

	EnvVarKeyNukerTestDbHost = "KEYNUKER_DB_HOST"

	EnvVarKeyNukerTestDbName = "KEYNUKER_DB_NAME"

	EnvVarKeyNukerTestDbUsername = "KEYNUKER_DB_KEY"

	EnvVarKeyNukerTestDbPassword = "KEYNUKER_DB_SECRET_KEY"

	EnvVarKeyNukerTestTargetAwsAccounts = "KEYNUKER_TARGET_AWS_ACCOUNTS"

	EnvVarKeyNukerTestIntegrationTestsEnabled = "KEYNUKER_INTEGRATION_TESTS_ENABLED"

	EnvVarKeyNukerTestIntegrationAccessKey       = "KEYNUKER_INTEGRATION_TEST_ACCESS_KEY"
	EnvVarKeyNukerTestIntegrationSecretAccessKey = "KEYNUKER_INTEGRATION_TEST_SECRET_ACCESS_KEY"

	EnvVarKeyNukerInitiatingAwsAccountCreds = "KEYNUKER_INITIATING_AWS_ACCOUNT"

	EnvVarKeyNukerTestIntegrationGithubApiBaseUrl = "KEYNUKER_INTEGRATION_TEST_GITHUB_BASE_API_URL"

	EnvVarKeyNukerTestGithubOrgs = "KEYNUKER_INTEGRATION_TEST_GITHUB_ORGS"

	EnvVarKeyNukerTestGithubLeakTargetRepo = "KEYNUKER_GITHUB_LEAK_TARGET_REPO"

	EnvVarKeyNukerEmailFromAddress = "KEYNUKER_EMAIL_FROM_ADDRESS"

	EnvVarKeyNukerAdminEmailCCAddress = "KEYNUKER_ADMIN_EMAIL_CC_ADDRESS"

	EnvVarKeyNukerMailerDomain = "KEYNUKER_MAILER_DOMAIN"

	EnvVarKeyNukerMailerApiKey = "KEYNUKER_MAILER_API_KEY"

	EnvVarKeyNukerMailerPublicApiKey = "KEYNUKER_MAILER_PUBLIC_API_KEY"
)

// Misc
const (

	// The integration test creates branches on the github repo.
	// Add improbable string at end to make it as unlikely as possible to collide with a real branch name
	KeyNukerIntegrationTestBranch = "KeyNukerIntegrationTestBranch-5a2f42dd3058f53ac9c5f22153257db7b594c663"

	GithubRefsHeadsPrefix = "refs/heads"

	GithubMasterBranch = "master"

	// The max size in bytes of blob content that will be scanned.
	// This should be raised to 100 MB once the stream based scanning is implemented.
	MaxSizeBytesBlobContent = 10000000 // 10 MB

	// The max execution time for an action in seconds
	MaxActionExecutionSeconds = time.Second * 300

	// The high watermark at which point an action should be aborted since approaching max
	HighWatermarkExecutionSeconds = MaxActionExecutionSeconds - (time.Second * 60)
)

var (

	// If there is no recorded checkpoint for a user, how far back should the scanning go in the github user event history?
	DefaultCheckpointEventTimeWindow time.Duration
)

func init() {
	DefaultCheckpointEventTimeWindow = time.Hour * -12

}


text:
from pyramid.events import subscriber
from openprocurement.tender.core.events import TenderInitializeEvent
from openprocurement.api.utils import get_now

@subscriber(TenderInitializeEvent, procurementMethodType="belowThreshold")
def tender_init_handler(event):
    """ initialization handler for belowThreshold tenders """
    tender = event.tender
    if not tender.enquiryPeriod.startDate:
        tender.enquiryPeriod.startDate = get_now()
    if not tender.tenderPeriod.startDate:
        tender.tenderPeriod.startDate = tender.enquiryPeriod.endDate
    now = get_now()
    tender.date = now
    if tender.lots:
        for lot in tender.lots:
            lot.date = now


text:
<?php

namespace Group3\Bundle\ABundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class AircrewType extends AbstractType
{
        /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('pilot')
            ->add('navigator')
            ->add('save', 'submit', array(
                'attr' => array('class' => 'pure-button pure-button-primary save-button')
            ))
        ;
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Group3\Bundle\ABundle\Entity\Aircrew'
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'group3_bundle_abundle_aircrew';
    }
}


text:
function Fout = real(F)
% REAL   Complex real part of a chebfun.
%
% REAL(F) is the real part of F.

% Copyright 2011 by The University of Oxford and The Chebfun Developers.
% See http://www.maths.ox.ac.uk/chebfun/ for Chebfun information.

Fout = F;
for k = 1:numel(F)
    Fout(k) = realcol(F(k));
end
% ---------------------------

function fout = realcol(f)

fout = f;
for i = 1:f.nfuns
    fout.funs(i) = real(f.funs(i));
end
fout.imps = real(f.imps);


text:
/**
 * Emotion Entity
 */
const Entity = require('../../../../src/Entity/entity');

module.exports = class EmotionEntity extends Entity {

	setup() {
		this.import = {
			file: "Data.Common.emotion",
			type: "json"
		};
	}

	parse(string) {
		var result = this.find(string);
		return result;
	}

}


text:
package de.fhg.igd.iva.colorspaces;

import java.awt.Color;

/**
 * @author Sebastian Mittelstaedt
 */
public abstract class AbstractColorSpace {

	public abstract double[] toRGB(double[] v);
	public abstract Color toColor(double[] v, boolean returnBlackForUndefinedRGB);
	public abstract double[] fromRGB(double[] rgb);
	public abstract double[] fromColor(Color c);

	protected static void fixRoundingErrors(double[] rgb)
	{
		final double eps = 0.01;

		for (int i = 0; i < rgb.length; i++)
		{
			double v = rgb[i];
			if (v > 1 && v < 1 + eps)
				rgb[i] = 1;

			if (v < 0 && v > -eps)
				rgb[i] = 0;
		}
	}

}


text:
var Polygon = function (PolygonData) {
    /// private
    var that = this;
    var sides = ko.observable(PolygonData.sides);
    var zoom = ko.observable(PolygonData.zoom || 1);
    var drawingmode = ko.observable(PolygonData.drawingmode);
    var width = ko.observable(PolygonData.width);
    //var padding = ko.observable(PolygonData.padding);

    // returns object raw data for storage / initialization
    var getdata = function () {
        return {
            'sides': sides(),
            'drawingmode': drawingmode(),
            'width': width(),
            'zoom': zoom()
        }
    };
    var init = function () {

    }();
    /// public
    return {
        // properties
        'sides': sides,
        'drawingmode': drawingmode,
        'width': width,
        'zoom': zoom,
        // methods
        'getdata' : getdata
    };
};


text:
class AddAlternativePhone < ActiveRecord::Migration
  def self.up
    add_column :addresses, :alternative_phone, :string
  end

  def self.down
    remove_column :addresses, :alternative_phone
  end
end


text:
package cucumber.table;

import gherkin.formatter.PrettyFormatter;
import gherkin.formatter.model.DataTableRow;
import gherkin.formatter.model.Row;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

public class DataTable {

    private final List<List<String>> raw;
    private final List<DataTableRow> gherkinRows;
    private final TableConverter tableConverter;

    public DataTable(List<DataTableRow> gherkinRows, TableConverter tableConverter) {
        this.gherkinRows = gherkinRows;
        this.tableConverter = tableConverter;
        this.raw = new ArrayList<List<String>>();
        for (Row row : gherkinRows) {
            List<String> list = new ArrayList<String>();
            list.addAll(row.getCells());
            this.raw.add(list);
        }
    }

    public List<List<String>> raw() {
        return this.raw;
    }

    public <T> List<T> asList(Type listType) {
        return tableConverter.toList(listType, this);
    }

    List<String> topCells() {
        return gherkinRows.get(0).getCells();
    }

    List<List<String>> cells(int firstRow) {
        List<List<String>> attributeValues = new ArrayList<List<String>>();
        List<DataTableRow> valueRows = gherkinRows.subList(firstRow, gherkinRows.size());
        for (Row valueRow : valueRows) {
            attributeValues.add(toStrings(valueRow));
        }
        return attributeValues;
    }

    private List<String> toStrings(Row row) {
        List<String> strings = new ArrayList<String>();
        for (String string : row.getCells()) {
            strings.add(string);
        }
        return strings;
    }

    public void diff(List<List<String>> other) {
        diff(tableConverter.toTable(other));
    }

    private void diff(DataTable other) {
        new TableDiffer(this, other).calculateDiffs();
    }

    public List<DataTableRow> getGherkinRows() {
        return gherkinRows;
    }

    @Override
    public String toString() {
        StringBuilder result = new StringBuilder();
        PrettyFormatter pf = new PrettyFormatter(result, true, false);
        pf.table(getGherkinRows());
        pf.eof();
        return result.toString();
    }

    List<DiffableRow> diffableRows() {
        List<DiffableRow> result = new ArrayList<DiffableRow>();
        List<List<String>> convertedRows = raw();
        for (int i = 0; i < convertedRows.size(); i++) {
            result.add(new DiffableRow(getGherkinRows().get(i), convertedRows.get(i)));
        }
        return result;
    }

    TableConverter getTableConverter() {
        return tableConverter;
    }

    class DiffableRow {
        public final Row row;
        public final List<String> convertedRow;

        public DiffableRow(Row row, List<String> convertedRow) {
            this.row = row;
            this.convertedRow = convertedRow;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            DiffableRow that = (DiffableRow) o;
            return convertedRow.equals(that.convertedRow);

        }

        @Override
        public int hashCode() {
            return convertedRow.hashCode();
        }
    }
}


text:
package org.apache.hadoop.hdfs.server.namenode.ha;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.FileUtil;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.ha.HAServiceProtocol.RequestSource;
import org.apache.hadoop.ha.HAServiceProtocol.StateChangeRequestInfo;
import org.apache.hadoop.ha.ServiceFailedException;
import org.apache.hadoop.hdfs.DFSConfigKeys;
import org.apache.hadoop.hdfs.DFSUtil;
import org.apache.hadoop.hdfs.HAUtil;
import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.apache.hadoop.hdfs.MiniDFSNNTopology;
import org.apache.hadoop.hdfs.server.namenode.NameNode;
import org.apache.hadoop.hdfs.server.namenode.NameNodeAdapter;
import org.apache.hadoop.test.GenericTestUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class TestInitializeSharedEdits {

  private static final Logger LOG =
      LoggerFactory.getLogger(TestInitializeSharedEdits.class);

  private static final Path TEST_PATH = new Path("/test");
  private Configuration conf;
  private MiniDFSCluster cluster;

  @Before
  public void setupCluster() throws IOException {
    conf = new Configuration();
    conf.setInt(DFSConfigKeys.DFS_HA_LOGROLL_PERIOD_KEY, 1);
    conf.setInt(DFSConfigKeys.DFS_HA_TAILEDITS_PERIOD_KEY, 1);
    HAUtil.setAllowStandbyReads(conf, true);

    MiniDFSNNTopology topology = MiniDFSNNTopology.simpleHATopology();

    cluster = new MiniDFSCluster.Builder(conf)
      .nnTopology(topology)
      .numDataNodes(0)
      .build();
    cluster.waitActive();

    shutdownClusterAndRemoveSharedEditsDir();
  }

  @After
  public void shutdownCluster() throws IOException {
    if (cluster != null) {
      cluster.shutdown();
      cluster = null;
    }
  }

  private void shutdownClusterAndRemoveSharedEditsDir() throws IOException {
    cluster.shutdownNameNode(0);
    cluster.shutdownNameNode(1);
    File sharedEditsDir = new File(cluster.getSharedEditsDir(0, 1));
    assertTrue(FileUtil.fullyDelete(sharedEditsDir));
  }

  private void assertCannotStartNameNodes() {
    // Make sure we can't currently start either NN.
    try {
      cluster.restartNameNode(0, false);
      fail("Should not have been able to start NN1 without shared dir");
    } catch (IOException ioe) {
      LOG.info("Got expected exception", ioe);
      GenericTestUtils.assertExceptionContains(
          "storage directory does not exist or is not accessible", ioe);
    }
    try {
      cluster.restartNameNode(1, false);
      fail("Should not have been able to start NN2 without shared dir");
    } catch (IOException ioe) {
      LOG.info("Got expected exception", ioe);
      GenericTestUtils.assertExceptionContains(
          "storage directory does not exist or is not accessible", ioe);
    }
  }

  private void assertCanStartHaNameNodes(String pathSuffix)
      throws ServiceFailedException, IOException, URISyntaxException,
      InterruptedException {
    // Now should be able to start both NNs. Pass "false" here so that we don't
    // try to waitActive on all NNs, since the second NN doesn't exist yet.
    cluster.restartNameNode(0, false);
    cluster.restartNameNode(1, true);

    // Make sure HA is working.
    cluster.getNameNode(0).getRpcServer().transitionToActive(
        new StateChangeRequestInfo(RequestSource.REQUEST_BY_USER));
    FileSystem fs = null;
    try {
      Path newPath = new Path(TEST_PATH, pathSuffix);
      fs = HATestUtil.configureFailoverFs(cluster, conf);
      assertTrue(fs.mkdirs(newPath));
      HATestUtil.waitForStandbyToCatchUp(cluster.getNameNode(0),
          cluster.getNameNode(1));
      assertTrue(NameNodeAdapter.getFileInfo(cluster.getNameNode(1),
          newPath.toString(), false, false, false).isDirectory());
    } finally {
      if (fs != null) {
        fs.close();
      }
    }
  }

  @Test
  public void testInitializeSharedEdits() throws Exception {
    assertCannotStartNameNodes();

    // Initialize the shared edits dir.
    assertFalse(NameNode.initializeSharedEdits(cluster.getConfiguration(0)));

    assertCanStartHaNameNodes("1");

    // Now that we've done a metadata operation, make sure that deleting and
    // re-initializing the shared edits dir will let the standby still start.

    shutdownClusterAndRemoveSharedEditsDir();

    assertCannotStartNameNodes();

    // Re-initialize the shared edits dir.
    assertFalse(NameNode.initializeSharedEdits(cluster.getConfiguration(0)));

    // Should *still* be able to start both NNs
    assertCanStartHaNameNodes("2");
  }

  @Test
  public void testFailWhenNoSharedEditsSpecified() throws Exception {
    Configuration confNoShared = new Configuration(conf);
    confNoShared.unset(DFSConfigKeys.DFS_NAMENODE_SHARED_EDITS_DIR_KEY);
    assertFalse(NameNode.initializeSharedEdits(confNoShared, true));
  }

  @Test
  public void testDontOverWriteExistingDir() throws IOException {
    assertFalse(NameNode.initializeSharedEdits(conf, false));
    assertTrue(NameNode.initializeSharedEdits(conf, false));
  }

  @Test
  public void testInitializeSharedEditsConfiguresGenericConfKeys() throws IOException {
    Configuration conf = new Configuration();
    conf.set(DFSConfigKeys.DFS_NAMESERVICES, "ns1");
    conf.set(DFSUtil.addKeySuffixes(DFSConfigKeys.DFS_HA_NAMENODES_KEY_PREFIX,
        "ns1"), "nn1,nn2");
    conf.set(DFSUtil.addKeySuffixes(DFSConfigKeys.DFS_NAMENODE_RPC_ADDRESS_KEY,
        "ns1", "nn1"), "localhost:1234");
    assertNull(conf.get(DFSConfigKeys.DFS_NAMENODE_RPC_ADDRESS_KEY));
    NameNode.initializeSharedEdits(conf);
    assertNotNull(conf.get(DFSConfigKeys.DFS_NAMENODE_RPC_ADDRESS_KEY));
  }
}


text:
package org.apache.ignite.internal.binary.streams;

/**
 * Binary heap output stream.
 */
public final class BinaryHeapOutputStream extends BinaryAbstractOutputStream {
    /** Allocator. */
    private final BinaryMemoryAllocatorChunk chunk;

    /** Data. */
    private byte[] data;

    /**
     * Constructor.
     *
     * @param cap Initial capacity.
     */
    public BinaryHeapOutputStream(int cap) {
        this(cap, BinaryMemoryAllocator.INSTANCE.chunk());
    }

    /**
     * Constructor.
     *
     * @param cap Capacity.
     * @param chunk Chunk.
     */
    public BinaryHeapOutputStream(int cap, BinaryMemoryAllocatorChunk chunk) {
        this.chunk = chunk;

        data = chunk.allocate(cap);
    }

    /** {@inheritDoc} */
    @Override public void close() {
        chunk.release(data, pos);
    }

    /** {@inheritDoc} */
    @Override public void ensureCapacity(int cnt) {
        if (cnt > data.length) {
            int newCap = capacity(data.length, cnt);

            data = chunk.reallocate(data, newCap);
        }
    }

    /** {@inheritDoc} */
    @Override public byte[] array() {
        return data;
    }

    /** {@inheritDoc} */
    @Override public byte[] arrayCopy() {
        byte[] res = new byte[pos];

        UNSAFE.copyMemory(data, BYTE_ARR_OFF, res, BYTE_ARR_OFF, pos);

        return res;
    }

    /** {@inheritDoc} */
    @Override public boolean hasArray() {
        return true;
    }

    /** {@inheritDoc} */
    @Override protected void writeByteAndShift(byte val) {
        data[pos++] = val;
    }

    /** {@inheritDoc} */
    @Override protected void copyAndShift(Object src, long off, int len) {
        UNSAFE.copyMemory(src, off, data, BYTE_ARR_OFF + pos, len);

        shift(len);
    }

    /** {@inheritDoc} */
    @Override protected void writeShortFast(short val) {
        UNSAFE.putShort(data, BYTE_ARR_OFF + pos, val);
    }

    /** {@inheritDoc} */
    @Override protected void writeCharFast(char val) {
        UNSAFE.putChar(data, BYTE_ARR_OFF + pos, val);
    }

    /** {@inheritDoc} */
    @Override protected void writeIntFast(int val) {
        UNSAFE.putInt(data, BYTE_ARR_OFF + pos, val);
    }

    /** {@inheritDoc} */
    @Override protected void writeLongFast(long val) {
        UNSAFE.putLong(data, BYTE_ARR_OFF + pos, val);
    }

    /** {@inheritDoc} */
    @Override public void unsafeWriteByte(byte val) {
        UNSAFE.putByte(data, BYTE_ARR_OFF + pos++, val);
    }

    /** {@inheritDoc} */
    @Override public void unsafeWriteShort(short val) {
        if (!LITTLE_ENDIAN)
            val = Short.reverseBytes(val);

        UNSAFE.putShort(data, BYTE_ARR_OFF + pos, val);

        shift(2);
    }

    /** {@inheritDoc} */
    @Override public void unsafeWriteShort(int pos, short val) {
        if (!LITTLE_ENDIAN)
            val = Short.reverseBytes(val);

        UNSAFE.putShort(data, BYTE_ARR_OFF + pos, val);
    }

    /** {@inheritDoc} */
    @Override public void unsafeWriteChar(char val) {
        if (!LITTLE_ENDIAN)
            val = Character.reverseBytes(val);

        UNSAFE.putChar(data, BYTE_ARR_OFF + pos, val);

        shift(2);
    }

    /** {@inheritDoc} */
    @Override public void unsafeWriteInt(int val) {
        if (!LITTLE_ENDIAN)
            val = Integer.reverseBytes(val);

        UNSAFE.putInt(data, BYTE_ARR_OFF + pos, val);

        shift(4);
    }

    /** {@inheritDoc} */
    @Override public void unsafeWriteInt(int pos, int val) {
        if (!LITTLE_ENDIAN)
            val = Integer.reverseBytes(val);

        UNSAFE.putInt(data, BYTE_ARR_OFF + pos, val);
    }

    /** {@inheritDoc} */
    @Override public void unsafeWriteLong(long val) {
        if (!LITTLE_ENDIAN)
            val = Long.reverseBytes(val);

        UNSAFE.putLong(data, BYTE_ARR_OFF + pos, val);

        shift(8);
    }
}