text:
<?xml version="1.0" encoding="UTF-8"?>
<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.vimalselvam</groupId>
    <artifactId>cucumber-extentsreport</artifactId>
    <version>3.1.1</version>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <packaging>jar</packaging>

    <name>Cucumber Extents Report</name>
    <description>A custom cucumber html report generated by ExtentsReport</description>
    <url>http://vimalselvam.com</url>

    <licenses>
        <license>
            <name>MIT License</name>
            <url>http://www.opensource.org/licenses/mit-license.php</url>
            <distribution>repo</distribution>
        </license>
    </licenses>

    <issueManagement>
        <url>https://github.com/email2vimalraj/CucumberExtentReporter/issues</url>
        <system>GitHub Issues</system>
    </issueManagement>

    <scm>
        <url>https://github.com/email2vimalraj/CucumberExtentReporter</url>
        <connection>scm:git:git://github.com/email2vimalraj/CucumberExtentReporter.git</connection>
        <developerConnection>scm:git:git@github.com/email2vimalraj/CucumberExtentReporter.git</developerConnection>
    </scm>

    <developers>
        <developer>
            <name>Vimalraj Selvam</name>
            <url>http://vimalselvam.com</url>
            <id>email2vimalraj</id>
            <roles>
                <role>Owner</role>
            </roles>
        </developer>
    </developers>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <cucumber.version>1.2.5</cucumber.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>cucumber-junit</artifactId>
            <version>${cucumber.version}</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>cucumber-testng</artifactId>
            <version>${cucumber.version}</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>2.53.0</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>cucumber-java</artifactId>
            <version>${cucumber.version}</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>com.aventstack</groupId>
            <artifactId>extentreports</artifactId>
            <version>[3.1.1,)</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <distributionManagement>
        <snapshotRepository>
            <id>ossrh</id>
            <url>https://oss.sonatype.org/content/repositories/snapshots</url>
        </snapshotRepository>
        <repository>
            <id>ossrh</id>
            <url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
        </repository>
    </distributionManagement>

    <profiles>
        <profile>
            <id>release</id>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.sonatype.plugins</groupId>
                        <artifactId>nexus-staging-maven-plugin</artifactId>
                        <version>1.6.3</version>
                        <extensions>true</extensions>
                        <configuration>
                            <serverId>ossrh</serverId>
                            <nexusUrl>https://oss.sonatype.org/</nexusUrl>
                            <autoReleaseAfterClose>true</autoReleaseAfterClose>
                        </configuration>
                    </plugin>

                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-source-plugin</artifactId>
                        <version>2.2.1</version>
                        <executions>
                            <execution>
                                <id>attach-sources</id>
                                <goals>
                                    <goal>jar-no-fork</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>

                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-javadoc-plugin</artifactId>
                        <version>2.10.3</version>
                        <executions>
                            <execution>
                                <id>attach-javadocs</id>
                                <goals>
                                    <goal>jar</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>

                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-gpg-plugin</artifactId>
                        <version>1.5</version>
                        <executions>
                            <execution>
                                <id>sign-artifacts</id>
                                <phase>verify</phase>
                                <goals>
                                    <goal>sign</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>

</project>


text:
package cli

import (
	"bufio"
	"bytes"
	"context"
	"os"
	"os/exec"
	"strings"

	"github.com/gopasspw/gopass/internal/backend/crypto/gpg"
	"github.com/gopasspw/gopass/internal/out"
	"github.com/gopasspw/gopass/pkg/debug"
)

// ListRecipients returns a parsed list of GPG public keys.
func (g *GPG) ListRecipients(ctx context.Context) ([]string, error) {
	if g.pubKeys == nil {
		kl, err := g.listKeys(ctx, "public")
		if err != nil {
			return nil, err
		}
		g.pubKeys = kl
	}

	if gpg.IsAlwaysTrust(ctx) {
		return g.pubKeys.Recipients(), nil
	}

	return g.pubKeys.UseableKeys(gpg.IsAlwaysTrust(ctx)).Recipients(), nil
}

// FindRecipients searches for the given public keys.
func (g *GPG) FindRecipients(ctx context.Context, search ...string) ([]string, error) {
	kl, err := g.listKeys(ctx, "public", search...)
	if err != nil || kl == nil {
		return nil, err
	}

	recp := kl.UseableKeys(gpg.IsAlwaysTrust(ctx)).Recipients()
	if gpg.IsAlwaysTrust(ctx) {
		recp = kl.Recipients()
	}

	debug.Log("found useable keys for %q: %q (all: %q)", search, recp, kl.Recipients())

	return recp, nil
}

// RecipientIDs returns a list of recipient IDs for a given encrypted blob.
func (g *GPG) RecipientIDs(ctx context.Context, buf []byte) ([]string, error) {
	recp := make([]string, 0, 5)

	// extract recipients from gpg output
	args := []string{"--batch", "--list-only", "--list-packets", "--no-default-keyring", "--secret-keyring", "/dev/null"}
	cmd := exec.CommandContext(ctx, g.binary, args...)
	cmd.Stdin = bytes.NewReader(buf)

	// switch to LANG C for more predictable output, switch back later
	for _, env := range os.Environ() {
		if strings.HasPrefix(env, "LANGUAGE=") {
			continue
		}
		cmd.Env = append(cmd.Env, env)
	}
	cmd.Env = append(cmd.Env, "LANGUAGE=C")

	debug.Log("%s %+v", cmd.Path, cmd.Args)

	cmdout, err := cmd.CombinedOutput()
	if err != nil {
		return []string{}, err
	}

	// parse the output
	scanner := bufio.NewScanner(bytes.NewBuffer(cmdout))
	for scanner.Scan() {
		line := strings.TrimSpace(scanner.Text())
		debug.Log("GPG Output: %s", line)
		if !strings.HasPrefix(line, ":pubkey enc packet:") {
			continue
		}

		m := splitPacket(line)
		keyid, found := m["keyid"]
		if !found {
			continue
		}

		kl, err := g.listKeys(ctx, "public", keyid)
		if err != nil || len(kl) < 1 {
			continue
		}

		recp = append(recp, kl[0].Fingerprint)
	}

	if g.throwKids {
		out.Warningf(ctx, "gpg option throw-keyids is set. some features might not work.")
	}

	return recp, nil
}

func splitPacket(in string) map[string]string {
	m := make(map[string]string, 3)
	p := strings.Split(in, ":")
	if len(p) < 3 {
		return m
	}

	p = strings.Split(strings.TrimSpace(p[2]), " ")
	for i := 0; i+1 < len(p); i += 2 {
		m[p[i]] = strings.Trim(p[i+1], ",")
	}

	return m
}

redpajama_set_name: RedPajamaGithub


text:
class Foo {
  @deco
  *generatorMethod() {}
}


text:
namespace DLaB.Xrm.Entities
{

	[System.Runtime.Serialization.DataContractAttribute()]
	[System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "9.0.0.9154")]
	public enum msdyn_odatav4ds_msdyn_paginationtype
	{

		[System.Runtime.Serialization.EnumMemberAttribute()]
		ClientsidePaging = 0,

		[System.Runtime.Serialization.EnumMemberAttribute()]
		ServersidePaging = 1,
	}
}


text:
<?php

$widget = (new CWidget())
	->setTitle(_('Discovery rules'))
	->addItem(get_header_host_table('discoveries', $data['hostid'],
		array_key_exists('itemid', $data) ? $data['itemid'] : 0
	));

// create form
$itemForm = (new CForm())
	->setName('itemForm')
	->addVar('form', $this->data['form'])
	->addVar('hostid', $this->data['hostid']);

if (!empty($this->data['itemid'])) {
	$itemForm->addVar('itemid', $this->data['itemid']);
}

// create form list
$itemFormList = new CFormList('itemFormList');
if (!empty($this->data['templates'])) {
	$itemFormList->addRow(_('Parent discovery rules'), $this->data['templates']);
}

$itemFormList->addRow(_('Name'), (new CTextBox('name', $this->data['name'], $this->data['limited']))
	->setWidth(ZBX_TEXTAREA_STANDARD_WIDTH)
	->setAttribute('autofocus', 'autofocus')
);

// append type to form list
if ($this->data['limited']) {
	$itemForm->addVar('type', $this->data['type']);
	$itemFormList->addRow(_('Type'),
		(new CTextBox('typename', item_type2str($this->data['type']), true))->setWidth(ZBX_TEXTAREA_SMALL_WIDTH)
	);
}
else {
	$typeComboBox = (new CComboBox('type', $this->data['type']))
		->addItems($this->data['types']);
	$itemFormList->addRow(_('Type'), $typeComboBox);
}

// append key to form list
$itemFormList->addRow(_('Key'), [
	(new CTextBox('key', $this->data['key'], $this->data['limited']))->setWidth(ZBX_TEXTAREA_STANDARD_WIDTH)
]);

// append interfaces to form list
if (!empty($this->data['interfaces'])) {
	$interfacesComboBox = new CComboBox('interfaceid', $this->data['interfaceid']);

	// set up interface groups
	$interfaceGroups = [];
	foreach (zbx_objectValues($this->data['interfaces'], 'type') as $interfaceType) {
		$interfaceGroups[$interfaceType] = new COptGroup(interfaceType2str($interfaceType));
	}

	// add interfaces to groups
	foreach ($this->data['interfaces'] as $interface) {
		$option = new CComboItem(
			$interface['interfaceid'],
			$interface['useip'] ? $interface['ip'].' : '.$interface['port'] : $interface['dns'].' : '.$interface['port'],
			$interface['interfaceid'] == $this->data['interfaceid'] ? 'yes' : 'no'
		);
		$option->setAttribute('data-interfacetype', $interface['type']);
		$interfaceGroups[$interface['type']]->addItem($option);
	}
	foreach ($interfaceGroups as $interfaceGroup) {
		$interfacesComboBox->addItem($interfaceGroup);
	}

	$span = (new CSpan(_('No interface found')))
		->addClass(ZBX_STYLE_RED)
		->setId('interface_not_defined')
		->setAttribute('style', 'display: none;');

	$itemFormList->addRow(_('Host interface'), [$interfacesComboBox, $span], 'interface_row');
	$itemForm->addVar('selectedInterfaceId', $this->data['interfaceid']);
}
$itemFormList->addRow(_('SNMP OID'),
	(new CTextBox('snmp_oid', $this->data['snmp_oid'], $this->data['limited']))->setWidth(ZBX_TEXTAREA_STANDARD_WIDTH),
	'row_snmp_oid'
);
$itemFormList->addRow(_('Context name'),
	(new CTextBox('snmpv3_contextname', $this->data['snmpv3_contextname']))->setWidth(ZBX_TEXTAREA_STANDARD_WIDTH),
	'row_snmpv3_contextname'
);
$itemFormList->addRow(_('SNMP community'),
	(new CTextBox('snmp_community', $this->data['snmp_community'], false, 64))->setWidth(ZBX_TEXTAREA_STANDARD_WIDTH),
	'row_snmp_community'
);
$itemFormList->addRow(_('Security name'),
	(new CTextBox('snmpv3_securityname', $this->data['snmpv3_securityname'], false, 64))
		->setWidth(ZBX_TEXTAREA_STANDARD_WIDTH),
	'row_snmpv3_securityname'
);

// append snmpv3 security level to form list
$securityLevelComboBox = new CComboBox('snmpv3_securitylevel', $this->data['snmpv3_securitylevel'], null, [
	ITEM_SNMPV3_SECURITYLEVEL_NOAUTHNOPRIV => 'noAuthNoPriv',
	ITEM_SNMPV3_SECURITYLEVEL_AUTHNOPRIV => 'authNoPriv',
	ITEM_SNMPV3_SECURITYLEVEL_AUTHPRIV => 'authPriv'
]);
$itemFormList->addRow(_('Security level'), $securityLevelComboBox, 'row_snmpv3_securitylevel');
$itemFormList->addRow(_('Authentication protocol'),
	(new CRadioButtonList('snmpv3_authprotocol', (int) $this->data['snmpv3_authprotocol']))
		->addValue(_('MD5'), ITEM_AUTHPROTOCOL_MD5)
		->addValue(_('SHA'), ITEM_AUTHPROTOCOL_SHA)
		->setModern(true),
	'row_snmpv3_authprotocol'
);
$itemFormList->addRow(_('Authentication passphrase'),
	(new CTextBox('snmpv3_authpassphrase', $this->data['snmpv3_authpassphrase'], false, 64))
		->setWidth(ZBX_TEXTAREA_STANDARD_WIDTH),
	'row_snmpv3_authpassphrase'
);
$itemFormList->addRow(_('Privacy protocol'),
	(new CRadioButtonList('snmpv3_privprotocol', (int) $this->data['snmpv3_privprotocol']))
		->addValue(_('DES'), ITEM_PRIVPROTOCOL_DES)
		->addValue(_('AES'), ITEM_PRIVPROTOCOL_AES)
		->setModern(true),
	'row_snmpv3_privprotocol'
);
$itemFormList->addRow(_('Privacy passphrase'),
	(new CTextBox('snmpv3_privpassphrase', $this->data['snmpv3_privpassphrase'], false, 64))
		->setWidth(ZBX_TEXTAREA_STANDARD_WIDTH),
	'row_snmpv3_privpassphrase'
);
$itemFormList->addRow(_('Port'),
	(new CTextBox('port', $this->data['port'], false, 64))->setWidth(ZBX_TEXTAREA_SMALL_WIDTH), 'row_port'
);
$itemFormList->addRow(_('IPMI sensor'),
	(new CTextBox('ipmi_sensor', $this->data['ipmi_sensor'], $this->data['limited'], 128))
		->setWidth(ZBX_TEXTAREA_STANDARD_WIDTH),
	'row_ipmi_sensor'
);

// append authentication method to form list
$authTypeComboBox = new CComboBox('authtype', $this->data['authtype'], null, [
	ITEM_AUTHTYPE_PASSWORD => _('Password'),
	ITEM_AUTHTYPE_PUBLICKEY => _('Public key')
]);
$itemFormList->addRow(_('Authentication method'), $authTypeComboBox, 'row_authtype');
$itemFormList->addRow(_('User name'),
	(new CTextBox('username', $this->data['username'], false, 64))->setWidth(ZBX_TEXTAREA_SMALL_WIDTH),
	'row_username'
);
$itemFormList->addRow(_('Public key file'),
	(new CTextBox('publickey', $this->data['publickey'], false, 64))->setWidth(ZBX_TEXTAREA_SMALL_WIDTH),
	'row_publickey'
);
$itemFormList->addRow(_('Private key file'),
	(new CTextBox('privatekey', $this->data['privatekey'], false, 64))->setWidth(ZBX_TEXTAREA_SMALL_WIDTH),
	'row_privatekey'
);
$itemFormList->addRow(_('Password'),
	(new CTextBox('password', $this->data['password'], false, 64))->setWidth(ZBX_TEXTAREA_SMALL_WIDTH),
	'row_password'
);
$itemFormList->addRow(_('Executed script'),
	(new CTextArea('params_es', $this->data['params']))->setWidth(ZBX_TEXTAREA_STANDARD_WIDTH),
	'label_executed_script'
);
$itemFormList->addRow(_('SQL query'),
	(new CTextArea('params_ap', $this->data['params']))->setWidth(ZBX_TEXTAREA_STANDARD_WIDTH),
	'label_params'
);

$itemFormList->addRow(_('Update interval (in sec)'),
	(new CNumericBox('delay', $this->data['delay'], 5))->setWidth(ZBX_TEXTAREA_NUMERIC_STANDARD_WIDTH),
	'row_delay'
);

// Append delay_flex to form list.
$delayFlexTable = (new CTable())
	->setId('delayFlexTable')
	->setHeader([_('Type'), _('Interval'), _('Period'), _('Action')])
	->setAttribute('style', 'width: 100%;');

foreach ($data['delay_flex'] as $i => $delay_flex) {
	$type_input = (new CRadioButtonList('delay_flex['.$i.'][type]', (int) $delay_flex['type']))
		->addValue(_('Flexible'), ITEM_DELAY_FLEX_TYPE_FLEXIBLE)
		->addValue(_('Scheduling'), ITEM_DELAY_FLEX_TYPE_SCHEDULING)
		->setModern(true);

	if ($delay_flex['type'] == ITEM_DELAY_FLEX_TYPE_FLEXIBLE) {
		$delay_input = (new CNumericBox('delay_flex['.$i.'][delay]', $delay_flex['delay'], 5, false, true, false))
			->setAttribute('placeholder', 50);
		$period_input = (new CTextBox('delay_flex['.$i.'][period]', $delay_flex['period'], false, 255))
			->setAttribute('placeholder', ZBX_DEFAULT_INTERVAL);
		$schedule_input = (new CTextBox('delay_flex['.$i.'][schedule]', '', false, 255))
			->setAttribute('placeholder', 'wd1-5h9-18')
			->setAttribute('style', 'display: none;');
	}
	else {
		$delay_input = (new CNumericBox('delay_flex['.$i.'][delay]', '', 5, false, true, false))
			->setAttribute('placeholder', 50)
			->setAttribute('style', 'display: none;');
		$period_input = (new CTextBox('delay_flex['.$i.'][period]', '', false, 255))
			->setAttribute('placeholder', ZBX_DEFAULT_INTERVAL)
			->setAttribute('style', 'display: none;');
		$schedule_input = (new CTextBox('delay_flex['.$i.'][schedule]', $delay_flex['schedule'], false, 255))
			->setAttribute('placeholder', 'wd1-5h9-18');
	}

	$button = (new CButton('delay_flex['.$i.'][remove]', _('Remove')))
		->addClass(ZBX_STYLE_BTN_LINK)
		->addClass('element-table-remove');

	$delayFlexTable->addRow([$type_input, [$delay_input, $schedule_input], $period_input, $button], 'form_row');
}

$delayFlexTable->addRow([(new CButton('interval_add', _('Add')))
	->addClass(ZBX_STYLE_BTN_LINK)
	->addClass('element-table-add')]);

$itemFormList->addRow(_('Custom intervals'),
		(new CDiv($delayFlexTable))
			->addClass(ZBX_STYLE_TABLE_FORMS_SEPARATOR)
			->setAttribute('style', 'min-width: '.ZBX_TEXTAREA_STANDARD_WIDTH.'px;'),
		'row_flex_intervals'
	)
	->addRow(_('Keep lost resources period (in days)'),
		(new CTextBox('lifetime', $this->data['lifetime'], false, 64))->setWidth(ZBX_TEXTAREA_SMALL_WIDTH)
	)
	->addRow(_('Allowed hosts'),
		(new CTextBox('trapper_hosts', $this->data['trapper_hosts']))->setWidth(ZBX_TEXTAREA_STANDARD_WIDTH),
	'row_trapper_hosts'
	)
	->addRow(_('Description'),
		(new CTextArea('description', $this->data['description']))->setWidth(ZBX_TEXTAREA_STANDARD_WIDTH)
);

// status
$enabledCheckBox = (new CCheckBox('status', ITEM_STATUS_ACTIVE))->setChecked($this->data['status'] == ITEM_STATUS_ACTIVE);
$itemFormList->addRow(_('Enabled'), $enabledCheckBox);

/*
 * Condition tab
 */
$conditionFormList = new CFormList();

// type of calculation
$conditionFormList->addRow(_('Type of calculation'),
	[
		new CComboBox('evaltype', $this->data['evaltype'], null, [
			CONDITION_EVAL_TYPE_AND_OR => _('And/Or'),
			CONDITION_EVAL_TYPE_AND => _('And'),
			CONDITION_EVAL_TYPE_OR => _('Or'),
			CONDITION_EVAL_TYPE_EXPRESSION => _('Custom expression')
		]),
		(new CDiv())->addClass(ZBX_STYLE_FORM_INPUT_MARGIN),
		(new CSpan(''))
			->setId('expression'),
		(new CTextBox('formula', $this->data['formula']))
			->setWidth(ZBX_TEXTAREA_STANDARD_WIDTH)
			->setId('formula')
			->setAttribute('placeholder', 'A or (B and C) …')
	],
	'conditionRow'
);

// macros
$conditionTable = (new CTable())
	->setId('conditions')
	->setAttribute('style', 'width: 100%;')
	->setHeader([_('Label'), _('Macro'), '', _('Regular expression'), _('Action')]);

$conditions = $this->data['conditions'];
if (!$conditions) {
	$conditions = [['macro' => '', 'value' => '', 'formulaid' => num2letter(0)]];
}
else {
	$conditions = CConditionHelper::sortConditionsByFormulaId($conditions);
}

// fields
foreach ($conditions as $i => $condition) {
	// formula id
	$formulaId = [
		new CSpan($condition['formulaid']),
		new CVar('conditions['.$i.'][formulaid]', $condition['formulaid'])
	];

	// macro
	$macro = (new CTextBox('conditions['.$i.'][macro]', $condition['macro'], false, 64))
		->setWidth(ZBX_TEXTAREA_MACRO_WIDTH)
		->addClass(ZBX_STYLE_UPPERCASE)
		->addClass('macro')
		->setAttribute('placeholder', '{#MACRO}')
		->setAttribute('data-formulaid', $condition['formulaid']);

	// value
	$value = (new CTextBox('conditions['.$i.'][value]', $condition['value'], false, 255))
		->setWidth(ZBX_TEXTAREA_MACRO_VALUE_WIDTH)
		->setAttribute('placeholder', _('regular expression'));

	// delete button
	$deleteButtonCell = [
		(new CButton('conditions_'.$i.'_remove', _('Remove')))
			->addClass(ZBX_STYLE_BTN_LINK)
			->addClass('element-table-remove')
	];

	$row = [$formulaId, $macro, new CSpan(_('matches')), $value,
		(new CCol($deleteButtonCell))->addClass(ZBX_STYLE_NOWRAP)
	];
	$conditionTable->addRow($row, 'form_row');
}

$conditionTable->setFooter(new CCol(
	(new CButton('macro_add', _('Add')))
		->addClass(ZBX_STYLE_BTN_LINK)
		->addClass('element-table-add')
));

$conditionFormList->addRow(_('Filters'),
	(new CDiv($conditionTable))
		->addClass(ZBX_STYLE_TABLE_FORMS_SEPARATOR)
		->setAttribute('style', 'min-width: '.ZBX_TEXTAREA_BIG_WIDTH.'px;')
);

// append tabs to form
$itemTab = (new CTabView())
	->addTab('itemTab', $this->data['caption'], $itemFormList)
	->addTab('macroTab', _('Filters'), $conditionFormList);
if (!hasRequest('form_refresh')) {
	$itemTab->setSelected(0);
}

// append buttons to form
if (!empty($this->data['itemid'])) {
	$itemTab->setFooter(makeFormFooter(
		new CSubmit('update', _('Update')), [
			new CSubmit('clone', _('Clone')),
			(new CButtonDelete(_('Delete discovery rule?'), url_params(['form', 'itemid', 'hostid'])))
				->setEnabled(!$data['limited']),
			new CButtonCancel(url_param('hostid'))
		]
	));
}
else {
	$itemTab->setFooter(makeFormFooter(
		new CSubmit('add', _('Add')),
		[new CButtonCancel(url_param('hostid'))]
	));
}

$itemForm->addItem($itemTab);
$widget->addItem($itemForm);

require_once dirname(__FILE__).'/js/configuration.host.discovery.edit.js.php';

return $widget;


text:
/*! @addtogroup Hash
 *
 * @ingroup Hash
 * @{
 * @details Functions to hash board positions
 *
 */

#include "hashkeys.h"
#include "castle_perms.h"
#include "piece.h"
#include "rand.h"
#include "square.h"
#include "utils.h"
#include <assert.h>

static uint64_t piece_keys[NUM_PIECES][NUM_SQUARES] = {{0}, {0}};
static uint64_t side_key = 0;
static uint64_t castle_keys[NUM_CASTLE_PERMS] = {0};
static uint64_t en_passant_sq_keys[NUM_SQUARES] = {0};

/**
 * @brief       Initialises the position hashkeys
 *
 */
uint64_t init_key_mgmt(void) {
    init_prng();

    uint64_t hashkey = 0;

    for (int num_pces = 0; num_pces < NUM_PIECES; num_pces++) {
        for (int num_sq = 0; num_sq < NUM_SQUARES; num_sq++) {
            const uint64_t rnd = genrand64_int64();
            piece_keys[num_pces][num_sq] = rnd;

            hashkey ^= piece_keys[num_pces][num_sq];
        }
    }

    side_key = genrand64_int64();
    hashkey ^= side_key;

    for (int num_sq = 0; num_sq < NUM_SQUARES; num_sq++) {
        en_passant_sq_keys[num_sq] = genrand64_int64();

        hashkey ^= en_passant_sq_keys[num_sq];
    }

    for (int i = 0; i < NUM_CASTLE_PERMS; i++) {
        castle_keys[i] = genrand64_int64();

        hashkey ^= castle_keys[i];
    }
    return hashkey;
}

uint64_t hash_piece_update(const enum piece pce, const enum square sq, const uint64_t key_to_modify) {
    assert(validate_piece(pce));
    assert(validate_square(sq));

    return key_to_modify ^ piece_keys[PIECE_AS_ARRAY_OFFSET(pce)][sq];
}

bool hash_compare(const uint64_t hashkey1, const uint64_t hashkey2) {
    return hashkey1 == hashkey2;
}

uint64_t hash_piece_update_move(const enum piece pce, const enum square from_sq, const enum square to_sq,
                                const uint64_t key_to_modify) {
    assert(validate_piece(pce));
    assert(validate_square(from_sq));
    assert(validate_square(to_sq));

    const uint64_t *pce_array = piece_keys[PIECE_AS_ARRAY_OFFSET(pce)];
    const uint64_t from_hash = key_to_modify ^ *(pce_array + from_sq);
    const uint64_t to_hash = from_hash ^ *(pce_array + to_sq);

    return to_hash;
}

/**
 * @brief               Flips the hash for the side
 * @param key_to_modify The hashkey to modify
 * @return              The updated hash key
 */
uint64_t hash_side_update(const uint64_t key_to_modify) {
    return key_to_modify ^ side_key;
}

/**
 * @brief               Flips the hash for the en passant square
 * @param key_to_modify The hashkey to modify
 * @return              The updated hash key
 */
uint64_t hash_en_passant(const enum square sq, const uint64_t key_to_modify) {
    assert(validate_square(sq));
    return key_to_modify ^ en_passant_sq_keys[sq];
}

/**
 * @brief               Flips the hash based on the castle permissions
 * @param cp            The permissions
 * @param key_to_modify The hashkey to modify
 * @return              The updated hash key
 */
uint64_t hash_castle_perm(const enum castle_permission cp, const uint64_t key_to_modify) {

    assert(validate_castle_permission(cp));

    const int cp_off = CP_ARRAY_OFFSET(cp);
    return key_to_modify ^ castle_keys[cp_off];
}


text:
Developer Documentation
=======================

.. toctree::
   :maxdepth: 2

   dev-installation
   api-docs
   development
   plugin-development
   developer-cookbook
   external-web-clients
   python-client
   security
   build-docs
   migration-guide


text:
**Pick up words and list them later**

This extension provides listing words. For example, you can pick up some keywords in an article when you read it. and later (after having finished reading it) you can check them.

**Usage**

1. select a word or phrase
1. right click and select "Add word-later: ***" in context menu
1. to check words, click "word-later" in toolbar then
sidebar shows listed words (if word-later button don't exist, click customize button and find it)


text:
\section{DataObjects}
\label{sec:DataObjects}

As seen in the previous chapters, different entities in the RAVEN
code interact with each other in order to create, ideally, an infinite number of
different calculation flows.
%
These interactions are made possible through a data handling system that each
entity understands.
%
This system is called the ``DataObjects'' framework.

The \xmlNode{DataObjects} tag is a container of data objects of various types that can
be constructed during the execution of a particular calculation flow.
%
These data objects can be used as input or output for a particular
\textbf{Model} (see Roles' meaning in section \ref{sec:models}), etc.
%
Currently, RAVEN supports 3 different data types, each with a particular
conceptual meaning.
%
These data types are instantiated as sub-nodes in the \xmlNode{DataObjects} block of
an input file:
\begin{itemize}
  \item \xmlNode{PointSet} is a collection of individual objects, each
  describing the state of the system at a certain point (e.g. in time).
  %
  It can be considered a mapping between multiple sets of parameters in the
  input space and the resulting sets of outcomes in the output space at a
  particular point (e.g. in time).
  %
  \item \xmlNode{HistorySet} is a collection of individual objects each
  describing the temporal evolution of the state of the system within a certain
  input domain.
  %
  It can be considered a mapping between multiple sets of parameters in the
  input space and the resulting sets of temporal evolution in the output
  space.
  %
   \item \xmlNode{DataSet} is a generalization of the previously described DataObject,
   aimed to contain a mixture of data (scalars, arrays, etc.). The variables here stored
   can be independent (i.e. scalars) or dependent (arrays) on certain dimensions (e.g. time, coordinates, etc.).
  %
  It can be considered a mapping between multiple sets of parameters in the
  input space (both dependent and/or independent) and the resulting sets of evolution in the output
  space (both dependent and/or independent).
  %
  \nb \textcolor{red} {\textbf{The  \xmlNode{DataSet} is currently usable in the  \xmlNode{EnsembleModel} only (see \ref{subsec:models_EnsembleModel} )}}
\end{itemize}

In summary, the DataObjects accept the following data in their input/output spaces:
\begin{table}[h]
\centering
\caption{DataObjects' accepted data formats.}
\label{DataObjectDataFormatTable}
\begin{tabular}{|c|c|c|}
\hline
\textbf{DataObject}                        & \textbf{Input Space} & \textbf{Output Space} \\ \hline
{\color[HTML]{FE0000} \textit{PointSet}}   & scalars              & scalars               \\ \hline
{\color[HTML]{FE0000} \textit{HistorySet}} & scalars              & vectors               \\ \hline
{\color[HTML]{FE0000} \textit{DataSet}}    & any                  & any                   \\ \hline
\end{tabular}
\end{table}

As noted above, each data object represents a mapping between a set of
parameters and the resulting outcomes.
%
The data objects are defined within the main XML block called \xmlNode{DataObjects}:
\begin{lstlisting}[style=XML]
<Simulation>
   ...
  <DataObjects>
    <PointSet name='***'>...</PointSet>
    <HistorySet name='***'>...</HistorySet>
    <DataSet name='***'>...</DataSet>
  </DataObjects>
   ...
</Simulation>
\end{lstlisting}

Independently on the type of data, the respective XML node has the following
available attributes:
\vspace{-5mm}
\begin{itemize}
  \itemsep0em
  \item \xmlAttr{name}, \xmlDesc{required string attribute}, is a user-defined
  identifier for this data object.
    %
  \nb As with other objects, this name can be used to refer to this specific
  entity from other input blocks in the XML.
  %
%  % Regarding the time attribute, we need to take a better decision... Now it is very confusing.
%  \item \xmlAttr{time}, \xmlDesc{optional float or string attribute}, time
%    attribute.
%    %
%    Here, the user can specify either the time (value) at which the outcomes
%    need to be taken (History-like object, it represents the time from which the
%    outcomes' evolution need to be tracked) or a string  that can be either
%    ``end'', at the end of the history, or ``all'', consider.
%    %
%    \default{random seed};
%  \item \xmlAttr{inputTs}, \xmlDesc{optional integer attribute}, used to
%  specify at which ``time step'' the input space needs to be retrieved.
%  %
%  \nb If the user wants to take conditions from the end of the simulation, s/he
%  can directly input ``-1.''
%  %
%  \default{0}
%  \item \xmlAttr{operator}, \xmlDesc{optional string attribute}, is aimed at
%  performing simple operations on the data to be stored.
%  %
%  %
%  The 3 options currently available are:
%  \begin{itemize}
%    \item \xmlString{max}
%    \item \xmlString{min}
%    \item \xmlString{average}
%  \end{itemize}
%  %
%  \default{None}

  \item \xmlAttr{hierarchical}, \xmlDesc{optional boolean attribute},
  This flag is going to ``control'' the printing/plotting of the DataObject in
  case a hierarchical structure is determined (e.g.
  data coming from Dynamic Event Tree-like approaches):
  \begin{itemize}
    \item if \textbf{True} all the branches of the tree are going to be printed/plotted independently
               (i.e. all the branches are going to be exposed independently)
    \item if \textbf{False} all the branches are going to be walked back and reconstructed in order to create independent histories
  \end{itemize}
  %
  \default{False}
\end{itemize}
\vspace{-5mm}
In each XML node (e.g. \xmlNode{PointSet}, \xmlNode{HistorySet} or  \xmlNode{DataSet}), the user
specifies the following sub-nodes:
\begin{itemize}
  \item \xmlNode{Input}, \xmlDesc{comma separated string, required field}, lists
  the input parameters to which this data is connected.
  %
  \item \xmlNode{Output}, \xmlDesc{comma separated string, required field}, lists
  the output parameters to which this data is connected.
  %
  \item \xmlNode{Index}, \xmlDesc{comma separated string, required for \xmlNode{DataSet}}, lists
  the dependent variables that depend on this index (specified through the attribute  \xmlAttr{var}).
  This XML node requires the following attribute:
   \begin{itemize}
     \item \xmlAttr{var}, \xmlDesc{required string attribute}, the dimension name of this index (e.g. time)
   \end{itemize}
 \item \xmlNode{options}, \xmlDesc{optional node}, contains additional option nodes
   for data objects.  This node contains the following subnodes:
   \begin{itemize}
     \item \xmlNode{pivotParameter}, \xmlDesc{optional, string}, specifies the \textit{pivotParameter} for a
       \xmlNode{HistorySet}. The pivot parameter is the shared index of the output variables in the data
       object.  \default time
    \item \xmlNode{inputRow}, \xmlDesc{integer, optional field}, used to
         specify  the row (in a CSV file or HDF5 table) from which the input space
        needs to be retrieved (e.g. the time-step);
    %
    \item \xmlNode{outputRow}, \xmlDesc{integer, optional field}, used to
         specify  the row (in the CSV file or HDF5 table) from which the output space
        needs to be retrieved (e.g. the time-step). If this node is inputted, the nodes
         \xmlNode{operator} and  \xmlNode{outputPivotValue} can not be inputted (mutually exclusive).
       \\\nb This XML node is available for DataObjects of type \xmlNode{PointSet} only;
    %
    \item \xmlNode{operator}, \xmlDesc{string, optional field}, is aimed to perform
         simple operations on the data to be stored.
         The 3 options currently available are:
         \begin{itemize}
            \item \xmlString{max}
            \item \xmlString{min}
            \item \xmlString{average}
         \end{itemize}
         If this node is inputted, the nodes
         \xmlNode{outputRow} and  \xmlNode{outputPivotValue} can not be inputted (mutually exclusive).
         \\\nb This XML node is available for DataObjects of type \xmlNode{PointSet} only;
   \end{itemize}

  %
\end{itemize}

The  \xmlNode{PointSet} and  \xmlNode{HistorySet} objects are a specialization of the  \xmlNode{DataSet}. In
the \xmlNode{PointSet}, the input and output space are all exclusively scalar values.  These values might be
extracted from a vector of values for each entry using the \xmlNode{options} node, but the end result is a
single scalar per input or output variable.

For the \xmlNode{HistorySet}, all inputs must be scalar, and all outputs must share an index (the
\textit{pivotParameter}.  There cannot be scalars in any of the outputs. The pivotParameter can be changed
through the corresponding node in the \xmlNode{options} node.

  %
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  %%%% This feature is being disabled until the DataObjects handle data in a
  %%%% more encapsulated fashion. When the data can handle this all internally
  %%%% then we can re-add this feature. As of now, determining the rows
  %%%% associated to the outputPivotValue or inputPivotValue requires knowing
  %%%% information outside of the "value" passed into
  %%%% DataObject.updateOutputValue or DataObject.updateInputValue, thus the
  %%%% caller has to do this computation, but currently the caller occurs in ~50
  %%%% different places according to my grep of "updateOutputValue"
  %%%% -- DPM 8/29/2017
  % \item \xmlNode{pivotParameter}, \xmlDesc{string, optional field} the name of
  %   the parameter whose values need to be used as reference for the values
  %   specified in the XML nodes \xmlNode{inputPivotValue},
  %   \xmlNode{outputPivotValue}, or \xmlNode{inputPivotValue} (if inputted).
  %   This field can be used, for example, if the driven code output file uses  a
  %   different name for the variable ``time'' or to specify a different reference
  %   parameter (e.g. PRESSURE). Default value is \xmlString{time}.
  %   \\\nb The variable specified here should be monotonic; the code does not
  %   check for eventual oscillation and is going to take the first occurance for
  %   the values specified in the XML nodes \xmlNode{inputPivotValue},
  %   \xmlNode{outputPivotValue}, and  \xmlNode{inputPivotValue};
  % %
  % \item \xmlNode{inputPivotValue}, \xmlDesc{float, optional field}, the value of the \xmlNode{pivotParameter} at which the input space needs to be retrieved
  %   If this node is inputted, the node  \xmlNode{inputRow} can not be inputted (mutually exclusive).
  %   %
  % \item \xmlNode{outputPivotValue}. This node can be either a float or a list of floats, depending on the type of DataObjects:
  %  \begin{itemize}
  %     \item if \xmlNode{HistorySet},\xmlNode{outputPivotValue}, \xmlDesc{list of floats, optional field},  list of values of the
  %                         \xmlNode{pivotParameter} at which the output space needs to be retrieved;
  %     \item if \xmlNode{PointSet},\xmlNode{outputPivotValue}, \xmlDesc{float, optional field},  the value of the \xmlNode{pivotParameter}
  %        at which the output space needs to be retrieved. If this node is inputted, the node  \xmlNode{outputRow} can not be inputted (mutually exclusive);
  %  \end{itemize}
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  %
Note that if the optional nodes in the block \xmlNode{options} are not inputted, the following default are applied:
\begin{itemize}
   \item the Input space (scalars) is retrieved from the first row in the CSVs files or HDF5 tables (if the parameters specified are not
      among the variables sampled by RAVEN); In case of the  \xmlNode{DataSet}, if any of the input space variables depend on an \xmlNode{Index}, they
      are going to be linked to the \xmlNode{Index} variable
   \item  the output space defaults are as follows:
   \begin{itemize}
       \item if \xmlNode{PointSet}, the output space is retrieved from the last row in the CSVs files or HDF5 tables;
       \item if \xmlNode{HistorySet}, the output space is represented by all the rows found in  the CSVs or HDF5 tables.
       \item if \xmlNode{DataSet}, the output space of the variables that do not depends on any index is retrieved from the last row in the CSVs files or HDF5 tables;
       on the contrary, the output space of the variables that depends on indexes is represented by all the rows found in  the CSVs or HDF5 tables (if they match
       with the indexes' dimension)
    \end{itemize}
\end{itemize}

\begin{lstlisting}[style=XML,morekeywords={operator,hierarchical,name,var}]
  <DataObjects>
    <PointSet name='outTPS1'>
      <options>
       <inputRow>1</inputRow>
       <outputRow>-1</outputRow>
      </options>
      <Input>pipe_Area,pipe_Dh,Dummy1</Input>
      <Output>pipe_Hw,pipe_Tw,time</Output>
    </PointSet>
    <HistorySet name='stories1'>
        <options>
            <pivotParameter>TIME</pivotParameter>
            <inputRow>1</inputRow>
            <outputRow>-1</outputRow>
        </options>
      <Input>pipe_Area,pipe_Dh</Input>
      <Output>pipe_Hw,pipe_Tw,time</Output>
    </HistorySet>
    <DataSet name='aDataSet'>
      <Input>pipe_Area,pipe_Dh</Input>
      <Output>pipe_Hw,pipe_Tw</Output>
      <Index var="time">pipe_Hw,pipe_Tw</Index>
    </DataSet>
  </DataObjects>
\end{lstlisting}

\section{Databases}
\label{sec:Databases}
The RAVEN framework provides the capability to store and retrieve data to/from
an external database.
%
Currently RAVEN has support for \textbf{netCDF4} and \textbf{HDF5} formats.
NetCDF shares native format with RAVEN's DataObjects, but HDF5 is also included for convenience.
%
This database, depending on the data format it is receiving, will organize
itself in a ``parallel'' or ``hierarchical'' fashion.
%
The user can create as many database objects as needed.
%
The Database objects are defined within the main XML block called
\xmlNode{Databases}:
\begin{lstlisting}[style=XML]
<Simulation>
  ...
  <Databases>
    ...
    <NetCDF name="aDatabaseName1" readMode="overwrite"/>
    <HDF5 name="aDatabaseName2" readMode="overwrite"/>
    ...
  </Databases>
  ...
</Simulation>
\end{lstlisting}
The specifications for these two formats are listed below.

\subsection{NetCDF}
The specifications of each Database of type NetCDF needs to be defined within the
XML block \xmlNode{NetCDF}, that recognizes the following attributes:
\vspace{-5mm}
\begin{itemize}
  \itemsep0em
  \item \xmlAttr{name}, \xmlDesc{required string attribute}, a user-defined
  identifier of this object.
  %
  \nb As with other objects, this is name can be used to reference this specific
  entity from other input blocks in the XML.
  \item \xmlAttr{readMode}, \xmlDesc{required string attribute}, defines whether an existing database should
    be read when loaded (\xmlString{read}) or overwritten (\xmlString{overwrite}).
    \nb if in \xmlString{read} mode and the database is not found, RAVEN will read in
    the data as empty and raise a warning, NOT an error.
  %
  \item \xmlAttr{directory}, \xmlDesc{optional string attribute}, this attribute
  can be used to specify a particular directory path where the database will be
  created or read from.  If an absolute path is given, RAVEN will respect it; otherwise,
  the path will be assumed to be relative to the \xmlNode{WorkingDir} from the \xmlNode{RunInfo} block.
  RAVEN recognizes path expansion tools such as tildes (\emph{user dir}), single dots (\emph{current dir}),
  and double dots (\emph{parent dir}).
  %
  \default{workingDir/DatabaseStorage}.  The \xmlNode{workingDir} is
   the one defined within the \xmlNode{RunInfo} XML block (see Section~\ref{sec:RunInfo}).
  \item \xmlAttr{filename}, \xmlDesc{optional string attribute}, specifies the
  filename of the database that will be created in the \xmlAttr{directory}.
  %
  \nb When this attribute is not specified, the newer database filename will be
  named \texttt{name.nc}, where \textit{name} corresponds to the \xmlAttr{name}
  attribute of this object.
  %
  \default{None}
\end{itemize}

Example:
\begin{lstlisting}[style=XML,morekeywords={directory,filename}]
<Databases>
  <NetCDF name="name1" directory=''path_to_a_dir'' readMode='overwrite'/>
  <HDF5 name="name2" filename=''Name2.nc'' readMode='read'/>
</Databases>
\end{lstlisting}

\subsection{HDF5}
The specifications of each Database of type HDF5 needs to be defined within the
XML block \xmlNode{HDF5}, that recognizes the following attributes:
\vspace{-5mm}
\begin{itemize}
  \itemsep0em
  \item \xmlAttr{name}, \xmlDesc{required string attribute}, a user-defined
  identifier of this object.
  %
  \nb As with other objects, this is name can be used to reference this specific
  entity from other input blocks in the XML.
  \item \xmlAttr{readMode}, \xmlDesc{required string attribute}, defines whether an existing database should
    be read when loaded (\xmlString{read}) or overwritten (\xmlString{overwrite}).
    \nb if in \xmlString{read} mode and the database is not found, RAVEN will read in
    the data as empty and raise a warning, NOT an error.
  %
  \item \xmlAttr{directory}, \xmlDesc{optional string attribute}, this attribute
  can be used to specify a particular directory path where the database will be
  created or read from.  If an absolute path is given, RAVEN will respect it; otherwise,
  the path will be assumed to be relative to the \xmlNode{WorkingDir} from the \xmlNode{RunInfo} block.
  RAVEN recognizes path expansion tools such as tildes (\emph{user dir}), single dots (\emph{current dir}),
  and double dots (\emph{parent dir}).
  %
  \default{workingDir/DatabaseStorage}.  The \xmlNode{workingDir} is
   the one defined within the \xmlNode{RunInfo} XML block (see Section~\ref{sec:RunInfo}).
  \item \xmlAttr{filename}, \xmlDesc{optional string attribute}, specifies the
  filename of the HDF5 that will be created in the \xmlAttr{directory}.
  %
  \nb When this attribute is not specified, the newer database filename will be
  named \texttt{name}.h5, where \textit{name} corresponds to the \xmlAttr{name}
  attribute of this object.
  %
  \default{None}
  \item \xmlAttr{compression}, \xmlDesc{optional string attribute}, compression
  algorithm to be used.
  %
  Available are:
  \begin{itemize}
    \item \xmlString{gzip}, best where portability is required.
    %
    Good compression, moderate speed.
    %
    \item \xmlString{lzf}, Low to moderate compression, very fast.
    %
  \end{itemize}
  \default{None}
\end{itemize}

In addition, the \xmlNode{HDF5} recognizes the following subnodes:
\begin{itemize}
  \itemsep0em
  \item \xmlNode{variables}, \xmlDesc{optional, comma-separated string}, allows only a pre-specified set of variables to be
    included in the HDF5 when it is written to.  If this node is not included, by default the HDF5 will
    include ALL of the input/output variables as a result of the step it is part of.  If included, only the
    comma-separated variable names will be included if found.

    \nb RAVEN will not error if one of the requested variables is not found; instead, it will silently pass.
    It is recommended that a small trial run is performed, loading the HDF5 back into a data object, to check
    that the correct variables are saved to the HDF5 before performing large-scale calculations.
\end{itemize}

Example:
\begin{lstlisting}[style=XML,morekeywords={directory,filename}]
<Databases>
  <HDF5 name="aDatabaseName1" directory=''path_to_a_dir'' compression=''lzf'' readMode='overwrite'/>
  <HDF5 name="aDatabaseName2" filename=''aDatabaseName2.h5'' readMode='read'/>
</Databases>
\end{lstlisting}


text:
import nspkg.nssubpkg.a

print(nspkg.nssubpkg.a.VAR)


text: Description of `dummy_ds_1` dummy config-based dataset.


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

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>Uses of Interface com.hazelcast.nio.serialization.DataSerializableFactory (Hazelcast Root 3.3.3 API)</title>
<meta name="date" content="2014-11-12">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Interface
com.hazelcast.nio.serialization.DataSerializableFactory

Packages that use DataSerializableFactory

Package
Description

com.hazelcast.cache.impl

     Hazelcast JSR-107 aka JCache implementation

com.hazelcast.client.impl

Implementation classes of the com.hazelcast.client interfaces

com.hazelcast.cluster

This package contains the cluster functionality.

com.hazelcast.collection

This package contains classes related to Collections (IList,ISet etc..)

com.hazelcast.concurrent.atomiclong

This package contains IAtomicLong functionality for Hazelcast.

 The IAtomicLong is the distributed version of the AtomicLong.

com.hazelcast.concurrent.atomicreference

This package contains IAtomicReferece functionality for Hazelcast.

 The IAtomicReference is the distributed version of the AtomicReference.

com.hazelcast.concurrent.countdownlatch

This package contains ICountDownLatch functionality for Hazelcast.

 The ICountDownLatch is the distributed version of the CountDownLatch.

com.hazelcast.concurrent.lock

This package contains Lock for Hazelcast.

 The ILock is the distributed version of the Lock.

com.hazelcast.concurrent.semaphore

This package contains ISemaphore functionality for Hazelcast.

 The ISemaphore is the distributed version of the Semaphore.

com.hazelcast.config

Provides classes for configuring HazelcastInstance.

com.hazelcast.executor.impl

This package contains IExecutorService functionality for Hazelcast.

 The IExecutorService extends the ExecutorService and provides all kinds
 of additional methods related to distributed systems.

com.hazelcast.map

Contains Hazelcast map module classes.

com.hazelcast.mapreduce.aggregation.impl

This package contains a set of predefined aggregation implementations

com.hazelcast.mapreduce.impl

This package contains the default implementation for the map reduce framework
 internals.

com.hazelcast.multimap.impl

Contains classes for Hazelcast MultiMap module.

com.hazelcast.nio.serialization

Contains interfaces/classes related to serialization;
 such as serializer interfaces, input/output streams.

com.hazelcast.partition

Contains the partition logic for Hazelcast.

com.hazelcast.queue.impl

This package contains the IQueue functionality.

 The IQueue is the distributed version of the BlockingQueue.

com.hazelcast.replicatedmap.impl.operation

This package contains some remote operations to execute on remote nodes

com.hazelcast.spi.impl

Contains implementations for Hazelcast SPI.

com.hazelcast.topic.impl

This package contains ITopic functionality for Hazelcast.

 With the ITopic it is possible to create publish subscribe solutions similar to JMS Topics.

com.hazelcast.web

Provides Hazelcast-based session replication.

Uses of DataSerializableFactory in com.hazelcast.cache.impl

Methods in com.hazelcast.cache.impl that return DataSerializableFactory

Modifier and Type
Method and Description

DataSerializableFactory
CacheDataSerializerHook.createFactory()

Uses of DataSerializableFactory in com.hazelcast.client.impl

Methods in com.hazelcast.client.impl that return DataSerializableFactory

Modifier and Type
Method and Description

DataSerializableFactory
ClientDataSerializerHook.createFactory()

Uses of DataSerializableFactory in com.hazelcast.cluster

Methods in com.hazelcast.cluster that return DataSerializableFactory

Modifier and Type
Method and Description

DataSerializableFactory
ClusterDataSerializerHook.createFactory()

Uses of DataSerializableFactory in com.hazelcast.collection

Methods in com.hazelcast.collection that return DataSerializableFactory

Modifier and Type
Method and Description

DataSerializableFactory
CollectionDataSerializerHook.createFactory()

Uses of DataSerializableFactory in com.hazelcast.concurrent.atomiclong

Methods in com.hazelcast.concurrent.atomiclong that return DataSerializableFactory

Modifier and Type
Method and Description

DataSerializableFactory
AtomicLongDataSerializerHook.createFactory()

Uses of DataSerializableFactory in com.hazelcast.concurrent.atomicreference

Methods in com.hazelcast.concurrent.atomicreference that return DataSerializableFactory

Modifier and Type
Method and Description

DataSerializableFactory
AtomicReferenceDataSerializerHook.createFactory()

Uses of DataSerializableFactory in com.hazelcast.concurrent.countdownlatch

Methods in com.hazelcast.concurrent.countdownlatch that return DataSerializableFactory

Modifier and Type
Method and Description

DataSerializableFactory
CountDownLatchDataSerializerHook.createFactory()

Uses of DataSerializableFactory in com.hazelcast.concurrent.lock

Methods in com.hazelcast.concurrent.lock that return DataSerializableFactory

Modifier and Type
Method and Description

DataSerializableFactory
LockDataSerializerHook.createFactory()

Uses of DataSerializableFactory in com.hazelcast.concurrent.semaphore

Methods in com.hazelcast.concurrent.semaphore that return DataSerializableFactory

Modifier and Type
Method and Description

DataSerializableFactory
SemaphoreDataSerializerHook.createFactory()

Uses of DataSerializableFactory in com.hazelcast.config

Methods in com.hazelcast.config that return types with arguments of type DataSerializableFactory

Modifier and Type
Method and Description

Map<Integer,DataSerializableFactory>
SerializationConfig.getDataSerializableFactories()

Methods in com.hazelcast.config with parameters of type DataSerializableFactory

Modifier and Type
Method and Description

SerializationConfig
SerializationConfig.addDataSerializableFactory(int factoryId,
                          DataSerializableFactory dataSerializableFactory)

Method parameters in com.hazelcast.config with type arguments of type DataSerializableFactory

Modifier and Type
Method and Description

SerializationConfig
SerializationConfig.addDataSerializableFactoryClass(int factoryId,
                               Class<? extends DataSerializableFactory> dataSerializableFactoryClass)

SerializationConfig
SerializationConfig.setDataSerializableFactories(Map<Integer,DataSerializableFactory> dataSerializableFactories)

Uses of DataSerializableFactory in com.hazelcast.executor.impl

Methods in com.hazelcast.executor.impl that return DataSerializableFactory

Modifier and Type
Method and Description

DataSerializableFactory
ExecutorDataSerializerHook.createFactory()

Uses of DataSerializableFactory in com.hazelcast.map

Methods in com.hazelcast.map that return DataSerializableFactory

Modifier and Type
Method and Description

DataSerializableFactory
MapDataSerializerHook.createFactory()

Uses of DataSerializableFactory in com.hazelcast.mapreduce.aggregation.impl

Methods in com.hazelcast.mapreduce.aggregation.impl that return DataSerializableFactory

Modifier and Type
Method and Description

DataSerializableFactory
AggregationsDataSerializerHook.createFactory()

Uses of DataSerializableFactory in com.hazelcast.mapreduce.impl

Methods in com.hazelcast.mapreduce.impl that return DataSerializableFactory

Modifier and Type
Method and Description

DataSerializableFactory
MapReduceDataSerializerHook.createFactory()

Uses of DataSerializableFactory in com.hazelcast.multimap.impl

Methods in com.hazelcast.multimap.impl that return DataSerializableFactory

Modifier and Type
Method and Description

DataSerializableFactory
MultiMapDataSerializerHook.createFactory()

Uses of DataSerializableFactory in com.hazelcast.nio.serialization

Classes in com.hazelcast.nio.serialization that implement DataSerializableFactory

Modifier and Type
Class and Description

class
ArrayDataSerializableFactory

Methods in com.hazelcast.nio.serialization that return DataSerializableFactory

Modifier and Type
Method and Description

DataSerializableFactory
DataSerializerHook.createFactory()

Methods in com.hazelcast.nio.serialization with parameters of type DataSerializableFactory

Modifier and Type
Method and Description

SerializationServiceBuilder
SerializationServiceBuilder.addDataSerializableFactory(int id,
                          DataSerializableFactory factory)

Uses of DataSerializableFactory in com.hazelcast.partition

Methods in com.hazelcast.partition that return DataSerializableFactory

Modifier and Type
Method and Description

DataSerializableFactory
PartitionDataSerializerHook.createFactory()

Uses of DataSerializableFactory in com.hazelcast.queue.impl

Methods in com.hazelcast.queue.impl that return DataSerializableFactory

Modifier and Type
Method and Description

DataSerializableFactory
QueueDataSerializerHook.createFactory()

Uses of DataSerializableFactory in com.hazelcast.replicatedmap.impl.operation

Methods in com.hazelcast.replicatedmap.impl.operation that return DataSerializableFactory

Modifier and Type
Method and Description

DataSerializableFactory
ReplicatedMapDataSerializerHook.createFactory()

Uses of DataSerializableFactory in com.hazelcast.spi.impl

Methods in com.hazelcast.spi.impl that return DataSerializableFactory

Modifier and Type
Method and Description

DataSerializableFactory
SpiDataSerializerHook.createFactory()

Uses of DataSerializableFactory in com.hazelcast.topic.impl

Methods in com.hazelcast.topic.impl that return DataSerializableFactory

Modifier and Type
Method and Description

DataSerializableFactory
TopicDataSerializerHook.createFactory()

Uses of DataSerializableFactory in com.hazelcast.web

Methods in com.hazelcast.web that return DataSerializableFactory

Modifier and Type
Method and Description

DataSerializableFactory
WebDataSerializerHook.createFactory()

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2014 Hazelcast, Inc.. All Rights Reserved.


text:
namespace HanRuEdu.LDAL
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;

    [MetadataType(typeof(EDU_ZDGL_02_WXDM_metadata))]
    public partial class EDU_ZDGL_02_WXDM
    {
        public EDU_ZDGL_02_WXDM()
        {
            WXDM = "";
            WXNR = "";
            WXJG = "";
        }
        public class EDU_ZDGL_02_WXDM_metadata
        {
            [Required(ErrorMessage = "±ØÌî")]
            [Display(Name = "񅧏")]
            public Int32 ID { get; set; }

            [Required(ErrorMessage = "±ØÌî",AllowEmptyStrings = true)]
            [Display(Name = "άÐÞ´úÂë")]
            [StringLength(200)]
            [DisplayFormat(ConvertEmptyStringToNull = false)]
            public String WXDM { get; set; }

            [Required(ErrorMessage = "±ØÌî",AllowEmptyStrings = true)]
            [Display(Name = "άÐÞÄÚÈÝ")]
            [StringLength(500)]
            [DisplayFormat(ConvertEmptyStringToNull = false)]
            public String WXNR { get; set; }

            [Required(ErrorMessage = "±ØÌî",AllowEmptyStrings = true)]
            [Display(Name = "άÐÞ½á¹û")]
            [StringLength(500)]
            [DisplayFormat(ConvertEmptyStringToNull = false)]
            public String WXJG { get; set; }

        }
    }
}


text:
package com.facebook.buck.versions;

import com.facebook.buck.core.cell.Cells;
import com.facebook.buck.core.cell.nameresolver.CellNameResolver;
import com.facebook.buck.core.description.arg.ConstructorArg;
import com.facebook.buck.core.model.BaseName;
import com.facebook.buck.core.model.BuildTarget;
import com.facebook.buck.core.model.targetgraph.TargetNode;
import com.facebook.buck.core.sourcepath.DefaultBuildTargetSourcePath;
import com.facebook.buck.core.sourcepath.SourcePath;
import com.facebook.buck.core.sourcepath.SourceWithFlags;
import com.facebook.buck.rules.coercer.DataTransferObjectDescriptor;
import com.facebook.buck.rules.coercer.ParamInfo;
import com.facebook.buck.rules.coercer.TypeCoercerFactory;
import com.facebook.buck.util.types.Pair;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedMap;
import com.google.common.collect.ImmutableSortedSet;
import java.util.Map;
import java.util.Optional;

/**
 * A helper class which uses reflection to translate {@link BuildTarget}s in {@link TargetNode}s.
 * The API methods use an {@link Optional} for their return types, so that {@link Optional#empty()}
 * can be used to signify a translation was not needed. This may allow some translation functions to
 * avoid copying or creating unnecessary new objects.
 */
public abstract class TargetNodeTranslator {

  private final TypeCoercerFactory typeCoercerFactory;
  // Translators registered for various types.
  private final ImmutableList<TargetTranslator<?>> translators;
  private final Cells cells;

  public TargetNodeTranslator(
      TypeCoercerFactory typeCoercerFactory,
      ImmutableList<TargetTranslator<?>> translators,
      Cells cells) {

    this.typeCoercerFactory = typeCoercerFactory;
    this.translators = translators;
    this.cells = cells;
  }

  public abstract Optional<BuildTarget> translateBuildTarget(BuildTarget target);

  public abstract Optional<ImmutableMap<BuildTarget, Version>> getSelectedVersions(
      BuildTarget target);

  private <A> Optional<Optional<A>> translateOptional(
      CellNameResolver cellNameResolver, BaseName targetBaseName, Optional<A> val) {
    if (!val.isPresent()) {
      return Optional.empty();
    }
    Optional<A> inner = translate(cellNameResolver, targetBaseName, val.get());
    if (!inner.isPresent()) {
      return Optional.empty();
    }
    return Optional.of(inner);
  }

  private <A> Optional<ImmutableList<A>> translateList(
      CellNameResolver cellNameResolver, BaseName targetBaseName, ImmutableList<A> val) {
    boolean modified = false;
    ImmutableList.Builder<A> builder = ImmutableList.builder();
    for (A a : val) {
      Optional<A> item = translate(cellNameResolver, targetBaseName, a);
      modified = modified || item.isPresent();
      builder.add(item.orElse(a));
    }
    return modified ? Optional.of(builder.build()) : Optional.empty();
  }

  private <A> Optional<ImmutableSet<A>> translateSet(
      CellNameResolver cellNameResolver, BaseName targetBaseName, ImmutableSet<A> val) {
    boolean modified = false;
    ImmutableSet.Builder<A> builder = ImmutableSet.builder();
    for (A a : val) {
      Optional<A> item = translate(cellNameResolver, targetBaseName, a);
      modified = modified || item.isPresent();
      builder.add(item.orElse(a));
    }
    return modified ? Optional.of(builder.build()) : Optional.empty();
  }

  private <A extends Comparable<?>> Optional<ImmutableSortedSet<A>> translateSortedSet(
      CellNameResolver cellNameResolver, BaseName targetBaseName, ImmutableSortedSet<A> val) {
    boolean modified = false;
    ImmutableSortedSet.Builder<A> builder = ImmutableSortedSet.naturalOrder();
    for (A a : val) {
      Optional<A> item = translate(cellNameResolver, targetBaseName, a);
      modified = modified || item.isPresent();
      builder.add(item.orElse(a));
    }
    return modified ? Optional.of(builder.build()) : Optional.empty();
  }

  private <A extends Comparable<?>, B> Optional<ImmutableMap<A, B>> translateMap(
      CellNameResolver cellNameResolver, BaseName targetBaseName, ImmutableMap<A, B> val) {
    boolean modified = false;
    ImmutableMap.Builder<A, B> builder = ImmutableMap.builder();
    for (Map.Entry<A, B> ent : val.entrySet()) {
      Optional<A> key = translate(cellNameResolver, targetBaseName, ent.getKey());
      Optional<B> value = translate(cellNameResolver, targetBaseName, ent.getValue());
      modified = modified || key.isPresent() || value.isPresent();
      builder.put(key.orElse(ent.getKey()), value.orElse(ent.getValue()));
    }
    return modified ? Optional.of(builder.build()) : Optional.empty();
  }

  private <A extends Comparable<?>, B> Optional<ImmutableSortedMap<A, B>> translateSortedMap(
      CellNameResolver cellNameResolver, BaseName targetBaseName, ImmutableSortedMap<A, B> val) {
    boolean modified = false;
    ImmutableSortedMap.Builder<A, B> builder = ImmutableSortedMap.naturalOrder();
    for (Map.Entry<A, B> ent : val.entrySet()) {
      Optional<A> key = translate(cellNameResolver, targetBaseName, ent.getKey());
      Optional<B> value = translate(cellNameResolver, targetBaseName, ent.getValue());
      modified = modified || key.isPresent() || value.isPresent();
      builder.put(key.orElse(ent.getKey()), value.orElse(ent.getValue()));
    }
    return modified ? Optional.of(builder.build()) : Optional.empty();
  }

  @VisibleForTesting
  <A, B> Optional<Pair<A, B>> translatePair(
      CellNameResolver cellNameResolver, BaseName targetBaseName, Pair<A, B> val) {
    Optional<A> first = translate(cellNameResolver, targetBaseName, val.getFirst());
    Optional<B> second = translate(cellNameResolver, targetBaseName, val.getSecond());
    if (!first.isPresent() && !second.isPresent()) {
      return Optional.empty();
    }
    return Optional.of(new Pair<>(first.orElse(val.getFirst()), second.orElse(val.getSecond())));
  }

  @VisibleForTesting
  Optional<DefaultBuildTargetSourcePath> translateBuildTargetSourcePath(
      CellNameResolver cellNameResolver,
      BaseName targetBaseName,
      DefaultBuildTargetSourcePath val) {
    BuildTarget target = val.getTarget();
    Optional<BuildTarget> translatedTarget = translate(cellNameResolver, targetBaseName, target);
    return translatedTarget.map(DefaultBuildTargetSourcePath::of);
  }

  @VisibleForTesting
  Optional<SourceWithFlags> translateSourceWithFlags(
      CellNameResolver cellNameResolver, BaseName targetBaseName, SourceWithFlags val) {
    Optional<SourcePath> translatedSourcePath =
        translate(cellNameResolver, targetBaseName, val.getSourcePath());
    return translatedSourcePath.map(sourcePath -> SourceWithFlags.of(sourcePath, val.getFlags()));
  }

  @SuppressWarnings("unchecked")
  private <A, T> Optional<Optional<T>> tryTranslate(
      CellNameResolver cellPathResolver,
      BaseName targetBaseName,
      TargetTranslator<A> translator,
      T object) {
    Class<A> clazz = translator.getTranslatableClass();
    if (!clazz.isAssignableFrom(object.getClass())) {
      return Optional.empty();
    }
    return Optional.of(
        (Optional<T>)
            translator.translateTargets(cellPathResolver, targetBaseName, this, (A) object));
  }

  @SuppressWarnings("unchecked")
  public <A> Optional<A> translate(
      CellNameResolver cellNameResolver, BaseName targetBaseName, A object) {

    // `null`s require no translating.
    if (object == null) {
      return Optional.empty();
    }

    // First try all registered translators.
    for (TargetTranslator<?> translator : translators) {
      if (translator.getTranslatableClass().isAssignableFrom(object.getClass())) {
        Optional<Optional<A>> translated =
            tryTranslate(cellNameResolver, targetBaseName, translator, object);
        if (translated.isPresent()) {
          return translated.get();
        }
      }
    }

    if (object instanceof Optional) {
      return (Optional<A>)
          translateOptional(cellNameResolver, targetBaseName, (Optional<?>) object);
    } else if (object instanceof ImmutableList) {
      return (Optional<A>)
          translateList(cellNameResolver, targetBaseName, (ImmutableList<?>) object);
    } else if (object instanceof ImmutableSortedSet) {
      return (Optional<A>)
          translateSortedSet(
              cellNameResolver,
              targetBaseName,
              (ImmutableSortedSet<? extends Comparable<?>>) object);
    } else if (object instanceof ImmutableSet) {
      return (Optional<A>) translateSet(cellNameResolver, targetBaseName, (ImmutableSet<?>) object);
    } else if (object instanceof ImmutableSortedMap) {
      return (Optional<A>)
          translateSortedMap(
              cellNameResolver,
              targetBaseName,
              (ImmutableSortedMap<? extends Comparable<?>, ?>) object);
    } else if (object instanceof ImmutableMap) {
      return (Optional<A>)
          translateMap(
              cellNameResolver, targetBaseName, (ImmutableMap<? extends Comparable<?>, ?>) object);
    } else if (object instanceof Pair) {
      return (Optional<A>) translatePair(cellNameResolver, targetBaseName, (Pair<?, ?>) object);
    } else if (object instanceof DefaultBuildTargetSourcePath) {
      return (Optional<A>)
          translateBuildTargetSourcePath(
              cellNameResolver, targetBaseName, (DefaultBuildTargetSourcePath) object);
    } else if (object instanceof SourceWithFlags) {
      return (Optional<A>)
          translateSourceWithFlags(cellNameResolver, targetBaseName, (SourceWithFlags) object);
    } else if (object instanceof BuildTarget) {
      return (Optional<A>) translateBuildTarget((BuildTarget) object);
    } else if (object instanceof TargetTranslatable) {
      TargetTranslatable<A> targetTranslatable = (TargetTranslatable<A>) object;
      return targetTranslatable.translateTargets(cellNameResolver, targetBaseName, this);
    } else {
      return Optional.empty();
    }
  }

  private boolean translateConstructorArg(
      CellNameResolver cellNameResolver,
      BaseName targetBaseName,
      ConstructorArg constructorArg,
      Object newConstructorArgOrBuilder) {
    boolean modified = false;

    for (ParamInfo<?> param :
        typeCoercerFactory
            .getConstructorArgDescriptor(constructorArg.getClass())
            .getParamInfos()
            .values()) {
      Object value = param.get(constructorArg);
      Optional<Object> newValue = translate(cellNameResolver, targetBaseName, value);
      modified |= newValue.isPresent();
      param.setCoercedValue(newConstructorArgOrBuilder, newValue.orElse(value));
    }
    return modified;
  }

  private <A extends ConstructorArg> Optional<A> translateConstructorArg(
      BaseName targetBaseName, TargetNode<A> node) {
    CellNameResolver cellNameResolver =
        cells.getCell(node.getBuildTarget().getCell()).getCellNameResolver();

    A constructorArg = node.getConstructorArg();
    DataTransferObjectDescriptor<A> newArgAndBuild =
        typeCoercerFactory.getConstructorArgDescriptor(
            node.getDescription().getConstructorArgType());
    Object builder = newArgAndBuild.getBuilderFactory().get();
    boolean modified =
        translateConstructorArg(cellNameResolver, targetBaseName, constructorArg, builder);
    if (!modified) {
      return Optional.empty();
    }
    return Optional.of(newArgAndBuild.build(builder, node.getBuildTarget()));
  }

  /**
   * @return a copy of the given {@link TargetNode} with all found {@link BuildTarget}s translated,
   *     or {@link Optional#empty()} if the node requires no translation.
   */
  public <A extends ConstructorArg> Optional<TargetNode<A>> translateNode(TargetNode<A> node) {
    CellNameResolver cellNameResolver =
        cells.getCell(node.getBuildTarget().getCell()).getCellNameResolver();

    BaseName targetBaseName = node.getBuildTarget().getBaseName();

    Optional<BuildTarget> target = translateBuildTarget(node.getBuildTarget());
    Optional<A> constructorArg = translateConstructorArg(targetBaseName, node);
    Optional<ImmutableSet<BuildTarget>> declaredDeps =
        translateSet(cellNameResolver, targetBaseName, node.getDeclaredDeps());
    Optional<ImmutableSortedSet<BuildTarget>> extraDeps =
        translateSortedSet(cellNameResolver, targetBaseName, node.getExtraDeps());
    Optional<ImmutableSortedSet<BuildTarget>> targetGraphOnlyDeps =
        translateSortedSet(cellNameResolver, targetBaseName, node.getTargetGraphOnlyDeps());

    Optional<ImmutableMap<BuildTarget, Version>> newSelectedVersions =
        getSelectedVersions(node.getBuildTarget());
    Optional<ImmutableMap<BuildTarget, Version>> oldSelectedVersions = node.getSelectedVersions();
    Optional<Optional<ImmutableMap<BuildTarget, Version>>> selectedVersions =
        oldSelectedVersions.equals(newSelectedVersions)
            ? Optional.empty()
            : Optional.of(newSelectedVersions);

    // If nothing has changed, don't generate a new node.
    if (!target.isPresent()
        && !constructorArg.isPresent()
        && !declaredDeps.isPresent()
        && !extraDeps.isPresent()
        && !targetGraphOnlyDeps.isPresent()
        && !selectedVersions.isPresent()) {
      return Optional.empty();
    }

    return Optional.of(
        node.withBuildTarget(target.orElse(node.getBuildTarget()))
            .withConstructorArg(constructorArg.orElse(node.getConstructorArg()))
            .withDeclaredDeps(declaredDeps.orElse(node.getDeclaredDeps()))
            .withExtraDeps(extraDeps.orElse(node.getExtraDeps()))
            .withTargetGraphOnlyDeps(targetGraphOnlyDeps.orElse(node.getTargetGraphOnlyDeps()))
            .withSelectedVersions(selectedVersions.orElse(oldSelectedVersions)));
  }
}


text:
import qumulo.lib.request as request
from qumulo.lib.uri import UriBuilder

@request.request
def disks_status_get(conninfo, credentials):
    method = "GET"
    uri = "/v1/debug/disks/"

    return request.rest_request(conninfo, credentials, method, uri)

@request.request
def set_error_threshold(conninfo, credentials, threshold):
    body = {'threshold': threshold}
    method = "POST"
    uri = str(UriBuilder(path="/v1/debug/disks/set-error-threshold"))

    return request.rest_request(conninfo, credentials, method, uri, body=body)


text:
package com.intellij.execution.junit;

import com.intellij.execution.ExecutionBundle;
import com.intellij.execution.Location;
import com.intellij.execution.actions.ConfigurationContext;
import com.intellij.execution.junit2.PsiMemberParameterizedLocation;
import com.intellij.execution.junit2.info.MethodLocation;
import com.intellij.ide.util.PsiClassListCellRenderer;
import com.intellij.openapi.actionSystem.PlatformCoreDataKeys;
import com.intellij.openapi.application.ReadAction;
import com.intellij.openapi.compiler.JavaCompilerBundle;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.fileEditor.FileEditor;
import com.intellij.openapi.fileEditor.TextEditor;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.util.Condition;
import com.intellij.psi.*;
import com.intellij.psi.search.searches.ClassInheritorsSearch;
import com.intellij.psi.util.PsiClassUtil;
import com.intellij.ui.ColoredListCellRenderer;
import com.intellij.util.ArrayUtil;
import com.intellij.util.ui.JBUI;

import javax.swing.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;

import static com.intellij.util.PopupUtilsKt.getBestPopupPosition;

public class InheritorChooser {

  protected void runForClasses(final List<PsiClass> classes, final PsiMethod method, final ConfigurationContext context, final Runnable performRunnable) {
    performRunnable.run();
  }

  protected void runForClass(final PsiClass aClass, final PsiMethod psiMethod, final ConfigurationContext context, final Runnable performRunnable) {
    performRunnable.run();
  }

  public boolean runMethodInAbstractClass(final ConfigurationContext context,
                                          final Runnable performRunnable,
                                          final PsiMethod psiMethod,
                                          final PsiClass containingClass) {
    return runMethodInAbstractClass(context, performRunnable, psiMethod, containingClass,
                                    psiClass -> psiClass.hasModifierProperty(PsiModifier.ABSTRACT));
  }

  public boolean runMethodInAbstractClass(final ConfigurationContext context,
                                          final Runnable performRunnable,
                                          final PsiMethod psiMethod,
                                          final PsiClass containingClass,
                                          final Condition<? super PsiClass> acceptAbstractCondition) {
    if (containingClass != null && acceptAbstractCondition.value(containingClass)) {
      final Location location = context.getLocation();
      if (location instanceof MethodLocation) {
        final PsiClass aClass = ((MethodLocation)location).getContainingClass();
        if (aClass != null && !aClass.hasModifierProperty(PsiModifier.ABSTRACT)) {
          return false;
        }
      } else if (location instanceof PsiMemberParameterizedLocation) {
        return false;
      }

      final List<PsiClass> classes = new ArrayList<>();
      if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> {
        final boolean isJUnit5 = ReadAction.compute(() -> JUnitUtil.isJUnit5(containingClass));
        ClassInheritorsSearch.search(containingClass).forEach(aClass -> {
          if (isJUnit5 && JUnitUtil.isJUnit5TestClass(aClass, true) || PsiClassUtil.isRunnableClass(aClass, true, true)) {
            classes.add(aClass);
          }
          return true;
        });
      }, ExecutionBundle.message("search.for.0.inheritors", containingClass.getQualifiedName()), true, containingClass.getProject())) {
        return true;
      }

      if (classes.size() == 1) {
        runForClass(classes.get(0), psiMethod, context, performRunnable);
        return true;
      }
      if (classes.isEmpty()) return false;
      final FileEditor fileEditor = PlatformCoreDataKeys.FILE_EDITOR.getData(context.getDataContext());
      if (fileEditor instanceof TextEditor) {
        final Document document = ((TextEditor)fileEditor).getEditor().getDocument();
        final PsiFile containingFile = PsiDocumentManager.getInstance(context.getProject()).getPsiFile(document);
        if (containingFile instanceof PsiClassOwner) {
          final List<PsiClass> psiClasses = new ArrayList<>(Arrays.asList(((PsiClassOwner)containingFile).getClasses()));
          psiClasses.retainAll(classes);
          if (psiClasses.size() == 1) {
            runForClass(psiClasses.get(0), psiMethod, context, performRunnable);
            return true;
          }
        }
      }
      final int numberOfInheritors = classes.size();
      final PsiClassListCellRenderer renderer = new PsiClassListCellRenderer() {
        @Override
        protected boolean customizeNonPsiElementLeftRenderer(ColoredListCellRenderer renderer,
                                                             JList list,
                                                             Object value,
                                                             int index,
                                                             boolean selected,
                                                             boolean hasFocus) {
          if (value == null) {
            renderer.append(JavaCompilerBundle.message("all.inheritors", numberOfInheritors));
            return true;
          }
          return super.customizeNonPsiElementLeftRenderer(renderer, list, value, index, selected, hasFocus);
        }
      };
      classes.sort(renderer.getComparator());

      //suggest to run all inherited tests
      classes.add(0, null);
      String locationName = psiMethod != null ? psiMethod.getName() : containingClass.getName();
      JBPopupFactory.getInstance()
        .createPopupChooserBuilder(classes)
        .setRenderer(renderer)
        .setTitle(ExecutionBundle.message("test.cases.choosing.popup.title", locationName))
        .setAutoselectOnMouseMove(false)
        .setNamerForFiltering(it -> it == null ? "" : it.getName())
        .setMovable(true)
        .setResizable(false)
        .setRequestFocus(true)
        .setMinSize(JBUI.size(270, 55))
        .setItemsChosenCallback((values) -> {
          if (values.isEmpty()) return;
          chooseAndPerform(values.toArray(), psiMethod, context, performRunnable, classes);
        })
        .createPopup()
        .show(getBestPopupPosition(context.getDataContext()));
      return true;
    }
    return false;
  }

  private void chooseAndPerform(Object[] values,
                                PsiMethod psiMethod,
                                ConfigurationContext context,
                                Runnable performRunnable,
                                List<PsiClass> classes) {
    classes.remove(null);
    if (values.length == 1) {
      final Object value = values[0];
      if (value instanceof PsiClass) {
        runForClass((PsiClass)value, psiMethod, context, performRunnable);
      }
      else {
        runForClasses(classes, psiMethod, context, performRunnable);
      }
      return;
    }
    if (ArrayUtil.contains(null, values)) {
      runForClasses(classes, psiMethod, context, performRunnable);
    }
    else {
      final List<PsiClass> selectedClasses = new ArrayList<>();
      for (Object value : values) {
        if (value instanceof PsiClass) {
          selectedClasses.add((PsiClass)value);
        }
      }
      runForClasses(selectedClasses, psiMethod, context, performRunnable);
    }
  }

  public static void chooseAbstractClassInheritors(final ConfigurationContext context,
                                                   final PsiClass psiClass,
                                                   final Consumer<List<PsiClass>> onClassesChosen) {
    InheritorChooser inheritorChooser = new InheritorChooser() {
      @Override
      protected void runForClasses(List<PsiClass> classes, PsiMethod method, ConfigurationContext context, Runnable performRunnable) {
        onClassesChosen.accept(classes);
      }

      @Override
      protected void runForClass(PsiClass aClass, PsiMethod psiMethod, ConfigurationContext context, Runnable performRunnable) {
        onClassesChosen.accept(List.of(aClass));
      }
    };
    if (!inheritorChooser.runMethodInAbstractClass(context, () -> {}, null, psiClass)) {
      onClassesChosen.accept(List.of(psiClass));
    }
  }
}


text:
#include "lapacke.h"
#include "lapacke_utils.h"

lapack_int LAPACKE_zsptrf( int matrix_order, char uplo, lapack_int n,
                           lapack_complex_double* ap, lapack_int* ipiv )
{
    if( matrix_order != LAPACK_COL_MAJOR && matrix_order != LAPACK_ROW_MAJOR ) {
        LAPACKE_xerbla( "LAPACKE_zsptrf", -1 );
        return -1;
    }
#ifndef LAPACK_DISABLE_NAN_CHECK
    /* Optionally check input matrices for NaNs */
    if( LAPACKE_zsp_nancheck( n, ap ) ) {
        return -4;
    }
#endif
    return LAPACKE_zsptrf_work( matrix_order, uplo, n, ap, ipiv );
}


text:
/**
 * Created by Assaf on 5/14/2016.
 */
angular.module('MaterialApp').constant('AUTH_EVENTS', {
  loginSuccess: 'auth-login-success',
  loginFailed: 'auth-login-failed',
  logoutSuccess: 'auth-logout-success',
  sessionTimeout: 'auth-session-timeout',
  notAuthenticated: 'auth-not-authenticated',
  notAuthorized: 'auth-not-authorized'
});


text:
package data

// error messages
const (
    nilEdgeList = "attempt to operate on a nil edge list"
)

type edgeList map[uint32]*Edge

func (m edgeList) add (e *Edge) {
    Assert (nilEdgeList, m != nil)
    Assert (nilEdge, e != nil)

    m[e.Id] = e
}

func (m edgeList) remove (e *Edge) {
    Assert (nilEdgeList, m != nil)
    Assert (nilEdge, e != nil)

    delete(m, e.Id)
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<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">
	<parent>
		<artifactId>schema-evolution</artifactId>
		<groupId>org.springframework.cloud.stream.schema</groupId>
		<version>1.0.0.BUILD-SNAPSHOT</version>
	</parent>
	<modelVersion>4.0.0</modelVersion>

	<artifactId>producer_v2</artifactId>
	<version>1.0.0.BUILD-SNAPSHOT</version>
	<dependencies>
		<dependency>
			<groupId>org.springframework.cloud.stream.schema</groupId>
			<artifactId>avro-codec</artifactId>
			<version>1.0.0.BUILD-SNAPSHOT</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-stream-binder-rabbit</artifactId>
		</dependency>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-math3</artifactId>
			<version>3.6</version>
			<scope>test</scope>
		</dependency>

	</dependencies>
	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.avro</groupId>
				<artifactId>avro-maven-plugin</artifactId>
				<version>${avro.version}</version>
				<executions>
					<execution>
						<phase>generate-sources</phase>
						<goals>
							<goal>schema</goal>
							<goal>protocol</goal>
							<goal>idl-protocol</goal>
						</goals>
						<configuration>
							<sourceDirectory>src/main/avro</sourceDirectory>
						</configuration>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>

</project>


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".ListOfAllCounters" >

    <ListView
        android:id="@+id/oldCounter"
        android:layout_width="fill_parent"
        android:layout_height="match_parent"
        android:scrollbars="vertical" >
    </ListView>

</RelativeLayout>


text:
package gr.uom.java.ast.util;

import org.eclipse.jdt.core.dom.BreakStatement;
import org.eclipse.jdt.core.dom.ContinueStatement;
import org.eclipse.jdt.core.dom.ReturnStatement;
import org.eclipse.jdt.core.dom.Statement;

public class InstanceOfBranchingStatement implements StatementInstanceChecker {

	public boolean instanceOf(Statement statement) {
		if(statement instanceof BreakStatement || statement instanceof ContinueStatement || statement instanceof ReturnStatement)
			return true;
		else
			return false;
	}

}


text:
namespace Caliburn.PresentationFramework.RoutedMessaging
{
    using System;

    /// <summary>
    /// The outcome of processing a message.
    /// </summary>
    public class MessageProcessingOutcome
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="MessageProcessingOutcome"/> class.
        /// </summary>
        /// <param name="result">The result.</param>
        /// <param name="resultType">Type of the result.</param>
        /// <param name="wasCancelled">if set to <c>true</c> [was cancelled].</param>
        public MessageProcessingOutcome(object result, Type resultType, bool wasCancelled)
        {
            Result = result;
            ResultType = resultType;
            WasCancelled = wasCancelled;
        }

        /// <summary>
        /// Gets or sets a value indicating whether message processing was cancelled.
        /// </summary>
        /// <value><c>true</c> if cancelled; otherwise, <c>false</c>.</value>
        public bool WasCancelled { get; private set; }

        /// <summary>
        /// Gets or sets the type of the result.
        /// </summary>
        /// <value>The type of the result.</value>
        public Type ResultType { get; set; }

        /// <summary>
        /// Gets or sets the result.
        /// </summary>
        /// <value>The result.</value>
        public object Result { get; set; }
    }
}


text:
/**
 *
 */
package com.hsjawanda.gaeobjectify.collections;

import java.util.ListIterator;

import lombok.NonNull;

import com.googlecode.objectify.Ref;
import com.hsjawanda.gaeobjectify.data.GaeDataUtil;

/**
 * @author Harshdeep S Jawanda (hsjawanda@gmail.com)
 *
 * @param <E>
 */
public class RefsListIterator<E> implements ListIterator<E> {

	private ListIterator<Ref<E>> wrapped;

	RefsListIterator(@NonNull ListIterator<Ref<E>> toWrap) {
		this.wrapped = toWrap;
	}

	@Override
	public void add(E arg0) {
		Ref<E> ref = GaeDataUtil.getNullableRefFromPojo(arg0);
		if (null != ref) {
			this.wrapped.add(ref);
		}
	}

	@Override
	public boolean hasNext() {
		return this.wrapped.hasNext();
	}

	@Override
	public boolean hasPrevious() {
		return this.wrapped.hasPrevious();
	}

	@Override
	public E next() {
		Ref<E> ref = this.wrapped.next();
		return null != ref ? ref.get() : null;
	}

	@Override
	public int nextIndex() {
		return this.wrapped.nextIndex();
	}

	@Override
	public E previous() {
		Ref<E> ref = this.wrapped.previous();
		return null != ref ? ref.get() : null;
	}

	@Override
	public int previousIndex() {
		return this.wrapped.previousIndex();
	}

	@Override
	public void remove() {
		this.wrapped.remove();
	}

	@Override
	public void set(E arg0) {
		Ref<E> ref = GaeDataUtil.getNullableRefFromPojo(arg0);
		if (null != ref) {
			this.wrapped.set(ref);
		}
	}

}


text:
// CUDA-specific support for FFT functionality -- this wraps the cuFFT library
// capabilities, and is only included into CUDA implementation code -- it will
// not introduce cuda headers into other code.

#ifndef TENSORFLOW_STREAM_EXECUTOR_CUDA_CUDA_FFT_H_
#define TENSORFLOW_STREAM_EXECUTOR_CUDA_CUDA_FFT_H_

#include "third_party/gpus/cuda/include/cufft.h"
#include "tensorflow/stream_executor/fft.h"
#include "tensorflow/stream_executor/platform/port.h"
#include "tensorflow/stream_executor/plugin_registry.h"
#include "tensorflow/stream_executor/scratch_allocator.h"

namespace stream_executor {

class Stream;

namespace gpu {

class GpuExecutor;

// Opaque and unique indentifier for the cuFFT plugin.
extern const PluginId kCuFftPlugin;

// CUDAFftPlan uses deferred initialization. Only a single call of
// Initialize() is allowed to properly create cufft plan and set member
// variable is_initialized_ to true. Newly added interface that uses member
// variables should first check is_initialized_ to make sure that the values of
// member variables are valid.
class CUDAFftPlan : public fft::Plan {
 public:
  CUDAFftPlan()
      : parent_(nullptr),
        plan_(-1),
        fft_type_(fft::Type::kInvalid),
        scratch_(nullptr),
        scratch_size_bytes_(0),
        is_initialized_(false) {}
  ~CUDAFftPlan() override;

  // Get FFT direction in cuFFT based on FFT type.
  int GetFftDirection() const;
  cufftHandle GetPlan() const {
    if (IsInitialized()) {
      return plan_;
    } else {
      LOG(FATAL) << "Try to get cufftHandle value before initialization.";
    }
  }

  // Initialize function for batched plan
  port::Status Initialize(GpuExecutor* parent, Stream* stream, int rank,
                          uint64* elem_count, uint64* input_embed,
                          uint64 input_stride, uint64 input_distance,
                          uint64* output_embed, uint64 output_stride,
                          uint64 output_distance, fft::Type type,
                          int batch_count, ScratchAllocator* scratch_allocator);

  // Initialize function for 1d,2d, and 3d plan
  port::Status Initialize(GpuExecutor* parent, Stream* stream, int rank,
                          uint64* elem_count, fft::Type type,
                          ScratchAllocator* scratch_allocator);

  port::Status UpdateScratchAllocator(Stream *stream,
                                      ScratchAllocator *scratch_allocator);

 protected:
  bool IsInitialized() const { return is_initialized_; }

 private:
  GpuExecutor* parent_;
  cufftHandle plan_;
  fft::Type fft_type_;
  DeviceMemory<uint8> scratch_;
  size_t scratch_size_bytes_;
  bool is_initialized_;
};

// FFT support for CUDA platform via cuFFT library.
//
// This satisfies the platform-agnostic FftSupport interface.
//
// Note that the cuFFT handle that this encapsulates is implicitly tied to the
// context (and, as a result, the device) that the parent GpuExecutor is tied
// to. This simply happens as an artifact of creating the cuFFT handle when a
// CUDA context is active.
//
// Thread-safe. The CUDA context associated with all operations is the CUDA
// context of parent_, so all context is explicit.
class CUDAFft : public fft::FftSupport {
 public:
  explicit CUDAFft(GpuExecutor* parent) : parent_(parent) {}
  ~CUDAFft() override {}

  TENSORFLOW_STREAM_EXECUTOR_GPU_FFT_SUPPORT_OVERRIDES

 private:
  GpuExecutor* parent_;

  // Two helper functions that execute dynload::cufftExec?2?.

  // This is for complex to complex FFT, when the direction is required.
  template <typename FuncT, typename InputT, typename OutputT>
  bool DoFftWithDirectionInternal(Stream *stream, fft::Plan *plan,
                                  FuncT cufft_exec,
                                  const DeviceMemory<InputT> &input,
                                  DeviceMemory<OutputT> *output);

  // This is for complex to real or real to complex FFT, when the direction
  // is implied.
  template <typename FuncT, typename InputT, typename OutputT>
  bool DoFftInternal(Stream *stream, fft::Plan *plan, FuncT cufft_exec,
                     const DeviceMemory<InputT> &input,
                     DeviceMemory<OutputT> *output);

  SE_DISALLOW_COPY_AND_ASSIGN(CUDAFft);
};

}  // namespace gpu
}  // namespace stream_executor

#endif  // TENSORFLOW_STREAM_EXECUTOR_CUDA_CUDA_FFT_H_


text:
layout: page
title: Alpha Limited Seminar
date: 2016-05-24
author: Linda Aguirre
tags: weekly links, java
status: published
summary: Aliquam condimentum mollis est, ut tempor.
banner: images/banner/leisure-05.jpg
booking:
  startDate: 04/21/2018
  endDate: 04/25/2018
  ctyhocn: LAXACHX
  groupCode: ALS
published: true
---
Pellentesque ornare condimentum risus, non eleifend nisl finibus eget. Donec dapibus risus eu maximus ullamcorper. Suspendisse potenti. Pellentesque suscipit finibus nisl. Aliquam porta magna luctus tellus tristique pellentesque. Morbi iaculis metus eget felis gravida, at facilisis libero eleifend. Mauris sagittis tincidunt blandit. Vivamus ornare lobortis augue, bibendum laoreet tellus blandit et. Phasellus interdum tortor vitae dapibus malesuada. Quisque tempor nisi orci.

* Donec laoreet nisl vel urna dignissim dictum vitae quis arcu
* Proin vel enim et purus lobortis facilisis
* Cras at dui eget nibh bibendum facilisis
* Nunc non arcu ullamcorper, laoreet mi lobortis, aliquam sem
* Ut auctor mauris eu pellentesque tristique
* In sodales elit quis nulla molestie luctus.

Nunc ac neque risus. Vestibulum auctor, nibh id pellentesque fringilla, ligula turpis viverra nunc, id tincidunt lacus eros vel ex. Pellentesque ullamcorper quam nulla. Nullam cursus luctus ligula non venenatis. Donec eget nisi in felis tempor gravida quis eget lacus. Aliquam id tortor aliquet, interdum risus fermentum, feugiat mi. Duis ut sodales nisi. Aenean vehicula elit tortor. Nullam maximus, elit eu tincidunt semper, risus nunc malesuada ligula, sed consectetur diam nibh vel quam. Integer massa diam, malesuada sed vehicula id, auctor ut libero. Aliquam sollicitudin, enim nec pellentesque tempor, nulla nisl placerat risus, a aliquet neque enim tempus velit. Vivamus sit amet maximus tortor. Sed feugiat semper orci, porttitor tristique neque sagittis in. In laoreet leo ut est fermentum tempus et in dui.


text:
<?xml version="1.0" encoding="UTF-8"?>
<article id="75">
	<title>MEDLARS: Report on the Evaluation of Its Operating Efficiency	</title>
	<author>Lancaster, F.W.	</author>
	<text>
		   A comprehensive program to evaluate the performance of MEDLARS was conducted
		by the National Library of Medicine in 1966 and 1967.. This report describes
		the methodology used and presents a summary of the principal results,
		conclusions, and recommendations..
	</text>
</article>


text:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <size
        android:width="1px"
        android:height="85dp" />
    <solid android:color="@color/divider" />
</shape>


text:
namespace Gu.Reactive.Tests.NotifyCollectionChangedExt
{
    using System;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.Collections.Specialized;
    using Gu.Reactive.Tests.Helpers;
    using NUnit.Framework;

    public static class ObserveCollectionChangedSlim
    {
        [Test]
        public static void SignalsInitial()
        {
            var changes = new List<NotifyCollectionChangedEventArgs>();
            var source = new ObservableCollection<int>();
            var observable = source.ObserveCollectionChangedSlim(signalInitial: true);
            using (observable.Subscribe(changes.Add))
            {
                CollectionAssert.AreEqual(new[] { CachedEventArgs.NotifyCollectionReset }, changes);
            }

            CollectionAssert.AreEqual(new[] { CachedEventArgs.NotifyCollectionReset }, changes);
            var expected = new[] { CachedEventArgs.NotifyCollectionReset, CachedEventArgs.NotifyCollectionReset, };

            using (observable.Subscribe(changes.Add))
            {
                CollectionAssert.AreEqual(expected, changes);
            }

            CollectionAssert.AreEqual(expected, changes);
        }

        [Test]
        public static void DoesNotSignalInitial()
        {
            var changes = new List<NotifyCollectionChangedEventArgs>();
            var source = new ObservableCollection<int>();
            using (source.ObserveCollectionChangedSlim(signalInitial: false)
                         .Subscribe(changes.Add))
            {
                CollectionAssert.IsEmpty(changes);
            }
        }

        [Test]
        public static void Reacts()
        {
            var changes = new List<NotifyCollectionChangedEventArgs>();
            var source = new ObservableCollection<int>();
            using (source.ObserveCollectionChangedSlim(signalInitial: false)
                         .Subscribe(changes.Add))
            {
                source.Add(1);
                CollectionAssert.AreEqual(new[] { Diff.CreateAddEventArgs(1, 0) }, changes, EventArgsComparer.Default);
            }
        }
    }
}


text:
from RTSim import RTSim

class RTRobot(RTSim):
    """
    RTRobot Controller for RTSim real-time robot simulation.
    https://github.com/FJFranklin/wifi-py-rpi-car-controller/tree/master/RTSim
    """

    def __init__(self, seconds=180, test_name='default'):
        # usage: RTRobot (seconds, test_name)
        # where test_name is one of 'default', 'random', 'TNT', 'CWC' or 'BSB'

        # This is the Python version of the coursework 'Matlab Robot':
        # In the following line, replace the number with your Student ID
        id_number = 170000000;

        RTSim.__init__(self, seconds, test_name, id_number)

    def setup(self):
        # setup() is called once at the beginning

        self.target = self.get_target()       # where we're trying to get to

        # For example:
        self.last_ping_time = 0               # see ping_receive()
        self.last_ping_distance = -1

        # To work out which of the trials we're running:
        results_so_far = self.get_result()
        test_name = results_so_far['Trial']
        print('This trial is:', test_name)

    def loop(self):
        # loop() is called repeatedly

        # For example:
        currentTime = self.millis() / 1000

        self.position = self.get_GPS()        # roughly where we are
        self.orientation = self.get_compass() # which direction we're looking

        if currentTime > 4:
            self.ping_send()                  # it won't actually send more often than every 0.1s

        self.set_ping_angle(180)
        self.set_wheel_speeds(-127, -126)

    def ping_receive(self, distance):
        # response to an self.ping_send()

        # For example:
        self.last_ping_time = self.millis()  # the last time we received a ping [in milliseconds]
        self.last_ping_distance = distance   # distance measured (-ve if no echo)

        if distance >= 0:                    # a -ve distance implies nothing seen
            print('position=(', self.position[0], ',', self.position[1], '), orientation=', self.orientation, '; distance=', distance, sep='')

if __name__ == "__main__":
    # Option to run from command line

    import argparse

    parser = argparse.ArgumentParser(description="RTRobot Coursework - Guide a two-wheeled robot round the map.")

    parser.add_argument('--duration', help='How many seconds to run [40].', default=40, type=int)
    parser.add_argument('--trial',    help='Specify map type [default].',   default='default', choices=['default', 'random', 'TNT', 'CWC', 'BSB'])

    args = parser.parse_args()

    R = RTRobot(args.duration, args.trial)
    print(R.get_result())