text:
package org.adligo.fabricate_tests.models.common;

import org.adligo.fabricate.models.common.I_AttributesOverlay;
import org.adligo.tests4j.system.shared.trials.SourceFileScope;
import org.adligo.tests4j_4mockito.MockitoSourceFileTrial;

@SourceFileScope (sourceClass=I_AttributesOverlay.class)
public class I_AttributesOverlayTrial extends MockitoSourceFileTrial {

}


text:
<ion-view view-title="Contents">
  <ion-content>
    <ion-refresher
      pulling-text="Pull to refresh..."
      on-refresh="doRefresh()">
    </ion-refresher>
    <ion-list>

          {{ content.title }}

{{ content.description }}

            g/{{ content.group.name }}
            u/{{ content.user.name }}

            {{ content.uv }}

            {{ content.dv }}

            {{ content.comments_count }}

    </ion-list>
  </ion-content>
</ion-view>

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<metadata>
  <groupId>com.ridemetric</groupId>
  <artifactId>motionmetric</artifactId>
  <version>1.3.2</version>
  <versioning>
    <versions>
      <version>1.3.2</version>
    </versions>
    <lastUpdated>20150925033647</lastUpdated>
  </versioning>
</metadata>


text:
/* Task Description */
/*
* Create an object domElement, that has the following properties and methods:
  * use prototypal inheritance, without function constructors
  * method init() that gets the domElement type
    * i.e. `Object.create(domElement).init('div')`
  * property type that is the type of the domElement
    * a valid type is any non-empty string that contains only Latin letters and digits
  * property innerHTML of type string
    * gets the domElement, parsed as valid HTML
      * <type attr1="value1" attr2="value2" ...> .. content / children's.innerHTML .. </type>
  * property content of type string
    * sets the content of the element
    * works only if there are no children
  * property attributes
    * each attribute has name and value
    * a valid attribute has a non-empty string for a name that contains only Latin letters and digits or dashes (-)
  * property children
    * each child is a domElement or a string
  * property parent
    * parent is a domElement
  * method appendChild(domElement / string)
    * appends to the end of children list
  * method addAttribute(name, value)
    * throw Error if type is not valid
  * method removeAttribute(attribute)
    * throw Error if attribute does not exist in the domElement
*/

/* Example

var meta = Object.create(domElement)
    .init('meta')
    .addAttribute('charset', 'utf-8');

var head = Object.create(domElement)
    .init('head')
    .appendChild(meta)

var div = Object.create(domElement)
    .init('div')
    .addAttribute('style', 'font-size: 42px');

div.content = 'Hello, world!';

var body = Object.create(domElement)
    .init('body')
    .appendChild(div)
    .addAttribute('id', 'cuki')
    .addAttribute('bgcolor', '#012345');

var root = Object.create(domElement)
    .init('html')
    .appendChild(head)
    .appendChild(body);

console.log(root.innerHTML);
Outputs:
<meta charset="utf-8"></meta>

Hello, world!

*/

function solve() {
    'use strict';
    var domElement = (function () {
        var domElement = {
            init: function (type) {
                if (type === undefined || type === '' || typeof type !== 'string' ||
                        /^[a-zA-Z0-9_]+(,[a-zA-Z0-9_]+)*$/.test(type) === false) {
                    throw new Error();
                }
                this.type = type;
                this.content = '';
                this.attibutes = [];
                this.children = [];
                this.parent = {};
                return this;
            },

            appendChild: function (child) {
                if (typeof child === 'string') {
                    var newObj = Object.create(domElement).init('emptyElement');
                    newObj.content = child;
                    this.children.push(newObj);
                } else {
                    child.parent = this;
                    this.children.push(child);
                }

                return this;
            },

            addAttribute: function (name, value) {
                if (name === undefined || /^[a-zA-Z0-9\-]+(,[a-zA-Z0-9\-]+)*$/.test(name) === false) {
                    throw new Error();
                }

                this.attibutes[name] = value;
                return this;
            },

            removeAttribute: function (name) {
                if (this.attibutes[name] === undefined) {
                    throw new Error();
                }

                delete this.attibutes[name];
                return this;
            },

            get innerHTML() {
                var output = '',
                    i,
                    len,
                    keys = Object.keys(this.attibutes);

                if (this.type !== 'emptyElement') {
                    output += '<' + this.type;
                    keys.sort();
                    for (i = 0, len = keys.length; i < len; i += 1) {
                        output += ' ' + keys[i] + '="' + this.attibutes[keys[i]] + '"';
                    }

                    output += '>';
                    len = this.children.length;

                    if (len === 0) {
                        output += this.content;
                    } else {
                        for (i = 0; i < len; i += 1) {
                            output += this.children[i].innerHTML;
                        }
                    }

                    output += '</' + this.type + '>';
                } else {
                    output = this.content;
                }

                return output;
            }
        }

        return domElement;
    } ());
    return domElement;
}

module.exports = solve;


text:
    <select class="normal">
      <option value="" disabled>Choose your option</option>
      <option value="1">Option 1</option>
      <option value="2">Option 2</option>
      <option value="3" selected>Option 3</option>
    </select>
    Materialize Select

    <select multiple class="multiple">
      <option value="" disabled>Choose your option</option>
      <option value="1">Option 1</option>
      <option value="2" selected>Option 2</option>
      <option value="3" selected>Option 3</option>
    </select>
    Materialize Select

    <select class="optgroup">
      <optgroup label="team 1">
        <option value="1">Option 1</option>
        <option value="2">Option 2</option>
      </optgroup>
      <optgroup label="team 2">
        <option value="3">Option 3</option>
        <option value="4">Option 4</option>
      </optgroup>
    </select>
    Materialize Select


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.nervepoint</groupId>
	<artifactId>google-translate-v2-java-maven-plugin</artifactId>
	<version>0.0.5-SNAPSHOT</version>
	<url>http://www.nervepoint.com/</url>
	<packaging>maven-plugin</packaging>

	<name>Google Translate V2 Maven Plugin</name>
	<description>A Maven plugin that provides translation of i18n resources using Google Translate V2 API</description>

	<parent>
		<groupId>org.sonatype.oss</groupId>
		<artifactId>oss-parent</artifactId>
		<version>7</version>
	</parent>

	<distributionManagement>
		<repository>
			<id>opensource-releases</id>
			<url>https://artifactory.jadaptive.com/opensource-releases</url>
		</repository>
		<snapshotRepository>
			<id>opensource-snapshots</id>
			<url>https://artifactory.jadaptive.com/opensource-snapshots</url>
		</snapshotRepository>
	</distributionManagement>

	<licenses>
		<license>
			<name>Apache License, Version 2.0</name>
			<url>http://www.apache.org/licenses/LICENSE-2.0.html</url>
			<distribution>repo</distribution>
		</license>
	</licenses>

	<scm>
		<url>http://github.com/ludup/google-translate-v2-java-maven-plugin</url>
		<connection>scm:git:https://github.com/ludup/google-translate-v2-java-maven-plugin</connection>
		<developerConnection>scm:git:https://github.com/ludup/google-translate-v2-java-maven-plugin</developerConnection>
	</scm>

	<developers>
		<developer>
			<id>lee</id>
			<name>Lee David Painter</name>
			<email>lee@nervepoint.com</email>
		</developer>
	</developers>

	<dependencies>
		<dependency>
			<groupId>org.apache.maven</groupId>
			<artifactId>maven-plugin-api</artifactId>
			<version>3.3.9</version>
		</dependency>
		<dependency>
			<groupId>org.apache.maven.plugin-tools</groupId>
			<artifactId>maven-plugin-annotations</artifactId>
			<version>3.5</version>
		</dependency>
		<dependency>
			<groupId>org.apache.maven</groupId>
			<artifactId>maven-project</artifactId>
			<version>2.2.1</version>
		</dependency>
		<dependency>
			<groupId>com.google.apis</groupId>
			<artifactId>google-api-services-translate</artifactId>
			<version>v2-rev27-1.17.0-rc</version>
		</dependency>
		<dependency>
			<groupId>com.google.http-client</groupId>
			<artifactId>google-http-client-jackson2</artifactId>
			<version>1.17.0-rc</version>
		</dependency>
		<dependency>
			<groupId>commons-codec</groupId>
			<artifactId>commons-codec</artifactId>
			<version>1.4</version>
		</dependency>
		<dependency>
			<groupId>commons-logging</groupId>
			<artifactId>commons-logging</artifactId>
			<version>1.1.1</version>
		</dependency>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
			<version>3.0.1</version>
		</dependency>
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<version>4.1.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient-cache</artifactId>
			<version>4.1.2</version>
		</dependency>
		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-core-asl</artifactId>
			<version>1.9.0</version>
		</dependency>
		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-jaxrs</artifactId>
			<version>1.9.0</version>
		</dependency>
		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-mapper-asl</artifactId>
			<version>1.9.0</version>
		</dependency>
		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-xc</artifactId>
			<version>1.9.0</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>1.6.2</version>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.7</version>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<profiles>
		<profile>
			<id>release-sign-artifacts</id>
			<activation>
				<property>
					<name>performRelease</name>
					<value>true</value>
				</property>
			</activation>
			<build>
				<plugins>
					<plugin>
						<groupId>org.apache.maven.plugins</groupId>
						<artifactId>maven-gpg-plugin</artifactId>
						<version>1.1</version>
						<executions>
							<execution>
								<id>sign-artifacts</id>
								<phase>verify</phase>
								<goals>
									<goal>sign</goal>
								</goals>
							</execution>
						</executions>
					</plugin>
				</plugins>
			</build>
		</profile>
		<profile>
			<activation>
				<jdk>[9,)</jdk>
			</activation>
			<build>
				<pluginManagement>
					<plugins>
						<plugin>
							<groupId>org.apache.maven.plugins</groupId>
							<artifactId>maven-javadoc-plugin</artifactId>
							<configuration>
								<!-- TODO: Why is this STILL broken! -->
								<javadocExecutable>${java.home}/bin/javadoc</javadocExecutable>
							</configuration>
						</plugin>
					</plugins>
				</pluginManagement>
			</build>
		</profile>
	</profiles>

	<build>
		<pluginManagement>

			<plugins>
				<plugin>
					<groupId>org.apache.maven.plugins</groupId>
					<artifactId>maven-javadoc-plugin</artifactId>
					<version>3.2.0</version>
					<configuration>
						<encoding>UTF-8</encoding>
						<excludePackageNames>**.impl.*</excludePackageNames>

						<!-- https://bugs.openjdk.java.net/browse/JDK-8212233 -->
						<source>8</source>
						<additionalparam>-Xdoclint:none</additionalparam>
					</configuration>
				</plugin>
			</plugins>
		</pluginManagement>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-plugin-plugin</artifactId>
				<version>3.5</version>
				<executions>
					<execution>
						<id>default-descriptor</id>
						<phase>process-classes</phase>
					</execution>
					<!-- if you want to generate help goal -->
					<execution>
						<id>help-goal</id>
						<goals>
							<goal>helpmojo</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.3.2</version>
				<configuration>
					<source>1.6</source>
					<target>1.6</target>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-source-plugin</artifactId>
				<executions>
					<execution>
						<id>attach-sources</id>
						<goals>
							<goal>jar</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-javadoc-plugin</artifactId>
				<executions>
					<execution>
						<id>attach-javadocs</id>
						<goals>
							<goal>jar</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-release-plugin</artifactId>
				<executions>
					<execution>
						<id>default</id>
						<goals>
							<goal>perform</goal>
						</goals>
						<configuration>
							<pomFileName>google-translate-v2-java-maven-plugin/pom.xml</pomFileName>
						</configuration>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>
</project>


text:
<?php

namespace PHPExiftool\Driver\Tag\CanonCustom;

use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;

/**
 * @ExclusionPolicy("all")
 */
class PF23ShutterButtonTime extends AbstractTag
{

    protected $Id = 12;

    protected $Name = 'PF23ShutterButtonTime';

    protected $FullName = 'CanonCustom::PersonalFuncValues';

    protected $GroupName = 'CanonCustom';

    protected $g0 = 'MakerNotes';

    protected $g1 = 'CanonCustom';

    protected $g2 = 'Camera';

    protected $Type = 'int16u';

    protected $Writable = true;

    protected $Description = 'PF23 Shutter Button Time';

    protected $flag_Permanent = true;

}


text:
import mock

from cinder import context
from cinder import exception
from cinder import test
from cinder.tests.unit import fake_snapshot
from cinder.tests.unit import fake_volume
from cinder.volume import configuration as conf
from cinder.volume.drivers.veritas import vrtshyperscale as vrts

class FakeDb(object):
    def volume_metadata_get(self, *a, **kw):
        return {}

    def volume_metadata_update(self, *a, **kw):
        return None

def _stub_volume(*args, **kwargs):
    updates = {'provider_location': 'hyperscale-sv:/hyperscale'}
    return fake_volume.fake_db_volume(**updates)

def _stub_snapshot(*args, **kwargs):
    updates = {'volume': _stub_volume(), 'name': 'vrts'}
    return fake_snapshot.fake_db_snapshot(**updates)

def _stub_stats():
    data = {}
    data["volume_backend_name"] = 'Veritas_HyperScale'
    data["vendor_name"] = 'Veritas Technologies LLC'
    data["driver_version"] = '1.0'
    data["storage_protocol"] = 'nfs'
    data['total_capacity_gb'] = 0.0
    data['free_capacity_gb'] = 0.0
    data['reserved_percentage'] = 0
    data['QoS_support'] = False
    return data

class VRTSHyperScaleDriverTestCase(test.TestCase):
    """Test case for Veritas HyperScale VolumeDriver."""

    driver_name = "cinder.volume.drivers.veritas.vrtshyperscale"

    @staticmethod
    def gvmv_side_effect(arg1, arg2):
        """Mock side effect for _get_volume_metadata_value."""
        # mock the return of get_volume_metadata_value
        # for different arguments
        if arg2 == 'Secondary_datanode_key':
            return '{9876}'
        elif arg2 == 'Secondary_datanode_ip':
            return '192.0.2.2'
        elif arg2 == 'current_dn_ip':
            return '192.0.2.1'
        elif arg2 == 'vsa_ip':
            return '192.0.2.1'

    @mock.patch('cinder.volume.drivers.veritas.vrtshyperscale.HyperScaleDriver'
                '._fetch_config_for_compute')
    @mock.patch('cinder.volume.drivers.veritas.vrtshyperscale.HyperScaleDriver'
                '._fetch_config_for_datanode')
    @mock.patch('cinder.volume.drivers.veritas.vrtshyperscale.HyperScaleDriver'
                '._fetch_config_for_controller')
    def setUp(self, mock_fcfcntr, mock_fcfd, mock_fcfc):
        mock_fcfcntr.return_value = None
        mock_fcfd.return_value = None
        mock_fcfc.return_value = None

        # Initialise a test seup
        super(VRTSHyperScaleDriverTestCase, self).setUp()

        self.configuration = mock.Mock(conf.Configuration(None))
        self.configuration.reserved_percentage = 0
        self.context = context.get_admin_context()
        self.driver = vrts.HyperScaleDriver(
            db=FakeDb(), configuration=self.configuration)
        self.driver.dn_routing_key = '{1234}'
        self.driver.datanode_ip = '192.0.2.1'
        self.volume = _stub_volume()
        self.snapshot = _stub_snapshot()

    @mock.patch('cinder.volume.drivers.veritas.vrtshyperscale.HyperScaleDriver'
                '._get_volume_metadata')
    @mock.patch('cinder.volume.drivers.veritas.vrtshyperscale.HyperScaleDriver'
                '._get_replicas')
    @mock.patch('cinder.volume.drivers.veritas.vrtshyperscale.HyperScaleDriver'
                '._get_volume_details_for_create_volume')
    @mock.patch('cinder.volume.drivers.veritas.utils'
                '.message_data_plane')
    @mock.patch('cinder.volume.api.API.update_volume_metadata')
    def test_create_volume_single_replicas(self, mock_uvm, mock_mdp,
                                           mock_gvdfcv, mock_get_replicas,
                                           mock_gvm):
        """Test single volume replica. Happy path test case."""
        # Mock volume meatadata
        mock_gvm.return_value = _stub_volume()

        # Mock number of replicas to 1
        mock_get_replicas.return_value = 1
        # assume volume details are populated correctly
        mock_gvdfcv.return_value = _stub_volume()

        # assume volume message is sent to data node successfully
        mock_mdp.return_value = ("", None)
        # assume that the volume metadata gets updated correctly
        mock_uvm.return_value = {}

        # declare the expected result
        expected_result = {
            'provider_location': 'hyperscale-sv:/hyperscale',
            'metadata': mock_gvm.return_value
        }

        # call create volume and get the result
        actual_result = self.driver.create_volume(self.volume)

        # Test if the return value matched the expected results
        self.assertDictEqual(actual_result, expected_result)

    @mock.patch('cinder.volume.drivers.veritas.utils'
                '.get_hyperscale_version')
    def test_check_for_setup_error(self, mock_ghv):
        """Test check for setup errors in Veritas HyperScale driver.

        The test case checks happy path execution when driver version 1.0.0
        is installed.
        """
        mock_ghv.return_value = "1.0.0"

        # check the driver for setup errors
        self.driver.check_for_setup_error()

    @mock.patch('cinder.volume.drivers.veritas.utils'
                '.get_hyperscale_version')
    def test_check_for_setup_error_unsupported_version(self, mock_ghv):
        """Test check for setup errors in Veritas HyperScale driver.

        The test case checks happy path execution when driver version 1.0.0
        is installed.
        """
        mock_ghv.return_value = "1.0.0.1"

        # check the driver for setup errors
        self.assertRaises(exception.VolumeBackendAPIException,
                          self.driver.check_for_setup_error)

    @mock.patch('cinder.volume.drivers.veritas.utils'
                '.get_hyperscale_version')
    def test_check_for_setup_error_exception(self, mock_ghv):
        """Test check for setup errors in Veritas HyperScale driver.

        The test case checks happy path execution when driver version 1.0.0
        is installed.
        """
        mock_ghv.side_effect = exception.ErrorInHyperScaleVersion(
            cmd_error="mock error")

        # check the driver for setup errors
        self.assertRaises(exception.VolumeBackendAPIException,
                          self.driver.check_for_setup_error)

    @mock.patch('cinder.volume.drivers.veritas.vrtshyperscale.HyperScaleDriver'
                '._get_volume_metadata_value')
    @mock.patch('cinder.volume.drivers.veritas.utils'
                '.message_data_plane')
    def test_delete_volume_no_replica(self, mock_mdp, mock_gvmv):
        """Test happy path for delete_volume one data nodes."""
        mock_gvmv.return_value = None
        self.driver.delete_volume(self.volume)

        message_body = {'display_name': self.volume['name']}

        mock_mdp.assert_called_with(self.driver.dn_routing_key,
                                    'hyperscale.storage.dm.volume.delete',
                                    **message_body)

    @mock.patch('cinder.volume.drivers.veritas.vrtshyperscale.HyperScaleDriver'
                '._get_volume_metadata_value')
    @mock.patch('cinder.volume.drivers.veritas.utils'
                '.message_data_plane')
    def test_delete_volume_more_than_one_replica(self, mock_mdp, mock_gvmv):
        """Test happy path for delete_volume with more than one data nodes."""
        mock_gvmv.side_effect = VRTSHyperScaleDriverTestCase.gvmv_side_effect

        message_body = {'display_name': self.volume['name']}

        # make the delete call
        self.driver.delete_volume(self.volume)

        # check if delete volume sent to reflection target on data node
        # check if mq message sent with 'Secondary_datanode_key'
        mock_mdp.assert_any_call(
            '{9876}', 'hyperscale.storage.dm.volume.delete', **message_body)

        # check if the delete is sent to primary data node as well
        mock_mdp.assert_any_call(self.driver.dn_routing_key,
                                 'hyperscale.storage.dm.volume.delete',
                                 **message_body)

    @mock.patch('cinder.volume.drivers.veritas.vrtshyperscale.HyperScaleDriver'
                '._get_volume_metadata_value')
    @mock.patch('cinder.volume.drivers.veritas.utils'
                '.message_data_plane')
    def test_delete_volume_no_replica_failure(self, mock_mdp, mock_gvmv):
        """Failure case for delete_volume one node in data plane."""
        mock_gvmv.side_effect = None
        self.driver.delete_volume(self.volume)
        mock_mdp.side_effect = exception.UnableToProcessHyperScaleCmdOutput(
            cmd_out='mock error')
        self.assertRaises(exception.VolumeIsBusy, self.driver.delete_volume,
                          self.volume)

    @mock.patch('cinder.volume.drivers.veritas.vrtshyperscale.HyperScaleDriver'
                '._get_volume_metadata_value')
    @mock.patch('cinder.volume.drivers.veritas.utils'
                '.message_data_plane')
    def test_delete_volume_more_than_one_replica_failure(self, mock_mdp,
                                                         mock_gvmv):
        """failure case for delete_volume with more than one data nodes."""
        mock_gvmv.side_effect = VRTSHyperScaleDriverTestCase.gvmv_side_effect

        mock_mdp.side_effect = exception.UnableToProcessHyperScaleCmdOutput(
            cmd_out='mock error')

        self.assertRaises(exception.VolumeIsBusy, self.driver.delete_volume,
                          self.volume)

    @mock.patch('cinder.volume.drivers.veritas.utils'
                '.get_guid_with_curly_brackets')
    def test_delete_snapshot_force_flag(self, mock_ggwcb):
        """Test snapshot deletion does not happen if force flag is set."""
        # get a mock snapshot object
        snapshot = fake_snapshot.fake_db_snapshot()
        # set the force in metadata of snapshot
        snapshot['metadata'] = {"force": "force"}

        # call the delete volume
        self.driver.delete_snapshot(snapshot)

        # if snapshot has force set in metadata then
        # get_guid_with_curly_brackets() will not be called because we
        # return as soon as we see force
        mock_ggwcb.assert_not_called()

    def test_delete_snapshot_isbusy_flag(self):
        """Test snapshot deletion throws exception if snapshot is busy."""
        # get a mock snapshot object
        snapshot = fake_snapshot.fake_db_snapshot()
        # set the force in metadata of snapshot
        snapshot['metadata'] = {"is_busy": "is_busy"}

        # call the delete volume to check if it raises Busy Exception
        self.assertRaises(exception.SnapshotIsBusy,
                          self.driver.delete_snapshot, snapshot)

    @mock.patch('cinder.volume.drivers.veritas.vrtshyperscale.HyperScaleDriver'
                '._get_volume_metadata')
    @mock.patch('cinder.volume.api.API.get_volume')
    @mock.patch('cinder.volume.drivers.veritas.utils'
                '.message_data_plane')
    def test_delete_snapshot_from_primary_dn(self, mock_mdp, mock_gv,
                                             mock_gvm):
        """Test snapshot deletion from primary DN."""
        # get mock volume
        mock_gv.return_value = None
        mock_gvm.return_value = {'current_dn_ip': self.driver.datanode_ip}

        message_body = {}
        message_body['volume_guid'] = '{' + self.volume['id'] + '}'
        message_body['snapshot_id'] = '{' + self.snapshot['id'] + '}'

        # call delete snapshot
        self.driver.delete_snapshot(self.snapshot)

        # assert msg is sent over mq with primary DN routing key
        mock_mdp.assert_called_with(self.driver.dn_routing_key,
                                    'hyperscale.storage.dm.version.delete',
                                    **message_body)

    @mock.patch('cinder.volume.drivers.veritas.vrtshyperscale.HyperScaleDriver'
                '._get_volume_metadata')
    @mock.patch('cinder.volume.api.API.get_volume')
    @mock.patch('cinder.volume.drivers.veritas.utils'
                '.message_data_plane')
    @mock.patch('cinder.volume.drivers.veritas.vrtshyperscale.HyperScaleDriver'
                '._get_volume_metadata_value')
    def test_delete_snapshot_from_current_dn(self, mock_gvmv, mock_mdp,
                                             mock_gv, mock_gvm):
        """Test snapshot deletion DN value from volume."""
        # get a mock volume
        mock_gv.return_value = _stub_volume()

        # get a mock value of DN from volume
        mock_gvmv.return_value = '{9876}'

        message_body = {}
        message_body['volume_guid'] = '{' + self.volume['id'] + '}'
        message_body['snapshot_id'] = '{' + self.snapshot['id'] + '}'

        # call delete snapshot
        self.driver.delete_snapshot(self.snapshot)

        # assert msg is sent over mq with key from volume's current_dn_owner
        mock_mdp.assert_called_with(
            '{9876}', 'hyperscale.storage.dm.version.delete', **message_body)

    @mock.patch('cinder.volume.drivers.veritas.utils'
                '.message_data_plane')
    def test_fetch_volume_stats_failure(self, mock_mdp):
        """Test case checking failure of pool for fetching stats."""
        # since we have initialised the pool to None in setup()
        # the function will return only the stub without populating
        # any free and used stats
        mock_obj = {'payload': {}}

        mock_mdp.return_value = (mock_obj, None)
        self.assertDictEqual(_stub_stats(), self.driver._fetch_volume_status())

    @mock.patch('cinder.volume.drivers.veritas.utils'
                '.message_data_plane')
    def test_create_cloned_volume_with_exception(self, mock_mdp):
        """Test case throws exception when command failed to execute."""
        vol_a = _stub_volume()
        vol_b = _stub_volume()
        mock_mdp.side_effect = exception.UnableToExecuteHyperScaleCmd(
            cmd_out='mock error')
        self.assertRaises(exception.UnableToExecuteHyperScaleCmd,
                          self.driver.create_cloned_volume, vol_b, vol_a)

    @mock.patch('cinder.volume.drivers.veritas.utils'
                '.message_data_plane')
    @mock.patch('cinder.volume.drivers.veritas.vrtshyperscale'
                '.HyperScaleDriver._select_rt')
    def test_create_cloned_volume_with_no_replica(self, mock_srt, mock_mdp):
        """Test case clone volume when there is no replica."""
        mock_obj = {'payload': {}}
        mock_mdp.return_value = (mock_obj, None)
        mock_srt.return_value = (None, None)
        vol_a = _stub_volume()
        vol_b = _stub_volume()
        self.assertDictContainsSubset({
            'provider_location': 'hyperscale-sv:/hyperscale'
        }, self.driver.create_cloned_volume(vol_b, vol_a))

    @mock.patch('cinder.volume.drivers.veritas.utils'
                '.message_data_plane')
    @mock.patch('cinder.volume.drivers.veritas.vrtshyperscale'
                '.HyperScaleDriver._select_rt')
    @mock.patch('cinder.volume.drivers.veritas.vrtshyperscale.HyperScaleDriver'
                '._get_volume_metadata_value')
    def test_create_cloned_volume_with_replica(self, mock_gvmv, mock_srt,
                                               mock_mdp):
        """Test case clone volume when there is replica."""
        mock_gvmv.side_effect = VRTSHyperScaleDriverTestCase.gvmv_side_effect
        mock_obj = {'payload': {}}
        mock_mdp.return_value = (mock_obj, None)
        mock_srt.return_value = ('{1234}', '192.0.2.2')
        vol_a = _stub_volume()
        vol_b = _stub_volume()
        metadata = {
            'current_dn_owner': '{1234}',
            'Potential_secondary_key': '{1234}',
            'Primary_datanode_ip': '192.0.2.1',
            'Potential_secondary_ip': '192.0.2.2',
            'current_dn_ip': '192.0.2.1',
            'source_volid': vol_a['id'],
            'size': vol_a['size']
        }
        self.assertDictContainsSubset({
            'provider_location': 'hyperscale-sv:/hyperscale',
            'metadata': metadata
        }, self.driver.create_cloned_volume(vol_b, vol_a))

    @mock.patch('cinder.volume.drivers.veritas.utils'
                '.message_data_plane')
    def test_extend_volume_with_exception(self, mock_mdp):
        """Test case extend volume to the given size in GB."""
        mock_mdp.side_effect = exception.UnableToProcessHyperScaleCmdOutput(
            cmd_out='mock error')
        self.assertRaises(exception.VolumeDriverException,
                          self.driver.extend_volume, _stub_volume(), 256)

    @mock.patch('cinder.volume.drivers.veritas.utils'
                '.message_data_plane')
    def test_extend_volume_no_exception(self, mock_mdp):
        """Test case extend volume thorws exception."""
        mock_mdp.return_value = (None, None)
        self.driver.extend_volume(_stub_volume(), 256)

    @mock.patch('cinder.volume.drivers.veritas.utils'
                '.message_data_plane')
    def test_create_volume_from_snapshot_with_exception(self, mock_mdp):
        """Test case create volume from snapshot thorws exception."""
        fake_volume, fake_snapshot = _stub_volume(), _stub_snapshot()
        mock_mdp.side_effect = exception.UnableToExecuteHyperScaleCmd(
            cmd_out='mock error')
        self.assertRaises(exception.UnableToExecuteHyperScaleCmd,
                          self.driver.create_volume_from_snapshot, fake_volume,
                          fake_snapshot)

    @mock.patch('cinder.volume.drivers.veritas.utils'
                '.message_data_plane')
    @mock.patch('cinder.volume.drivers.veritas.vrtshyperscale'
                '.HyperScaleDriver._select_rt')
    def test_create_volume_from_snapshot_with_no_replica(self, mock_srt,
                                                         mock_mdp):
        """Test case create volume from snapshot when there is no replica."""
        mock_obj = {'payload': {}}
        mock_mdp.return_value = (mock_obj, None)
        mock_srt.return_value = (None, None)
        fake_volume, fake_snapshot = _stub_volume(), _stub_snapshot()
        self.assertDictContainsSubset({
            'provider_location': 'hyperscale-sv:/hyperscale'
        }, self.driver.create_volume_from_snapshot(fake_volume, fake_snapshot))

    @mock.patch('cinder.volume.drivers.veritas.utils'
                '.message_data_plane')
    @mock.patch('cinder.volume.drivers.veritas.vrtshyperscale'
                '.HyperScaleDriver._select_rt')
    @mock.patch('cinder.volume.drivers.veritas.vrtshyperscale.HyperScaleDriver'
                '._get_volume_metadata_value')
    def test_create_volume_from_snapshot_with_replica(self, mock_gvmv,
                                                      mock_srt, mock_mdp):
        """Test case create volume from snapshot when there is replica."""
        mock_gvmv.side_effect = VRTSHyperScaleDriverTestCase.gvmv_side_effect
        mock_obj = {'payload': {}}
        mock_mdp.return_value = (mock_obj, None)
        mock_srt.return_value = ('{1234}', '192.0.2.2')
        fake_volume, fake_snapshot = _stub_volume(), _stub_snapshot()
        metadata = {
            'current_dn_owner': '{1234}',
            'Potential_secondary_key': '{1234}',
            'Primary_datanode_ip': '192.0.2.1',
            'Potential_secondary_ip': '192.0.2.2',
            'current_dn_ip': '192.0.2.1',
            'snapshot_id': fake_snapshot['id'],
            'parent_volume_guid': '{' + fake_snapshot['volume']['id'] + '}'
        }
        self.assertDictContainsSubset({
            'provider_location': 'hyperscale-sv:/hyperscale',
            'metadata': metadata
        }, self.driver.create_volume_from_snapshot(fake_volume, fake_snapshot))

    def test_initialize_connection(self):
        """Test case intialize_connection."""
        fake_volume = _stub_volume()
        expected_data = {
            'driver_volume_type': 'veritas_hyperscale',
            'data': {
                'export': fake_volume['provider_location'],
                'name': fake_volume['name']
            }
        }
        self.assertEqual(expected_data,
                         self.driver.initialize_connection(fake_volume, None))

    @mock.patch('cinder.volume.drivers.veritas.utils'
                '.message_compute_plane')
    @mock.patch('cinder.volume.drivers.veritas.utils'
                '.episodic_snap')
    @mock.patch('cinder.volume.drivers.veritas.vrtshyperscale.HyperScaleDriver'
                '._get_volume_metadata_value')
    def test_create_snapshot_with_exception(
            self, mock_gvmv, mock_es, mock_mcp):
        """Test case create snapshot throws exception."""
        mock_gvmv.side_effect = VRTSHyperScaleDriverTestCase.gvmv_side_effect
        mock_es_obj = {'payload': {'update': False}}
        mock_es.return_value = mock_es_obj
        mock_mcp.side_effect = exception.UnableToExecuteHyperScaleCmd(
            cmd_out='mock error')
        fake_snapshot = _stub_snapshot()
        self.assertRaises(exception.UnableToExecuteHyperScaleCmd,
                          self.driver.create_snapshot, fake_snapshot)

    @mock.patch('cinder.volume.drivers.veritas.utils'
                '.message_controller')
    @mock.patch('cinder.volume.drivers.veritas.utils'
                '.message_data_plane')
    @mock.patch('cinder.volume.drivers.veritas.utils'
                '.episodic_snap')
    @mock.patch('cinder.volume.drivers.veritas.vrtshyperscale.HyperScaleDriver'
                '._get_volume_metadata_value')
    @mock.patch('cinder.volume.drivers.veritas.utils'
                '.message_compute_plane')
    def test_create_snapshot_user(
            self, mock_cdp, mock_gvmv, mock_es, mock_mdp, mock_mc):
        """Test case user snapshot."""
        mock_gvmv.side_effect = VRTSHyperScaleDriverTestCase.gvmv_side_effect
        mock_es_obj = {'payload': {'update': False}}
        mock_es.return_value = mock_es_obj
        mock_obj = {'payload': {}}
        mock_mdp.return_value = ("", None)
        mock_mc.return_value = ("", None)
        mock_cdp.return_value = (mock_obj, None)
        fake_snapshot = _stub_snapshot()
        expected = {
            'metadata': {
                'status': 'creating',
                'datanode_ip': '192.0.2.1',
                'TYPE': vrts.TYPE_USER_SNAP
            }
        }
        self.assertEqual(expected, self.driver.create_snapshot(fake_snapshot))


text:
ACCEPTED

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

#### Published in
null

#### Original name
Memecylon danguyanum H. Perrier

### Remarks
null


text:
@import WatchConnectivity;

@interface WatchConnectivity () <WCSessionDelegate>

@end

@implementation WatchConnectivity

#pragma mark - Public

+ (instancetype)sharedInstance {
    static WatchConnectivity *sharedInstance;
    static dispatch_once_t token;
    dispatch_once(&token, ^{
        sharedInstance = [WatchConnectivity new];
    });

    return sharedInstance;
}

- (void)setup {
    WCSession *session = [WCSession defaultSession];
    session.delegate = self;
    [session activateSession];
}

- (void)updateApplicationContext:(NSDictionary *)context {
    WCSession *session = [WCSession defaultSession];
    @try {
        NSError *error = nil;
        [session updateApplicationContext:context error:&error];

    } @catch (NSException *exception) {
        //handle error
    }
}

- (NSDictionary *)receivedApplicationContext {
    WCSession *session = [WCSession defaultSession];
    return session.receivedApplicationContext;
}

#pragma mark - <WCSessionDelegate>

- (void)sessionWatchStateDidChange:(WCSession *)session {
    //handle session state
}

@end


text:
from test_support import *

print 'Subclassing Java from Python (test_jsubclass.py)'

from java.lang import Runnable, Thread

# Overriding Methods

print 'override methods'
class MyThread(Thread):
        count = 0
        def run(self):
                self.count = self.count+1

t1 = MyThread()
t1.start()
t1.join()
assert t1.count == 1, 'subclassing java.lang.Thread'

print 'pass subclass back to java'

class MyRun(Runnable):
        count = 0
        def run(self):
                self.count = self.count+1

run = MyRun()
t = Thread(run)
t.start()
t.join()
assert run.count == 1, 'subclassing java.lang.Thread'

print "invoke super's constructor"

class MyThread(Thread):
        def __init__(self):
                self.name = "Python-"+self.name

t = MyThread()
assert t.name[:14] == "Python-Thread-", 'automatic constructor call'

class MyThread(Thread):
        def __init__(self):
                Thread.__init__(self, "Python-Thread")

t = MyThread()
assert t.name == "Python-Thread", 'explicit constructor call'


text:
function test_behat() {
  local BEHAT_BIN="${1}/behat";

  if [ -x "${BEHAT_BIN}" ]; then
    echo 'Running behat...';
    eval "${BEHAT_BIN} --stop-on-failure" || exit 1;
  fi;
}

# Run codecept suites
function test_codecept() {
  local CODECEPT_BIN="${1}/codecept";

  if [ -x "${CODECEPT_BIN}" ]; then
    echo 'Running codecept...';
    eval "${CODECEPT_BIN} run" || exit 1;
  fi;
}
# Run phpspec suites
function test_phpspec() {
  local PHPSPEC_BIN="${1}/phpspec";

  if [ -x "${PHPSPEC_BIN}" ]; then
    echo 'Running phpspec...';
    eval "${PHPSPEC_BIN} run --no-code-generation --format pretty --stop-on-failure" || exit 1;
  fi;
}

# Analyse code against agreed rulesets
function test_phpcs() {
  local PHPCS_BIN="${1}/phpcs";
  local SRC_DIR="${2}";

  if [ -x "${PHPCS_BIN}" ]; then
    echo 'Running CodeSniffer...';
    eval "${PHPCS_BIN} --extensions=php -q ${SRC_DIR}" || exit 1;
  fi;
}

# Check code for smells and complexity
function test_phpmd() {
  local PHPMD_BIN="${1}/phpmd";
  local SRC_DIR="${2}";

  if [ -x "${PHPMD_BIN}" ]; then
    echo 'Running Mess Detector...';
    eval "${PHPMD_BIN} ${SRC_DIR} text phpmd.xml" || exit 1;
  fi;
}
# Update composer
function test_composer_update() {
  composer update \
  --prefer-dist \
  --optimize-autoloader \
  --no-suggest;
}

# Run all local automated code checks
function test_all() {
  local SRC_DIR="${PWD}/src";
  local BIN_DIR="${PWD}/bin";
  clear;

  echo 'Validating composer...';
  composer validate || exit 1;

  test_composer_update;
  test_phpspec  "${BIN_DIR}";
  test_phpcs    "${BIN_DIR}" "${SRC_DIR}";
  test_phpmd    "${BIN_DIR}" "${SRC_DIR}";
  test_behat    "${BIN_DIR}";
  test_codecept "${BIN_DIR}";

}

test_all;


text:
package com.toluene.commonbatis;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.toluene.commonbatis.criterion.Criterion;

public class Criteria {

    private List<Criterion> criteria = new ArrayList<Criterion>();

    public List<Criterion> getCriteria() {
        return Collections.unmodifiableList(criteria);
    }

    public void setCriteria(List<Criterion> criteria) {
        this.criteria = criteria;
    }

    public Criteria add(Criterion criterion) {
        criteria.add(criterion);
        return this;
    }

}


text:
import { mount } from '@vue/test-utils';
import LessonsSearchFilters from '../LessonsSearchFilters';
import makeStore from '../../../../../../test/makeStore';

function makeWrapper(props) {
  const wrapper = mount(LessonsSearchFilters, {
    store: makeStore(),
    propsData: {
      value: {
        kind: 'html5',
        channel: '123',
        role: null,
      },
      searchResults: {
        results: [],
        content_kinds: [],
        channel_ids: [],
      },
      ...props,
    },
  });
  const kSelects = () => wrapper.findAll({ name: 'KSelect' });
  const els = {
    kindSelect: () => kSelects().at(0),
    channelSelect: () => kSelects().at(1),
    roleSelect: () => kSelects().at(2),
  };
  return { wrapper, els };
}

describe('LessonsSearchFilters', () => {
  it('has the correct content kind filter options based on search results', () => {
    const { els } = makeWrapper({
      searchResults: {
        results: [],
        channel_ids: [],
        content_kinds: ['html5', 'exercise'],
      },
    });
    expect(els.kindSelect().props().options).toEqual([
      { label: 'All', value: null },
      { label: 'Apps', value: 'html5' },
      { label: 'Exercises', value: 'exercise' },
    ]);
  });

  it('has the correct channel filter options based on search results', async () => {
    const { wrapper, els } = makeWrapper();
    wrapper.vm.$store.state.core.channels.list = [{ id: '123', title: 'Channel 123' }];
    wrapper.setProps({
      searchResults: {
        channel_ids: ['123'],
        content_kinds: [],
        results: [
          { kind: 'html5', channel_id: '123' },
          { kind: 'exercise', channel_id: '123' },
        ],
      },
    });
    await wrapper.vm.$nextTick();
    expect(els.channelSelect().props().options).toEqual([
      { label: 'All', value: null },
      { label: 'Channel 123', value: '123' },
    ]);
  });

  it('does not show role filter options when there are no coach contents', () => {
    const { wrapper } = makeWrapper();
    const kSelects = wrapper.findAll({ name: 'KSelect' });
    expect(kSelects.length).toEqual(2);
  });

  it('has the correct role filter options when there are coach contents', () => {
    const { els } = makeWrapper({
      searchResults: {
        channel_ids: [],
        content_kinds: [],
        results: [
          { kind: 'topic', channel_id: '123', num_coach_contents: 1 },
          { kind: 'exercise', channel_id: '123', num_coach_contents: 0 },
        ],
      },
    });
    expect(els.roleSelect().props().options).toEqual([
      { label: 'Show', value: null },
      { label: 'Hide', value: 'nonCoach' },
    ]);
  });

  it('emits the correct event when the content kind filter has changed', () => {
    const { wrapper, els } = makeWrapper();
    els.kindSelect().vm.$emit('change', { value: 'documents' });
    expect(wrapper.emitted().input[0][0]).toEqual({
      channel: '123',
      kind: 'documents',
      role: null,
    });
  });

  it('emits the correct event when the channel filter has changed', () => {
    const { wrapper, els } = makeWrapper();
    els.channelSelect().vm.$emit('change', { value: '456' });
    expect(wrapper.emitted().input[0][0]).toEqual({
      channel: '456',
      kind: 'html5',
      role: null,
    });
  });

  it('emits the correct event when the role filter has changed', () => {
    const { wrapper, els } = makeWrapper({
      searchResults: {
        channel_ids: [],
        content_kinds: [],
        results: [
          { kind: 'topic', channel_id: '123', num_coach_contents: 1 },
          { kind: 'exercise', channel_id: '123', num_coach_contents: 0 },
        ],
      },
    });
    els.roleSelect().vm.$emit('change', { value: 'coach' });
    expect(wrapper.emitted().input[0][0]).toEqual({
      channel: '123',
      kind: 'html5',
      role: 'coach',
    });
  });
});


text:
using System;
using net.r_eg.MvsSln.Core;
using Xunit;

namespace MvsSlnTest.Core
{
    public class SynchSubscribersTest
    {
        [Fact]
        public void ContainerTest1()
        {
            var data = new SynchSubscribers<IHandler>();
            Assert.Equal(0, data.Count);

            var listener1 = new Listener1();
            var listener2 = new Listener2();

            data.Register(listener1);
            data.Register(listener2);
            Assert.Equal(2, data.Count);

            data.Unregister(listener1);
            Assert.Equal(1, data.Count);

            // existence

            Assert.True(data.Contains(listener2));
            Assert.False(data.Contains(listener1));

            Assert.True(data.Exists(listener2.Id));
            Assert.False(data.Exists(listener1.Id));

            // re-adding + duplicates

            data.Register(listener1);
            data.Register(listener1);
            Assert.Equal(2, data.Count);
            Assert.True(data.Contains(listener1));
            Assert.True(data.Exists(listener1.Id));

            // access by id

            Assert.Equal(listener1.Id, data.GetById(listener1.Id).Id);
            Assert.Equal(listener2.Id, data.GetById(listener2.Id).Id);

            var nonexistent = "{8A805C3B-9941-4B82-94D0-E641EBA3881B}";
            Assert.Null(data.GetById(new Guid(nonexistent)));

            data.Reset();
            Assert.Equal(0, data.Count);
        }

        [Fact]
        public void ContainerTest2()
        {
            var data = new SynchSubscribers<IHandler>();

            var listener1 = new Listener1();
            var listener2 = new Listener2();

            data.Register(listener1);
            data.Register(listener2);

            var enumerator = data.GetEnumerator();

            Assert.True(enumerator.MoveNext());
            Assert.Equal(listener1.Id, enumerator.Current.Id);
            Assert.True(enumerator.MoveNext());
            Assert.Equal(listener2.Id, enumerator.Current.Id);

            data.Unregister(listener1);
            data.Register(listener1);

            enumerator = data.GetEnumerator();

            Assert.True(enumerator.MoveNext());
            Assert.Equal(listener2.Id, enumerator.Current.Id);
            Assert.True(enumerator.MoveNext());
            Assert.Equal(listener1.Id, enumerator.Current.Id);
        }

        [Fact]
        public void ContainerTest3()
        {
            var data = new SynchSubscribers<IHandler>();

            var listener1 = new Listener1();
            var listener2 = new Listener2();

            data.Register(listener1);
            data.Register(listener2);

            Assert.Equal(listener1.Id, data[0].Id);
            Assert.Equal(listener2.Id, data[listener2.Id].Id);
        }

        private class Listener1: IHandler
        {
            public Guid Id
            {
                get;
                private set;
            } = new Guid("{E2201272-33E1-4336-9BAE-0C77EF90B66C}");
        }

        private class Listener2: IHandler
        {
            public Guid Id
            {
                get;
                private set;
            } = new Guid("{E361DC9E-E45B-45CC-9800-CE80B6C16BDB}");
        }
    }
}


text:
'use strict';

describe('AddController', function() {
  var scope, ctrl, $httpBackend, marketadService, getCtrl;

  beforeEach(module('kauppapaikka'));

  beforeEach(inject(function(_$httpBackend_, _marketadService_, $rootScope, $controller) {
    $httpBackend = _$httpBackend_;
    marketadService = _marketadService_;
    scope = $rootScope.$new();

    getCtrl = function() {
      ctrl = $controller('AddController', {$scope: scope, marketadService: marketadService});
    };
  }));

  afterEach(function() {
    $httpBackend.verifyNoOutstandingExpectation();
    $httpBackend.verifyNoOutstandingRequest();
  });

  it('should set scope.submitted to false on init', function() {
    var ctrl = getCtrl();
    expect(scope.submitted).toBe(false);
  });

});


text:
using System.Threading;
using System.Threading.Tasks;
using System.Reflection;
using Xunit;

namespace System.Data.SqlClient.ManualTesting.Tests
{
    public static class MARSTest
    {
        private static readonly string s_yukonConnectionString = (new SqlConnectionStringBuilder(DataTestClass.SQL2005_Northwind) { MultipleActiveResultSets = true }).ConnectionString;

#if DEBUG
        [Fact]
        public static void MARSAsyncTimeoutTest()
        {
            using (SqlConnection connection = new SqlConnection(s_yukonConnectionString))
            {
                connection.Open();
                SqlCommand command = new SqlCommand("WAITFOR DELAY '01:00:00';SELECT 1", connection);
                command.CommandTimeout = 1;
                Task<object> result = command.ExecuteScalarAsync();

                Assert.True(((IAsyncResult)result).AsyncWaitHandle.WaitOne(30 * 1000), "Expected timeout after one second, but no results after 30 seconds");
                Assert.True(result.IsFaulted, string.Format("Expected task result to be faulted, but instead it was {0}", result.Status));
                Assert.True(connection.State == ConnectionState.Open, string.Format("Expected connection to be open after soft timeout, but it was {0}", connection.State));

                Type type = typeof(SqlDataReader).GetTypeInfo().Assembly.GetType("System.Data.SqlClient.TdsParserStateObject");
                FieldInfo field = type.GetField("_skipSendAttention", BindingFlags.NonPublic | BindingFlags.Static);

                Assert.True(field != null, "Error: This test cannot succeed on retail builds because it uses the _skipSendAttention test hook");

                field.SetValue(null, true);
                try
                {
                    SqlCommand command2 = new SqlCommand("WAITFOR DELAY '01:00:00';SELECT 1", connection);
                    command2.CommandTimeout = 1;
                    result = command2.ExecuteScalarAsync();

                    Assert.True(((IAsyncResult)result).AsyncWaitHandle.WaitOne(30 * 1000), "Expected timeout after six or so seconds, but no results after 30 seconds");
                    Assert.True(result.IsFaulted, string.Format("Expected task result to be faulted, but instead it was {0}", result.Status));

                    // Pause here to ensure that the async closing is completed
                    Thread.Sleep(200);
                    Assert.True(connection.State == ConnectionState.Closed, string.Format("Expected connection to be closed after hard timeout, but it was {0}", connection.State));
                }
                finally
                {
                    field.SetValue(null, false);
                }
            }
        }

        [Fact]
        public static void MARSSyncTimeoutTest()
        {
            using (SqlConnection connection = new SqlConnection(s_yukonConnectionString))
            {
                connection.Open();
                SqlCommand command = new SqlCommand("WAITFOR DELAY '01:00:00';SELECT 1", connection);
                command.CommandTimeout = 1;
                bool hitException = false;
                try
                {
                    object result = command.ExecuteScalar();
                }
                catch (Exception e)
                {
                    Assert.True(e is SqlException, "Expected SqlException but found " + e);
                    hitException = true;
                }
                Assert.True(hitException, "Expected a timeout exception but ExecutScalar succeeded");

                Assert.True(connection.State == ConnectionState.Open, string.Format("Expected connection to be open after soft timeout, but it was {0}", connection.State));

                Type type = typeof(SqlDataReader).GetTypeInfo().Assembly.GetType("System.Data.SqlClient.TdsParserStateObject");
                FieldInfo field = type.GetField("_skipSendAttention", BindingFlags.NonPublic | BindingFlags.Static);

                Assert.True(field != null, "Error: This test cannot succeed on retail builds because it uses the _skipSendAttention test hook");

                field.SetValue(null, true);
                hitException = false;
                try
                {
                    SqlCommand command2 = new SqlCommand("WAITFOR DELAY '01:00:00';SELECT 1", connection);
                    command2.CommandTimeout = 1;
                    try
                    {
                        object result = command2.ExecuteScalar();
                    }
                    catch (Exception e)
                    {
                        Assert.True(e is SqlException, "Expected SqlException but found " + e);
                        hitException = true;
                    }
                    Assert.True(hitException, "Expected a timeout exception but ExecutScalar succeeded");

                    Assert.True(connection.State == ConnectionState.Closed, string.Format("Expected connection to be closed after hard timeout, but it was {0}", connection.State));
                }
                finally
                {
                    field.SetValue(null, false);
                }
            }
        }
#endif

        [Fact]
        public static void MARSSyncBusyReaderTest()
        {
            using (SqlConnection conn = new SqlConnection(s_yukonConnectionString))
            {
                conn.Open();

                using (SqlDataReader reader1 = (new SqlCommand("select * from Orders", conn)).ExecuteReader())
                {
                    int rows1 = 0;
                    while (reader1.Read())
                    {
                        rows1++;
                        if (rows1 == 415)
                            break;
                    }
                    Assert.True(rows1 == 415, "MARSSyncBusyReaderTest Failure, #1");

                    using (SqlDataReader reader2 = (new SqlCommand("select * from Orders", conn)).ExecuteReader())
                    {
                        int rows2 = 0;
                        while (reader2.Read())
                        {
                            rows2++;
                            if (rows2 == 415)
                                break;
                        }
                        Assert.True(rows2 == 415, "MARSSyncBusyReaderTest Failure, #2");

                        for (int i = 415; i < 830; i++)
                        {
                            Assert.True(reader1.Read() && reader2.Read(), "MARSSyncBusyReaderTest Failure #3");
                            Assert.True(reader1.GetInt32(0) == reader2.GetInt32(0),
                                        "MARSSyncBusyReaderTest, Failure #4" + "\n" +
                                        "reader1.GetInt32(0): " + reader1.GetInt32(0) + "\n" +
                                        "reader2.GetInt32(0): " + reader2.GetInt32(0));
                        }

                        Assert.False(reader1.Read() || reader2.Read(), "MARSSyncBusyReaderTest, Failure #5");
                    }
                }
            }
        }

        [Fact]
        public static void MARSSyncExecuteNonQueryTest()
        {
            using (SqlConnection conn = new SqlConnection(s_yukonConnectionString))
            {
                conn.Open();

                using (SqlCommand comm1 = new SqlCommand("select * from Orders", conn))
                using (SqlCommand comm2 = new SqlCommand("select * from Orders", conn))
                using (SqlCommand comm3 = new SqlCommand("select * from Orders", conn))
                using (SqlCommand comm4 = new SqlCommand("select * from Orders", conn))
                using (SqlCommand comm5 = new SqlCommand("select * from Orders", conn))
                {
                    comm1.ExecuteNonQuery();
                    comm2.ExecuteNonQuery();
                    comm3.ExecuteNonQuery();
                    comm4.ExecuteNonQuery();
                    comm5.ExecuteNonQuery();
                }
            }
        }

        [Fact]
        public static void MARSSyncExecuteReaderTest1()
        {
            using (SqlConnection conn = new SqlConnection(s_yukonConnectionString))
            {
                conn.Open();

                using (SqlDataReader reader1 = (new SqlCommand("select * from Orders", conn)).ExecuteReader())
                using (SqlDataReader reader2 = (new SqlCommand("select * from Orders", conn)).ExecuteReader())
                using (SqlDataReader reader3 = (new SqlCommand("select * from Orders", conn)).ExecuteReader())
                using (SqlDataReader reader4 = (new SqlCommand("select * from Orders", conn)).ExecuteReader())
                using (SqlDataReader reader5 = (new SqlCommand("select * from Orders", conn)).ExecuteReader())
                {
                    int rows = 0;
                    while (reader1.Read())
                    {
                        rows++;
                    }
                    Assert.True(rows == 830, "MARSSyncExecuteReaderTest1 failure, #1");

                    rows = 0;
                    while (reader2.Read())
                    {
                        rows++;
                    }
                    Assert.True(rows == 830, "MARSSyncExecuteReaderTest1 failure, #2");

                    rows = 0;
                    while (reader3.Read())
                    {
                        rows++;
                    }
                    Assert.True(rows == 830, "MARSSyncExecuteReaderTest1 failure, #3");

                    rows = 0;
                    while (reader4.Read())
                    {
                        rows++;
                    }
                    Assert.True(rows == 830, "MARSSyncExecuteReaderTest1 failure, #4");

                    rows = 0;
                    while (reader5.Read())
                    {
                        rows++;
                    }
                    Assert.True(rows == 830, "MARSSyncExecuteReaderTest1 failure, #5");
                }
            }
        }

        [Fact]
        public static void MARSSyncExecuteReaderTest2()
        {
            using (SqlConnection conn = new SqlConnection(s_yukonConnectionString))
            {
                conn.Open();

                using (SqlDataReader reader1 = (new SqlCommand("select * from Orders", conn)).ExecuteReader())
                using (SqlDataReader reader2 = (new SqlCommand("select * from Orders", conn)).ExecuteReader())
                using (SqlDataReader reader3 = (new SqlCommand("select * from Orders", conn)).ExecuteReader())
                using (SqlDataReader reader4 = (new SqlCommand("select * from Orders", conn)).ExecuteReader())
                using (SqlDataReader reader5 = (new SqlCommand("select * from Orders", conn)).ExecuteReader())
                {
                    for (int i = 0; i < 830; i++)
                    {
                        Assert.True(reader1.Read() && reader2.Read() && reader3.Read() && reader4.Read() && reader5.Read(), "MARSSyncExecuteReaderTest2 Failure #1");
                    }

                    Assert.False(reader1.Read() || reader2.Read() || reader3.Read() || reader4.Read() || reader5.Read(), "MARSSyncExecuteReaderTest2 Failure #2");
                }
            }
        }

        [Fact]
        public static void MARSSyncExecuteReaderTest3()
        {
            using (SqlConnection conn = new SqlConnection(s_yukonConnectionString))
            {
                conn.Open();

                using (SqlDataReader reader1 = (new SqlCommand("select * from Orders", conn)).ExecuteReader())
                using (SqlDataReader reader2 = (new SqlCommand("select * from Orders", conn)).ExecuteReader())
                using (SqlDataReader reader3 = (new SqlCommand("select * from Orders", conn)).ExecuteReader())
                using (SqlDataReader reader4 = (new SqlCommand("select * from Orders", conn)).ExecuteReader())
                using (SqlDataReader reader5 = (new SqlCommand("select * from Orders", conn)).ExecuteReader())
                {
                    for (int i = 0; i < 830; i++)
                    {
                        Assert.True(reader1.Read() && reader2.Read() && reader3.Read() && reader4.Read() && reader5.Read(), "MARSSyncExecuteReaderTest3 Failure #1");

                        // All reads succeeded - check values.
                        Assert.True(reader1.GetInt32(0) == reader2.GetInt32(0) &&
                                    reader2.GetInt32(0) == reader3.GetInt32(0) &&
                                    reader3.GetInt32(0) == reader4.GetInt32(0) &&
                                    reader4.GetInt32(0) == reader5.GetInt32(0),
                                    "MARSSyncExecuteReaderTest3, Failure #2" + "\n" +
                                    "reader1.GetInt32(0): " + reader1.GetInt32(0) + "\n" +
                                    "reader2.GetInt32(0): " + reader2.GetInt32(0) + "\n" +
                                    "reader3.GetInt32(0): " + reader3.GetInt32(0) + "\n" +
                                    "reader4.GetInt32(0): " + reader4.GetInt32(0) + "\n" +
                                    "reader5.GetInt32(0): " + reader5.GetInt32(0));
                    }

                    Assert.False(reader1.Read() || reader2.Read() || reader3.Read() || reader4.Read() || reader5.Read(), "MARSSyncExecuteReaderTest3 Failure #3");
                }
            }
        }

        [Fact]
        public static void MARSSyncExecuteReaderTest4()
        {
            using (SqlConnection conn = new SqlConnection(s_yukonConnectionString))
            {
                conn.Open();

                using (SqlDataReader reader1 = (new SqlCommand("select * from Orders where OrderID = 10248", conn)).ExecuteReader())
                using (SqlDataReader reader2 = (new SqlCommand("select * from Orders where OrderID = 10249", conn)).ExecuteReader())
                using (SqlDataReader reader3 = (new SqlCommand("select * from Orders where OrderID = 10250", conn)).ExecuteReader())
                {
                    Assert.True(reader1.Read() && reader2.Read() && reader3.Read(), "MARSSyncExecuteReaderTest4 failure #1");

                    Assert.True(reader1.GetInt32(0) == 10248 &&
                                reader2.GetInt32(0) == 10249 &&
                                reader3.GetInt32(0) == 10250,
                                "MARSSyncExecuteReaderTest4 failure #2");

                    Assert.False(reader1.Read() || reader2.Read() || reader3.Read(), "MARSSyncExecuteReaderTest4 failure #3");
                }
            }
        }
    }
}


text:
package com.chiorichan;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.DefaultHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.ssl.SslHandshakeCompletionEvent;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Timer;

import javax.net.ssl.SSLEngine;

import com.chiorichan.packet.Packet;
import com.chiorichan.packet.PacketException;
import com.google.common.base.Charsets;

/**
 * @author Chiori Greene
 * @email chiorigreene@gmail.com
 */
public class Handler extends SimpleChannelInboundHandler<Object>
{
	private Timer timer = new Timer( "Heartbeat", true );
	private boolean ssl;
	private ServerMessageBus bus;
	private String url;

	public Handler( boolean ssl )
	{
		this.ssl = ssl;
	}

	@Override
	public void channelInactive( ChannelHandlerContext ctx )
	{
		timer.cancel();
		if ( bus != null && bus.client() != null )
			bus.client().disconnect();
	}

	public String getUri( String uri )
	{
		try
		{
			uri = URLDecoder.decode( uri, Charsets.UTF_8.name() );
		}
		catch ( UnsupportedEncodingException e )
		{
			try
			{
				uri = URLDecoder.decode( uri, Charsets.ISO_8859_1.name() );
			}
			catch ( UnsupportedEncodingException e1 )
			{
				e1.printStackTrace();
			}
		}
		catch ( IllegalArgumentException e1 )
		{

		}

		if ( uri.contains( "?" ) )
			uri = uri.substring( 0, uri.indexOf( "?" ) );

		if ( !uri.startsWith( "/" ) )
			uri = "/" + uri;

		return uri;
	}

	@Override
	protected void messageReceived( ChannelHandlerContext ctx, Object obj ) throws Exception
	{
		if ( obj instanceof DefaultHttpRequest )
		{
			DefaultHttpRequest request = ( ( DefaultHttpRequest ) obj );
			url = getUri( request.uri() );

			FullHttpResponse response = new DefaultFullHttpResponse( HttpVersion.HTTP_1_0, HttpResponseStatus.valueOf( 200 ), Unpooled.copiedBuffer( new byte[0] ) );

			response.headers().add( "Content-Type", "application/octet-stream" );

			ctx.write( response );
			ctx.write( "\r\n\r\n" ); // 0d 0a
			ctx.flush();

			if ( ssl )
			{
				SSLEngine engine = SslContextFactory.getServerContext().createSSLEngine();
				engine.setUseClientMode( false );
				engine.setEnabledProtocols( new String[] {"TLSv1"} );
				engine.setEnabledCipherSuites( new String[] {"SSL_RSA_WITH_RC4_128_SHA", "SSL_RSA_WITH_RC4_128_MD5"} );

				ctx.pipeline().addFirst( "ssl", new MarchSslHandler( engine ) );
			}
			else
				start( ctx );
		}
		else if ( obj instanceof HttpContent )
			try
			{
				System.out.println( "From Client Message Received: " + obj );

				HttpContent msg = ( HttpContent ) obj;
				ByteBuf buf = msg.content();

				if ( buf.readableBytes() < 1 )
				{
					System.out.println( "WARNING: Received an empty message!" );
					return;
				}

				int mark = buf.readerIndex();
				Packet[] rcvds = Packet.decode( buf );

				if ( rcvds.length > 0 )
					bus.handle( rcvds );
				else
					bus.incoming( buf.copy( mark, buf.readerIndex() - mark ) );
			}
			catch ( PacketException e )
			{
				System.out.println( e.hexDump() );
				throw e;
			}
		else
			System.out.println( "Received an unknown packet type: " + obj );
	}

	public void start( ChannelHandlerContext ctx )
	{
		bus = new ServerMessageBus( ssl, url, ctx );

		bus.start0();
		bus.startPinger();
	}

	@Override
	public void userEventTriggered( ChannelHandlerContext ctx, Object evt )
	{
		if ( evt instanceof SslHandshakeCompletionEvent )
		{
			SslHandshakeCompletionEvent event = ( SslHandshakeCompletionEvent ) evt;
			if ( event.isSuccess() )
				start( ctx );
			else
			{
				System.err.println( "SSL Handshake Failed!" );
				ctx.close();
			}
		}
	}
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>Mozilla DTD format — Translate Toolkit 1.11.0 documentation</title>

    <link rel="stylesheet" href="../_static/basic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <link rel="stylesheet" href="../_static/bootstrap.css" type="text/css" />
    <link rel="stylesheet" href="../_static/bootstrap-sphinx.css" type="text/css" />

    <link rel="top" title="Translate Toolkit 1.11.0 documentation" href="../index.html" />
    <link rel="up" title="Translation Related File Formats" href="index.html" />
    <link rel="next" title="OpenOffice.org GSI/SDF format" href="gsi.html" />
    <link rel="prev" title="Mozilla and Java properties files" href="properties.html" />

        Translate Toolkit
        1.11.0

  Site

Features

Installation

Converters

Tools

Scripts

Use Cases

Supported formats

Translate Styleguide

Documentation

Building

Testing

Contributing

Translate Toolkit Developers Guide

Making a Translate Toolkit Release

Changelog

Release Notes

History of the Translate Toolkit

License

API

  Page

Mozilla DTD format

References

Features

Issues

« Mozilla and Java properties files

OpenOffice.org GSI/SDF format »

<form class="navbar-search pull-right" action="../search.html" method="get">
  <input type="text" name="q" placeholder="Search" />
  <input type="hidden" name="check_keywords" value="yes" />
  <input type="hidden" name="area" value="default" />
</form>

Mozilla DTD format¶

Mozilla makes use of a .dtd file to store many of its translatable elements,
the moz2po converter can handle these.

References¶

XML specification

Features¶

Comments – these are handled correctly and integrated with the unit

Accelerators – if a unit has an associated access key entry then these are
combined into a single unit

Translator directive – all LOCALIZATION NOTE items such as DONT_TRANSLATE
are handled and such items are discarded

Issues¶

We don’t escape character entities like <tt class="docutils literal">&lt;</tt>, <tt class="docutils literal">&#38;</tt> – this doesn’t
break anything but it would be nicer to see © rather than &copy;

Back to top ↑

        © 2012, Translate.org.za.

      Created using Sphinx 1.2.1.


text:
package core;

/**
 * InvalidDefaultGatewayException Class that extends from the Simulation Exception
 * class
 * @author michal_reith
 * @author angela_brown
 * @version v0.20
 **/
public class InvalidDefaultGatewayException extends SimulationException{

	/**
	 *
	 */
	private static final long serialVersionUID = -5881360180537741813L;

	/**
	 * This method throw inExceptionMsg up to the super class Simulation
	 * Excpetion
	 * @author angela_brown
	 * @author michael_reith
	 * @param inExceptionMsg - The Excpetion Message
	 * @version v0.20
	 **/
	public InvalidDefaultGatewayException(String inExceptionMsg) {
		super(inExceptionMsg);
	}

}


text:
package ua.khpi.oop.lytvyn15;

import java.util.Comparator;

/**
 *
 *
 * @author student Lytvyn I.I. KIT-26A
 */
public interface ClientComparator extends Comparator<Client> {
	/*
	 * (non-Javadoc)
	 *
	 * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
	 */
	@Override
	public int compare(Client first, Client second);
}


text:
from __future__ import division

from builtins import str # pylint: disable=redefined-builtin

import calendar
import csv
import datetime
import io
import json
import os
import tempfile
import time

from zipfile import ZipFile

from past.utils import old_div

import arrow
import pytz

from django.conf import settings
from django.template.loader import render_to_string
from django.utils import timezone
from django.utils.text import slugify

from ..models import DataPoint, DataSourceReference, DataGeneratorDefinition

def generator_name(identifier): # pylint: disable=unused-argument
    return 'System Status'

def visualization(source, generator):
    context = {}
    context['source'] = source
    context['generator_identifier'] = generator

    start = timezone.now() - datetime.timedelta(days=7)

    context['values'] = DataPoint.objects.filter(source=source.identifier, generator_identifier=generator, created__gte=start).order_by('-created')

    filename = settings.MEDIA_ROOT + os.path.sep + 'pdk_visualizations' + os.path.sep + source.identifier + os.path.sep + 'pdk-system-status' + os.path.sep + 'timestamp-counts.json'

    try:
        with io.open(filename, encoding='utf-8') as infile:
            hz_data = json.load(infile)

            context['hz_data'] = hz_data
    except IOError:
        context['hz_data'] = {}

    return render_to_string('generators/pdk_device_system_status_template.html', context)

def data_table(source, generator):
    context = {}
    context['source'] = source
    context['generator_identifier'] = generator

    start = timezone.now() - datetime.timedelta(days=7)

    context['values'] = DataPoint.objects.filter(source=source.identifier, generator_identifier=generator, created__gte=start).order_by('-created')

    return render_to_string('generators/pdk_device_system_status_table_template.html', context)

def compile_report(generator, sources, data_start=None, data_end=None, date_type='created'): # pylint: disable=too-many-locals, too-many-branches, too-many-statements
    now = arrow.get()
    filename = tempfile.gettempdir() + os.path.sep + 'pdk_export_' + str(now.timestamp) + str(old_div(now.microsecond, 1e6)) + '.zip'

    with ZipFile(filename, 'w') as export_file:
        seen_sources = []

        for source in sources:
            export_source = source

            seen_index = 1

            while slugify(export_source) in seen_sources:
                export_source = source + '__' + str(seen_index)

                seen_index += 1

            seen_sources.append(slugify(export_source))

            identifier = slugify(generator + '__' + export_source)

            secondary_filename = tempfile.gettempdir() + os.path.sep + identifier + '.txt'

            with io.open(secondary_filename, 'w', encoding='utf-8') as outfile:
                writer = csv.writer(outfile, delimiter='\t')

                columns = [
                    'Source',
                    'Created Timestamp',
                    'Created Date',
                    'Recorded Timestamp',
                    'Recorded Date',
                    'Available Storage',
                    'Other Storage',
                    'App Storage',
                    'Total Storage',
                    'App Runtime',
                    'System Runtime',
                ]

                writer.writerow(columns)

                source_reference = DataSourceReference.reference_for_source(source)
                generator_definition = DataGeneratorDefinition.definition_for_identifier(generator)

                points = DataPoint.objects.filter(source_reference=source_reference, generator_definition=generator_definition)

                if data_start is not None:
                    if date_type == 'recorded':
                        points = points.filter(recorded__gte=data_start)
                    else:
                        points = points.filter(created__gte=data_start)

                if data_end is not None:
                    if date_type == 'recorded':
                        points = points.filter(recorded__lte=data_end)
                    else:
                        points = points.filter(created__lte=data_end)

                points = points.order_by('source', 'created')

                for point in points:
                    properties = point.fetch_properties()

                    row = []

                    created = point.created.astimezone(pytz.timezone(settings.TIME_ZONE))
                    recorded = point.recorded.astimezone(pytz.timezone(settings.TIME_ZONE))

                    row.append(point.source)
                    row.append(calendar.timegm(point.created.utctimetuple()))
                    row.append(created.isoformat())
                    row.append(calendar.timegm(point.recorded.utctimetuple()))
                    row.append(recorded.isoformat())

                    row.append(properties['storage_available'])
                    row.append(properties['storage_other'])
                    row.append(properties['storage_app'])
                    row.append(properties['storage_total'])

                    if 'runtime' in properties:
                        row.append(properties['runtime'])
                    else:
                        row.append(None)

                    if 'system_runtime' in properties:
                        row.append(properties['system_runtime'])
                    else:
                        row.append(None)

                    writer.writerow(row)

            export_file.write(secondary_filename, slugify(generator) + '/' + slugify(export_source) + '.txt')

            os.remove(secondary_filename)

    return filename

def compile_visualization(identifier, points, folder, source=None): # pylint: disable=unused-argument, too-many-locals
    now = timezone.now()

    latest = points.order_by('-created').first()

    if latest is not None:
        now = latest.created

    now = now.replace(second=0, microsecond=0)

    remainder = now.minute % 10

    now = now.replace(minute=(now.minute - remainder))

    start = now - datetime.timedelta(days=2)

    points = points.filter(created__lte=now, created__gte=start).order_by('created')

    end = start + datetime.timedelta(seconds=600)
    point_index = 0
    point_count = points.count()

    point = None

    if point_count > 0:
        point = points[point_index]

    timestamp_counts = {}

    keys = []

    while start < now:
        timestamp = str(time.mktime(start.timetuple()))

        keys.append(timestamp)

        timestamp_counts[timestamp] = 0

        while point is not None and point.created < end and point_index < (point_count - 1):
            timestamp_counts[timestamp] += 1

            point_index += 1

            point = points[point_index]

        start = end
        end = start + datetime.timedelta(seconds=600)

    timestamp_counts['keys'] = keys

    with io.open(folder + os.path.sep + 'timestamp-counts.json', 'wb') as outfile:
        json.dump(timestamp_counts, outfile, indent=2)


text:
using ConvexHull.Utils;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConvexHull
{
    class ConvexHullAlgorithm
    {
        static void printS(List<PointF> S)
        {
            System.IO.File.WriteAllText("D:/points.txt", " ");
            for (int i = 0; i < S.Count; i++)
            {
                //Console.WriteLine(S[i].X + ", " + S[i].Y);
                System.IO.File.AppendAllText("D:/points.txt", S[i].X + ", " + S[i].Y + Environment.NewLine);

            }
        }

        static public List<PointF> Compute(List<PointF> Points)
        {
            Points.Sort(delegate(PointF a, PointF b) { return a.X.CompareTo(b.X); });

            printS(Points);

            List<HullPoint> SS = new List<HullPoint>();

            for (int i = 0; i < Points.Count; i++)
            {
                SS.Add(new HullPoint(Points[i].X, Points[i].Y, i));
            }

            HullPoint start = ComputeCovexHull(SS, 0, Points.Count - 1).FirstOrDefault();
            HullPoint x = start;

            List<PointF> newPoints = new List<PointF>();
            do
            {
                newPoints.Add(new PointF(x.X, x.Y));
                x = x.next;
            } while (x != start);

            return newPoints;
        }

        // orientation -1 : for vectors counterclockwise of a->b
        // orientation  1 : for vectors clockwise of a->b

        // To see if a->b is a tangent we must see in all the points of U lie on either of the half planes defined by a->b
        // We use the Z coordinate of a->b and a->c cross product. We require all for points of U that to be > 0 (unless a->c is counterclockwise to a->b)
        static private bool isTangent(HullPoint a, HullPoint b, List<HullPoint> U, int orientation)
        {
            for (int i = 0; i < U.Count; i++)
                if (Vector.getCrossProductZ(a, b, U[i]) * orientation > 0)
                    return false;
            return true;
        }

        // direction -1 : counterclockwise
        // direction  1 : clockwise

        // Simply walk along U in the given direction untill a tangent is found. That is guaranteed to happen!
        static private HullPoint findTangent(HullPoint a, HullPoint b, List<HullPoint> U, int direction, int orientation)
        {
            while (true)
            {
                if (isTangent(a, b, U, orientation)) return b;
                b = direction == 1 ? b.next : b.prev;
            }
        }

        // A is the left Convex Hull B is the right Convex Hull
        static private List<HullPoint> combine(List<HullPoint> A, List<HullPoint> B)
        {
            bool debug = false;

            // The rightmost point in A and the leftmost point in B are origins for the tangent search
            HullPoint rightA = A.Max();
            HullPoint leftB = B.Min();

            if (debug)
            {
                Console.WriteLine();
                Console.Write("\n\n## In A is : \n");
                foreach (HullPoint point in A)
                    Console.WriteLine(point.index + " " + point.X + ", " + point.Y);
                Console.Write("\n## In B is : \n");
                foreach (HullPoint point in B)
                    Console.WriteLine(point.index + " " + point.X + ", " + point.Y);
                Console.WriteLine();
            }

            // a and b are temporary variables for finding the upper tangent
            HullPoint a = rightA, b = leftB;
            while (true)
            {
                // Clockwise, Case 1
                b = findTangent(a, b, B, 1, 1);

                // Case 4
                if (isTangent(b, a, A, -1)) break;

                // Counterclockwise, Case 4
                a = findTangent(b, a, A, -1, -1);

                // Case 1
                if (isTangent(a, b, B, 1)) break;
            }
            HullPoint topA = a, topB = b;
            if (debug) Console.WriteLine("\n***Upper tangent is : " + a.index + " " + b.index);

            // a and b are temporary variables for finding the bottom tangent
            a = rightA; b = leftB;
            while (true)
            {
                // Counterclockwise, Case 2
                b = findTangent(a, b, B, -1, -1);

                // Case 3
                if (isTangent(b, a, A, 1)) break;

                // Clockwise, Case 3
                a = findTangent(b, a, A, 1, 1);

                // Case 2
                if (isTangent(a, b, B, -1)) break;
            }
            HullPoint bottomA = a, bottomB = b;
            if (debug) Console.WriteLine("\n*** Lower tangent is : " + a.index + " " + b.index);

            // "Stiching" up the top and bottom of the two Convex Hulls together
            topA.next = topB; topB.prev = topA;

            bottomA.prev = bottomB; bottomB.next = bottomA;

            // The Union of both convex hull can be found by starting at any of the Tangent points and walking untill the same point is reached again
            List<HullPoint> U = new List<HullPoint>();

            HullPoint x = a;
            if (debug) Console.Write("\n\nThe run is : \n");
            do
            {
                U.Add(x);
                if (debug) Console.Write(x.X + ", " + x.Y + Environment.NewLine);
                x = x.next;
            } while (x != a);

            return U;
        }

        static private List<HullPoint> ComputeCovexHull(List<HullPoint> S, int l, int r)
        {
            // Base case with 1 point is a Simple Convex Hull
            if (r - l + 1 == 1)
            {
                List<HullPoint> C = new List<HullPoint>();
                C.Add(S[l]);
                C[0].next = C[0];
                C[0].prev = C[0];
                return C;
            }

            // Base case with 2 points is a Convex Hull with both of them
            if (r - l + 1 == 2)
            {
                List<HullPoint> C = new List<HullPoint>();

                C.Add(S[l]); C.Add(S[r]);

                // Important they have to be linked together
                C[0].next = C[1]; C[0].prev = C[1];

                C[1].next = C[0]; C[1].prev = C[0];

                return C;
            }

            int mid = (l + r) / 2;

            List<HullPoint> A = ComputeCovexHull(S, l, mid);
            List<HullPoint> B = ComputeCovexHull(S, mid + 1, r);

            return combine(A, B);
        }

    }
}


text:
'use strict';

angular.module('app')
.config(function ($stateProvider) {
  $stateProvider.state('top', {
    url: '/top',
    title: 'Top Pairs',
    description: 'Want to see everyone\'s favorite cards? See the most popular and the most controversial.',
    templateUrl: 'views/top/top.html',
    controller: 'topView',
    abstract: true
  });
});


text:
namespace kaldi {
namespace nnet2 {

// Computes one-sided K-L divergence from p to q.
BaseFloat KlDivergence(const Vector<BaseFloat> &p,
                       const Vector<BaseFloat> &q) {
  BaseFloat sum_p = p.Sum(), sum_q = q.Sum();
  if (fabs(sum_p - 1.0) > 0.01 || fabs(sum_q - 1.0) > 0.01) {
    KALDI_WARN << "KlDivergence: vectors are not close to being normalized "
               << sum_p << ", " << sum_q;
  }
  KALDI_ASSERT(p.Dim() == q.Dim());
  double ans = 0.0;

  for (int32 i = 0; i < p.Dim(); i++) {
    BaseFloat p_prob = p(i) / sum_p, q_prob = q(i) / sum_q;
    ans += p_prob * log(p_prob / q_prob);
  }
  return ans;
}

void PrintPriorDiagnostics(const Vector<BaseFloat> &old_priors,
                           const Vector<BaseFloat> &new_priors) {
  if (old_priors.Dim() == 0) {
    KALDI_LOG << "Model did not previously have priors attached.";
  } else {
    Vector<BaseFloat> diff_prior(new_priors);
    diff_prior.AddVec(-1.0, old_priors);
    diff_prior.ApplyAbs();
    int32 max_index;
    diff_prior.Max(&max_index);
    KALDI_LOG << "Adjusting priors: largest absolute difference was for "
              << "pdf " << max_index << ", " << old_priors(max_index)
              << " -> " << new_priors(max_index);
    KALDI_LOG << "Adjusting priors: K-L divergence from old to new is "
              << KlDivergence(old_priors, new_priors);
  }
}

} // namespace nnet2
} // namespace kaldi

int main(int argc, char *argv[]) {
  try {
    using namespace kaldi;
    using namespace kaldi::nnet2;
    typedef kaldi::int32 int32;

    const char *usage =
        "Set the priors of the neural net to the computed posterios from the net,\n"
        "on typical data (e.g. training data). This is correct under more general\n"
        "circumstances than using the priors of the class labels in the training data\n"
        "\n"
        "Typical usage of this program will involve computation of an average pdf-level\n"
        "posterior with nnet-compute or nnet-compute-from-egs, piped into nnet-sum-rows\n"
        "and then vector-sum, to compute the average posterior\n"
        "\n"
        "Usage: nnet-adjust-priors [options] <nnet-in> <summed-posterior-vector-in> <nnet-out>\n"
        "e.g.:\n"
        " nnet-adjust-priors final.mdl prior.vec final.mdl\n";

    bool binary_write = true;
    BaseFloat prior_floor = 1.0e-15; // Have a very low prior floor, since this method
                                     // isn't likely to have a problem with very improbable
                                     // classes.

    ParseOptions po(usage);
    po.Register("binary", &binary_write, "Write output in binary mode");
    po.Register("prior-floor", &prior_floor, "When setting priors, floor for "
                "priors (only used to avoid generating NaNs upon inversion)");

    po.Read(argc, argv);

    if (po.NumArgs() != 3) {
      po.PrintUsage();
      exit(1);
    }

    std::string nnet_rxfilename = po.GetArg(1),
        posterior_vec_rxfilename = po.GetArg(2),
        nnet_wxfilename = po.GetArg(3);

    TransitionModel trans_model;
    AmNnet am_nnet;
    {
      bool binary_read;
      Input ki(nnet_rxfilename, &binary_read);
      trans_model.Read(ki.Stream(), binary_read);
      am_nnet.Read(ki.Stream(), binary_read);
    }

    Vector<BaseFloat> posterior_vec;
    ReadKaldiObject(posterior_vec_rxfilename, &posterior_vec);

    KALDI_ASSERT(posterior_vec.Sum() > 0.0);
    posterior_vec.Scale(1.0 / posterior_vec.Sum()); // Renormalize

    Vector<BaseFloat> old_priors(am_nnet.Priors());

    PrintPriorDiagnostics(old_priors, posterior_vec);

    am_nnet.SetPriors(posterior_vec);

    {
      Output ko(nnet_wxfilename, binary_write);
      trans_model.Write(ko.Stream(), binary_write);
      am_nnet.Write(ko.Stream(), binary_write);
    }
    KALDI_LOG << "Modified priors of neural network model and wrote it to "
              << nnet_wxfilename;
    return 0;
  } catch(const std::exception &e) {
    std::cerr << e.what() << '\n';
    return -1;
  }
}


text:
/*
 * @(#)osapi_sharedMemorySegment_impl.h    generated by: makeheader    Mon Dec  3 23:07:47 2007
 *
 *		built from:	sharedMemorySegment_impl.ifc
 */

#ifndef osapi_sharedMemorySegment_impl_h
#define osapi_sharedMemorySegment_impl_h

#ifdef __cplusplus
    extern "C" {
#endif

struct RTIOsapiSharedMemorySegmentHeader {
    /*i Size requested by the caller of attachOrCreate */
    int size;

    /*i PID of the process that created the segment.
	It is set to the PID when the segment is created, and is set
	to ZERO when the segment is destroyed. In this way it makes
	safe the check of Pid == process_itself in the createOrAttach.
        On Integrity this is not used because Integrity doesn't
	guarantee an unique ID for each process.
     */
    RTI_UINT32 ownerPid;

    /*i Key that identifies this segment */
    int key;

    /*i The total size of the allocated buffer */
    int allocatedSize;
};

struct RTIOsapiSharedMemorySegmentHandleImpl {
    /*i handle to the shared memory.
        Used as a reference when delete the shared memory.
    */
    RTIOsapiSharedMemoryNativeHandle_Segment nativeHandle;

    /*i pointer to the first byte of the shared segment. The segment header
        can be found on top.
    */
    struct RTIOsapiSharedMemorySegmentHeader * ptrHeader;  /* NULL=unattached */

    /*i Pointer to the user's data inside the segment.
        This is equivalent of ptrHeader+sizeof(RTOsapiSharedMemorySegmentHeader)
    */
    void * ptrUserData;
};

struct RTIOsapiSharedMemorySegmentHandle {
    union {
	struct RTIOsapiSharedMemorySegmentHandleImpl handle;
	int pad[8];
    } impl;
};

#define RTIOsapiSharedMemorySegment_getAddress(h) \
    ((h)->impl.handle.ptrUserData)

#define RTIOsapiSharedMemorySegment_getSize(h) \
    ((h)->impl.handle.ptrHeader->size)

#define RTIOsapiSharedMemorySegment_getKey(h) \
    ((h)->impl.handle.ptrHeader->key)

#define RTIOsapiSharedMemorySegment_getOwnerPid(h) \
    ((h)->impl.handle.ptrHeader->ownerPid)

#ifdef __cplusplus
    }	/* extern "C" */
#endif

#endif /* osapi_sharedMemorySegment_impl_h */