text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

	<modelVersion>4.0.0</modelVersion>
	<groupId>com.shiziqiu</groupId>
	<artifactId>shiziqiu-configuration</artifactId>
	<version>0.0.1</version>
	<packaging>pom</packaging>

	<name>shiziqiu-configuration</name>
	<description>A lightweight distributed configuration management platform.</description>
	<url>http://www.shiziqiu.com/</url>

	<modules>
		<module>shiziqiu-configuration-util</module>
		<module>shiziqiu-configuration-core</module>
		<module>shiziqiu-configuration-console</module>
		<module>shiziqiu-configuration-example</module>
	</modules>

	<properties>
		<shiziqiuVersion>0.0.1</shiziqiuVersion>
		<slf4jVersion>1.7.5</slf4jVersion>
		<zookeeperVersion>3.4.6</zookeeperVersion>
		<ehcacheVersion>2.9.1</ehcacheVersion>
		<springVersion>3.2.13.RELEASE</springVersion>
		<aspectjVersion>1.8.2</aspectjVersion>
		<jacksonVersion>1.9.13</jacksonVersion>
		<dbcpVersion>1.4</dbcpVersion>
		<poolVersion>1.6</poolVersion>
		<freemarkerVersion>2.3.20</freemarkerVersion>
		<langVersion>2.6</langVersion>
		<collectionsVersion>3.2.1</collectionsVersion>
		<mybatisSpringVersion>1.2.2</mybatisSpringVersion>
		<mybatisVersion>3.2.8</mybatisVersion>
		<mysqlVersion>5.1.29</mysqlVersion>

	</properties>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.1</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
					<encoding>UTF8</encoding>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-war-plugin</artifactId>
				<version>2.2</version>
				<configuration>
					<archiveClasses>false</archiveClasses>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-surefire-plugin</artifactId>
				<version>2.19.1</version>
				<configuration>
					<skip>true</skip>
				</configuration>
			</plugin>
		</plugins>
	</build>

	<licenses>
		<license>
			<name>GNU General Public License, version 2</name>
			<url>http://opensource.org/licenses/GPL-2.0</url>
		</license>
	</licenses>

	<developers>
		<developer>
			<id>shiziqiu</id>
			<name>shiziqiu</name>
			<email>1046414905@qq.com</email>
			<url>https://github.com/shiziqiu</url>
		</developer>
	</developers>

	<profiles>
		<profile>
			<id>release</id>
			<build>
				<plugins>
					<!-- Source -->
					<plugin>
						<groupId>org.apache.maven.plugins</groupId>
						<artifactId>maven-source-plugin</artifactId>
						<version>2.2.1</version>
						<executions>
							<execution>
								<phase>package</phase>
								<goals>
									<goal>jar-no-fork</goal>
								</goals>
							</execution>
						</executions>
					</plugin>
					<!-- Javadoc -->
					<plugin>
						<groupId>org.apache.maven.plugins</groupId>
						<artifactId>maven-javadoc-plugin</artifactId>
						<version>2.9.1</version>
						<executions>
							<execution>
								<phase>package</phase>
								<goals>
									<goal>jar</goal>
								</goals>
							</execution>
						</executions>
					</plugin>
					<!-- GPG -->
					<plugin>
						<groupId>org.apache.maven.plugins</groupId>
						<artifactId>maven-gpg-plugin</artifactId>
						<version>1.8</version>
						<configuration>
							<useAgent>false</useAgent>
						</configuration>
						<executions>
							<execution>
								<phase>verify</phase>
								<goals>
									<goal>sign</goal>
								</goals>
							</execution>
						</executions>
					</plugin>
				</plugins>
			</build>
			<distributionManagement>
				<snapshotRepository>
					<id>oss</id>
					<url>https://oss.sonatype.org/content/repositories/snapshots/</url>
				</snapshotRepository>
				<repository>
					<id>oss</id>
					<url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
				</repository>
			</distributionManagement>
		</profile>
	</profiles>

</project>


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

<title>ModelQualityExperimentPublisher</title>
<meta name="date" content="2014-01-08">
<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 Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

cpsr.environment.simulation

Class ModelQualityExperimentPublisher

java.lang.Object

cpsr.environment.simulation.ModelQualityExperimentPublisher

public class ModelQualityExperimentPublisher
extends java.lang.Object

Constructor Summary

Constructors

Constructor and Description

ModelQualityExperimentPublisher(ModelQualityExperiment experiment,
                               java.lang.String simulatorName,
                               PSRObserver psrObserver,
                               java.util.Properties psrProperties,
                               java.util.Properties planningProperties)

Method Summary

Methods

Modifier and Type
Method and Description

void
publishResults(java.lang.String directory)

void
writeHistSizes(java.lang.String filepath)

void
writeLikes(java.lang.String filepath)

void
writeSingularVals(java.lang.String filepath)

void
writeSummary(java.lang.String filepath)

void
writeTestSizes(java.lang.String filepath)

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

ModelQualityExperimentPublisher

public ModelQualityExperimentPublisher(ModelQualityExperiment experiment,
                               java.lang.String simulatorName,
                               PSRObserver psrObserver,
                               java.util.Properties psrProperties,
                               java.util.Properties planningProperties)

Method Detail

publishResults

public void publishResults(java.lang.String directory)

writeSummary

public void writeSummary(java.lang.String filepath)

writeSingularVals

public void writeSingularVals(java.lang.String filepath)

writeLikes

public void writeLikes(java.lang.String filepath)

writeHistSizes

public void writeHistSizes(java.lang.String filepath)

writeTestSizes

public void writeTestSizes(java.lang.String filepath)

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

redpajama_set_name: RedPajamaGithub


text:
package com.gdn.venice.persistence;

import java.io.Serializable;
import javax.persistence.*;

import java.sql.Time;
import java.util.List;

/**
 * The persistent class for the log_pickup_schedules database table.
 *
 */
@Entity
@Table(name="log_pickup_schedules")
public class LogPickupSchedule implements Serializable {
	private static final long serialVersionUID = 1L;

	@Id
@GeneratedValue(strategy=GenerationType.TABLE, generator="log_pickup_schedules")
	@TableGenerator(name="log_pickup_schedules", table="openjpaseq", pkColumnName="id", valueColumnName="sequence_value", allocationSize=1)  //flush every 1 insert
	@Column(name="pickup_schedules_id", unique=true, nullable=false)
	private Long pickupSchedulesId;

	@Column(name="from_time", nullable=false)
	private Time fromTime;

	@Column(name="include_public_holidays", nullable=false)
	private Boolean includePublicHolidays;

	@Column(name="pickup_schedule_desc", nullable=false, length=100)
	private String pickupScheduleDesc;

	@Column(name="to_time", nullable=false)
	private Time toTime;

	//bi-directional many-to-one association to LogLogisticsProvider
    @ManyToOne
	@JoinColumn(name="logistics_provider_id", nullable=false)
	private LogLogisticsProvider logLogisticsProvider;

	//bi-directional many-to-many association to LogScheduleDayOfWeek
	@ManyToMany(mappedBy="logPickupSchedules")//, fetch=FetchType.EAGER)
	private List<LogScheduleDayOfWeek> logScheduleDayOfWeeks;

    public LogPickupSchedule() {
    }

	public Long getPickupSchedulesId() {
		return this.pickupSchedulesId;
	}

	public void setPickupSchedulesId(Long pickupSchedulesId) {
		this.pickupSchedulesId = pickupSchedulesId;
	}

	public Time getFromTime() {
		return this.fromTime;
	}

	public void setFromTime(Time fromTime) {
		this.fromTime = fromTime;
	}

	public Boolean getIncludePublicHolidays() {
		return this.includePublicHolidays;
	}

	public void setIncludePublicHolidays(Boolean includePublicHolidays) {
		this.includePublicHolidays = includePublicHolidays;
	}

	public String getPickupScheduleDesc() {
		return this.pickupScheduleDesc;
	}

	public void setPickupScheduleDesc(String pickupScheduleDesc) {
		this.pickupScheduleDesc = pickupScheduleDesc;
	}

	public Time getToTime() {
		return this.toTime;
	}

	public void setToTime(Time toTime) {
		this.toTime = toTime;
	}

	public LogLogisticsProvider getLogLogisticsProvider() {
		return this.logLogisticsProvider;
	}

	public void setLogLogisticsProvider(LogLogisticsProvider logLogisticsProvider) {
		this.logLogisticsProvider = logLogisticsProvider;
	}

	public List<LogScheduleDayOfWeek> getLogScheduleDayOfWeeks() {
		return this.logScheduleDayOfWeeks;
	}

	public void setLogScheduleDayOfWeeks(List<LogScheduleDayOfWeek> logScheduleDayOfWeeks) {
		this.logScheduleDayOfWeeks = logScheduleDayOfWeeks;
	}

}


text:
<?xml version="1.0" encoding="UTF-8"?>

<channel name="xfce4-panel" version="1.0">
  <property name="configver" type="int" value="2"/>
  <property name="panels" type="array">
    <value type="int" value="1"/>
    <value type="int" value="2"/>
    <property name="panel-1" type="empty">
      <property name="position" type="string" value="p=6;x=0;y=0"/>
      <property name="length" type="uint" value="100"/>
      <property name="position-locked" type="bool" value="true"/>
      <property name="size" type="uint" value="30"/>
      <property name="plugin-ids" type="array">
        <value type="int" value="1"/>
        <value type="int" value="3"/>
        <value type="int" value="15"/>
        <value type="int" value="4"/>
        <value type="int" value="5"/>
        <value type="int" value="6"/>
        <value type="int" value="16"/>
        <value type="int" value="2"/>
      </property>
    </property>
    <property name="panel-2" type="empty">
      <property name="position" type="string" value="p=10;x=0;y=0"/>
      <property name="position-locked" type="bool" value="true"/>
      <property name="plugin-ids" type="array">
        <value type="int" value="7"/>
        <value type="int" value="8"/>
        <value type="int" value="9"/>
        <value type="int" value="10"/>
        <value type="int" value="11"/>
        <value type="int" value="12"/>
        <value type="int" value="13"/>
        <value type="int" value="14"/>
      </property>
    </property>
  </property>
  <property name="plugins" type="empty">
    <property name="plugin-1" type="string" value="applicationsmenu"/>
    <property name="plugin-2" type="string" value="actions"/>
    <property name="plugin-3" type="string" value="tasklist"/>
    <property name="plugin-15" type="string" value="separator">
      <property name="expand" type="bool" value="true"/>
      <property name="style" type="uint" value="0"/>
    </property>
    <property name="plugin-4" type="string" value="pager"/>
    <property name="plugin-5" type="string" value="clock"/>
    <property name="plugin-6" type="string" value="systray">
      <property name="names-visible" type="array">
        <value type="string" value="xfce4-power-manager"/>
      </property>
    </property>
    <property name="plugin-7" type="string" value="showdesktop"/>
    <property name="plugin-8" type="string" value="separator"/>
    <property name="plugin-9" type="string" value="launcher">
      <property name="items" type="array">
        <value type="string" value="14077719801.desktop"/>
      </property>
    </property>
    <property name="plugin-10" type="string" value="launcher">
      <property name="items" type="array">
        <value type="string" value="14077719802.desktop"/>
      </property>
    </property>
    <property name="plugin-11" type="string" value="launcher">
      <property name="items" type="array">
        <value type="string" value="14077719803.desktop"/>
      </property>
    </property>
    <property name="plugin-12" type="string" value="launcher">
      <property name="items" type="array">
        <value type="string" value="14077719804.desktop"/>
      </property>
    </property>
    <property name="plugin-13" type="string" value="separator"/>
    <property name="plugin-14" type="string" value="directorymenu">
      <property name="base-directory" type="string" value="/home/vagrant"/>
    </property>
    <property name="plugin-16" type="string" value="xkb-plugin"/>
  </property>
</channel>


text:
from builtins import str
from tests import PMGLiveServerTestCase
import unittest
from pmg.models import db, BillType, Minister, Bill
from tests.fixtures import (
    dbfixture,
    UserData,
    RoleData,
    BillData,
    HouseData,
    BillTypeData,
)
from flask import escape

class TestAdminBillPage(PMGLiveServerTestCase):
    def setUp(self):
        super(TestAdminBillPage, self).setUp()

        self.fx = dbfixture.data(RoleData, UserData, BillData, HouseData, BillTypeData)
        self.fx.setup()
        self.user = self.fx.UserData.admin

    def tearDown(self):
        self.delete_created_objects()
        self.fx.teardown()
        super(TestAdminBillPage, self).tearDown()

    def test_admin_bill_page(self):
        """
        Test admin bill page (/admin/bill)
        """
        self.make_request("/admin/bill", self.user, follow_redirects=True)
        self.assertIn("Bills", self.html)
        self.containsBill(self.fx.BillData.farm)
        self.containsBill(self.fx.BillData.food)

    def containsBill(self, bill):
        self.assertIn(bill.title, self.html)
        self.assertIn(bill.type.name, self.html)
        self.assertIn(bill.code, self.html)

    def test_admin_create_bill(self):
        """
        Create a bill with the admin interface (/admin/bill/new/)
        """
        before_count = len(Bill.query.all())
        url = "/admin/bill/new/?url=%2Fadmin%2Fbill%2F"
        data = {
            "year": "2020",
            "title": "Cool Bill",
            "type": str(self.fx.BillTypeData.section_74.id),
            "introduced_by": "James",
            "date_of_introduction": "2019-07-03",
            "place_of_introduction": str(self.fx.HouseData.na.id),
            "date_of_assent": "2019-07-03",
            "effective_date": "2019-07-03",
            "act_name": "Fundamental",
        }
        response = self.make_request(url, self.user, data=data, method="POST")
        after_count = len(Bill.query.all())
        self.assertEqual(302, response.status_code)
        self.assertLess(before_count, after_count)

        created_bill = Bill.query.filter(Bill.title == data["title"]).scalar()
        self.assertTrue(created_bill)
        self.created_objects.append(created_bill)

    def test_admin_create_bill_event_titles_help_section(self):
        """
        The admin bill create page should show help text for
        which bill event title are allowed when the bill type is "bill-passed".
        """
        url = "/admin/bill/new"
        response = self.make_request(url, self.user, follow_redirects=True)

        self.assertIn(escape("Help?"), self.html)
        self.assertIn(
            escape('When event type is "Bill passed", event title must be one of'),
            self.html,
        )
        self.assertIn(
            escape(
                "Bill passed by the National Assembly and transmitted to the "
                "NCOP for concurrence"
            ),
            self.html,
        )

    def test_admin_action_bill(self):
        """
        Delete a bill with the admin interface (/admin/bill/action/)
        """
        before_count = len(Bill.query.all())
        url = "/admin/bill/action/"
        data = {
            "url": "/admin/bill/",
            "action": "delete",
            "rowid": [str(self.fx.BillData.food.id),],
        }
        response = self.make_request(url, self.user, data=data, method="POST")
        after_count = len(Bill.query.all())
        self.assertEqual(302, response.status_code)
        self.assertGreater(before_count, after_count)

    def test_admin_delete_bill(self):
        """
        Delete a bill on the admin interface
        (/admin/bill/delete/)
        """
        before_count = len(Bill.query.all())
        url = "/admin/bill/delete/"
        data = {
            "url": "/admin/bill/",
            "id": str(self.fx.BillData.food.id),
        }
        response = self.make_request(
            url, self.user, follow_redirects=True, data=data, method="POST"
        )
        after_count = len(Bill.query.all())
        self.assertEqual(200, response.status_code)
        self.assertGreater(before_count, after_count)

    def test_admin_edit_bill(self):
        """
        Edit a bill with the admin interface (/admin/bill/edit/)
        """
        bill = db.session.query(Bill).first()
        new_title = "Cool Bill"
        url = "/admin/bill/edit/?id=%d" % bill.id
        data = {
            "year": "2020",
            "title": new_title,
            "type": str(self.fx.BillTypeData.section_74.id),
            "introduced_by": "James",
            "date_of_introduction": "2019-07-03",
            "place_of_introduction": str(self.fx.HouseData.na.id),
            "date_of_assent": "2019-07-03",
            "effective_date": "2019-07-03",
            "act_name": "Fundamental",
        }
        response = self.make_request(
            url, self.user, follow_redirects=True, data=data, method="POST"
        )
        self.assertEqual(200, response.status_code)

        db.session.refresh(bill)
        self.assertEqual(new_title, bill.title)


text:
package ch.ifocusit.telecom.service;

import ch.ifocusit.telecom.domain.Bill;
import ch.ifocusit.telecom.repository.BillRepository;

import java.time.YearMonth;
import java.util.Optional;

/**
 * @author Julien Boz
 */
public class BillingService {

    private BillRepository repository;

    public Optional<Bill> getBill(String month) {
        return repository.get(YearMonth.parse(month));
    }
}


text: Please select date.


text:
High Resolution Timer
=====================

Overview
--------

Although FreeRTOS provides software timers, these timers have a few limitations:

- Mmaximum resolution is equal to RTOS tick period
- Timer callbacks are dispatched from a low-priority task

Hardware timers are free from both of the limitations, but often they are less convenient to use. For example, application components may need timer events to fire at certain times in the future, but the hardware timer only contains one "compare" value used for interrupt generation. This means that some facility needs to be built on top of the hardware timer to manage the list of pending events can dispatch the callbacks for these events as corresponding hardware interrupts happen.

``esp_timer`` set of APIs provide such facility. Internally, ``esp_timer`` uses a 32-bit hardware timer (FRC1, "legacy" timer). ``esp_timer`` provides one-shot and periodic timers, microsecond time resolution, and 64-bit range.

Timer callbacks are dispatched from a high-priority ``esp_timer`` task. Because all the callbacks are dispatched from the same task, it is recommended to only do the minimal possible amount of work from the callback itself, posting an event to a lower priority task using a queue instead.

.. note: Provisions are made to dispatch some simple callbacks directly from the interrupt handler, if needed. However this option is not implemented at the moment.

Using ``esp_timer`` APIs
------------------------

Single timer is represented by :cpp:type:`esp_timer_handle_t` type. Timer has a callback function associated with it. This callback function is called from the ``esp_timer`` task each time the timer elapses.

- To create a timer, call :cpp:func:`esp_timer_create`.
- To delete the timer when it is no longer needed, call :cpp:func:`esp_timer_delete`.

The timer can be started in one-shot mode or in periodic mode.

- To start the timer in one-shot mode, call :cpp:func:`esp_timer_start_once`, passing the time interval after which the callback should be called. When the callback gets called, the timer is considered to be stopped.

- To start the timer in periodic mode, call :cpp:func:`esp_timer_start_periodic`, passing the period with which the callback should be called. The timer keeps running until :cpp:func:`esp_timer_stop` is called.

Note that the timer must not be running when :cpp:func:`esp_timer_start_once` or :cpp:func:`esp_timer_start_periodic` is called. To restart a running timer, call :cpp:func:`esp_timer_stop` first, then call one of the start functions.

Obtaining Current Time
----------------------

``esp_timer`` also provides a convenience function to obtain the time passed since start-up, with microsecond precision: :cpp:func:`esp_timer_get_time`. This function returns the number of microseconds since ``esp_timer`` was initialized, which usually happens shortly before ``app_main`` function is called.

Unlike `gettimeofday` function, values returned by :cpp:func:`esp_timer_get_time`:

- Start from zero after the chip wakes up from deep sleep
- Do not have timezone or DST adjustments applied

API Reference
-------------

.. include:: /_build/inc/esp_timer.inc


text:
'use strict';

var path   = require('path')
  , chai   = require('chai')
  , expect = chai.expect
  , should = chai.should()
  , helper = require(path.join(__dirname, 'lib', 'agent_helper'))
  ;

describe("agent instrumentation of MongoDB", function () {
  describe("shouldn't cause bootstrapping to fail", function () {
    var agent
      , initialize
      ;

    before(function () {
      agent = helper.loadMockedAgent();
      initialize = require(path.join(__dirname, '..', 'lib',
                                     'instrumentation', 'mongodb'));
    });

    after(function () {
      helper.unloadAgent(agent);
    });

    it("when passed no module", function () {
      expect(function () { initialize(agent); }).not.throws();
    });

    it("when passed an empty module", function () {
      expect(function () { initialize(agent, {}); }).not.throws();
    });
  });

  describe("when capturing terms is disabled", function () {
    var agent
      , segment
      , terms
      ;

    before(function (done) {
      function StubCollection () {}

      StubCollection.prototype.findAndModify = function findAndModify(terms, options, callback) {
        this.terms = terms;
        this.options = options;
        process.nextTick(function cb_nextTick() { callback(null, 1); });
      };

      var mockodb    = {Collection : StubCollection}
        , collection = new mockodb.Collection('test')
        , initialize = require(path.join(__dirname, '..', 'lib',
                                         'instrumentation', 'mongodb'))
        ;

      agent = helper.loadMockedAgent();
      agent.on('transactionFinished', function (transaction) {
        // need to generate the trace so exclusive times are added to segment parameters
        transaction.getTrace().generateJSON(function cb_generateJSON() {
          terms = collection.terms;
          segment = transaction.trace.root.children[0];

          done();
        });
      });

      initialize(agent, mockodb);

      helper.runInTransaction(agent, function (trans) {
        collection.findAndModify({val : 'hi'}, {w : 333}, function () {
          process.nextTick(function cb_nextTick() { trans.end(); });
        });
      });
    });

    after(function () {
      helper.unloadAgent(agent);
    });

    it("shouldn't modify query terms", function () {
      should.not.exist(terms.nr_exclusive_duration_millis);
    });

    it("shouldn't copy query terms onto segment parameters", function () {
      should.not.exist(segment.parameters.val);
    });
  });

  describe("when capturing terms is enabled", function () {
    var agent
      , segment
      , terms
      ;

    before(function (done) {
      function StubCollection () {}

      StubCollection.prototype.findAndModify = function findAndModify(terms, options, callback) {
        this.terms = terms;
        this.options = options;
        process.nextTick(function cb_nextTick() { callback(null, 1); });
      };

      var mockodb    = {Collection : StubCollection}
        , collection = new mockodb.Collection('test')
        , initialize = require(path.join(__dirname, '..', 'lib',
                                         'instrumentation', 'mongodb'))
        ;

      agent = helper.loadMockedAgent();
      agent.config.capture_params = true;
      agent.config.ignored_params = ['other'];
      agent.on('transactionFinished', function (transaction) {
        // need to generate the trace so exclusive times are added to segment parameters
        transaction.getTrace().generateJSON(function cb_generateJSON() {
          terms = collection.terms;
          segment = transaction.trace.root.children[0];

          done();
        });
      });

      initialize(agent, mockodb);

      helper.runInTransaction(agent, function (trans) {
        collection.findAndModify({val : 'hi', other : 'bye'}, {w : 333}, function () {
          process.nextTick(function cb_nextTick() { trans.end(); });
        });
      });
    });

    after(function () {
      helper.unloadAgent(agent);
    });

    it("shouldn't modify query terms", function () {
      should.not.exist(terms.nr_exclusive_duration_millis);
    });

    it("should append query terms onto segment parameters", function () {
      expect(segment.parameters.val).equal('hi');
    });

    it("should respect ignored parameter list", function () {
      should.not.exist(segment.parameters.other);
    });
  });

  describe("with child MongoDB operations", function () {
    var agent
      , transaction
      , collection
      , error
      , removed
      ;

    before(function (done) {
      function StubCollection (name) {
        this.collectionName = name;
      }

      StubCollection.prototype.findAndRemove = function findAndRemove(terms, options, callback) {
        this.findAndModify(terms, options, callback);
      };

      StubCollection.prototype.findAndModify = function findAndModify(terms, options, callback) {
        this.terms = terms;
        this.options = options;
        process.nextTick(function cb_nextTick() {
          callback(null, 1);
        });
      };

      var mockodb = {Collection : StubCollection};

      agent = helper.loadMockedAgent();
      agent.on('transactionFinished', done.bind(null, null));

      var initialize = require(path.join(__dirname, '..', 'lib',
                                     'instrumentation', 'mongodb'));
      initialize(agent, mockodb);

      collection = new mockodb.Collection('test');

      helper.runInTransaction(agent, function (trans) {
        transaction = trans;
        collection.findAndRemove({val : 'hi'}, {w : 333}, function (err, rem) {
          error = err;
          removed = rem;

          transaction.end();
        });
      });
    });

    after(function () {
      helper.unloadAgent(agent);
    });

    it("should have left the query terms alone", function () {
      expect(collection.terms).eql({val : 'hi'});
    });

    it("should have left the query options alone", function () {
      expect(collection.options).eql({w : 333});
    });

    it("shouldn't have messed with the error parameter", function () {
      should.not.exist(error);
    });

    it("shouldn't have messed with the result parameter", function () {
      expect(removed).equal(1);
    });

    it("should have only one segment (the parent) under the trace root", function () {
      var root = transaction.getTrace().root;
      expect(root.children.length).equal(1);
    });

    it("should have recorded the findAndRemove operation", function () {
      var root   = transaction.getTrace().root
        , parent = root.children[0]
        ;

      expect(parent.name).equal('Datastore/statement/MongoDB/test/findAndRemove');
    });

    it("should have no child segments under the parent", function () {
      var root   = transaction.getTrace().root
        , parent = root.children[0]
        ;

      expect(parent.children.length).equal(0);
    });

    it("should have gathered metrics", function () {
      var metrics = transaction.metrics;
      should.exist(metrics);
    });

    it("should have recorded only one database call", function () {
      var metrics = transaction.metrics;
      expect(metrics.getMetric('Datastore/all').callCount).equal(1);
    });

    it("should have that call be the findAndRemove", function () {
      var metrics = transaction.metrics
        , metric  = metrics.getMetric('Datastore/statement/MongoDB/test/findAndRemove')
        ;

      should.exist(metric);
      expect(metric.callCount).equal(1);
    });
  });
});


text:
Program that allows you see shadows of simple 4D figures on your screen.

Requirements:
 SDL2 for graphics

 SDL2_ttf for text rendering

 GLM for 3D mathematics.

**Controls:**

Choose figure:

1 - hypercube(tesseract)

2 - tor

3 - hypersphere

F1 - change between othographic and stereographic 4D projections.

F2 - reset 4D angles(ZW YW XW)

F3 - reset 3D angles(XZ(Y) YZ(X) XY(Z))

Q - zoom in

E - zoom out

R - move figure up in W axis

F - move figure down in W axis

C - move figure down in Z axis

SPACE - move figure up in Z axis

W - move figure up in Y axis

S - move figure down in Y axis

A - move figure up in X axis

D - move figure down in X axis

RMB - change Z and Y angles

LMB - change X angle

Alt + RMB - change YW and XW angles

Alt + LMB - change ZW angles


text:
<?php

namespace Model;

require_once("Color.php");
require_once("SessionColorPersistor.php");

class Palette {
	/**
	* @var integer numberOfVariations
	*/
	public $numberOfVariations = 0;

	/**
	* @var array of Color objects, colors
	*/
	private $colors = array();

	/**
	 * @param int $numberOfVariations example: 8
	 * @param SessionColorPersistor $persistance
	 */
	public function __construct($numberOfVariations, SessionColorPersistor $persistance) {
		$this->numberOfVariations = $numberOfVariations;
		$this->colorPersistance = $persistance;
		$this->createPalette();
	}

	/**
	* @return array of Color objects, colors
	*/
	public function getAllColors() {
		return $this->colors;
	}

	/**
	* @return Color
	*/
	public function getSelectedColor() {
		return $this->colorPersistance->load();
	}

	/**
	* @todo: restrict to colors in palette
	* @param Color selection
	*/
	public function setSelectedColor(Color $selection) {
		$this->colorPersistance->save($selection);
	}

	/**
	* Create a palette with a variation of colors
	*/
	private function createPalette() {
		//how much color between 0.0 and 1.0 is every step?
		$stepPerVariation = 1.0 /($this->numberOfVariations - 1);

		//blue is held constant
		$b = 1;

		//create all variations of red and green
		for ($r = 0; $r < $this->numberOfVariations; $r++) {
			for ($g = 0; $g < $this->numberOfVariations; $g++) {
				$this->colors[] = new Color($r * $stepPerVariation,
											$g * $stepPerVariation,
											$b * $stepPerVariation);
			}
		}
	}
}


text:
layout: page
title: Top-Level API
id: top-level
section: Top-Level API
---

Marty.createApplication(constructor)

Creates a [application]({% url /api/application/index.html %}) class with the given constructor.

Marty.createStore(properties)

Creates a [store]({% url /api/stores/index.html %}) class with the given properties.

Marty.createQueries(properties)

Register [queries]({% url /api/queries/index.html %}) class with the given properties.

Marty.createStateSource(properties)

Register a [state source]({% url /api/state-source/index.html %}) class with the given properties.

Marty.createActionCreators(properties)

Register [action creators]({% url /api/action-creators/index.html %}) class with the given properties.

Marty.createStateMixin(options)

Creates a [state mixin]({% url /guides/state-mixin/index.html %}).

Marty.createConstants(options)

Creates [constants]({% url /guides/constants/index.html %}).

Marty.createContainer(InnerComponent, options)

Wraps the component with a [container component]({% url /guides/containers/index.html %}) that is responsible for fetching state from stores and passing it to the inner component.

Marty.isServer

True if the current process is being executed within node.js or io.js.

Marty.isBrowser

True if the current process is being executed within a browser.

Marty.warnings

Configurable list of warnings that Marty emits. Setting the key to false will stop the warning from happening. We will warn you when a feature is being deprecated so disabling warnings can make upgrading difficult in the future.

{% highlight js %}
Marty.warnings.reservedFunction = false;
{% endhighlight %}

Marty.warnings.without(warningsToDisable*, callback, [context])

Disables a warning for the duration of the callback.

{% highlight js %}
Marty.warnings.without(['reservedFunction', 'superNotCalledWithOptions'], function () {
  // do something evil
});
{% endhighlight %}

Marty.version

The current version of Marty.


text:
"""
Enforce that Java files which look like they contain JUnit test cases
are referenced by a test BUCK target. In other words: find tests that
will not run with `buck test --all`
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import argparse
import codecs
import fnmatch
import json
import os
import platform
import subprocess
import sys
import tempfile

IGNORE_PREFIXES = [
  'buck-out',
  'src/com/facebook/buck/testrunner',
  # t13833822
  'src/com/facebook/buck/intellij/ideabuck/tests/integration',
]
# Due to path length issues during build on Windows the apple test target is
# only created on OSx.
if sys.platform != "darwin":
    IGNORE_PREFIXES.extend([
        'test/com/facebook/buck/apple'
    ])
# make the prefixes platform-specific
IGNORE_PREFIXES = [os.path.join(*p.split('/')) for p in IGNORE_PREFIXES]

def isPathIgnored(path):
    for prefix in IGNORE_PREFIXES:
        if path.startswith(prefix):
            return True
    return False

def containsJUnitImport(path):
    with codecs.open(path, "r", "utf-8") as f:
        for l in f.readlines():
            if "import org.junit.Test" in l:
                return True
    return False

def getTestFiles(repo_root):
    test_files = []
    for root, dirs, files in os.walk(repo_root):
        for f in files:
            absolute_path = os.path.join(root, f)
            if not f.endswith(".java"):
                continue
            if 'testdata' in absolute_path:
                continue
            if not containsJUnitImport(absolute_path):
                continue
            relative_path = os.path.relpath(absolute_path, repo_root)
            if isPathIgnored(relative_path):
                continue
            assert os.path.exists(absolute_path), "%s doesn't exist" % line
            test_files.append(relative_path)
    return sorted(test_files)

def getOwningRulesData(repo_root, test_files):
    t_fd, t_name = tempfile.mkstemp(text=True)
    try:
        with open(t_name, "w") as t_file:
            for f in test_files:
                t_file.write(f)
                t_file.write("\n")
        os.close(t_fd)
        env = dict(os.environ.items())
        env['NO_BUCKD'] = '1'
        if platform.system() == 'Windows':
            buck_path = os.path.join(repo_root, 'bin', 'buck.bat')
            cmd_prefix = ['cmd.exe', '/C', buck_path]
        else:
            buck_path = os.path.join(repo_root, 'bin', 'buck')
            cmd_prefix = [buck_path]
        cmd_output = run_process(
            cmd_prefix + ['targets', '--json',
                          '--referenced-file', '@' + t_name],
            env=env,
            cwd=repo_root)
        # Drop anything that appears before the JSON output.
        cmd_output = cmd_output[cmd_output.index("["):]
        return json.loads(cmd_output)
    except ValueError as e:
        print('Problem parsing result to json', cmd_output)
        raise e
    finally:
        if os.path.exists(t_name):
            os.unlink(t_name)

def findUnreferencedTestFiles(test_files, owning_rules):
    referenced_test_files = set()
    for rule in owning_rules:
        base_path = rule['buck.base_path']
        rule_type = rule['buck.type']
        # On windows base_path is still unix-style
        base_path = os.path.join(*base_path.split('/'))
        if not rule_type.endswith('_test'):
            continue
        for src in rule['srcs']:
            referenced_test_files.add(os.path.join(base_path, src))
    return set(test_files).difference(referenced_test_files)

def findRepoRoot(cwd):
    while os.path.exists(cwd):
        if os.path.exists(os.path.join(cwd, '.buckconfig')):
            return cwd
        cwd = os.path.dirname(cwd)
    raise Exception('Could not locate buck repo root.')

def run_process(*args, **kwargs):
    process = subprocess.Popen(stdout=subprocess.PIPE, *args, **kwargs)
    stdout, _ = process.communicate()
    retcode = process.poll()
    if retcode != 0:
        raise Exception('Error %s running %s' % (retcode, args))
    return stdout

def getMisplacedBuckFilesInTestdata(repo_root):
    buck_files = []
    for root, dirs, files in os.walk(repo_root):
        for f in files:
            full_path = os.path.join(root, f)
            if not f == 'BUCK':
                continue
            if 'testdata' not in full_path:
                continue
            buck_files.append(full_path)
    return buck_files

def main():
    repo_root = findRepoRoot(os.getcwd())
    test_files = getTestFiles(repo_root)
    owning_rules = getOwningRulesData(repo_root, test_files)
    unreferenced_files = findUnreferencedTestFiles(test_files, owning_rules)
    for f in unreferenced_files:
        print(f, "looks like a test file, but is not covered by a test rule.")

    misplaced_buck_files = getMisplacedBuckFilesInTestdata(repo_root)
    for b in misplaced_buck_files:
        print(b, "lives in `testdata`, you should rename it to BUCK.fixture " +
              "otherwise it will be accidentally picked up by the build.")

    if len(unreferenced_files) == 0 and len(misplaced_buck_files) == 0:
        print('No unreferenced test files found, all is good.')
        return 0
    else:
        return 1

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


text:
<?php

/*
 * This file is part of Gush package.
 *
 * (c) Luis Cordova <cordoval@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Gush\Template\PullRequest\Create;

class EnterpriseTemplate extends AbstractSymfonyTemplate
{
    /**
     * {@inheritdoc}
     */
    public function getRequirements()
    {
        return [
            'branch' => ['Branch', 'master'],
            'bug_fix' => ['Bug fix?', 'no'],
            'new_feature' => ['New feature?', 'no'],
            'bc_breaks' => ['BC breaks?', 'no'],
            'deprecations' => ['Deprecations?', 'no'],
            'tests_pass' => ['Tests pass?', 'yes'],
            'fixed_tickets' => ['Fixed tickets', ''],
            'license' => ['License', 'Proprietary'],
            'doc_pr' => ['Doc PR', ''],
            'description' => ['Description', ''],
        ];
    }

    public function getName()
    {
        return 'pull-request-create/enterprise';
    }
}


text:
# Customize Type Generator

<!-- toc -->

- [What can Type Generator Addon do ?](#what-can-type-generator-addon-do-)
- [How to implement Type Generator Addon](#how-to-implement-type-generator-addon)
  - [Write `TypeGenAddonFactory` function](#write-typegenaddonfactory-function)
  - [Template String and Addon Factory](#template-string-and-addon-factory)
  - [GraphQL AST hooks](#graphql-ast-hooks)
  - [Custom Scalar hook](#custom-scalar-hook)
  - [Change output files' content using `ctx.source`](#change-output-files-content-using-ctxsource)
    - [Add TypeScript statement](#add-typescript-statement)
    - [Add import statement](#add-import-statement)
- [Addon example](#addon-example)
- [API reference](#api-reference)

<!-- tocstop -->

## What can Type Generator Addon do ?

With Type Generator Addons you can:

- Mapping custom scalar types defined in your GraphQL schema to TypeScript type what you want.
- Generating new complex types using query result types or fragment types.
- Adding comment to generated .ts files, like `/* tslint:disable */`.
- etc,,,

## How to implement Type Generator Addon

### Write `TypeGenAddonFactory` function

First, create a new TypeScript file, `my-addon.ts`, and edit it as the following:

```ts
/* my-addon.ts */

import type { TypeGenAddonFactory } from 'ts-graphql-plugin';

const addonFactory: TypeGenAddonFactory = ctx => {
  return {
    document() {
      ctx.source.writeLeadingComment('Hello, my addon!');
    },
  };
};

module.exports = addonFactory;
```

Next, edit your tsconfig.json and configure to use the above addon:

```js
/* tsconfig.json */
{
  "compilerOptions": {
    "plugins": [
      {
        "name": "ts-graphql-plugin",
        "schema": "schema.graphql",
        "tag": "gql",
        "typegen": {
          "addons": [
            "./my-addon"
          ]
        }
      }
    ]
  }
}
```

Run `ts-graphql-plugin typegen` command. Then, the head of each generated .ts file should be the following:

```ts
/* Hello, my addon! */
/* eslint-disable */
/* This is an autogenerated file. Do not edit this file directly! */

// Your query result / variables / fragments types
```

### Template String and Addon Factory

The core type generator generates type files for each GraphQL template string in your TypeScript source files.

For example, the following `query` template string generates a type file, `__generated__/repository-query.ts` .

```ts
/* ghe-query.ts */

const query = gql`
  # fragment definition
  fragment IssueItem on Issue {
    id
    url
  }

  # fragment definition
  fragment RepoItem on Repository {
    id
    description
    issues(first: 10) {
      nodes {
        ...IssueItem
      }
    }
  }

  # operation definition
  query RepositoryQuery($limit: Int!) {
    viewer {
      repositories(first: $limit) {
        nodes {
          ...RepoItem
        }
      }
    }
  }
`;
```

And `TypeGenAddonFactory` function is called once for each GraphQL template string (i.e. for each output type file). So, the `ctx` argument of this function contains both the input template string and type file content to be output.

`ctx` has also reference to your GraphQL schema.

### GraphQL AST hooks

Addon can implement methods to be called back for top-level GraphQL AST node, `FragmentDefinition` and `OperationDefinition`.
You can access the type declaration statements the core generator created from the fragments or operations in these callback methods. They're useful to create some complex types from query result types or fragment object types.

```ts
const addonFactory: TypeGenAddonFactory = ctx => {
  return {
    fragmentDefinition({ graphqlNode, tsNode }) {
      // graphqlNode is the fragment definition node
      // tsNode is TypeScript type declaration node for the fragment
    },
    operationDefinition({ graphqlNode, tsResultNode, tsVariableNode }) {
      // graphqlNode is the operation(query/mutation/subscription) definition AST node.
      // tsResultNode is TypeScript type declaration node for result of the operation.
      // tsVariableNode is TypeScript type declaration node for variables of the operation.
    },
  };
};
```

And `document` callback is corresponding to the whole GraphQL document AST node. It's typically used to implement post-processing for the output .ts file.

```ts
const addonFactory: TypeGenAddonFactory = ctx => {
  return {
    document({ graphqlNode }) {
      // graphqlNode is the whole GraphQL document AST node.
    },
  };
};
```

### Custom Scalar hook

`customScalar` is a special callback method to customize mapping GraphQL scalar field to TypeScript types.

The core generator outputs `any` for custom scalr fields because the generator does not know which TypeScript type should they be mapped to.

```ts
const addonFactory: TypeGenAddonFactory = ctx => {
  return {
    customScalar({ scalarType }) {
      if (scalarType.name === 'URL') {
        return ts.factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword);
      }
    },
  };
};
```

The above example maps `URL` custom scalar field to TypeScript string type.

If `customScalar` function returns `undefined`, the core generator determines mapping result.

### Change output files' content using `ctx.source`

`source` in the addon factory context is an utility object to help to change output type file's content.

#### Add TypeScript statement

You can add TypeScript statements to the output file with `pushStatement` function. This function accepts `ts.Statement` AST node object.

```ts
const addonFactory: TypeGenAddonFactory = ctx => {
  return {
    document() {
      const statement = ts.factory.createTypeAliasDeclaration(
        undefined,
        [ts.createModifier(ts.SyntaxKind.ExportKeyword)],
        ts.factory.createIdentifier('Hoge'),
        undefined,
        ts.factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword),
      );
      ctx.source.pushStatement(statement);
    },
  };
};
```

Tips: Using `template` function provided from [Talt](https://github.com/Quramy/talt), the above code is equivalent to the following:

```ts
import { template } from 'talt';

const addonFactory: TypeGenAddonFactory = ctx => {
  return {
    document() {
      ctx.source.pushStatement(template.statement`export type Hoge = string`());
    },
  };
};
```

#### Add import statement

Sometimes, you want to import TypeScript types defined in other files and use them with generated types.

```ts
import { AwesomeType } from '../../util/types';

export type RepositoryQuery = {
  viewer: {
    /* ... */
  };
};

export type WrapRepositoryQuery = AwesomeType<RepositoryQuery>;
```

`ctx.source.pushNamedImportIfNeeded` helps to create import declaration:

```ts
/* my-addon.ts */

import { template } from 'talt';

const addonFactory: TypeGenAddonFactory = ctx => {
  return {
    operationDefinition({ tsResultNode }) {
      ctx.source.pushNamedImportIfNeeded('AwesomeType', '../../util/types');

      ctx.source.pushStatement(
        template.statement`
          export type WRAPPED_TYPE_ID = AwesomeType<RESULT_TYPE_ID>
        `({
          WRAPPED_TYPE_ID: ts.factory.createIdentifier(`Wrap${tsResultNode.name.text}`),
          RESULT_TYPE_ID: ts.factory.createIdentifier(tsResultNode.name.text),
        }),
      );
    },
  };
};
```

## Addon example

There is working example of Type Generator Addon under the [project-fixtures/typegen-addon-prj](../project-fixtures/typegen-addon-prj) directory in this repository.

## API reference

See ts-graphql-plugin's .d.ts files or [definition in this repository](../src/typegen/addon/types.ts).


text:
require 'forwardable'

class MathModel::InputParamsList
  include ActiveModel::Model
  attr_accessor :list_of_params
  extend Forwardable

  def self.factory(params = {})
    list = new
    raw_data = params[:raw_data]
    parameter_space = params[:parameter_space]
    mapped = parameter_space.map_normals(raw_data)
    mapped.each do |input|
      list.list_of_params.push(MathModel::InputParams.new({params: input}))
    end
    list
  end

  def_delegators :@list_of_params, :length, :size, :each, :each_with_index, :map, :collect

  def initialize(attributes = {})
    super
    self.list_of_params = []
  end

  def create_run_list(setting)
    exec = setting.executable
    run_list = MathModel::RunList.new
    each do |input|
      p "INPUT"
      p input
      p "SETTING"
      p setting
      run = exec.run(input, setting)
      p "RUN CREATED"
      run_list.add(run)
    end
    return run_list
  end

  private

  def extract_params(obj)
    return obj.normal_sample
  end
end


text:
package pb

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
)

// AccessTokenResponse stores the normal result of access token fetching.
type AccessTokenResponse struct {
	AccessToken string  `json:"access_token"`
	ExpiresIn   float64 `json:"expires_in"`
}

// AccessTokenErrorResponse stores the error result of access token fetching.
type AccessTokenErrorResponse struct {
	Errcode string
	Errmsg  string
}

// FetchAccessToken provides underlying access token fetching implementation.
func FetchAccessToken(requestLine string) (string, float64, error) {
	resp, err := http.Get(requestLine)
	if err != nil || resp.StatusCode != http.StatusOK {
		return "", 0.0, err
	}

	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", 0.0, err
	}

	//Json Decoding
	if bytes.Contains(body, []byte("access_token")) {
		atr := AccessTokenResponse{}
		err = json.Unmarshal(body, &atr)
		if err != nil {
			return "", 0.0, err
		}
		return atr.AccessToken, atr.ExpiresIn, nil
	}

	ater := AccessTokenErrorResponse{}
	err = json.Unmarshal(body, &ater)
	if err != nil {
		return "", 0.0, err
	}
	return "", 0.0, fmt.Errorf("%s", ater.Errmsg)
}


text:
  CREATE MATERIALIZED VIEW "GROUNDFISH"."GSAGER" ("AGER", "NAME")
  ORGANIZATION HEAP PCTFREE 5 PCTUSED 40 INITRANS 1 MAXTRANS 255 NOCOMPRESS NOLOGGING
  STORAGE(INITIAL 65536 NEXT 65536 MINEXTENTS 1 MAXEXTENTS 2147483645
  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT)
  TABLESPACE "MFD_GROUNDFISH"
  BUILD IMMEDIATE
  USING INDEX
  REFRESH FORCE ON DEMAND START WITH sysdate+0 NEXT (trunc(sysdate+1)+19/24)
  USING DEFAULT LOCAL ROLLBACK SEGMENT
  DISABLE QUERY REWRITE
  AS select * from groundfish.gsager@groundfish.sabs;

   COMMENT ON MATERIALIZED VIEW "GROUNDFISH"."GSAGER"  IS 'snapshot table for snapshot GROUNDFISH.GSAGER';
  GRANT SELECT ON "GROUNDFISH"."GSAGER" TO PUBLIC;

  GRANT SELECT ON "GROUNDFISH"."GSAGER" TO "MFLIB";

  GRANT SELECT ON "GROUNDFISH"."GSAGER" TO "VDC";

  GRANT SELECT ON "GROUNDFISH"."GSAGER" TO "HUBLEYB";

  GRANT SELECT ON "GROUNDFISH"."GSAGER" TO "GREYSONP";


text:
package com.example.syncadapterexample;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

public class MyAuthenticatorService extends Service {

	private MyAuthenticator _authenticator;

	@Override
	public void onCreate(){
		_authenticator = new MyAuthenticator(this);
	}

	@Override
	public IBinder onBind(Intent intent) {
		return _authenticator.getIBinder();
	}
}


text:
package org.apache.flink.api.common.typeutils;

import org.apache.flink.core.memory.DataInputDeserializer;
import org.apache.flink.core.memory.DataInputView;
import org.apache.flink.core.memory.DataOutputSerializer;
import org.apache.flink.core.memory.DataOutputView;

import org.junit.Test;

import java.io.IOException;
import java.io.ObjectInputStream;

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

/**
 * Tests the backwards compatibility of the TypeSerializerConfigSnapshot.
 */
@SuppressWarnings({"serial", "deprecation"})
public class TypeSerializerSnapshotTest {

	@Test
	public void testBridgeCompatibilityCheck() throws Exception {
		TestSerializerConfigSnapshot snap = new TestSerializerConfigSnapshot();

		TestSerializer serCompat = new TestSerializer(true);
		TypeSerializerSchemaCompatibility<Object> resultCompat = snap.resolveSchemaCompatibility(serCompat);
		assertTrue(resultCompat.isCompatibleAsIs());

		TestSerializer serIncompat = new TestSerializer(false);
		TypeSerializerSchemaCompatibility<Object> resultIncompat = snap.resolveSchemaCompatibility(serIncompat);
		assertTrue(resultIncompat.isIncompatible());
	}

	@Test
	public void testSerializeConfigWhenSerializerMissing() throws Exception {
		TestSerializer ser = new TestSerializer();
		TypeSerializerConfigSnapshot<Object> snap = (TypeSerializerConfigSnapshot<Object>) ser.snapshotConfiguration();

		try {
			TypeSerializerSnapshot.writeVersionedSnapshot(new DataOutputSerializer(64), snap);
			fail("exception expected");
		}
		catch (IllegalStateException e) {
			// expected
		}
	}

	@Test
	public void testSerializerDeserializationFailure() throws Exception {
		TestSerializer ser = new TestSerializer();
		TypeSerializerConfigSnapshot<Object> snap = (TypeSerializerConfigSnapshot<Object>) ser.snapshotConfiguration();
		snap.setPriorSerializer(ser);

		DataOutputSerializer out = new DataOutputSerializer(64);

		TypeSerializerSnapshot.writeVersionedSnapshot(out, snap);
		TypeSerializerSnapshot<Object> readBack = TypeSerializerSnapshot.readVersionedSnapshot(
				new DataInputDeserializer(out.getCopyOfBuffer()), getClass().getClassLoader());

		assertNotNull(readBack);

		try {
			readBack.restoreSerializer();
			fail("expected exception");
		}
		catch (IllegalStateException e) {
			// expected
		}

		((TypeSerializerConfigSnapshot<Object>) readBack).setPriorSerializer(
				new UnloadableDummyTypeSerializer<>(new byte[0]));
		try {
			readBack.restoreSerializer();
			fail("expected exception");
		}
		catch (IllegalStateException e) {
			// expected
		}
	}

	// ------------------------------------------------------------------------

	private static final class TestSerializer extends TypeSerializer<Object> {

		private final boolean compatible;

		TestSerializer() {
			this(true);
		}

		TestSerializer(boolean compatible) {
			this.compatible = compatible;
		}

		@Override
		public boolean isImmutableType() {
			throw new UnsupportedOperationException();
		}

		@Override
		public TypeSerializer<Object> duplicate() {
			throw new UnsupportedOperationException();
		}

		@Override
		public Object createInstance() {
			throw new UnsupportedOperationException();
		}

		@Override
		public Object copy(Object from) {
			throw new UnsupportedOperationException();
		}

		@Override
		public Object copy(Object from, Object reuse) {
			throw new UnsupportedOperationException();
		}

		@Override
		public int getLength() {
			throw new UnsupportedOperationException();
		}

		@Override
		public void serialize(Object record, DataOutputView target) throws IOException {
			throw new UnsupportedOperationException();
		}

		@Override
		public Object deserialize(DataInputView source) throws IOException {
			throw new UnsupportedOperationException();
		}

		@Override
		public Object deserialize(Object reuse, DataInputView source) throws IOException {
			throw new UnsupportedOperationException();
		}

		@Override
		public void copy(DataInputView source, DataOutputView target) throws IOException {
			throw new UnsupportedOperationException();
		}

		@Override
		public boolean equals(Object obj) {
			return obj instanceof TestSerializer;
		}

		@Override
		public boolean canEqual(Object obj) {
			return true;
		}

		@Override
		public int hashCode() {
			return 0;
		}

		private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
			throw new IOException("cannot deserialize");
		}

		@Override
		public TypeSerializerSnapshot<Object> snapshotConfiguration() {
			return new TestSerializerConfigSnapshot();
		}

		@Override
		public CompatibilityResult<Object> ensureCompatibility(TypeSerializerConfigSnapshot<?> configSnapshot) {
			return compatible ? CompatibilityResult.compatible() : CompatibilityResult.requiresMigration();
		}
	}

	public static class TestSerializerConfigSnapshot extends TypeSerializerConfigSnapshot<Object> {

		@Override
		public int getVersion() {
			return 0;
		}
	}
}


text:
{% extends "mails/messages/activity_base.html" %}
{% load i18n %}

{% block message%}

        {% blocktrans context 'email' %}{{team_name}} has applied to your activity "{{title}}".{% endblocktrans %}

        {% blocktrans context 'email' %}Next steps{% endblocktrans %}

{% blocktrans context 'email' %}Contact team captain {{team_captain_name}} to settle on a date, time and location for when they will participate in this activity.{% endblocktrans %}

{% blocktrans context 'email' %}Add this information to the team via the unscheduled team list on the activity page so it is visible for the team members.{% endblocktrans %}

{% blocktrans context 'email' %}Accept the team after you have added the details so when the team members are invited  to join the activity it includes the time, date and location.{% endblocktrans %}

{% blocktrans context 'email' %}Team captain contact details:{% endblocktrans %}

{{team_captain_email}}

{% endblock %}


text:
'use strict';

const { isType, isFunction, isUserType } = require('lib/util');
const symbols = require('internal/symbols');
const { decodeCommon } = require('lib/decode');
const { encodeCommon } = require('lib/encode');
const { encodingLengthCommon } = require('lib/encoding-length');
const Metadata = require('internal/meta');

module.exports = when;

/**
 * Type for conditions.
 * @param {Function|bool} condition
 * @param {Object} type Any builtin type or schema.
 * @returns {Object}
 */
function when(condition, type) {
  if (!isType(type) && !isUserType(type)) {
    throw new TypeError('Argument #2 should be a valid type.');
  }

  const result = {
    encode,
    decode,
    encodingLength,
    [symbols.skip]: false,
  };

  return result;

  /**
   * Encode value if condition is truthy.
   * @param {any} value
   * @param {EncodeStream} wstream
   */
  function encode(value, wstream) {
    const context = Metadata.clone(this);
    encode.bytes = 0;

    const status = isFunction(condition)
      ? Boolean(condition(context))
      : Boolean(condition);

    result[symbols.skip] = !status;

    if (!status) {
      Metadata.clean(context);
      return;
    }

    encodeCommon(value, wstream, type, context);
    encode.bytes = context.bytes;

    Metadata.clean(context);
  }

  /**
   * Decode value if condition is truthy.
   * @param {DecodeStream} rstream
   * @returns {any}
   */
  function decode(rstream) {
    const context = Metadata.clone(this);
    decode.bytes = 0;

    const status = isFunction(condition)
      ? Boolean(condition(context))
      : Boolean(condition);

    result[symbols.skip] = !status;

    if (!status) {
      Metadata.clean(context);
      return;
    }

    const value = decodeCommon(rstream, type, context);

    decode.bytes = context.bytes;
    Metadata.clean(context);

    return value; // eslint-disable-line consistent-return
  }

  /**
   * Get the number bytes of an encoded value
   * when condition is truthy or 0.
   * @param {any} value
   * @returns {number}
   */
  function encodingLength(value) {
    const context = Metadata.clone(this);

    const status = isFunction(condition)
      ? Boolean(condition(context))
      : Boolean(condition);

    if (status) {
      encodingLengthCommon(value, type, context);
    }

    Metadata.clean(context);
    return context.bytes;
  }
}


text:
using namespace Storage::Disk;

G64::G64(const std::string &file_name) :
		file_(file_name) {
	// read and check the file signature
	if(!file_.check_signature("GCR-1541")) throw Error::InvalidFormat;

	// check the version number
	int version = file_.get8();
	if(version != 0) throw Error::UnknownVersion;

	// get the number of tracks and track size
	number_of_tracks_ = file_.get8();
	maximum_track_size_ = file_.get16le();
}

HeadPosition G64::get_maximum_head_position() {
	// give at least 84 tracks, to yield the normal geometry but,
	// if there are more, shove them in
	return HeadPosition(number_of_tracks_ > 84 ? number_of_tracks_ : 84, 2);
}

std::shared_ptr<Track> G64::get_track_at_position(Track::Address address) {
	std::shared_ptr<Track> resulting_track;

	// seek to this track's entry in the track table
	file_.seek(long((address.position.as_half() * 4) + 0xc), SEEK_SET);

	// read the track offset
	const uint32_t track_offset = file_.get32le();

	// if the track offset is zero, this track doesn't exist, so...
	if(!track_offset) return nullptr;

	// seek to the track start
	file_.seek(long(track_offset), SEEK_SET);

	// get the real track length
	const uint16_t track_length = file_.get16le();

	// grab the byte contents of this track
	const std::vector<uint8_t> track_contents = file_.read(track_length);

	// seek to this track's entry in the speed zone table
	file_.seek(long((address.position.as_half() * 4) + 0x15c), SEEK_SET);

	// read the speed zone offsrt
	const uint32_t speed_zone_offset = file_.get32le();

	// if the speed zone is not constant, create a track based on the whole table; otherwise create one that's constant
	if(speed_zone_offset > 3) {
		// seek to start of speed zone
		file_.seek(long(speed_zone_offset), SEEK_SET);

		// read the speed zone bytes
		const uint16_t speed_zone_length = (track_length + 3) >> 2;
		uint8_t speed_zone_contents[speed_zone_length];
		file_.read(speed_zone_contents, speed_zone_length);

		// divide track into appropriately timed PCMSegments
		std::vector<PCMSegment> segments;
		unsigned int current_speed = speed_zone_contents[0] >> 6;
		unsigned int start_byte_in_current_speed = 0;
		for(unsigned int byte = 0; byte < track_length; byte ++) {
			unsigned int byte_speed = speed_zone_contents[byte >> 2] >> (6 - (byte&3)*2);
			if(byte_speed != current_speed || byte == uint16_t(track_length-1)) {
				unsigned int number_of_bytes = byte - start_byte_in_current_speed;

				PCMSegment segment(
					Encodings::CommodoreGCR::length_of_a_bit_in_time_zone(current_speed),
					number_of_bytes * 8,
					&track_contents[start_byte_in_current_speed]);
				segments.push_back(std::move(segment));

				current_speed = byte_speed;
				start_byte_in_current_speed = byte;
			}
		}

		resulting_track = std::make_shared<PCMTrack>(std::move(segments));
	} else {
		PCMSegment segment(
			Encodings::CommodoreGCR::length_of_a_bit_in_time_zone(unsigned(speed_zone_offset)),
			track_length * 8,
			track_contents
		);

		resulting_track = std::make_shared<PCMTrack>(std::move(segment));
	}

	// TODO: find out whether it's possible for a G64 to supply only a partial track. I don't think it is, which would make the
	// above correct but supposing I'm wrong, the above would produce some incorrectly clocked tracks

	return resulting_track;
}


text:
import binaryen from "../index.js";

// Create a module with a single function
var myModule = new binaryen.Module();

myModule.addFunction("add", binaryen.createType([ binaryen.i32, binaryen.i32 ]), binaryen.i32, [ binaryen.i32 ],
  myModule.block(null, [
    myModule.local.set(2,
      myModule.i32.add(
        myModule.local.get(0, binaryen.i32),
        myModule.local.get(1, binaryen.i32)
      )
    ),
    myModule.return(
      myModule.local.get(2, binaryen.i32)
    )
  ])
);
myModule.addFunctionExport("add", "add");

// Optimize the module using default passes and levels
myModule.optimize();

// Validate the module
if (!myModule.validate())
  throw new Error("validation error");

// Generate text format and binary
var textData = myModule.emitText();
var wasmData = myModule.emitBinary();

console.log(textData);
console.log("1 + 2 = " + new WebAssembly.Instance(new WebAssembly.Module(wasmData)).exports.add(1, 2));


text:
void steepestDescentEngine(OBMol &moleculeA, OBMol &moleculeB, double alpha, double betaRadians) {
    cout << endl << "BEGIN STEEPEST DESCENT SEARCH" << endl
        << "alpha = " << alpha << endl << "beta = " << betaRadians << endl << "Initializing data..." << endl;

    vector<double> coordsMoleculeA, coordsMoleculeB, centerOfMassA, force, torque, delT, delR, tempA, bestAInThisStep;
    vector<int> atomicNumsA, atomicNumsB;

    generateCoordsMatrixFromMolecule(coordsMoleculeA, moleculeA);
    generateCoordsMatrixFromMolecule(coordsMoleculeB, moleculeB);
    generateAtomicNumbersListFromMolecule(atomicNumsA, moleculeA);
    generateAtomicNumbersListFromMolecule(atomicNumsB, moleculeB);
    getMoleculeCenterCoords(centerOfMassA, moleculeA);

    double currentStepH = 1, bestVolumeOverlapSoFar = volumeOverlap(coordsMoleculeA, coordsMoleculeB, atomicNumsA, atomicNumsB);

    while (currentStepH > 0) {
        cout << "stepping... ";
        double bestHInThisStep = 0;
        bestAInThisStep = coordsMoleculeA;

        // calculate force and torque, and normalize them
        calculateForceAndTorqueVectors(force, torque, coordsMoleculeA, coordsMoleculeB, atomicNumsA, atomicNumsB, centerOfMassA);
        normalizeVector(force); normalizeVector(torque);

        for (double h=0; h < 1.0; h += 0.01) {
            generateSteepestDescentTranslationalVector(delT, force, h, alpha); // generate deviation translational vector
            generateSteepestDescentRotationMatrix(delR, torque, h, betaRadians); // generate deviation rotational matrix

            // rotate and translate
            tempA = coordsMoleculeA;
            translate3DMatrixCoordinates(tempA, -centerOfMassA[0], -centerOfMassA[1], -centerOfMassA[2]);
            rotate3DMatrixCoordinates(tempA, delR);
            translate3DMatrixCoordinates(tempA, centerOfMassA[0] + delT[0], centerOfMassA[1] + delT[1], centerOfMassA[2] + delT[2]); // move coordinates back FROM center of rotation and add the translational displacement

            double currentVolOverlap = volumeOverlap(tempA, coordsMoleculeB, atomicNumsA, atomicNumsB);
            if (currentVolOverlap > bestVolumeOverlapSoFar) { // check overlap goodness
                bestHInThisStep = h;
                bestVolumeOverlapSoFar = currentVolOverlap;
                bestAInThisStep = tempA;
            }
        }
        coordsMoleculeA = bestAInThisStep; currentStepH = bestHInThisStep;
        cout << "Best h in this step is " << bestHInThisStep << " and volume overlap is at " << bestVolumeOverlapSoFar << endl;
    }

    cout << "\nThe convergent solution coordinates of A produces a volume overlap of " << bestVolumeOverlapSoFar << endl;
    cout << "\nRESULTING A:" << endl; printMatrix(coordsMoleculeA, coordsMoleculeA.size() / 3, 3, false);

    cout << "\nEND STEEOEST DESCENT SEARCH.  SAVING COORDINATES TO MOLECULE A...\n\n";
    saveCoordsMatrixToMolecule(moleculeA, coordsMoleculeA);
}

void sampleTest(OBMol &molecule) {
    cout << "BESGIN TEST" << endl;
    vector<double> abc;
    generateCovarMatrixFromMolecule(abc, molecule);
    for (int i=0; i<abc.size(); i+=3) { cout << "{" << abc[i] << "," << abc[i+1] << "," << abc[i+2] << "},"; } cout << endl;
    vector<double> eigenvectors, eigenvalues;
    generateEigenMatrix(eigenvectors, eigenvalues, abc);

    for (int i=0; i<eigenvalues.size(); i++) cout << eigenvalues[i] << " ";
        cout << endl;
    for (int i=0; i<eigenvectors.size(); i++) cout << eigenvectors[i] << " ";
        cout << endl;
    cout << "END TEST" << endl << endl;
}

void testEigen() {
    double xyz[] = {7, 9, 2, 9, 1, 6, 2, 6, 10};
    vector<double> sample(xyz, &xyz[9]);
    for (int i=0; i<sample.size(); i++) cout << sample[i] << " ";
        cout << endl;

    vector<double> eigenvectors, eigenvalues;
    generateEigenMatrix(eigenvectors, eigenvalues, sample);
    for (int i=0; i<eigenvalues.size(); i++) cout << eigenvalues[i] << " ";
        cout << endl;
    for (int i=0; i<eigenvectors.size(); i++) cout << eigenvectors[i] << " ";
        cout << endl << endl << endl << endl;
}

void testGenRot() {
    double a[] = {1, 2, 3, 2, 4, 5, 3, 5, 6};
    vector<double> vA(a, &a[9]);
    double b[] = {7, 9, 2, 2, 1, 0, 2, 6, 10};
    vector<double> vB(b, &b[9]);
    vector<double> c;
    generatePCARotationMatrix(c, 3, vA, vB);
    cout << endl << endl;
    for (int i=0; i<vA.size(); i++) cout << vA[i] << " ";
        cout << endl;
    for (int i=0; i<vB.size(); i++) cout << vB[i] << " ";
        cout << endl;
    for (int i=0; i<c.size(); i++) cout << c[i] << " ";
        cout << endl;
}

void testRot() {
    cout << "BEGIN ROTATE TEST" << endl;
    double a[] = {1, 2, 3, 2, 4, 5, 3, 5, 6};
    vector<double> vA(a, &a[9]);
    double b[] = {7, 9, 2, 2, 1, 0, 2, 6, 10};
    vector<double> vB(b, &b[9]);
    vector<double> c;
    for (int i=0; i<vA.size(); i++) cout << vA[i] << " ";
        cout << endl;
    for (int i=0; i<vB.size(); i++) cout << vB[i] << " ";
        cout << endl;
    /*rotate3DMatrixCoordinates(vA, vB);
    for (int i=0; i<vA.size(); i++) cout << vA[i] << " ";
        cout << endl;
    for (int i=0; i<vB.size(); i++) cout << vB[i] << " ";
        cout << endl;
    vB.push_back(199);
    cout << endl;
    printMatrix(vB, 5, 2);
    */
    vector<double> C; vA.resize(3); vB.resize(3);
    generateMatrixWFromNormalizedVectorW(C, vB);
    for (int i=0; i<C.size(); i++) cout << C[i] << " ";
        cout << endl;
    cout << "END ROTATE TEST" << endl;
}

/*
    generatePCARotationMatrix(Rx, 1, eVectA, eVectB);
    generatePCARotationMatrix(Ry, 2, eVectA, eVectB);
    generatePCARotationMatrix(Rz, 3, eVectA, eVectB);

    // the transformation itself, R(p - p0) + q0
    translate3DMatrixCoordinates(coordA, -comA[0], -comA[1], -comA[2]);
    rotate3DMatrixCoordinates(coordA, Rx);
    translate3DMatrixCoordinates(coordA, comB[0], comB[1], comB[2]);

    saveCoordsMatrixToMolecule(moleculeA, coordA);
    OBConversion obconversion;
    obconversion.SetOutFormat("sdf");

    obconversion.WriteFile(&moleculeA, "newA.sdf");
    cout << "OOOOKKKKKKK" << endl;
*/

/*

// older implementation of volumeOverlap

double volumeOverlap (OBMol &moleculeA, OBMol &moleculeB) {
    double totalVolumeOverlap = 0;

    const double constP = 2.0 * M_SQRT2;
    const double A = 4.0 * M_PI * constP / 3.0;
    const double B = -M_PI * pow(0.75 * constP * M_1_PI, 2.0/3.0);

    for (OBAtomIterator iterA = moleculeA.BeginAtoms(); iterA != moleculeA.EndAtoms(); iterA++) {
        double *coordsOfAtomI = (*iterA)->GetCoordinate();
        double vdwRA = etab.GetVdwRad((*iterA)->GetAtomicNum());

        for (OBAtomIterator iterB = moleculeB.BeginAtoms(); iterB != moleculeB.EndAtoms(); iterB++) {
            double *coordsOfAtomJ = (*iterB)->GetCoordinate();
            double vdwRB = etab.GetVdwRad((*iterB)->GetAtomicNum());

            double sqvA = vdwRA * vdwRA;
            double sqvB = vdwRB * vdwRB;
            double C = sqvA + sqvB;

            double distanceSquared = pow(coordsOfAtomJ[0]-coordsOfAtomI[0], 2) + pow(coordsOfAtomJ[1]-coordsOfAtomI[1], 2) + pow(coordsOfAtomJ[2]-coordsOfAtomI[2], 2);

            totalVolumeOverlap += A * pow(sqvA * sqvB  / C, 1.5) * exp(B * distanceSquared / C );
        }
    }
    return totalVolumeOverlap;
}
*/

/*
    OBConversion obconversion;
    obconversion.SetInFormat("sdf");

    OBMol mol2;
    obconversion.ReadFile(&mol2, argv[2]);

    OBMol mol;
    bool notatend = obconversion.ReadFile(&mol, argv[1]);

    while (notatend) {
        std::cout << "Molecular Weight: " << mol.GetMolWt() << std::endl;
        for (OBAtomIterator iter = mol.BeginAtoms(); iter != mol.EndAtoms(); iter++) {
            cout << (*iter)->GetVector() << ", " << (*iter)->GetCoordinate()[0] << endl;
        }
        mol.Clear();
        notatend = obconversion.Read(&mol);
    }

   ifstream ifs(argv[1]);
    if(!ifs) {
        cout << "Cannot open input file\n";
        return 1;
    }

    ofstream ofs(argv[2]);
    if(!ofs) {
        cout << "Cannot open output file\n";
        return 1;
    }
    OpenBabel::OBConversion conv(&ifs, &ofs);
    if(!conv.SetInAndOutFormats("CML","MOL")) {
        cout << "Formats not available\n";
        return 1;
    }
    int n = conv.Convert();
    cout << n << " molecules converted\n";

*/

/*
    // Print the rotor keys
    RotorKeys keys = cs.GetRotorKeys();
    for (RotorKeys::iterator key = keys.begin(); key != keys.end(); ++key) {
        for (unsigned int i = 1; i < key->size(); ++i) cout << key->at(i) << " ";
        cout << endl;
    }
*/

    //sampleTest(mol);
    //testRot();
    //testEigen();

/*
    vector< vector<double> > coordAs, coordBs, comAs, comBs, eVectAs, eVectBs;
    vector<double> VDWsA, VDWsB, massesA, massesB, currentPCACoordA, currentSDCoordA, bestCoordsA;

    double molecularWeightA = molecules[0].GetMolWt(), molecularWeightB = molecules[1].GetMolWt();
    double bestVolumeOverlap = -1;
    int bestJ = -1, bestI = -1, stepCount = 0;

    generateVDWRadiusListFromMolecule(VDWsA, molecules[0]);
    generateVDWRadiusListFromMolecule(VDWsB, molecules[1]);
    generateAtomicMassesListFromMolecule(massesA, molecules[0]);
    generateAtomicMassesListFromMolecule(massesB, molecules[1]);
    generateCoordsMatrixFromMoleculeConformers(coordAs, molecules[0]);
    generateCoordsMatrixFromMoleculeConformers(coordBs, molecules[1]);
    getMoleculeConformerCenterCoords(comAs, molecules[0]);
    getMoleculeConformerCenterCoords(comBs, molecules[1]);
    eVectAs.resize( molecules[0].NumConformers() ), eVectBs.resize( molecules[1].NumConformers() );
    for (unsigned int k=0; k < molecules[0].NumConformers(); k++) getPCAEigenMatrix(eVectAs[k], coordAs[k], massesA, molecularWeightA);
    for (unsigned int k=0; k < molecules[1].NumConformers(); k++) getPCAEigenMatrix(eVectBs[k], coordBs[k], massesB, molecularWeightB);
    cout << "Finished setting up data; running search...\n";

    for (unsigned int j=0; j < molecules[1].NumConformers(); j++) {
        for (unsigned int i=0; i < molecules[0].NumConformers(); i++) {
            PCAEngine(currentPCACoordA, coordAs[i], coordBs[j], eVectAs[i], eVectBs[j], comAs[i], comBs[j], VDWsA, VDWsB);
            double currentVolumeOverlap = steepestDescentEngine(currentSDCoordA, currentPCACoordA, coordBs[j], VDWsA, VDWsB, comAs[i], 1.0, 10.0 * M_PI / 180.0);
            if (currentVolumeOverlap > bestVolumeOverlap) {
                bestVolumeOverlap = currentVolumeOverlap;
                bestCoordsA = currentSDCoordA;
                bestI = i; bestJ = j;
            }
            cout << "finished round " << ++stepCount << endl;
        }
    }

    cout << "\nThe best overlap is between conformer A#" << bestI << " and B#" << bestJ << ", which, after PCA followed by Steepest Descent, produces a volume overlap of " << bestVolumeOverlap << endl;
    cout << "\nSaving those best conformers to file..." << endl;

    saveCoordsMatrixToMolecule(molecules[0], bestCoordsA);
    molecules[1].SetConformer(bestJ);
*/

        /*importMoleculeConformersFromFile(molecules, argv[1]);
    molecules[0].SetConformer(atoi(argv[2]));
    molecules[0].DeleteHydrogens();
    for (OBAtomIterator iter = molecules[0].BeginAtoms(); iter != molecules[0].EndAtoms(); iter++) cout << (*iter)->x() << "\t" << (*iter)->y() << "\t" << (*iter)->z() << endl;
    writeMoleculeToFile(argv[3], molecules[0]);
    *///volumeOverlap(molecules[1], molecules[0], true);
    //removeNonBondedAtomsInMolecule(molecules[0]);
    //generateConformers(molecules[0]);
    //writeMoleculeConformersToFile(argv[2], molecules[0], true);

/*    cout << "VEC SIZE: " << molecules.size() << endl;
    cout << "NUM CONFORMERS: " << molecules[0].NumConformers() << endl;
    cout << "NUM ATOMS: " << molecules[0].NumAtoms() << endl;
*/
    //molecules[1].SetConformer(10);

    //findBestPCAOrientation(molecules[0], molecules[1]);
    //runSteepestDescent(molecules[0], molecules[1], 0.5, 10.0 * M_PI / 180.0);
    //PCAPlusSteepestDescent(molecules[0], molecules[1], 0.5, 10.0 * M_PI / 180.0);


text:
/**
 * A helper that wraps an encoder or a decoder so that they can be used without
 * doing actual I/O in unit tests or higher level codecs.
 *
 * @apiviz.exclude CodecEmbedder$
 */
package org.jboss.netty.handler.codec.embedder;


text:
package cn.felord.wepay.ali.sdk.api.domain;

import cn.felord.wepay.ali.sdk.api.AlipayObject;
import cn.felord.wepay.ali.sdk.api.internal.mapping.ApiField;

/**
 * 券模板创建
 *
 * @author auto create
 * @version $Id: $Id
 */
public class AlipayOfflineMarketingVoucherCreateModel extends AlipayObject {

	private static final long serialVersionUID = 4752396624181592621L;

	/**
	 * 预算信息
	 */
	@ApiField("budget_info")
	private BudgetInfo budgetInfo;

	/**
	 * 券码池编号。该值调用:alipay.offline.marketing.voucher.code.upload接口生成
	 */
	@ApiField("code_inventory_id")
	private String codeInventoryId;

	/**
	 * 扩展参数
	 */
	@ApiField("ext_info")
	private String extInfo;

	/**
	 * 发放规则信息
	 */
	@ApiField("get_rule")
	private GetRuleInfo getRule;

	/**
	 * 外部流水号.需商家自己生成并保证每次请求的唯一性
	 */
	@ApiField("out_biz_no")
	private String outBizNo;

	/**
	 * 券模板信息
	 */
	@ApiField("voucher_info")
	private VoucherInfo voucherInfo;

	/**
	 *
Getter for the field budgetInfo.

	 *
	 * @return a {@link cn.felord.wepay.ali.sdk.api.domain.BudgetInfo} object.
	 */
	public BudgetInfo getBudgetInfo() {
		return this.budgetInfo;
	}
	/**
	 *
Setter for the field budgetInfo.

	 *
	 * @param budgetInfo a {@link cn.felord.wepay.ali.sdk.api.domain.BudgetInfo} object.
	 */
	public void setBudgetInfo(BudgetInfo budgetInfo) {
		this.budgetInfo = budgetInfo;
	}

	/**
	 *
Getter for the field codeInventoryId.

	 *
	 * @return a {@link java.lang.String} object.
	 */
	public String getCodeInventoryId() {
		return this.codeInventoryId;
	}
	/**
	 *
Setter for the field codeInventoryId.

	 *
	 * @param codeInventoryId a {@link java.lang.String} object.
	 */
	public void setCodeInventoryId(String codeInventoryId) {
		this.codeInventoryId = codeInventoryId;
	}

	/**
	 *
Getter for the field extInfo.

	 *
	 * @return a {@link java.lang.String} object.
	 */
	public String getExtInfo() {
		return this.extInfo;
	}
	/**
	 *
Setter for the field extInfo.

	 *
	 * @param extInfo a {@link java.lang.String} object.
	 */
	public void setExtInfo(String extInfo) {
		this.extInfo = extInfo;
	}

	/**
	 *
Getter for the field getRule.

	 *
	 * @return a {@link cn.felord.wepay.ali.sdk.api.domain.GetRuleInfo} object.
	 */
	public GetRuleInfo getGetRule() {
		return this.getRule;
	}
	/**
	 *
Setter for the field getRule.

	 *
	 * @param getRule a {@link cn.felord.wepay.ali.sdk.api.domain.GetRuleInfo} object.
	 */
	public void setGetRule(GetRuleInfo getRule) {
		this.getRule = getRule;
	}

	/**
	 *
Getter for the field outBizNo.

	 *
	 * @return a {@link java.lang.String} object.
	 */
	public String getOutBizNo() {
		return this.outBizNo;
	}
	/**
	 *
Setter for the field outBizNo.

	 *
	 * @param outBizNo a {@link java.lang.String} object.
	 */
	public void setOutBizNo(String outBizNo) {
		this.outBizNo = outBizNo;
	}

	/**
	 *
Getter for the field voucherInfo.

	 *
	 * @return a {@link cn.felord.wepay.ali.sdk.api.domain.VoucherInfo} object.
	 */
	public VoucherInfo getVoucherInfo() {
		return this.voucherInfo;
	}
	/**
	 *
Setter for the field voucherInfo.

	 *
	 * @param voucherInfo a {@link cn.felord.wepay.ali.sdk.api.domain.VoucherInfo} object.
	 */
	public void setVoucherInfo(VoucherInfo voucherInfo) {
		this.voucherInfo = voucherInfo;
	}

}


text:
import React from 'react'
import { shallow } from 'enzyme'

import PairingBoard from './PairingBoard.js'
import PersonList from './PersonList'

describe('<PairingBoard/>', () => {
    let wrapper, props
    const InnerPairingBoard = PairingBoard.DecoratedComponent.WrappedComponent

    beforeEach(() => {
        props  = {
            id: 77,
            name: 'PairingBoard1',
            people: [
                { name: 'George' },
                { name: 'Hank Muchacho' }
            ],
            roles: [
                { name: 'Interrupt' }
            ],
            exempt: false,
            editMode: false,
            editErrorMessage: 'some error message',
            isOver: false,
            renamePairingBoard: jasmine.createSpy('renamePairingBoardSpy'),
            deletePairingBoard: jasmine.createSpy('deletePairingBoardSpy'),
            moveRole: jasmine.createSpy('moveRoleSpy'),
            deleteRole: jasmine.createSpy('deleteRoleSpy'),
            setNewRoleModalOpen: jasmine.createSpy('setNewRoleModalOpen'),
            setPairingBoardEditMode: jasmine.createSpy('setPairingBoardEditModeSpy'),
            connectDropTarget: jasmine.createSpy('connectDropTargetSpy')
        }

        props.connectDropTarget.and.callFake(i => i)

        wrapper = shallow(<InnerPairingBoard {...props} />)
    })

    it('renders the pairing board with only the pairing board class', () => {
        expect(wrapper.prop('className')).toBe('pairing-board')
    })

    it('renders the pairing board header', () => {
        const pairingBoardHeader = wrapper.find('PairingBoardHeader')
        expect(pairingBoardHeader.prop('name')).toBe('PairingBoard1')
        expect(pairingBoardHeader.prop('exempt')).toBe(false)
        expect(pairingBoardHeader.prop('editMode')).toBe(false)
        expect(pairingBoardHeader.prop('editErrorMessage')).toBe('some error message')
    })

    it('passes the header a rename function that calls renamePairingBoard with a callback that sets editMode to false', () => {
        const passedRenameFunction = wrapper.find('PairingBoardHeader').prop('renamePairingBoard')
        passedRenameFunction('SomeNewName')

        expect(props.renamePairingBoard).toHaveBeenCalledWith(77, 'SomeNewName', jasmine.anything())

        const successCallback = props.renamePairingBoard.calls.mostRecent().args[2]
        successCallback()

        expect(props.setPairingBoardEditMode).toHaveBeenCalledWith(77, false)
    })

    it('passes the header a delete function that calls deletePairingBoard', () => {
        const passedDeleteFunction = wrapper.find('PairingBoardHeader').prop('deletePairingBoard')
        passedDeleteFunction()

        expect(props.deletePairingBoard).toHaveBeenCalledWith(77)
    })

    it('passes the header a enable edit mode function that sets editMode to true', () => {
        const passedEnableEditModeFunction = wrapper.find('PairingBoardHeader').prop('enableEditMode')
        passedEnableEditModeFunction()

        expect(props.setPairingBoardEditMode).toHaveBeenCalledWith(77, true)
    })

    it('passes the header a open new role modal function that calls setNewRoleModalOpen', () => {
        const passedOpenNewRoleModalFunction = wrapper.find('PairingBoardHeader').prop('openNewRoleModal')
        passedOpenNewRoleModalFunction()

        expect(props.setNewRoleModalOpen).toHaveBeenCalledWith(77, true)
    })

    it('renders the list of roles with curried methods', () => {
        const roles = wrapper.find('RoleList')
        expect(roles.prop('roles')).toBe(props.roles)

        roles.prop('moveRole')(123, { pairingBoardId: 444 })
        expect(props.moveRole).toHaveBeenCalledWith(77, 123, { pairingBoardId: 444 })

        roles.prop('deleteRole')(123)
        expect(props.deleteRole).toHaveBeenCalledWith(77, 123)
    })

    it('renders the list of people', () => {
        const people = wrapper.find(PersonList)
        expect(people.prop('people')).toBe(props.people)
    })

    it('adds the editing class when editMode is true', () => {
        props.editMode = true
        wrapper = shallow(<InnerPairingBoard {...props} />)
        expect(wrapper.prop('className')).toContain('editing')
    })

    it('adds the exempt class when exempt is true', () => {
        props.exempt = true
        wrapper = shallow(<InnerPairingBoard {...props} />)
        expect(wrapper.prop('className')).toContain('exempt')
    })

    it('adds the drop-target class when isOver is true', () => {
        props.isOver = true
        wrapper = shallow(<InnerPairingBoard {...props} />)
        expect(wrapper.prop('className')).toContain('drop-target')
    })
})


text:
We describe the files for generating the Ubuntu Dialogue Corpus, and the dataset itself.

## UPDATES FROM UBUNTU CORPUS v1.0:

There are several updates and bug fixes that are present in v2.0. The updates are significant enough that results on the two datasets will not be equivalent, and should not be compared. However, models that do well on the first dataset should transfer to the second dataset (with perhaps a new hyperparameter search).

- Separated the train/validation/test sets by time. The training set goes from the beginning (2004) to about April 27, 2012, the  validation set goes from April 27 to August 7, 2012, and the test set goes from August 7 to December 1, 2012. This more closely mimics real life implementation, where you are training a model on past data to predict future data.
- Changed the sampling procedure for the context length in the validation and test sets, from an inverse distribution to a uniform distribution (between 2 and the max context size). This increases the average context length, which we consider desirable since we would like to model long-term dependencies.
- Changed the tokenization and entity replacement procedure. After complaints stating v1 was too aggressive, we've decided to remove these. It is up to each person using the dataset to come up with their own tokenization/ entity replacement scheme. We plan to use the tokenization internally.
- Added differentiation between the end of an utterance (`__eou__`) and end of turn (`__eot__`). In the original dataset, we concatenated all consecutive utterances by the same user in to one utterance, and put `__EOS__` at the end. Here, we also denote where the original utterances were (with `__eou__`). Also, the terminology should now be consistent between the training and test set (instead of both `__EOS__` and `</s>`).
- Fixed a bug that caused the distribution of false responses in the test and validation sets to be different from the true responses. In particular, the number of words in the false responses was shorter on average than for the true responses, which could have been exploited by some models.

## UBUNTU CORPUS GENERATION FILES:

### generate.sh:
#### DESCRIPTION:
Script that calls `create_ubuntu_dataset.py`. This is the script you should run in order to download the dataset. The parameters passed to this script will be passed to `create_ubuntu_dataset.py`. Example usage: `./generate.sh -t -s -l`.

### create_ubuntu_dataset.py:
#### DESCRIPTION:
Script for generation of train, test and valid datasets from Ubuntu Corpus 1 on 1 dialogs.
The script downloads 1on1 dialogs from internet and then it randomly samples all the datasets with positive and negative examples.
Copyright IBM 2015

#### ARGUMENTS:
- `--data_root`: directory where 1on1 dialogs will downloaded and extracted, the data will be downloaded from [cs.mcgill.ca/~jpineau/datasets/ubuntu-corpus-1.0/ubuntu_dialogs.tgz](http://cs.mcgill.ca/~jpineau/datasets/ubuntu-corpus-1.0/ubuntu_dialogs.tgz) (default = '.')
- `--seed`: seed for random number generator (default = 1234)
- `-o`, `--output`: output file for writing to csv (default = None)
- `-t`, `--tokenize`: tokenize the output (`nltk.word_tokenize`)
- `-s`, `--stem`: stem the output (`nltk.stem.SnowballStemmer`) - applied only when `-t` flag is present
- `-l`, `--lemmatize`: lemmatize the output (`nltk.stem.WorldNetLemmatizer`) - applied only when `-t` flag is present

*Note:* if both `-s` and `-l` are present, the stemmer is applied before the lemmatizer.

#### Subparsers:
`train`: train set generator
- `-p`: positive example probability, ie. the ratio of positive examples to total examples in the training set (default = 0.5)
- `-e`, `--examples`: number of training examples to generate. Note that this will generate slightly fewer examples than desired, as there is a 'post-processing' step that filters  (default = 1000000)

`valid`: validation set generator
- `-n`: number of distractor examples for each context (default = 9)

`test`: test set generator
- `-n`: number of distractor examples for each context (default = 9)

### meta folder: trainfiles.csv, valfiles.csv, testfiles.csv:
#### DESCRIPTION:
Maps the original dialogue files to the training, validation, and test sets.

## UBUNTU CORPUS FILES (after generating):

### train.csv:
Contains the training set. It is separated into 3 columns: the context of the conversation, the candidate response or 'utterance', and a flag or 'label' (= 0 or 1) denoting whether the response is a 'true response' to the context (flag = 1), or a randomly drawn response from elsewhere in the dataset (flag = 0). This triples format is described in the paper. When generated with the default settings, train.csv is 463Mb, with 1,000,000 lines (ie. examples, which corresponds to 449,071 dialogues) and with a vocabulary size of ~~1,344,621~~. Note that, to generate the full dataset, you should use the `--examples` argument for the `create_ubuntu_dataset.py` file.

### valid.csv:
Contains the validation set. Each row represents a question. Separated into 11 columns: the context, the true response or 'ground truth utterance', and 9 false responses or 'distractors' that were randomly sampled from elsewhere in the dataset. Your model gets a question correct if it selects the ground truth utterance from amongst the 10 possible responses. When generated with the default settings, `valid.csv` is 27Mb, with 19,561 lines and a vocabulary size of 115,688.

### test.csv:
Contains the test set. Formatted in the same way as the validation set. When generated with the default settings, test.csv is 27Mb, with 18,921 lines and a vocabulary size of 115,623.

## BASELINE RESULTS

#### Dual Encoder LSTM model:
```
1 in 2:
	recall@1: 0.868730970907
1 in 10:
	recall@1: 0.552213717862
	recall@2: 0.72099120433,
	recall@5: 0.924285351827
```

#### Dual Encoder RNN model:
```
1 in 2:
	recall@1: 0.776539210705,
1 in 10:
	recall@1: 0.379139142954,
	recall@2: 0.560689786585,
	recall@5: 0.836350355691,
```

#### TF-IDF model:
```
1 in 2:
	recall@1:  0.749260042283
1 in 10:
	recall@1:  0.48810782241
	recall@2:  0.587315010571
	recall@5:  0.763054968288
```

## HYPERPARAMETERS USED

Code for the model can be found here (might not be up to date with the new dataset): https://github.com/npow/ubottu

#### Dual Encoder LSTM model:
```
act_penalty=500
batch_size=256
conv_attn=False
corr_penalty=0.0
emb_penalty=0.001
fine_tune_M=True
fine_tune_W=False
forget_gate_bias=2.0
hidden_size=200
is_bidirectional=False
lr=0.001
lr_decay=0.95
max_seqlen=160
n_epochs=100
n_recurrent_layers=1
optimizer='adam'
penalize_activations=False
penalize_emb_drift=False
penalize_emb_norm=False
pv_ndims=100
seed=42
shuffle_batch=False
sort_by_len=False
sqr_norm_lim=1
use_pv=False
xcov_penalty=0.0
```

#### Dual Encoder RNN model:
```
act_penalty=500
batch_size=512
conv_attn=False
corr_penalty=0.0
emb_penalty=0.001
fine_tune_M=False
fine_tune_W=False
forget_gate_bias=2.0
hidden_size=100
is_bidirectional=False
lr=0.0001
lr_decay=0.95
max_seqlen=160
n_epochs=100
n_recurrent_layers=1
optimizer='adam'
penalize_activations=False
penalize_emb_drift=False
penalize_emb_norm=False
pv_ndims=100
seed=42
shuffle_batch=False
sort_by_len=False
sqr_norm_lim=1
use_pv=False
xcov_penalty=0.0
```


text:
<?php

namespace StingerSoft\GaugePresentationBundle\Repository;

use Doctrine\Common\Persistence\ObjectRepository;

interface SlideRepositoryInterface extends ObjectRepository {
}


text: require "sidekiq/job-manager"


text:
import * as ts from 'typescript';

import {NgccReflectionHost} from '../host/ngcc_host';
import {getOriginalSymbol, isDefined} from '../utils';

import {FileParser} from './file_parser';
import {ParsedClass} from './parsed_class';
import {ParsedFile} from './parsed_file';

export class Esm2015FileParser implements FileParser {
  checker = this.program.getTypeChecker();

  constructor(protected program: ts.Program, protected host: NgccReflectionHost) {}

  parseFile(file: ts.SourceFile): ParsedFile[] {
    const moduleSymbol = this.checker.getSymbolAtLocation(file);
    const map = new Map<ts.SourceFile, ParsedFile>();
    if (moduleSymbol) {
      const exportClasses = this.checker.getExportsOfModule(moduleSymbol)
                                .map(getOriginalSymbol(this.checker))
                                .filter(exportSymbol => exportSymbol.flags & ts.SymbolFlags.Class);

      const classDeclarations = exportClasses.map(exportSymbol => exportSymbol.valueDeclaration)
                                    .filter(isDefined)
                                    .filter(ts.isClassDeclaration);

      const decoratedClasses =
          classDeclarations
              .map(declaration => {
                const decorators = this.host.getDecoratorsOfDeclaration(declaration);
                return decorators && declaration.name &&
                    new ParsedClass(declaration.name.text, declaration, decorators);
              })
              .filter(isDefined);

      decoratedClasses.forEach(clazz => {
        const file = clazz.declaration.getSourceFile();
        if (!map.has(file)) {
          map.set(file, new ParsedFile(file));
        }
        map.get(file) !.decoratedClasses.push(clazz);
      });
    }
    return Array.from(map.values());
  }
}