text:
package net.riezebos.thoth.markdown;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.junit.Test;

import net.riezebos.thoth.markdown.filehandle.ClasspathFileSystem;
import net.riezebos.thoth.markdown.filehandle.FileHandle;
import net.riezebos.thoth.markdown.util.ProcessorError;

public class IncludeProcessorTest {

  private static final String RESOURCE_BASE = "net/riezebos/thoth/markdown/";

  @Test
  public void testIncludeImages() throws IOException {
    ClasspathFileSystem factory = getFileHandleFactory();
    IncludeProcessor includeProcessor = new IncludeProcessor();
    includeProcessor.setLibrary("/net/riezebos/thoth/");
    includeProcessor.setFileSystem(factory);
    FileHandle handle = factory.getFileHandle("/net/riezebos/thoth/markdown/IncludeImagesTest.md");
    String result = includeProcessor.execute(handle);
    assertTrue(result.indexOf("![](images/img1.txt)") != -1);
    assertTrue(result.indexOf("![](images/img2.txt)") != -1);
    assertTrue(result.indexOf("![](images/img3.txt)") != -1);
    assertTrue(result.indexOf("![](../markdown/images/img1.txt)") != -1);

    // Check generated headers of the images
    assertTrue(result.indexOf("#2 img1") != -1);
    assertTrue(result.indexOf("#3 img2") != -1);
  }

  @Test
  public void testIncludeImagesFail() throws IOException {
    ClasspathFileSystem factory = getFileHandleFactory();
    IncludeProcessor includeProcessor = new IncludeProcessor();
    includeProcessor.setLibrary("/net/riezebos/thoth/");
    includeProcessor.setFileSystem(factory);
    FileHandle handle = factory.getFileHandle("/net/riezebos/thoth/markdown/IncludeImagesFail.md");
    includeProcessor.execute(handle);
    List<ProcessorError> errors = includeProcessor.getErrors();
    assertTrue(errors.get(0).getErrorMessage().indexOf("spec invalid") != -1);
  }

  @Test
  public void testIncludeImages2() throws IOException {
    ClasspathFileSystem factory = getFileHandleFactory();
    IncludeProcessor includeProcessor = new IncludeProcessor();
    includeProcessor.setLibrary("/net/riezebos/thoth/");
    includeProcessor.setFileSystem(factory);
    FileHandle handle = factory.getFileHandle("/net/riezebos/thoth/markdown/IncludeImagesTest2.md");
    String result = includeProcessor.execute(handle);

    // Absolute link must be relativized now; so:
    assertTrue(result.indexOf("![](../markdown/images/img2.txt)") != -1);
  }

  @Test
  public void testIncludeCode() throws IOException {
    ClasspathFileSystem factory = getFileHandleFactory();
    IncludeProcessor includeProcessor = new IncludeProcessor();
    includeProcessor.setFileSystem(factory);
    FileHandle handle = factory.getFileHandle("/net/riezebos/thoth/markdown/CodeTest.md");
    String result = includeProcessor.execute(handle);
    assertTrue(result.indexOf("\tof code") != -1);
    assertTrue(result.indexOf("\twhen included") != -1);
  }

  @Test
  public void testIncludeCodeFail() throws IOException {
    ClasspathFileSystem factory = getFileHandleFactory();
    IncludeProcessor includeProcessor = new IncludeProcessor();
    includeProcessor.setFileSystem(factory);
    FileHandle handle = factory.getFileHandle("/net/riezebos/thoth/markdown/CodeFailTest.md");
    includeProcessor.execute(handle);
    List<ProcessorError> errors = includeProcessor.getErrors();
    assertTrue(errors.get(0).getErrorMessage().indexOf("not found") != -1);
  }

  @Test
  public void testIncludeCodeAbsolute() throws IOException {
    ClasspathFileSystem factory = getFileHandleFactory();
    IncludeProcessor includeProcessor = new IncludeProcessor();
    includeProcessor.setLibrary("/net/riezebos/thoth/");
    includeProcessor.setFileSystem(factory);
    FileHandle handle = factory.getFileHandle("/net/riezebos/thoth/markdown/CodeTest2.md");
    String result = includeProcessor.execute(handle);
    assertTrue(result.indexOf("\tof code") != -1);
    assertTrue(result.indexOf("\twhen included") != -1);
  }

  @Test
  public void testIncludeLevels() throws IOException {
    ClasspathFileSystem factory = getFileHandleFactory();
    IncludeProcessor includeProcessor = new IncludeProcessor();
    includeProcessor.setFileSystem(factory);
    FileHandle handle = factory.getFileHandle("/net/riezebos/thoth/markdown/IncludeTest1.md");
    String result = includeProcessor.execute(handle);
    // Must have a level two header because of indent level 1 specified at include:
    assertTrue(result.indexOf("##1") != -1);
    long latestIncludeModificationDate = includeProcessor.getLatestIncludeModificationDate();
    assertEquals(80000, latestIncludeModificationDate);
  }

  @Test
  public void testToc() throws IOException {
    ClasspathFileSystem factory = getFileHandleFactory();
    IncludeProcessor includeProcessor = new IncludeProcessor();
    includeProcessor.setFileSystem(factory);
    includeProcessor.loadSoftLinks(getResource("softlinks.properties"));
    String source = includeProcessor.execute("IncludeProcessor.md", getResource("IncludeProcessor.md"));
    assertTrue(source.indexOf("<tableofcontents>") != -1);
    assertTrue(source.indexOf("###[1 Chapter one](#1chapterone)") != -1);

    includeProcessor.setSoftlinkFile("softlinks.properties");
    includeProcessor.reset();

    source = includeProcessor.execute(null, getResource("IncludeProcessor.md"));
    assertTrue(source.indexOf("###[1 Chapter one](#1chapterone)") != -1);

    includeProcessor.reset();
    FileHandle handle = factory.getFileHandle("/net/riezebos/thoth/markdown/IncludeProcessor.md");
    source = includeProcessor.execute(handle);
    assertTrue(source.indexOf("###[1 Chapter one](#1chapterone)") != -1);
  }

  @Test
  public void testCyclic() throws IOException {
    ClasspathFileSystem factory = getFileHandleFactory();
    IncludeProcessor includeProcessor = new IncludeProcessor();
    includeProcessor.setFileSystem(factory);
    FileHandle cyclic = factory.getFileHandle("/net/riezebos/thoth/markdown/Cyclic.md");
    includeProcessor.execute(cyclic);
    List<ProcessorError> errors = includeProcessor.getErrors();
    assertTrue(errors.get(0).getErrorMessage().indexOf("include depth") != -1);
  }

  @Test
  public void testIncludeAbs() throws IOException {
    ClasspathFileSystem factory = getFileHandleFactory();
    IncludeProcessor includeProcessor = new IncludeProcessor();
    includeProcessor.setLibrary("/net/riezebos/thoth/");
    includeProcessor.setFileSystem(factory);
    FileHandle handle = factory.getFileHandle("/net/riezebos/thoth/markdown/IncludeTestAbs.md");
    String result = includeProcessor.execute(handle);

    // Absolute link must be relativized now; so:
    assertTrue(result.indexOf("Some other text") != -1);
  }

  @Test
  public void testIncludeFail() throws IOException {
    ClasspathFileSystem factory = getFileHandleFactory();
    IncludeProcessor includeProcessor = new IncludeProcessor();
    includeProcessor.setLibrary("/net/riezebos/thoth/markdown");
    includeProcessor.setSoftlinkFile("softlinks.properties");
    includeProcessor.setFileSystem(factory);
    FileHandle handle = factory.getFileHandle("/net/riezebos/thoth/markdown/IncludeTestFail.md");
    includeProcessor.execute(handle);
    List<ProcessorError> errors = includeProcessor.getErrors();
    assertTrue(errors.get(0).getErrorMessage().indexOf("Include not found") != -1);

    includeProcessor.reset();
    handle = factory.getFileHandle("/net/riezebos/thoth/markdown/InvalidSoftlink.md");
    includeProcessor.execute(handle);
    errors = includeProcessor.getErrors();
    assertTrue(errors.get(0).getErrorMessage().indexOf("Include not found") != -1);
    assertTrue(errors.get(0).getErrorMessage().indexOf("translated by softlink") != -1);

  }

  protected ClasspathFileSystem getFileHandleFactory() throws IOException {
    ClasspathFileSystem factory = new ClasspathFileSystem();
    factory.registerFiles("/net/riezebos/thoth/resources.lst");
    return factory;
  }

  protected InputStream getResource(String testResource) {
    InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(RESOURCE_BASE + testResource);
    return in;
  }

  @Test
  public void testUsage() throws IOException {
    IncludeProcessor includeProcessor = new IncludeProcessor();
    String outMessage = execMain(includeProcessor, new String[] {"-help"});
    assertTrue(outMessage.indexOf("Usage:") != -1);

    includeProcessor.setFileSystem(getFileHandleFactory());
    includeProcessor.setLibrary("/net/riezebos/thoth/");
    outMessage = execMain(includeProcessor, new String[] {"-file", "/net/riezebos/thoth/markdown/IncludeProcessor.md"//
        , "-library", "/net/riezebos/thoth"//
        , "-softlinkFile", "softlinks.properties"//
        , "-numbering", "0"//
    });
    assertTrue(outMessage.indexOf("##Paragraph one of chapter one") != -1);
  }

  @Test
  public void testTarget() throws IOException {
    IncludeProcessor includeProcessor = new IncludeProcessor();
    includeProcessor.setFileSystem(getFileHandleFactory());
    includeProcessor.setLibrary("/net/riezebos/thoth/");
    File tempFile = File.createTempFile("tmp", "tmp");
    tempFile.deleteOnExit();
    execMain(includeProcessor, new String[] {"-file", "/net/riezebos/thoth/markdown/IncludeProcessor.md"//
        , "-library", "/net/riezebos/thoth"//
        , "-softlinkFile", "softlinks.properties"//
        , "-target", tempFile.getAbsolutePath()//
    });
    BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(tempFile), "UTF-8"));
    String line = br.readLine();
    assertTrue(line != null && line.equals("MARKDOWN TESTS"));
    br.close();
  }

  private String execMain(IncludeProcessor includeProcessor, String[] args) throws FileNotFoundException, IOException, UnsupportedEncodingException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    PrintStream out = new PrintStream(bos, true);
    includeProcessor.setOut(out);
    includeProcessor.execute(args);
    out.close();
    String outMessage = new String(bos.toByteArray(), "UTF-8");
    return outMessage;
  }

}


text:
import Vue from 'vue'
import mockFirebaseApp from '~/__mocks__/firebaseAppMock'
import mockGetters from '~/__mocks__/getterMocks'
jest.mock('~/firebaseapp', () => mockFirebaseApp)
jest.mock('~/store/getters', () => mockGetters)
import store from '~/store'
import IndexPage from '~/pages/index'
import AboutPage from '~/pages/about'
import LoginPage from '~/pages/login'
import PomodoroPage from '~/pages/pomodoro'
import SettingsPage from '~/pages/settings'
import StatisticsPage from '~/pages/statistics'
import WorkoutsPage from '~/pages/workouts'

describe('pages', () => {
  test('index snapshot', () => {
    let $mounted = new Vue({
      template: '<index-page></index-page>',
      store: store(),
      components: {
        'index-page': IndexPage
      }
    }).$mount()
    let $html = $mounted.$el.outerHTML
    expect($html).toMatchSnapshot()
  })

  test('about snapshot', () => {
    let $mounted = new Vue({
      template: '<about-page></about-page>',
      store: store(),
      components: {
        'about-page': AboutPage
      }
    }).$mount()
    let $html = $mounted.$el.outerHTML
    expect($html).toMatchSnapshot()
  })

  test('login snapshot', () => {
    let $mounted = new Vue({
      template: '<login-page></login-page>',
      store: store(),
      components: {
        'login-page': LoginPage
      }
    }).$mount()
    let $html = $mounted.$el.outerHTML
    expect($html).toMatchSnapshot()
  })

  test('pomodoro snapshot', () => {
    let $mounted = new Vue({
      template: '<pomodoro-page></pomodoro-page>',
      store: store(),
      components: {
        'pomodoro-page': PomodoroPage
      }
    }).$mount()
    let $html = $mounted.$el.outerHTML
    expect($html).toMatchSnapshot()
  })

  test('settings snapshot', () => {
    let $mounted = new Vue({
      template: '<settings-page></settings-page>',
      store: store(),
      components: {
        'settings-page': SettingsPage
      }
    }).$mount()
    let $html = $mounted.$el.outerHTML
    expect($html).toMatchSnapshot()
  })

  test('statistics snapshot', () => {
    let $mounted = new Vue({
      template: '<statistics-page></statistics-page>',
      store: store(),
      components: {
        'statistics-page': StatisticsPage
      }
    }).$mount()
    let $html = $mounted.$el.outerHTML
    expect($html).toMatchSnapshot()
  })

  test('workouts snapshot', () => {
    let $mounted = new Vue({
      template: '<workouts-page></workouts-page>',
      store: store(),
      components: {
        'workouts-page': WorkoutsPage
      }
    }).$mount()
    let $html = $mounted.$el.outerHTML
    expect($html).toMatchSnapshot()
  })
})

redpajama_set_name: RedPajamaGithub


text:
import style from './section.module.scss';

export interface SectionProps {
  make: 'wide' | 'narrow' | 'readable' | 'contained';
}

export const Section: React.FC<SectionProps> = ({ children, make = 'contained' }) => {
  const classNames: string[] = [style.Section];

  switch (make) {
    case 'contained':
      // classNames.push(style.Section_make_contained);
      break;
    case 'narrow':
      classNames.push(style.Section_make_narrow);
      break;
    case 'wide':
      classNames.push(style.Section_make_wide);
      break;
    case 'readable':
      classNames.push(style.Section_make_readable);
      break;
    default:
      throw new Error(`Unknown section type: ${make}`);
    // no default
  }

  const className = classNames.join(' ');
  return
{children}
;
};


text:
<?php

/**
 * @package CRM
 * @copyright CiviCRM LLC (c) 2004-2015
 *
 * Generated from xml/schema/CRM/Core/Tag.xml
 * DO NOT EDIT.  Generated by CRM_Core_CodeGen
 */
require_once 'CRM/Core/DAO.php';
require_once 'CRM/Utils/Type.php';
class CRM_Core_DAO_Tag extends CRM_Core_DAO
{
  /**
   * static instance to hold the table name
   *
   * @var string
   */
  static $_tableName = 'civicrm_tag';
  /**
   * static instance to hold the field values
   *
   * @var array
   */
  static $_fields = null;
  /**
   * static instance to hold the keys used in $_fields for each field.
   *
   * @var array
   */
  static $_fieldKeys = null;
  /**
   * static instance to hold the FK relationships
   *
   * @var string
   */
  static $_links = null;
  /**
   * static instance to hold the values that can
   * be imported
   *
   * @var array
   */
  static $_import = null;
  /**
   * static instance to hold the values that can
   * be exported
   *
   * @var array
   */
  static $_export = null;
  /**
   * static value to see if we should log any modifications to
   * this table in the civicrm_log table
   *
   * @var boolean
   */
  static $_log = true;
  /**
   * Tag ID
   *
   * @var int unsigned
   */
  public $id;
  /**
   * Name of Tag.
   *
   * @var string
   */
  public $name;
  /**
   * Optional verbose description of the tag.
   *
   * @var string
   */
  public $description;
  /**
   * Optional parent id for this tag.
   *
   * @var int unsigned
   */
  public $parent_id;
  /**
   * Is this tag selectable / displayed
   *
   * @var boolean
   */
  public $is_selectable;
  /**
   *
   * @var boolean
   */
  public $is_reserved;
  /**
   *
   * @var boolean
   */
  public $is_tagset;
  /**
   *
   * @var string
   */
  public $used_for;
  /**
   * FK to civicrm_contact, who created this tag
   *
   * @var int unsigned
   */
  public $created_id;
  /**
   * Date and time that tag was created.
   *
   * @var datetime
   */
  public $created_date;
  /**
   * class constructor
   *
   * @return civicrm_tag
   */
  function __construct()
  {
    $this->__table = 'civicrm_tag';
    parent::__construct();
  }
  /**
   * Returns foreign keys and entity references
   *
   * @return array
   *   [CRM_Core_Reference_Interface]
   */
  static function getReferenceColumns()
  {
    if (!self::$_links) {
      self::$_links = static ::createReferenceColumns(__CLASS__);
      self::$_links[] = new CRM_Core_Reference_Basic(self::getTableName() , 'parent_id', 'civicrm_tag', 'id');
      self::$_links[] = new CRM_Core_Reference_Basic(self::getTableName() , 'created_id', 'civicrm_contact', 'id');
    }
    return self::$_links;
  }
  /**
   * Returns all the column names of this table
   *
   * @return array
   */
  static function &fields()
  {
    if (!(self::$_fields)) {
      self::$_fields = array(
        'id' => array(
          'name' => 'id',
          'type' => CRM_Utils_Type::T_INT,
          'title' => ts('Tag ID') ,
          'description' => 'Tag ID',
          'required' => true,
        ) ,
        'name' => array(
          'name' => 'name',
          'type' => CRM_Utils_Type::T_STRING,
          'title' => ts('Tag Name') ,
          'description' => 'Name of Tag.',
          'required' => true,
          'maxlength' => 64,
          'size' => CRM_Utils_Type::BIG,
        ) ,
        'description' => array(
          'name' => 'description',
          'type' => CRM_Utils_Type::T_STRING,
          'title' => ts('Description') ,
          'description' => 'Optional verbose description of the tag.',
          'maxlength' => 255,
          'size' => CRM_Utils_Type::HUGE,
        ) ,
        'parent_id' => array(
          'name' => 'parent_id',
          'type' => CRM_Utils_Type::T_INT,
          'title' => ts('Parent Tag') ,
          'description' => 'Optional parent id for this tag.',
          'default' => 'NULL',
          'FKClassName' => 'CRM_Core_DAO_Tag',
        ) ,
        'is_selectable' => array(
          'name' => 'is_selectable',
          'type' => CRM_Utils_Type::T_BOOLEAN,
          'title' => ts('Display Tag?') ,
          'description' => 'Is this tag selectable / displayed',
          'default' => '1',
        ) ,
        'is_reserved' => array(
          'name' => 'is_reserved',
          'type' => CRM_Utils_Type::T_BOOLEAN,
          'title' => ts('Reserved') ,
        ) ,
        'is_tagset' => array(
          'name' => 'is_tagset',
          'type' => CRM_Utils_Type::T_BOOLEAN,
          'title' => ts('Tagset') ,
        ) ,
        'used_for' => array(
          'name' => 'used_for',
          'type' => CRM_Utils_Type::T_STRING,
          'title' => ts('Used For') ,
          'maxlength' => 64,
          'size' => CRM_Utils_Type::BIG,
          'default' => 'NULL',
          'html' => array(
            'type' => 'Select',
          ) ,
          'pseudoconstant' => array(
            'optionGroupName' => 'tag_used_for',
            'optionEditPath' => 'civicrm/admin/options/tag_used_for',
          )
        ) ,
        'created_id' => array(
          'name' => 'created_id',
          'type' => CRM_Utils_Type::T_INT,
          'title' => ts('Tag Created By') ,
          'description' => 'FK to civicrm_contact, who created this tag',
          'FKClassName' => 'CRM_Contact_DAO_Contact',
        ) ,
        'created_date' => array(
          'name' => 'created_date',
          'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
          'title' => ts('Tag Created Date') ,
          'description' => 'Date and time that tag was created.',
        ) ,
      );
    }
    return self::$_fields;
  }
  /**
   * Returns an array containing, for each field, the arary key used for that
   * field in self::$_fields.
   *
   * @return array
   */
  static function &fieldKeys()
  {
    if (!(self::$_fieldKeys)) {
      self::$_fieldKeys = array(
        'id' => 'id',
        'name' => 'name',
        'description' => 'description',
        'parent_id' => 'parent_id',
        'is_selectable' => 'is_selectable',
        'is_reserved' => 'is_reserved',
        'is_tagset' => 'is_tagset',
        'used_for' => 'used_for',
        'created_id' => 'created_id',
        'created_date' => 'created_date',
      );
    }
    return self::$_fieldKeys;
  }
  /**
   * Returns the names of this table
   *
   * @return string
   */
  static function getTableName()
  {
    return self::$_tableName;
  }
  /**
   * Returns if this table needs to be logged
   *
   * @return boolean
   */
  function getLog()
  {
    return self::$_log;
  }
  /**
   * Returns the list of fields that can be imported
   *
   * @param bool $prefix
   *
   * @return array
   */
  static function &import($prefix = false)
  {
    if (!(self::$_import)) {
      self::$_import = array();
      $fields = self::fields();
      foreach($fields as $name => $field) {
        if (CRM_Utils_Array::value('import', $field)) {
          if ($prefix) {
            self::$_import['tag'] = & $fields[$name];
          } else {
            self::$_import[$name] = & $fields[$name];
          }
        }
      }
    }
    return self::$_import;
  }
  /**
   * Returns the list of fields that can be exported
   *
   * @param bool $prefix
   *
   * @return array
   */
  static function &export($prefix = false)
  {
    if (!(self::$_export)) {
      self::$_export = array();
      $fields = self::fields();
      foreach($fields as $name => $field) {
        if (CRM_Utils_Array::value('export', $field)) {
          if ($prefix) {
            self::$_export['tag'] = & $fields[$name];
          } else {
            self::$_export[$name] = & $fields[$name];
          }
        }
      }
    }
    return self::$_export;
  }
}


text:
apt-get install -y php zip

# Install composer
cd ../
wget https://raw.githubusercontent.com/Erdiko/docker/master/php/scripts/composer.sh
chmod 770 composer.sh
./composer.sh

# Install erdiko
composer create erdiko/erdiko erdiko dev-develop --keep-vcs

# Swap out with latest code to be tested
rm -rf ./erdiko/vendor/erdiko/core
cp -R ./code ./erdiko/vendor/erdiko/core

cd erdiko
echo $CIRCLE_BRANCH

# decide which docker environment to bring up
if [ "$CIRCLE_BRANCH" == "release" ]; then
    docker-compose -f docker-compose.travis.regression.yml up -d
else
    docker-compose -f docker-compose-ci.yml up -d
fi

# copy code into container (Circle CI doesn't allow volume maps)
docker cp ./ erdiko_php:/code
docker cp ./ erdiko_web:/code

docker-compose ps
ls -lah


text:
        <button type="button" class="close" data-dismiss="modal">×</button>

Add People

                We're adding your users, but Canvas is responding slowly.

                Please check the People page in a few minutes to verify that your new users have been added.

        <button type="button" class="btn btn-primary" data-dismiss="modal">Done</button>


text:
<?php

/*
	Application config
	----------------------------------- */

	namespace CRD\Core;

	// Default timezone
	date_default_timezone_set('Europe/London');

	// Start the app
	$app = new App($path);

	// App name, also cache prefix
	$app->name = 'Leaderboard';

	// Set app version string
	$app->version = '1.4';

	// MySQL connection settings
	$app->credentials->host = 'localhost';
	$app->credentials->database = 'leaderboard';
	$app->credentials->username = 'sample';
	$app->credentials->password = 'password';

	// Add queries config
	require_once ($path . '/config.queries.php');
?>


text:
HTML templating languages can be lovely, but it's often a pain to rewrite raw HTML into their particular syntax. Metamorphic lets you do 99% of the work with a simple command-line tool.

## Install
Metamorphic is written using Node.js and distributed as an NPM package. Once you've [installed NPM](http://nodejs.org/download/), copy the following into your Terminal:

`npm install metamorphic`

## Usage
To convert a HTML file into [HAML](http://haml.info):

`metamorphic haml index.html`

Metamorphic supports several templating languages:

* [HAML](http://haml.info) as `metamorphic haml <file>`
* [Jade](http://jade-lang.com) as `metamorphic jade <file>`
* [Slim](http://slim-lang.com) as `metamorphic slim <file>`
* [Compojure](https://github.com/weavejester/compojure) as `metamorphic compojure <file>`

## Contribute
Metamorphic was built by [Michael Mokrysz](https://46bit.com) at the very end of 2012, and is openly licensed under two-clause BSD.

I'd love contributions (whether code refactoring, new templating languages, or fixes) - fork the repo on [Github](https://github.com/46Bit/metamorphic) and get hacking.


text:
class RemoveEstateFromBlocks < ActiveRecord::Migration[4.2]
  def change
    remove_column :blocks, :estate, :string
  end
end


text:
import GafferUI
import GafferUITest

class ModuleTest( GafferUITest.TestCase ) :

	def testUUID( self ) :

		import uuid
		uuid.uuid4()

	def testNamespacePollution( self ) :

		import GafferUI

		self.assertRaises( AttributeError, getattr, GafferUI, "uuid" )
		self.assertRaises( AttributeError, getattr, GafferUI, "IECore" )
		self.assertRaises( AttributeError, getattr, GafferUI, "Gaffer" )

if __name__ == "__main__":
	unittest.main()


text:
<?php

namespace Craft;

class GitLab_MergerequestsService extends BaseApplicationComponent
{

  public function getMergeRequests($projectid, $options=array())
  {
    $action='projects/'.intval($projectid).'/merge_requests';
    return craft()->gitLab->_call($action, $options);
  }

  public function getMergeRequest($projectid, $mrid, $options=array())
  {
    $action='projects/'.intval($projectid).'/merge_requests/'.intval($mrid);
    return craft()->gitLab->_call($action, $options);
  }

  public function getMergeRequestCommits($projectid, $mrid, $options=array())
  {
    $action='projects/'.intval($projectid).'/merge_requests/'.intval($mrid).'/commits';
    return craft()->gitLab->_call($action, $options);
  }

  public function getMergeRequestChanges($projectid, $mrid, $options=array())
  {
    $action='projects/'.intval($projectid).'/merge_requests/'.intval($mrid).'/changes';
    return craft()->gitLab->_call($action, $options);
  }

  public function getMergeRequestClosesIssues($projectid, $mrid, $options=array())
  {
    $action='projects/'.intval($projectid).'/merge_requests/'.intval($mrid).'/closes_issues';
    return craft()->gitLab->_call($action, $options);
  }

}


text:
/*jslint indent: 2, plusplus: true */
"use strict";

module.exports = {
  app: undefined,
  pathUtils: require('./pathUtils.js'),
  init: function (app) {
    this.app = app;
  },
  canHandleMethod: function (method) {
    return method === '/ls/';
  },
  handle: function (method, params, req, res, errCallback) {
    var
      path = this.pathUtils.fixPath(params.path),
      node = this.pathUtils.nodeForPath(this.app.library.tree, path),
      result = [],
      i,
      child,
      o,
      pathPrefix = (path === '/') ? '/' : path + '/';

    if (node === undefined) {
      errCallback('path not found');
    } else {
      for (i = 0; i < node.children.length; ++i) {
        child = node.children[i];
        o = { path: pathPrefix + child.name };
        o.name = child.name;

        if (child.children) { // folder
          o.type = 'directory';
          o.count = child.filesCount;
          if (o.count === 0) {
            continue;
          }
        } else {
          o.type = 'file';
          if (!child.numberOfChunks) {
            continue;
          }
        }

        result.push(o);
      }

      res.end(JSON.stringify(result));
    }
  }
};


text:
define(['backbone', 'config', 'jQuery'], function (Backbone, Config, $) {
    var voteModel = Backbone.Model.extend({
        defaults: {
            candidate_id: '0',
            first_name: 'FirstName',
            last_name: 'LastName'
        },

        voteByCandidateId: function (candidate_id) {
            $.ajax({
                url: Config.path + '/vote',
                param: {
                    candidate_id: candidate_id
                }
            }).done(function (data) {
                console.log(data);
            });
        },
        url: Config.path + '/vote'
    });
    var voteModelCollection = Backbone.Collection.extend({
        model: voteModel,
        url: Config.path + '/vote'
    });

});


text:
devcon remove vjoy.inf "ROOT\VID_1234&PID_BEAD&REV_0002"
devcon dp_enum
@ECHO -------------------------------
@ECHO Type devcon dp_delete oem*.inf
@ECHO -------------------------------


text:
module JSONAPI
  class ResourceControllerMetal < ActionController::Metal
    MODULES = [
      AbstractController::Rendering,
      ActionController::Rendering,
      ActionController::Renderers::All,
      ActionController::StrongParameters,
      ActionController::ForceSSL,
      ActionController::Instrumentation,
      JSONAPI::ActsAsResourceController
    ].freeze

    MODULES.each do |mod|
      include mod
    end
  end
end


text:
import os
import sys
import os.path
import socket

import mock
from mock import patch

import libcloud.security

from libcloud.utils.py3 import reload
from libcloud.httplib_ssl import LibcloudHTTPSConnection

from libcloud.test import unittest

ORIGINAL_CA_CERS_PATH = libcloud.security.CA_CERTS_PATH

class TestHttpLibSSLTests(unittest.TestCase):

    def setUp(self):
        libcloud.security.VERIFY_SSL_CERT = False
        libcloud.security.CA_CERTS_PATH = ORIGINAL_CA_CERS_PATH
        self.httplib_object = LibcloudHTTPSConnection('foo.bar')

    def test_custom_ca_path_using_env_var_doesnt_exist(self):
        os.environ['SSL_CERT_FILE'] = '/foo/doesnt/exist'

        try:
            reload(libcloud.security)
        except ValueError:
            e = sys.exc_info()[1]
            msg = 'Certificate file /foo/doesnt/exist doesn\'t exist'
            self.assertEqual(str(e), msg)
        else:
            self.fail('Exception was not thrown')

    def test_custom_ca_path_using_env_var_is_directory(self):
        file_path = os.path.dirname(os.path.abspath(__file__))
        os.environ['SSL_CERT_FILE'] = file_path

        expected_msg = 'Certificate file can\'t be a directory'
        self.assertRaisesRegexp(ValueError, expected_msg,
                                reload, libcloud.security)

    def test_custom_ca_path_using_env_var_exist(self):
        # When setting a path we don't actually check that a valid CA file is
        # provided.
        # This happens later in the code in httplib_ssl.connect method
        file_path = os.path.abspath(__file__)
        os.environ['SSL_CERT_FILE'] = file_path

        reload(libcloud.security)

        self.assertEqual(libcloud.security.CA_CERTS_PATH, [file_path])

    @patch('warnings.warn')
    def test_setup_verify(self, _):
        libcloud.security.CA_CERTS_PATH = []

        # Should throw a runtime error
        libcloud.security.VERIFY_SSL_CERT = True

        expected_msg = libcloud.security.CA_CERTS_UNAVAILABLE_ERROR_MSG
        self.assertRaisesRegexp(RuntimeError, expected_msg,
                                self.httplib_object._setup_verify)

        libcloud.security.VERIFY_SSL_CERT = False
        self.httplib_object._setup_verify()

    @patch('warnings.warn')
    def test_setup_ca_cert(self, _):
        # verify = False, _setup_ca_cert should be a no-op
        self.httplib_object.verify = False
        self.httplib_object._setup_ca_cert()

        self.assertEqual(self.httplib_object.ca_cert, None)

        # verify = True, a valid path is provided, self.ca_cert should be set to
        # a valid path
        self.httplib_object.verify = True

        libcloud.security.CA_CERTS_PATH = [os.path.abspath(__file__)]
        self.httplib_object._setup_ca_cert()

        self.assertTrue(self.httplib_object.ca_cert is not None)

        # verify = True, no CA certs are available, exception should be thrown
        libcloud.security.CA_CERTS_PATH = []

        expected_msg = libcloud.security.CA_CERTS_UNAVAILABLE_ERROR_MSG
        self.assertRaisesRegexp(RuntimeError, expected_msg,
                                self.httplib_object._setup_ca_cert)

    @mock.patch('socket.create_connection', mock.MagicMock())
    @mock.patch('socket.socket', mock.MagicMock())
    @mock.patch('ssl.wrap_socket')
    def test_connect_throws_friendly_error_message_on_ssl_wrap_connection_reset_by_peer(self, mock_wrap_socket):
        # Test that we re-throw a more friendly error message in case
        # "connection reset by peer" error occurs when trying to establish a
        # SSL connection
        libcloud.security.VERIFY_SSL_CERT = True
        self.httplib_object.verify = True
        self.httplib_object.http_proxy_used = False

        # No connection reset by peer, original exception should be thrown
        mock_wrap_socket.side_effect = Exception('foo bar fail')

        expected_msg = 'foo bar fail'
        self.assertRaisesRegexp(Exception, expected_msg,
                                self.httplib_object.connect)

        # Connection reset by peer, wrapped exception with friendly error
        # message should be thrown
        mock_wrap_socket.side_effect = socket.error('Connection reset by peer')

        expected_msg = 'Failed to establish SSL / TLS connection'
        self.assertRaisesRegexp(socket.error, expected_msg,
                                self.httplib_object.connect)

        # Same error but including errno
        with self.assertRaises(socket.error) as cm:
            mock_wrap_socket.side_effect = socket.error(104, 'Connection reset by peer')
            self.httplib_object.connect()

        e = cm.exception
        self.assertEqual(e.errno, 104)
        self.assertTrue(expected_msg in str(e))

if __name__ == '__main__':
    sys.exit(unittest.main())


text:
#import "EC2InstanceBlockDeviceMappingSpecification.h"

#ifdef AWS_MULTI_FRAMEWORK
#import <AWSRuntime/AmazonServiceRequestConfig.h>
#else
#import "../AmazonServiceRequestConfig.h"
#endif

/**
 * Modify Instance Attribute Request
 */

@interface EC2ModifyInstanceAttributeRequest:AmazonServiceRequestConfig

{
    NSString       *instanceId;
    NSString       *attribute;
    NSString       *value;
    NSMutableArray *blockDeviceMappings;
    bool           sourceDestCheck;
    bool           sourceDestCheckIsSet;
    bool           disableApiTermination;
    bool           disableApiTerminationIsSet;
    NSString       *instanceType;
    NSString       *kernel;
    NSString       *ramdisk;
    NSString       *userData;
    NSString       *instanceInitiatedShutdownBehavior;
    NSMutableArray *groups;
    bool           ebsOptimized;
    bool           ebsOptimizedIsSet;
}

/**
 * The ID of the instance whose attribute is being modified.
 */
@property (nonatomic, retain) NSString *instanceId;

/**
 * The name of the attribute being modified.
 Available attribute
 * names: instanceType, kernel,
 * ramdisk, userData,
 * disableApiTermination,
 * instanceInitiatedShutdownBehavior,
 * rootDevice, blockDeviceMapping
 *

 * Constraints:

 * Allowed Values: instanceType, kernel, ramdisk, userData, disableApiTermination, instanceInitiatedShutdownBehavior, rootDeviceName, blockDeviceMapping, productCodes, sourceDestCheck, groupSet, ebsOptimized
 */
@property (nonatomic, retain) NSString *attribute;

/**
 * The new value of the instance attribute being modified.
 Only valid
 * when kernel, ramdisk, userData,
 * disableApiTermination or
 * instanceInitiateShutdownBehavior is specified as the
 * attribute being modified.
 */
@property (nonatomic, retain) NSString *value;

/**
 * The new block device mappings for the instance whose attributes are
 * being modified.
 Only valid when blockDeviceMapping is specified as
 * the attribute being modified.
 */
@property (nonatomic, retain) NSMutableArray *blockDeviceMappings;

/**
 * Boolean value
 */
@property (nonatomic) bool           sourceDestCheck;

@property (nonatomic, readonly) bool sourceDestCheckIsSet;

/**
 * Boolean value
 */
@property (nonatomic) bool           disableApiTermination;

@property (nonatomic, readonly) bool disableApiTerminationIsSet;

/**
 * String value
 */
@property (nonatomic, retain) NSString *instanceType;

/**
 * String value
 */
@property (nonatomic, retain) NSString *kernel;

/**
 * String value
 */
@property (nonatomic, retain) NSString *ramdisk;

/**
 * String value
 */
@property (nonatomic, retain) NSString *userData;

/**
 * String value
 */
@property (nonatomic, retain) NSString *instanceInitiatedShutdownBehavior;

/**
 * The value of the Groups property for this object.
 */
@property (nonatomic, retain) NSMutableArray *groups;

/**
 * Boolean value
 */
@property (nonatomic) bool           ebsOptimized;

@property (nonatomic, readonly) bool ebsOptimizedIsSet;

/**
 * Default constructor for a new ModifyInstanceAttributeRequest object.  Callers should use the
 * property methods to initialize this object after creating it.
 */
-(id)init;

/**
 * Constructs a new ModifyInstanceAttributeRequest object.
 * Callers should use properties to initialize any additional object members.
 *
 * @param theInstanceId The ID of the instance whose attribute is being
 * modified.
 * @param theAttribute The name of the attribute being modified.

 * Available attribute names: instanceType,
 * kernel, ramdisk, userData,
 * disableApiTermination,
 * instanceInitiatedShutdownBehavior,
 * rootDevice, blockDeviceMapping
 */
-(id)initWithInstanceId:(NSString *)theInstanceId andAttribute:(NSString *)theAttribute;

/**
 * Adds a single object to blockDeviceMappings.
 * This function will alloc and init blockDeviceMappings if not already done.
 */
-(void)addBlockDeviceMapping:(EC2InstanceBlockDeviceMappingSpecification *)blockDeviceMappingObject;

/**
 * Adds a single object to groups.
 * This function will alloc and init groups if not already done.
 */
-(void)addGroup:(NSString *)groupObject;

/**
 * Returns a string representation of this object; useful for testing and
 * debugging.
 *
 * @return A string representation of this object.
 */
-(NSString *)description;

@end


text:
package com.sap.cloud.lm.sl.cf.persistence.services;

import static org.junit.Assert.assertEquals;
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.InputStream;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;

import com.sap.cloud.lm.sl.cf.persistence.DataSourceWithDialect;
import com.sap.cloud.lm.sl.cf.persistence.model.FileEntry;
import com.sap.cloud.lm.sl.cf.persistence.processors.DefaultFileDownloadProcessor;
import com.sap.cloud.lm.sl.cf.persistence.processors.DefaultFileUploadProcessor;

public class FileServiceTest extends DatabaseFileServiceTest {

    @Mock
    private FileStorage fileStorage;

    @Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
        super.setUp();
    }

    @Test
    public void addFileUploadFileErrorTest() throws Exception {
        Mockito.doThrow(new FileStorageException("expected exception"))
            .when(fileStorage)
            .addFile((FileEntry) Mockito.any(), (File) Mockito.any());

        InputStream resourceStream = getResource(PIC_RESOURCE_NAME);
        String space = SPACE_1;
        String namespace = NAMESPACE_1;
        try {
            fileService.addFile(space, namespace, PIC_STORAGE_NAME, new DefaultFileUploadProcessor(), resourceStream);
            fail("addFile should fail with exception");
        } catch (FileStorageException e) {
            Mockito.verify(fileStorage, Mockito.times(1))
                .addFile((FileEntry) Mockito.any(), (File) Mockito.any());
            List<FileEntry> listFiles = fileService.listFiles(space, namespace);
            assertEquals(0, listFiles.size());
        }
    }

    @Test
    public void processFileContentTest() throws Exception {
        DefaultFileDownloadProcessor downloadProcessor = new DefaultFileDownloadProcessor(SPACE_1, "1111-2222-3333-4444",
            Mockito.mock(FileContentProcessor.class));
        fileService.processFileContent(downloadProcessor);
        Mockito.verify(fileStorage, Mockito.times(1))
            .processFileContent(Mockito.eq(downloadProcessor));
    }

    @Test
    public void deleteBySpaceAndNamespaceTest() throws Exception {
        super.deleteBySpaceAndNamespaceTest();
        Mockito.verify(fileStorage, Mockito.times(1))
            .deleteFilesBySpaceAndNamespace(Mockito.eq(SPACE_1), Mockito.eq(NAMESPACE_1));
    }

    @Test
    public void deleteBySpaceAndNamespaceWithTwoNamespacesTest() throws Exception {
        super.deleteBySpaceAndNamespaceWithTwoNamespacesTest();
        Mockito.verify(fileStorage, Mockito.times(1))
            .deleteFilesBySpaceAndNamespace(Mockito.eq(SPACE_1), Mockito.eq(NAMESPACE_1));
    }

    @Test
    public void deleteBySpaceTest() throws Exception {
        super.deleteBySpaceTest();
        Mockito.verify(fileStorage, Mockito.times(1))
            .deleteFilesBySpace(Mockito.eq(SPACE_1));
    }

    @Test
    public void deleteFileTest() throws Exception {
        FileEntry fileEntry = addTestFile(SPACE_1, NAMESPACE_1);

        boolean deleteFile = fileService.deleteFile(SPACE_2, fileEntry.getId());
        assertFalse(deleteFile);
        Mockito.verify(fileStorage, Mockito.times(1))
            .deleteFile(Mockito.eq(fileEntry.getId()), Mockito.eq(SPACE_2));

        deleteFile = fileService.deleteFile(SPACE_1, fileEntry.getId());
        assertTrue(deleteFile);
        Mockito.verify(fileStorage, Mockito.times(1))
            .deleteFile(Mockito.eq(fileEntry.getId()), Mockito.eq(SPACE_1));
    }

    @Test
    public void deleteFileErrorTest() throws Exception {
        FileEntry fileEntry = addTestFile(SPACE_1, NAMESPACE_1);

        Mockito.doThrow(new FileStorageException("expected exception"))
            .when(fileStorage)
            .deleteFile(Mockito.eq(fileEntry.getId()), Mockito.eq(SPACE_1));

        try {
            fileService.deleteFile(SPACE_1, fileEntry.getId());
            fail("deleteFile should fail with an exception!");
        } catch (FileStorageException e) {
            Mockito.verify(fileStorage, Mockito.times(1))
                .deleteFile(Mockito.eq(fileEntry.getId()), Mockito.eq(SPACE_1));
            FileEntry fileStillExists = fileService.getFile(SPACE_1, fileEntry.getId());
            assertNotNull(fileStillExists);
        }
    }

    @Test
    public void deleteByModificationTimeTest() throws Exception {
        super.deleteByModificationTimeTest();
        Mockito.verify(fileStorage, Mockito.times(1))
            .deleteFilesModifiedBefore((Date) Mockito.any());
    }

    @Test
    @SuppressWarnings("unchecked")
    public void deleteFilesEntriesWithoutContentTest() throws Exception {
        FileEntry noContent = addTestFile(SPACE_1, NAMESPACE_1);
        FileEntry noContent2 = addTestFile(SPACE_2, NAMESPACE_1);
        addTestFile(SPACE_1, NAMESPACE_2);
        addTestFile(SPACE_2, NAMESPACE_2);
        Mockito.when(fileStorage.getFileEntriesWithoutContent(Mockito.anyList()))
            .thenReturn(Arrays.asList(noContent, noContent2));
        int deleteWithoutContent = fileService.deleteFilesEntriesWithoutContent();
        assertEquals(2, deleteWithoutContent);
        assertNull(fileService.getFile(SPACE_1, noContent.getId()));
        assertNull(fileService.getFile(SPACE_2, noContent2.getId()));
    }

    @Override
    protected FileEntry addFile(String space, String namespace, String fileName, String resourceName) throws Exception {
        FileEntry fileEntry = super.addFile(space, namespace, fileName, resourceName);
        Mockito.verify(fileStorage, Mockito.times(1))
            .addFile(Mockito.eq(fileEntry), (File) Mockito.any());
        return fileEntry;
    }

    @Override
    protected FileService createFileService(DataSourceWithDialect dataSource) {
        return new FileService(dataSource, fileStorage);
    }

    @Override
    protected void verifyFileIsStored(FileEntry fileEntry) throws Exception {
        Mockito.verify(fileStorage, Mockito.times(1))
            .addFile(Mockito.eq(fileEntry), (File) Mockito.any());
    }
}


text:
package org.seqcode.gseutils.graphs;

public class UndirectedAlgorithms extends Algorithms {

	private UndirectedGraph graph;

	public UndirectedAlgorithms(UndirectedGraph ug) {
		super(ug);
		graph = ug;
	}

}


text:
package gov.va.med.lom.javaBroker.rpc.patient.models;

import gov.va.med.lom.javaBroker.rpc.BaseBean;

import java.io.Serializable;
import java.util.Date;

public class PatientInfo extends BaseBean implements Serializable {

  private String name;
  private String sex;
  private String ssn;
  private Date dob;
  private String dobStr;
  private Date deceasedDate;
  private String deceasedDateStr;
  private int age;
  private boolean veteran;
  private int scPct;
  private String location;
  private String roomBed;
  private boolean inpatient;

  public PatientInfo() {
    this.name = null;
    this.sex = null;
    this.ssn = null;
    this.dob = null;
    this.dobStr = null;
    this.deceasedDate = null;
    this.deceasedDateStr = null;
    this.age = 0;
    this.veteran = false;
    this.scPct = 0;
    this.location = null;
    this.roomBed = null;
    this.inpatient = false;
  }

  public int getAge() {
    return age;
  }

  public void setAge(int age) {
    this.age = age;
  }

  public Date getDeceasedDate() {
    return deceasedDate;
  }

  public void setDeceasedDate(Date deceasedDate) {
    this.deceasedDate = deceasedDate;
  }

  public Date getDob() {
    return dob;
  }

  public void setDob(Date dob) {
    this.dob = dob;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public String getSex() {
    return sex;
  }

  public void setSex(String sex) {
    this.sex = sex;
  }

  public String getSsn() {
    return ssn;
  }

  public void setSsn(String ssn) {
    this.ssn = ssn;
  }

  public String getLocation() {
    return location;
  }

  public void setLocation(String location) {
    this.location = location;
  }

  public String getRoomBed() {
    return roomBed;
  }

  public void setRoomBed(String roomBed) {
    this.roomBed = roomBed;
  }

  public int getScPct() {
    return scPct;
  }

  public void setScPct(int scPct) {
    this.scPct = scPct;
  }

  public boolean getVeteran() {
    return veteran;
  }

  public void setVeteran(boolean veteran) {
    this.veteran = veteran;
  }

  public boolean getInpatient() {
    return inpatient;
  }

  public void setInpatient(boolean inpatient) {
    this.inpatient = inpatient;
  }

  public String getDeceasedDateStr() {
    return deceasedDateStr;
  }

  public void setDeceasedDateStr(String deceasedDateStr) {
    this.deceasedDateStr = deceasedDateStr;
  }

  public String getDobStr() {
    return dobStr;
  }

  public void setDobStr(String dobStr) {
    this.dobStr = dobStr;
  }
}


text:
'use strict';

exports.description = "Create a Node Module, including Nodeunit unit tests";
exports.notes = "";

exports.after = "You should now install project dependencies with _npm install_." +
    " After that, you may start the environment with _grunt_.";

exports.warnOn = '*';

exports.template = function(grunt, init, done){
    init.process({},[
        init.prompt("name"),
        init.prompt("description"),
        init.prompt("version"),
        init.prompt("repository"),
        init.prompt("homepage"),
        init.prompt("bugs"),
        init.prompt("author")
    ],function(err,props){

        props.keywords = [];

        props.devDependencies = {
            "grunt-plato": "~0.2.1",
            "grunt-jsdoc": "~0.4.0",
            "grunt-contrib-watch": "~0.5.3",
            "grunt-concurrent": "~0.3.1",
            "grunt-contrib-uglify":"~0.2.4",
            "grunt-jasmine-node": "~0.1.0",
            "grunt-jasmine-node-coverage": "~0.1.6",
            "grunt-karma":"~0.7.1",
            "karma-coverage":"~0.1",
            "grunt-contrib-jshint": "~0.6.4",
            "grunt-strip": "~0.2.1",
            "grunt": "~0.4.1",
            "grunt-contrib-connect": "~0.5.0",
            "grunt-bump": "0.0.11"
        };

        var files = init.filesToCopy(props);

        //init.addLicenseFiles(files, props.licenses);
        init.copyAndProcess(files,props);
        init.writePackageJSON('package.json',props);

        done();
    });
};


text:
#ifndef TENSORFLOW_LITE_TESTING_TFLITE_DRIVER_H_
#define TENSORFLOW_LITE_TESTING_TFLITE_DRIVER_H_

#include <map>
#include <memory>

#include "tensorflow/lite/delegates/flex/delegate.h"
#include "tensorflow/lite/interpreter.h"
#include "tensorflow/lite/kernels/register.h"
#include "tensorflow/lite/kernels/register_ref.h"
#include "tensorflow/lite/model.h"
#include "tensorflow/lite/testing/test_runner.h"

namespace tflite {
namespace testing {

// A test runner that feeds inputs into TF Lite and verifies its outputs.
class TfLiteDriver : public TestRunner {
 public:
  explicit TfLiteDriver(bool use_nnapi, const string& delegate = "",
                        bool reference_kernel = false);
  ~TfLiteDriver() override;

  void LoadModel(const string& bin_file_path) override;
  const std::vector<int>& GetInputs() override {
    return interpreter_->inputs();
  }
  const std::vector<int>& GetOutputs() override {
    return interpreter_->outputs();
  }
  void ReshapeTensor(int id, const string& csv_values) override;
  void AllocateTensors() override;
  void ResetTensor(int id) override;
  void SetInput(int id, const string& csv_values) override;
  void SetExpectation(int id, const string& csv_values) override;
  void SetShapeExpectation(int id, const string& csv_values) override;
  void Invoke() override;
  bool CheckResults() override;
  string ReadOutput(int id) override;
  void SetThreshold(double relative_threshold, double absolute_threshold);

 private:
  void DeallocateStringTensor(TfLiteTensor* t) {
    if (t) {
      free(t->data.raw);
      t->data.raw = nullptr;
    }
  }
  void AllocateStringTensor(int id, size_t num_bytes, TfLiteTensor* t) {
    t->data.raw = reinterpret_cast<char*>(malloc(num_bytes));
    t->bytes = num_bytes;
    tensors_to_deallocate_[id] = t;
  }

  void ResetLSTMStateTensors();

  class Expectation;

  std::unique_ptr<OpResolver> resolver_;
  std::unique_ptr<FlexDelegate> delegate_;
  bool use_nnapi_ = false;
  std::unique_ptr<FlatBufferModel> model_;
  std::unique_ptr<Interpreter> interpreter_;
  std::map<int, std::unique_ptr<Expectation>> expected_output_;
  std::map<int, std::unique_ptr<Expectation>> expected_output_shape_;
  bool must_allocate_tensors_ = true;
  std::map<int, TfLiteTensor*> tensors_to_deallocate_;
  double relative_threshold_;
  double absolute_threshold_;
};

}  // namespace testing
}  // namespace tflite

#endif  // TENSORFLOW_LITE_TESTING_TFLITE_DRIVER_H_


text:
#include "dtls/DtlsSocket.h"

#include <iostream>
#include <cassert>
#include <cstring>
#include <string>

#ifdef HAVE_CONFIG_H
#include "./config.h"
#endif

using dtls::DtlsSocket;
using dtls::SrtpSessionKeys;
using std::memcpy;

DEFINE_LOGGER(DtlsSocket, "dtls.DtlsSocket");

int dummy_cb(int d, X509_STORE_CTX *x) {
  return 1;
}

DtlsSocket::DtlsSocket(DtlsSocketContext* socketContext, enum SocketType type):
              mSocketContext(socketContext),
              mSocketType(type),
              mHandshakeCompleted(false) {
  ELOG_DEBUG("Creating Dtls Socket");
  mSocketContext->setDtlsSocket(this);
  SSL_CTX* mContext = mSocketContext->getSSLContext();
  assert(mContext);
  mSsl = SSL_new(mContext);
  assert(mSsl != 0);
  SSL_set_mtu(mSsl, DTLS_MTU);

  switch (type) {
    case Client:
      SSL_set_connect_state(mSsl);
      // SSL_set_mode(mSsl, SSL_MODE_ENABLE_PARTIAL_WRITE |
      //         SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
      break;
    case Server:
      SSL_set_accept_state(mSsl);
      SSL_set_verify(mSsl, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, dummy_cb);
      break;
    default:
      assert(0);
  }

  dwrap_bio_method = BIO_f_dwrap();

  BIO* mem_in_BIO = BIO_new(BIO_s_mem());
  mInBio = BIO_new(dwrap_bio_method);
  BIO_push(mInBio, mem_in_BIO);

  BIO* mem_out_BIO = BIO_new(BIO_s_mem());
  mOutBio = BIO_new(dwrap_bio_method);
  BIO_push(mOutBio, mem_out_BIO);

  SSL_set_bio(mSsl, mInBio, mOutBio);
  SSL_accept(mSsl);
  ELOG_DEBUG("Dtls Socket created");
}

DtlsSocket::~DtlsSocket() {
  close();
}

void DtlsSocket::close() {
  // Properly shutdown the socket and free it - note: this also free's the BIO's
  if (mSsl != NULL) {
    ELOG_DEBUG("SSL Shutdown");
    SSL_shutdown(mSsl);
    SSL_free(mSsl);
    BIO_f_wrap_destroy(dwrap_bio_method);
    mSsl = NULL;
  }
}

void DtlsSocket::startClient() {
  assert(mSocketType == Client);
  doHandshakeIteration();
}

bool DtlsSocket::handlePacketMaybe(const unsigned char* bytes, unsigned int len) {
  if (mSsl == NULL) {
    ELOG_WARN("handlePacketMaybe called after DtlsSocket closed: %p", this);
    return false;
  }
  DtlsSocketContext::PacketType pType = DtlsSocketContext::demuxPacket(bytes, len);

  if (pType != DtlsSocketContext::dtls) {
    return false;
  }

  if (mSsl == nullptr) {
    return false;
  }

  (void) BIO_reset(mInBio);
  (void) BIO_reset(mOutBio);

  int r = BIO_write(mInBio, bytes, len);
  assert(r == static_cast<int>(len));  // Can't happen

  // Note: we must catch any below exceptions--if there are any
  try {
    doHandshakeIteration();
  } catch (int e) {
    return false;
  }
  return true;
}

void DtlsSocket::forceRetransmit() {
  (void) BIO_reset(mInBio);
  (void) BIO_reset(mOutBio);
  BIO_ctrl(mInBio, BIO_CTRL_DGRAM_SET_RECV_TIMEOUT, 0, 0);

  doHandshakeIteration();
}

void DtlsSocket::doHandshakeIteration() {
  boost::mutex::scoped_lock lock(handshakeMutex_);
  int ssl_error_code;

  if (mHandshakeCompleted) {
    return;
  }

  int return_value = SSL_do_handshake(mSsl);

  // See what was written
  unsigned char *outBioData;
  int outBioLen = BIO_get_mem_data(mOutBio, &outBioData);
  if (outBioLen > DTLS_MTU) {
    ELOG_WARN("message: BIO data bigger than MTU - packet could be lost, outBioLen %u, MTU %u",
        outBioLen, DTLS_MTU);
  }

  // Now handle handshake errors */
  switch (ssl_error_code = SSL_get_error(mSsl, return_value)) {
    case SSL_ERROR_NONE:
      mHandshakeCompleted = true;
      mSocketContext->handshakeCompleted();
      break;
    case SSL_ERROR_WANT_READ:
      break;
    default:
      ELOG_ERROR("message: SSL error %d", ssl_error_code);
      char error_string_buffer[1024];

      ERR_error_string_n(ssl_error_code, error_string_buffer, sizeof(error_string_buffer));

      mSocketContext->handshakeFailed(error_string_buffer);
      // Note: need to fall through to propagate alerts, if any
      break;
  }

  // If mOutBio is now nonzero-length, then we need to write the
  // data to the network. TODO(pedro): warning, MTU issues!
  if (outBioLen) {
    mSocketContext->write(outBioData, outBioLen);
  }
}

bool DtlsSocket::getRemoteFingerprint(char *fprint) {
  X509* x = SSL_get_peer_certificate(mSsl);
  if (!x) {  // No certificate
    return false;
  }

  computeFingerprint(x, fprint);
  X509_free(x);
  return true;
}

bool DtlsSocket::checkFingerprint(const char* fingerprint, unsigned int len) {
  char fprint[100];

  if (getRemoteFingerprint(fprint) == false) {
    return false;
  }

  // used to be strncasecmp
  if (strncmp(fprint, fingerprint, len)) {
    ELOG_WARN("Fingerprint mismatch, got %s expecting %s", fprint, fingerprint);
    return false;
  }

  return true;
}

void DtlsSocket::getMyCertFingerprint(char *fingerprint) {
  mSocketContext->getMyCertFingerprint(fingerprint);
}

SrtpSessionKeys* DtlsSocket::getSrtpSessionKeys() {
  // TODO(pedro): probably an exception candidate
  assert(mHandshakeCompleted);

  SrtpSessionKeys* keys = new SrtpSessionKeys();

  unsigned char material[SRTP_MASTER_KEY_LEN << 1];
  if (!SSL_export_keying_material(mSsl, material, sizeof(material), "EXTRACTOR-dtls_srtp", 19, NULL, 0, 0)) {
    return keys;
  }

  size_t offset = 0;

  memcpy(keys->clientMasterKey, &material[offset], SRTP_MASTER_KEY_KEY_LEN);
  offset += SRTP_MASTER_KEY_KEY_LEN;
  memcpy(keys->serverMasterKey, &material[offset], SRTP_MASTER_KEY_KEY_LEN);
  offset += SRTP_MASTER_KEY_KEY_LEN;
  memcpy(keys->clientMasterSalt, &material[offset], SRTP_MASTER_KEY_SALT_LEN);
  offset += SRTP_MASTER_KEY_SALT_LEN;
  memcpy(keys->serverMasterSalt, &material[offset], SRTP_MASTER_KEY_SALT_LEN);
  offset += SRTP_MASTER_KEY_SALT_LEN;
  keys->clientMasterKeyLen = SRTP_MASTER_KEY_KEY_LEN;
  keys->serverMasterKeyLen = SRTP_MASTER_KEY_KEY_LEN;
  keys->clientMasterSaltLen = SRTP_MASTER_KEY_SALT_LEN;
  keys->serverMasterSaltLen = SRTP_MASTER_KEY_SALT_LEN;

  return keys;
}

SRTP_PROTECTION_PROFILE* DtlsSocket::getSrtpProfile() {
  // TODO(pedro): probably an exception candidate
  assert(mHandshakeCompleted);
  return SSL_get_selected_srtp_profile(mSsl);
}

// Fingerprint is assumed to be long enough
void DtlsSocket::computeFingerprint(X509 *cert, char *fingerprint) {
  unsigned char md[EVP_MAX_MD_SIZE];
  int r;
  unsigned int i, n;

  // r = X509_digest(cert, EVP_sha1(), md, &n);
  r = X509_digest(cert, EVP_sha256(), md, &n);
  // TODO(javier) - is sha1 vs sha256 supposed to come from DTLS handshake?
  // fixing to to SHA-256 for compatibility with current web-rtc implementations
  assert(r == 1);

  for (i = 0; i < n; i++) {
    sprintf(fingerprint, "%02X", md[i]);  // NOLINT
    fingerprint += 2;

    if (i < (n-1))
    *fingerprint++ = ':';
    else
    *fingerprint++ = 0;
  }
}

void DtlsSocket::handleTimeout() {
  (void) BIO_reset(mInBio);
  (void) BIO_reset(mOutBio);
  if (DTLSv1_handle_timeout(mSsl) > 0) {
    ELOG_DEBUG("Dtls timeout occurred!");

    // See what was written
    unsigned char *outBioData;
    int outBioLen = BIO_get_mem_data(mOutBio, &outBioData);
    if (outBioLen > DTLS_MTU) {
      ELOG_WARN("message: BIO data bigger than MTU - packet could be lost, outBioLen %u, MTU %u",
          outBioLen, DTLS_MTU);
    }

    // If mOutBio is now nonzero-length, then we need to write the
    // data to the network. TODO(pedro): warning, MTU issues!
    if (outBioLen) {
      mSocketContext->write(outBioData, outBioLen);
    }
  }
}

// TODO(pedro): assert(0) into exception, as elsewhere
void DtlsSocket::createSrtpSessionPolicies(srtp_policy_t& outboundPolicy, srtp_policy_t& inboundPolicy) {
  assert(mHandshakeCompleted);

  /* we assume that the default profile is in effect, for now */
  srtp_profile_t profile = srtp_profile_aes128_cm_sha1_80;
  int key_len = srtp_profile_get_master_key_length(profile);
  int salt_len = srtp_profile_get_master_salt_length(profile);

  /* get keys from srtp_key and initialize the inbound and outbound sessions */
  uint8_t *client_master_key_and_salt = new uint8_t[SRTP_MAX_KEY_LEN];
  uint8_t *server_master_key_and_salt = new uint8_t[SRTP_MAX_KEY_LEN];
  srtp_policy_t client_policy;
  memset(&client_policy, 0, sizeof(srtp_policy_t));
  client_policy.window_size = 128;
  client_policy.allow_repeat_tx = 1;
  srtp_policy_t server_policy;
  memset(&server_policy, 0, sizeof(srtp_policy_t));
  server_policy.window_size = 128;
  server_policy.allow_repeat_tx = 1;

  SrtpSessionKeys* srtp_key = getSrtpSessionKeys();
  /* set client_write key */
  client_policy.key = client_master_key_and_salt;
  if (srtp_key->clientMasterKeyLen != key_len) {
    ELOG_WARN("error: unexpected client key length");
    assert(0);
  }
  if (srtp_key->clientMasterSaltLen != salt_len) {
    ELOG_WARN("error: unexpected client salt length");
    assert(0);
  }

  memcpy(client_master_key_and_salt, srtp_key->clientMasterKey, key_len);
  memcpy(client_master_key_and_salt + key_len, srtp_key->clientMasterSalt, salt_len);

  /* initialize client SRTP policy from profile  */
  srtp_err_status_t err = srtp_crypto_policy_set_from_profile_for_rtp(&client_policy.rtp, profile);
  if (err) assert(0);

  err = srtp_crypto_policy_set_from_profile_for_rtcp(&client_policy.rtcp, profile);
  if (err) assert(0);
  client_policy.next = NULL;

  /* set server_write key */
  server_policy.key = server_master_key_and_salt;

  if (srtp_key->serverMasterKeyLen != key_len) {
    ELOG_WARN("error: unexpected server key length");
    assert(0);
  }
  if (srtp_key->serverMasterSaltLen != salt_len) {
    ELOG_WARN("error: unexpected salt length");
    assert(0);
  }

  memcpy(server_master_key_and_salt, srtp_key->serverMasterKey, key_len);
  memcpy(server_master_key_and_salt + key_len, srtp_key->serverMasterSalt, salt_len);

  delete srtp_key;

  /* initialize server SRTP policy from profile  */
  err = srtp_crypto_policy_set_from_profile_for_rtp(&server_policy.rtp, profile);
  if (err) assert(0);

  err = srtp_crypto_policy_set_from_profile_for_rtcp(&server_policy.rtcp, profile);
  if (err) assert(0);
  server_policy.next = NULL;

  if (mSocketType == Client) {
    client_policy.ssrc.type = ssrc_any_outbound;
    outboundPolicy = client_policy;

    server_policy.ssrc.type  = ssrc_any_inbound;
    inboundPolicy = server_policy;
  } else {
    server_policy.ssrc.type  = ssrc_any_outbound;
    outboundPolicy = server_policy;

    client_policy.ssrc.type = ssrc_any_inbound;
    inboundPolicy = client_policy;
  }
  /* zeroize the input keys (but not the srtp session keys that are in use) */
  // not done...not much of a security whole imho...the lifetime of these seems odd though
  //    memset(client_master_key_and_salt, 0x00, SRTP_MAX_KEY_LEN);
  //    memset(server_master_key_and_salt, 0x00, SRTP_MAX_KEY_LEN);
  //    memset(&srtp_key, 0x00, sizeof(srtp_key));
}

  /* ====================================================================

  Copyright (c) 2007-2008, Eric Rescorla and Derek MacDonald
  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.

  3. None of the contributors names may be used to endorse or promote
  products derived from this software without specific prior written
  permission.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 COPYRIGHT
  OWNER 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.

  ==================================================================== */


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>org.apache.flume.sink.hive Class Hierarchy (Apache Flume 1.7.0 API)</title>
<meta name="date" content="2016-10-12">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For Package org.apache.flume.sink.hive

Package Hierarchies:

All Packages

Class Hierarchy

java.lang.Object

org.apache.flume.sink.AbstractSink (implements org.apache.flume.lifecycle.LifecycleAware, org.apache.flume.Sink)

org.apache.flume.sink.hive.HiveSink (implements org.apache.flume.conf.Configurable)

org.apache.flume.sink.hive.Config

org.apache.flume.sink.hive.HiveDelimitedTextSerializer (implements org.apache.flume.sink.hive.HiveEventSerializer)

org.apache.flume.sink.hive.HiveJsonSerializer (implements org.apache.flume.sink.hive.HiveEventSerializer)

Interface Hierarchy

org.apache.flume.conf.Configurable

org.apache.flume.sink.hive.HiveEventSerializer

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2009-2016 Apache Software Foundation. All Rights Reserved.


text:
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************

using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using SDKTemplate;
using System;
using System.Text;
using Windows.Globalization;

namespace CalendarSample
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class DisplayCalendarStatistics : Page
    {
        // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
        // as NotifyUser()
        MainPage rootPage = MainPage.Current;

        public DisplayCalendarStatistics()
        {
            this.InitializeComponent();
        }

        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.  The Parameter
        /// property is typically used to configure the page.</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        /// <summary>
        /// This is the click handler for the 'Display' button.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Display_Click(object sender, RoutedEventArgs e)
        {
            // This scenario uses the Windows.Globalization.Calendar class to display the calendar
            // system statistics.

            // Store results here.
            StringBuilder results = new StringBuilder();

            // Create Calendar objects using different constructors.
            Calendar calendar = new Calendar();
            Calendar japaneseCalendar = new Calendar(new[] { "ja-JP" }, CalendarIdentifiers.Japanese, ClockIdentifiers.TwelveHour);
            Calendar hebrewCalendar = new Calendar(new[] { "he-IL" }, CalendarIdentifiers.Hebrew, ClockIdentifiers.TwentyFourHour);

            // Display individual date/time elements.
            results.AppendLine("User's default calendar system: " + calendar.GetCalendarSystem());
            results.AppendLine("Months in this Year: " + calendar.NumberOfMonthsInThisYear);
            results.AppendLine("Days in this Month: " + calendar.NumberOfDaysInThisMonth);
            results.AppendLine("Hours in this Period: " + calendar.NumberOfHoursInThisPeriod);
            results.AppendLine("Era: " + calendar.EraAsString());
            results.AppendLine();
            results.AppendLine("Calendar system: " + japaneseCalendar.GetCalendarSystem());
            results.AppendLine("Months in this Year: " + japaneseCalendar.NumberOfMonthsInThisYear);
            results.AppendLine("Days in this Month: " + japaneseCalendar.NumberOfDaysInThisMonth);
            results.AppendLine("Hours in this Period: " + japaneseCalendar.NumberOfHoursInThisPeriod);
            results.AppendLine("Era: " + japaneseCalendar.EraAsString());
            results.AppendLine();
            results.AppendLine("Calendar system: " + hebrewCalendar.GetCalendarSystem());
            results.AppendLine("Months in this Year: " + hebrewCalendar.NumberOfMonthsInThisYear);
            results.AppendLine("Days in this Month: " + hebrewCalendar.NumberOfDaysInThisMonth);
            results.AppendLine("Hours in this Period: " + hebrewCalendar.NumberOfHoursInThisPeriod);
            results.AppendLine("Era: " + hebrewCalendar.EraAsString());
            results.AppendLine();

            // Display results
            OutputTextBlock.Text = results.ToString();
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"  >
    <stroke
        android:width="2dp"
        android:color="#FFFFFF"/>
    <solid android:color="#F0F4C3"/>
    <corners android:radius="10dp"/>

</shape>


text:
import Registry from '../../Registry';
import * as Null from '.';

/**
 * Register `.Null` assertion in default registry.
 *
 * @author Maciej Chałapuk (maciej@chalapuk.pl)
 */
Null.registerIn(Registry.instance);


text:
//-----------------------------------------------------------------------
// <copyright file="QueryBuilder.cs" company="Akka.NET Project">
//     Copyright (C) 2009-2016 Typesafe Inc. <http://www.typesafe.com>
//     Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------

using System;
using System.Data.Common;

namespace Akka.Persistence.Sql.Common.Snapshot
{
    /// <summary>
    /// Flattened and serialized snapshot object used as intermediate representation
    /// before saving snapshot with metadata inside SQL Server database.
    /// </summary>
    public class SnapshotEntry
    {
        /// <summary>
        /// Persistence identifier of persistent actor, current snapshot relates to.
        /// </summary>
        public readonly string PersistenceId;

        /// <summary>
        /// Sequence number used to identify snapshot in it's persistent actor scope.
        /// </summary>
        public readonly long SequenceNr;

        /// <summary>
        /// Timestamp used to specify date, when the snapshot has been made.
        /// </summary>
        public readonly DateTime Timestamp;

        /// <summary>
        /// Stringified fully qualified CLR type name of the serialized object.
        /// </summary>
        public readonly string SnapshotType;

        /// <summary>
        /// Serialized object data.
        /// </summary>
        public readonly byte[] Snapshot;

        public SnapshotEntry(string persistenceId, long sequenceNr, DateTime timestamp, string snapshotType, byte[] snapshot)
        {
            PersistenceId = persistenceId;
            SequenceNr = sequenceNr;
            Timestamp = timestamp;
            SnapshotType = snapshotType;
            Snapshot = snapshot;
        }
    }

    /// <summary>
    /// Query builder used for prepare SQL commands used for snapshot store persistence operations.
    /// </summary>
    public interface ISnapshotQueryBuilder
    {
        /// <summary>
        /// Deletes a single snapshot identified by it's persistent actor's <paramref name="persistenceId"/>,
        /// <paramref name="sequenceNr"/> and <paramref name="timestamp"/>.
        /// </summary>
        DbCommand DeleteOne(string persistenceId, long sequenceNr, DateTime timestamp);

        /// <summary>
        /// Deletes all snapshot matching persistent actor's <paramref name="persistenceId"/> as well as
        /// upper (inclusive) bounds of the both <paramref name="maxSequenceNr"/> and <paramref name="maxTimestamp"/>.
        /// </summary>
        DbCommand DeleteMany(string persistenceId, long maxSequenceNr, DateTime maxTimestamp);

        /// <summary>
        /// Inserts a single snapshot represented by provided <see cref="SnapshotEntry"/> instance.
        /// </summary>
        DbCommand InsertSnapshot(SnapshotEntry entry);

        /// <summary>
        /// Selects a single snapshot identified by persistent actor's <paramref name="persistenceId"/>,
        /// matching upper (inclusive) bounds of both <paramref name="maxSequenceNr"/> and <paramref name="maxTimestamp"/>.
        /// In case, when more than one snapshot matches specified criteria, one with the highest sequence number will be selected.
        /// </summary>
        DbCommand SelectSnapshot(string persistenceId, long maxSequenceNr, DateTime maxTimestamp);
    }

}


text:
title: Blog Template
layout: post
author: amal.shakir
permalink: /blog-template/
source-id: 1i4l9z5PwgwSTU_4eRKqGsQNDmTMYt98ubbdUqLQ-ACQ
published: true
---

    Title
    Blog 1 - a Brand New Year
    Date
    1109/17

    Starting point:
    Learning about Excel, sorry, google sheets, on the board

    Target for this lesson?
    To grapple at the basics and create a foundation of my knowledge

    Did I reach my target?
(add details to "Lesson Review")
    Yup

    Lesson Review

    How did I learn? What strategies were effective?

    The lesson was mainly just listening and copying of the board, so as long as I listened I would of been fine, and I did listen, and so I was fine.

Working next to Finn helped as we work well together, so if a team activity comes up, I'll be fine.

    What limited my learning? Which habits do I need to work on?

    Nothing really, I listened well and create my tables and so it was fine, nothing actually went wrong.

    What will I change for next time? How will I improve my learning?

    Ditto to above, it was fine and the lesson didn't provide any curveballs as long as I listened.


text:
public class FloggerTest {

  private static final com.google.common.flogger.FluentLogger LOGGER1 = com.google.common.flogger.FluentLogger.forEnclosingClass();

  public void logSomething(){
    LOGGER1.atInfo().log("Hello World!");
  }

  public static void main(String[] args) {
    LOGGER1.atInfo().log("Test");
    new FloggerTest().logSomething();
  }
}


text:
package com.onboard.service.index.impl.test;

import java.util.Date;
import java.util.List;
import java.util.Map;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.onboard.domain.mapper.model.common.BaseCriteria;
import com.onboard.domain.mapper.model.common.BaseExample;
import com.onboard.domain.mapper.model.common.BaseItem;
import com.onboard.domain.model.type.Indexable;
import com.onboard.service.index.custom.IndexableService;
import com.onboard.service.index.model.IndexDocument;
import com.onboard.test.moduleutils.ModuleHelper;

public class IndexSampleHelper {

    public static IndexableService getASampleIndexableService() {
        return new IndexableService() {

            @Override
            public String modelType() {
                return ModuleHelper.type;
            }

            @Override
            public IndexDocument indexableToIndexDocument(Indexable indexable) {
                return getASampleIndexDocument();
            }

            @Override
            public List<Indexable> getIndexablesByExample(com.onboard.domain.mapper.model.common.BaseExample baseExample) {
                return Lists.newArrayList();
            }
        };
    }

    public static IndexDocument getASampleIndexDocument() {
        return new IndexDocument() {

            @Override
            public void setTitle(String title) {

            }

            @Override
            public void setContent(String content) {

            }

            @Override
            public boolean needIndex() {
                return true;
            }

            @Override
            public String getTitle() {
                return ModuleHelper.title;
            }

            @Override
            public List<Integer> getRelatorIds() {
                return Lists.newArrayList();
            }

            @Override
            public String getProjectName() {
                return ModuleHelper.projectName;
            }

            @Override
            public Integer getProjectId() {
                return ModuleHelper.projectId;
            }

            @Override
            public String getModelType() {
                return ModuleHelper.modelType;
            }

            @Override
            public Integer getModelId() {
                return ModuleHelper.id;
            }

            @Override
            public Indexable getIndexable() {
                return getASampleIndexable();
            }

            @Override
            public String getId() {
                return ModuleHelper.content;
            }

            @Override
            public Map<String, Object> getExtendIndexFields() {
                return Maps.newHashMap();
            }

            @Override
            public String getCreatorName() {
                return ModuleHelper.creatorName;
            }

            @Override
            public Integer getCreatorId() {
                return ModuleHelper.creatorId;
            }

            @Override
            public String getCreatorAvatar() {
                return ModuleHelper.creatorAvatar;
            }

            @Override
            public Date getCreatedTime() {
                return ModuleHelper.created;
            }

            @Override
            public String getContent() {
                return ModuleHelper.content;
            }

            @Override
            public Integer getCompanyId() {
                return ModuleHelper.companyId;
            }

            @Override
            public String getAttachTitle() {
                return ModuleHelper.title;
            }
        };
    }

    public static Indexable getASampleIndexable() {
        return new Indexable() {

            @Override
            public Integer getId() {
                return ModuleHelper.id;
            }

            @Override
            public String getType() {
                return ModuleHelper.type;
            }

            @Override
            public Integer getProjectId() {
                return ModuleHelper.projectId;
            }

            @Override
            public Boolean getDeleted() {
                return false;
            }

            @Override
            public String getCreatorName() {
                return ModuleHelper.creatorName;
            }

            @Override
            public Integer getCreatorId() {
                return ModuleHelper.creatorId;
            }

            @Override
            public Integer getCompanyId() {
                return ModuleHelper.companyId;
            }

            @Override
            public void setProjectId(Integer projectId) {
                // TODO Auto-generated method stub

            }

            @Override
            public void setCompanyId(Integer companyId) {
                // TODO Auto-generated method stub

            }

            @Override
            public void setCreatorId(Integer creatorId) {
                // TODO Auto-generated method stub

            }

            @Override
            public void setCreatorName(String creatorName) {
                // TODO Auto-generated method stub

            }

            @Override
            public String getCreatorAvatar() {
                // TODO Auto-generated method stub
                return null;
            }

            @Override
            public void setCreatorAvatar(String creatorAvatar) {
                // TODO Auto-generated method stub

            }

            @Override
            public Date getCreated() {
                // TODO Auto-generated method stub
                return null;
            }

            @Override
            public void setCreated(Date created) {
                // TODO Auto-generated method stub

            }

            @Override
            public Date getUpdated() {
                // TODO Auto-generated method stub
                return null;
            }

            @Override
            public void setUpdated(Date updated) {
                // TODO Auto-generated method stub

            }

            @Override
            public void setDeleted(Boolean deleted) {
                // TODO Auto-generated method stub

            }

            @Override
            public void setId(Integer id) {
                // TODO Auto-generated method stub

            }

            @Override
            public BaseItem copy() {
                // TODO Auto-generated method stub
                return null;
            }

            @Override
            public boolean trashRequried() {
                // TODO Auto-generated method stub
                return false;
            }
        };
    }

    public static BaseExample getASampleBaseExample() {
        return new BaseExample() {

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

            @Override
            public int getStart() {
                return ModuleHelper.start;
            }

            @Override
            public List<BaseCriteria> getOredBaseCriteria() {
                return Lists.newArrayList();
            }

            @Override
            public String getOrderByClause() {
                return null;
            }

            @Override
            public int getLimit() {
                return ModuleHelper.limit;
            }

            @Override
            public void setOrderByClause(String orderByClause) {
                // TODO Auto-generated method stub

            }

            @Override
            public void setDistinct(boolean distinct) {
                // TODO Auto-generated method stub

            }

            @Override
            public void setStart(int start) {
                // TODO Auto-generated method stub

            }

            @Override
            public void setLimit(int limit) {
                // TODO Auto-generated method stub

            }

            @Override
            public void setLimit(int start, int limit) {
                // TODO Auto-generated method stub

            }

            @Override
            public void clear() {
                // TODO Auto-generated method stub

            }
        };
    }

    public static List<Indexable> getASampleIndexableList() {
        return Lists.newArrayList(getASampleIndexable());
    }
}


text:
using System;

namespace P01_StudentSystem
{
    public class StartUp
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
        }
    }
}


text:
layout: post
title:  "Escrita Ilusória"
date:   2018-01-01
source: Módulo Básico 171, Módulo Básico Edição Revisada 181.
tags: [nenhum, bardo]
---

**arcana 3 (ilusão)**

**Alcance**: toque

**Teste de Resistência**: Vontade anula.

**Duração**: 1 semana (D)

**Alvo**: 1 objeto de até 5kg

**Tempo de Execução**: 10 minutos

Esta magia permite escrever um texto sobre um objeto. A escrita ilusória parece um idioma exótico — apenas você e aqueles que você escolher quando lançar a magia podem entendê-la.
Quando alguém não autorizado tenta ler, a magia dispara um efeito ilusório que força o leitor a fazer um teste de Vontade.
Em caso de falha, o leitor é afetado por uma sugestão que dura no máximo 30 minutos.
A sugestão normalmente é algo como "esqueça o que leu e vá embora".
O texto mágico pode ser lido por alguém não autorizado com uma combinação das magias visão da verdade e ler magias ou compreender idiomas.


text:
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping default-access="field" package="org.motechproject.server.model.rct">
    <class name="RCTFacility" table="motechmodule_rct_facility">
        <id name="id" type="long" column="rct_facility_id">
            <generator class="native"/>
        </id>
        <many-to-one name="facility" property-ref="facilityId" column="facility_id" unique="true"/>
        <property name="active" type="boolean" column="active"/>
    </class>
</hibernate-mapping>


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Revue mycol. , Toulouse 14: 10 (1892)

#### Original name
Ramularia picridis Fautrey & Roum., 1892

### Remarks
null


text:
'use strict';

var gulp = require('gulp'),
  mocha = require('gulp-mocha'),
  uglify = require('gulp-uglify'),
  pump = require('pump'),
  source = require('vinyl-source-stream'),
  browserify = require('browserify'),
  rename = require('gulp-rename'),
  runSequence = require('run-sequence');

var env = process.env.NODE_ENV || 'development';
// read gulp directory contents for the tasks...

console.log('Invoking gulp -',env);
gulp.task('mocha', function() {
  return gulp.src('*.spec.js', {read: false})
  .pipe(mocha({
    timeout: 10000,
    reporter: 'spec' // 'nyan'
  }))
  .once('error', function (err) {
    console.error(err.stack);
    process.exit(1);
  });
});

gulp.task('browserify', function() {
  return browserify('./index.js', {
    standalone: 'RegExPipeline'
  })
    .bundle()
    //Pass desired output filename to vinyl-source-stream
    .pipe(source('regex-pipeline.js'))
    // Start piping stream to tasks!
    .pipe(gulp.dest('./dist/'));
});

gulp.task('compress', function (cb) {
  pump([
      gulp.src('dist/*.js'),
      uglify(),
      rename({
        suffix: '.min'
      }),
      gulp.dest('dist')
    ],
    cb
  );
});

gulp.task('build', function (cb) {
  runSequence(
    'mocha',
    'browserify',
    'compress'
  );
})


text:
<?php

noDirectCheck() or die("No direct access to this file!");
// THIS is the primary SYSTEM LIBRARY of FUNCTIONS for the Framework :)

//MySQL Query Database
function myquery($query) {
	mysql_connect(dbhost, dbuser, dbpass);
	mysql_select_db(dbname);
	$result = mysql_query($query);
	if (!mysql_errno() && @mysql_num_rows($result) > 0) {
	}
	else {
		$result = FALSE;
	}
	mysql_close();
	return $result;
}
// MySQL Num Rows
function myrows($result) {
	$rows = @mysql_num_rows($result);
	return $rows;
}
// MySQL fetch array
function myarray($result) {
	$array = mysql_fetch_array($result);
	return $array;
}
// MySQL escape string
function myescape($query) {
	$escape = mysql_escape_string($query);
	return $escape;
}
//Initilize Session
function initSession($session) {
	if (!isset($session['initiated'])) {
		session_regenerate_id();
		$session['initiated'] = true;
	}
	return $session;
}
//Agent Session
function agentSession($session,$agent) {
	$fingerprint = md5($agent . secretPUBLIC);
	if (isset($session['HTTP_USER_AGENT'])) {
		if ($session['HTTP_USER_AGENT'] != $fingerprint) {
			die();
			exit;
		}
	} else {
		$session['HTTP_USER_AGENT'] = $fingerprint;
	}
	return $session;
}

function safeGet($getting) {

	if((isset($getting['com'])) AND (preg_match('/(\w|\d|\-)+/',$getting['com']))) {
		$gotten['com'] = $getting['com'];
	}
	else {
		$gotten['com'] = defCOM;
	}
	if((isset($getting['action'])) AND (preg_match('/(\w|\d|\-)+/',$getting['action']))) {
		$gotten['action'] = $getting['action'];
	}
	else {
		$gotten['action'] = defACTION;
	}
	if((isset($getting['tpl'])) AND (preg_match('/(\w|\d|\-)+/',$getting['tpl']))) {
		$gotten['tpl'] = $getting['tpl'];
	}
	else {
		$gotten['tpl'] = defTPL;
	}
	if((isset($getting['tplv'])) AND (preg_match('/(\w|\d|\-)+/',$getting['tplv']))) {
		$gotten['tplv'] = $getting['tplv'];
	}
	else {
		$gotten['tplv'] = 'default';
	}
	if((isset($getting['id'])) AND (preg_match('/(\d)+/',$getting['id']))) {
		$gotten['id'] = $getting['id'];
	}
	else {
		$gotten['id'] = defID;
	}
    if((isset($getting['uuid'])) AND (preg_match('/(\d|\w|\-)+/',$getting['uuid']))) {
		$gotten['uuid'] = $getting['uuid'];
	}
	else {
		$gotten['uuid'] = defUUID;
	}
	return $gotten;

}

function myUUID(){
    if (function_exists('com_create_guid')){
        return com_create_guid();
    } else{
        mt_srand((double)microtime()*10000);//optional for php 4.2.0 and up.
        $charid = strtoupper(md5(uniqid(rand(), true)));
        $hyphen = chr(45);// "-"
        $uuid = chr(123)// "{"
                .substr($charid, 0, 8).$hyphen
                .substr($charid, 8, 4).$hyphen
                .substr($charid,12, 4).$hyphen
                .substr($charid,16, 4).$hyphen
                .substr($charid,20,12)
                .chr(125);// "}"
        return $uuid;
    }
}

function validateDataWhite($get) {

	return $outcome;
}

function stripDataWhite($data) {
	str_replace("\n","",$data);

	return $data
}


text:
// CLASS HEADER
#include <dali/internal/event/events/ray-test.h>

// INTERNAL INCLUDES
#include <dali/internal/event/actors/actor-impl.h>
#include <dali/internal/event/common/event-thread-services.h>
#include <dali/internal/update/nodes/node.h>
#include <dali/public-api/math/vector2.h>
#include <dali/public-api/math/vector3.h>
#include <dali/public-api/math/vector4.h>

using Dali::Internal::SceneGraph::Node;

namespace Dali
{
namespace Internal
{
RayTest::RayTest()
: mEventThreadServices(EventThreadServices::Get())
{
}

bool RayTest::SphereTest(const Internal::Actor& actor, const Vector4& rayOrigin, const Vector4& rayDir) const
{
  /*
   http://wiki.cgsociety.org/index.php/Ray_Sphere_Intersection

   Mathematical Formulation

   Given the above mentioned sphere, a point 'p' lies on the surface of the sphere if

   ( p - c ) dot ( p - c ) = r^2

   Given a ray with a point of origin 'o', and a direction vector 'd':

   ray(t) = o + td, t >= 0

   we can find the t at which the ray intersects the sphere by setting ray(t) equal to 'p'

   (o + td - c ) dot ( o + td - c ) = r^2

   To solve for t we first expand the above into a more recognisable quadratic equation form

   ( d dot d )t^2 + 2( o - c ) dot dt + ( o - c ) dot ( o - c ) - r^2 = 0

   or

   At2 + Bt + C = 0

   where

   A = d dot d
   B = 2( o - c ) dot d
   C = ( o - c ) dot ( o - c ) - r^2

   which can be solved using a standard quadratic formula.

   Note that in the absence of positive, real, roots, the ray does not intersect the sphere.

   Practical Simplification

   In a renderer, we often differentiate between world space and object space. In the object space
   of a sphere it is centred at origin, meaning that if we first transform the ray from world space
   into object space, the mathematical solution presented above can be simplified significantly.

   If a sphere is centred at origin, a point 'p' lies on a sphere of radius r2 if

   p dot p = r^2

   and we can find the t at which the (transformed) ray intersects the sphere by

   ( o + td ) dot ( o + td ) = r^2

   According to the reasoning above, we expand the above quadratic equation into the general form

   At2 + Bt + C = 0

   which now has coefficients:

   A = d dot d
   B = 2( d dot o )
   C = o dot o - r^2
   */

  // Early out if not on the scene
  if(!actor.OnScene())
  {
    return false;
  }

  const Node&       node            = actor.GetNode();
  const BufferIndex bufferIndex     = EventThreadServices::Get().GetEventBufferIndex();
  const Vector3&    translation     = node.GetWorldPosition(bufferIndex);
  const Vector3&    size            = node.GetSize(bufferIndex);
  const Vector3&    scale           = node.GetWorldScale(bufferIndex);
  const Rect<int>&  touchAreaOffset = actor.GetTouchAreaOffset(); // (left, right, bottom, top)

  // Transforms the ray to the local reference system. As the test is against a sphere, only the translation and scale are needed.
  const Vector3 rayOriginLocal(rayOrigin.x - translation.x - (touchAreaOffset.left + touchAreaOffset.right) * 0.5, rayOrigin.y - translation.y - (touchAreaOffset.top + touchAreaOffset.bottom) * 0.5, rayOrigin.z - translation.z);

  // Computing the radius is not needed, a square radius is enough so can just use size but we do need to scale the sphere
  const float width  = size.width * scale.width + touchAreaOffset.right - touchAreaOffset.left;
  const float height = size.height * scale.height + touchAreaOffset.bottom - touchAreaOffset.top;

  float squareSphereRadius = 0.5f * (width * width + height * height);

  float a  = rayDir.Dot(rayDir);                                      // a
  float b2 = rayDir.Dot(rayOriginLocal);                              // b/2
  float c  = rayOriginLocal.Dot(rayOriginLocal) - squareSphereRadius; // c

  return (b2 * b2 - a * c) >= 0.0f;
}

bool RayTest::ActorTest(const Internal::Actor& actor, const Vector4& rayOrigin, const Vector4& rayDir, Vector2& hitPointLocal, float& distance) const
{
  bool hit = false;

  if(actor.OnScene())
  {
    const Node& node = actor.GetNode();

    // Transforms the ray to the local reference system.
    // Calculate the inverse of Model matrix
    Matrix invModelMatrix(false /*don't init*/);
    invModelMatrix = node.GetWorldMatrix(0);
    invModelMatrix.Invert();

    Vector4 rayOriginLocal(invModelMatrix * rayOrigin);
    Vector4 rayDirLocal(invModelMatrix * rayDir - invModelMatrix.GetTranslation());

    // Test with the actor's XY plane (Normal = 0 0 1 1).
    float a = -rayOriginLocal.z;
    float b = rayDirLocal.z;

    if(fabsf(b) > Math::MACHINE_EPSILON_1)
    {
      // Ray travels distance * rayDirLocal to intersect with plane.
      distance = a / b;

      const Vector2&   size            = Vector2(node.GetSize(EventThreadServices::Get().GetEventBufferIndex()));
      const Rect<int>& touchAreaOffset = actor.GetTouchAreaOffset(); // (left, right, bottom, top)
      hitPointLocal.x                  = rayOriginLocal.x + rayDirLocal.x * distance + size.x * 0.5f;
      hitPointLocal.y                  = rayOriginLocal.y + rayDirLocal.y * distance + size.y * 0.5f;

      // Test with the actor's geometry.
      hit = (hitPointLocal.x >= touchAreaOffset.left) && (hitPointLocal.x <= (size.x + touchAreaOffset.right) && (hitPointLocal.y >= touchAreaOffset.top) && (hitPointLocal.y <= (size.y + touchAreaOffset.bottom)));
    }
  }

  return hit;
}

} // namespace Internal

} // namespace Dali


text:
@interface JXCBaseRequest (Setter)

@property (nonatomic, strong, readwrite, nullable) NSURLSessionTask *requestTask;
@property (nonatomic, strong, readwrite, nullable) NSData *responseData;
@property (nonatomic, strong, readwrite, nullable) id responseJSONObject;
@property (nonatomic, strong, readwrite, nullable) id responseObject;
@property (nonatomic, strong, readwrite, nullable) NSString *responseString;
@property (nonatomic, strong, readwrite, nullable) NSError *error;

@end

@interface JXCNetworkPrivate : NSObject

@end


text:
namespace IO
{
    // =========================== Saving Interactions =======================
    void Write_Neighbours_Exchange( const Data::Spin_System& system, const std::string filename );
    void Write_Neighbours_DMI( const Data::Spin_System& system, const std::string filename );

    // =========================== Saving Energies ===========================
    void Write_Energy_Header( const Data::Spin_System& s, const std::string filename,
                              std::vector<std::string> firstcolumns={"iteration", "E_tot"},
                              bool contributions=true, bool normalize_nos=true,
                              bool readability_toggle = true  );
    // Appends the Energy of a spin system with energy contributions (without header)
    void Append_Image_Energy( const Data::Spin_System& s, const int iteration,
                               const std::string filename, bool normalize_nos=true,
                               bool readability_toggle = true );
    // Save energy contributions of a spin system
    void Write_Image_Energy( const Data::Spin_System& system, const std::string filename,
                             bool normalize_by_nos=true, bool readability_toggle = true );

    // Saves Energies of all images with header and contributions
    void Write_Chain_Energies( const Data::Spin_System_Chain& c, const int iteration,
                               const std::string filename, bool normalize_nos=true,
                               bool readability_toggle = true );
    // Saves the Energies interpolated by the GNEB method
    void Write_Chain_Energies_Interpolated( const Data::Spin_System_Chain& c,
                                            const std::string filename, bool normalize_nos=true,
                                            bool readability_toggle = true);
};
#endif


text:
package net.glowstone.net.codec.play.entity;

import com.flowpowered.network.Codec;
import com.flowpowered.network.util.ByteBufUtils;
import io.netty.buffer.ByteBuf;
import java.io.IOException;
import net.glowstone.net.message.play.entity.EntityEffectMessage;

public final class EntityEffectCodec implements Codec<EntityEffectMessage> {

    @Override
    public EntityEffectMessage decode(ByteBuf buf) throws IOException {
        int id = ByteBufUtils.readVarInt(buf);
        byte effect = buf.readByte();
        byte amplifier = buf.readByte();
        int duration = ByteBufUtils.readVarInt(buf);
        byte flags = buf.readByte();
        boolean ambient = (flags & 1) == 1;
        boolean showParticles = (flags & 2) == 2;
        return new EntityEffectMessage(id, effect, amplifier, duration, showParticles, ambient);
    }

    @Override
    public ByteBuf encode(ByteBuf buf, EntityEffectMessage message) throws IOException {
        ByteBufUtils.writeVarInt(buf, message.getId());
        buf.writeByte(message.getEffect());
        buf.writeByte(message.getAmplifier());
        ByteBufUtils.writeVarInt(buf, message.getDuration());

        byte flags = 0;
        if (message.isAmbient()) {
            flags |= 1;
        }
        if (message.isShowParticles()) {
            flags |= 2;
        }

        buf.writeByte(flags);
        return buf;
    }
}