text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
	Copyright (C) 2013-2016 Nanjing StarOS Technology Co., Ltd
	All rights reserved.

	@file 		staros_websocket_policy.xml
	@brief 		handle policy' data
	@version 	1.1.0
	@auth 		qiulei
	@date		2018/01/13

	Licensed under the Apache License, Version 2.0 (the "License");
	you may not use this file except in compliance with the License.
	You may obtain a copy of the License at

	http://www.apache.org/licenses/LICENSE-2.0

	Unless required by applicable law or agreed to in writing, software
	distributed under the License is distributed on an "AS IS" BASIS,
	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	See the License for the specific language governing permissions and
	limitations under the License.
-->
<starlang xmlns="http://www.staros.xyz/starcore/xml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" scope="application">
	<!--
		@brief		处理 policy 数据请求
		@auth 		qiulei
		@date		2018/01/13
		Input:
		Output:
	-->
	<function name="HandlePolicysRequest">
		<log level="100"><![CDATA[----staros_websocket_policy.xml 33行,enter HandlePolicysRequest]]></log>
		<string name="policyjson"/>
		<string name="outjson"/>

		<function name="GetAllPolicy" class="PolicyManager">
			<parameters>
				<string name="policystr" out="context.policyjson"/>
			</parameters>
		</function>
		<log level="100"><![CDATA[----staros_websocket_policy.xml 43行,<%=context.policyjson.toString()%>]]></log>
		<script><![CDATA[
				context.print("staros_websocket_policy.xml 44,policyjson="+context.policyjson.toString());
				var policyobj=JSON.parse(context.policyjson.toString());
				var jsonroot = new Object();
					jsonroot['event'] = "policyDataResponse";
					jsonroot['payload'] = policyobj;

				var strjson=JSON.stringify(jsonroot);
				context.print("----staros_websocket_policy.xml 51,strjson="+strjson);
				context.outjson.setValue(strjson);
			]]></script>

		<log level="100"><![CDATA[----staros_websocket_policy.xml 53行,execute HandlePolicysRequest over]]></log>
		<websocket name="restfulserver" method="SendText" transportid="event.getParam('transportid').toString()">
			<jsonsrc src="outjson"/>
		</websocket>
	</function>

	<!--qiulei 20180113  pm funcition:HandlePolicyDetailsRequest-->
	<function name="HandlePolicyDetailsRequest">
		<log level="100"><![CDATA[----staros_websocket_policy.xml 62行,enter HandlePolicyDetailsRequest]]></log>
		<string name="datapathid"/>
		<script><![CDATA[
			var info = JSON.parse(event.getParam('eventdata').toString());
			context.print("----staros_websocket_policy.xml  62 info="+info);
			var  dataid = info.payload.id;
			var final_id=dataid.split(":")[1];
			context.datapathid.setValue(final_id);
		]]></script>

		<string name="onepolicystr"/>
		<function name="GetPolicybyid" class="PolicyManager">
			<parameters>
				<string name="policyid" in="context.datapathid.toString()"/>
				<string name="onepolicystr" out="context.onepolicystr"/>
			</parameters>
		</function>

		<script><![CDATA[
			var policyobj=JSON.parse(context.onepolicystr.toString());
			var jsonroot = new Object();
				jsonroot['event'] = "policyDetailsResponse";
				jsonroot['payload'] = policyobj;

			var strjson=JSON.stringify(jsonroot);
			context.outjson.setValue(strjson);
		]]></script>

		<log level="100"><![CDATA[----staros_websocket_policy.xml 91行,execute HandlePolicyDetailsRequest over]]></log>
		<websocket name="restfulserver" method="SendText" transportid="event.getParam('transportid').toString()">
			<jsonsrc src="onepolicystr"/>
		</websocket>
	</function>
</starlang>


text:
(function (window, app, data) {

    'use strict';

	var myFT = new FT();
	var container = FT.query("#container");
	myFT.applyClickTag(container, 1);

})(window, window.app, window.data);

redpajama_set_name: RedPajamaGithub


text:
package org.pentaho.hadoop.mapreduce.converter.converters;

import org.apache.hadoop.io.Text;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.hadoop.mapreduce.converter.TypeConversionException;
import org.pentaho.hadoop.mapreduce.converter.TypeConverterFactory;
import org.pentaho.hadoop.mapreduce.converter.spi.ITypeConverter;

/**
 * Converts {@link Text} objects to {@link Long} objects
 */
public class TextToLongConverter implements ITypeConverter<Text, Long> {
  @Override
  public boolean canConvert( Class from, Class to ) {
    return Text.class.equals( from ) && Long.class.equals( to );
  }

  @Override
  public Long convert( ValueMetaInterface meta, Text obj ) throws TypeConversionException {
    try {
      return Long.parseLong( obj.toString() );
    } catch ( NumberFormatException ex ) {
      throw new TypeConversionException(
        BaseMessages.getString( TypeConverterFactory.class, "ErrorConverting", Long.class.getSimpleName(), obj ), ex );
    }
  }
}


text:
--TEST--
MongoDB\Driver\Manager::getEncryptedFieldsMap()
--FILE--
<?php

require_once __DIR__ . "/../utils/basic.inc";

/* autoEncryption requires keyVaultNamespace and a kmsProvider. Additionally,
 * disable mongocryptd spawning since it is not required for this test. */
$baseOptions = [
    'keyVaultNamespace' => CSFLE_KEY_VAULT_NS,
    'kmsProviders' => ['local' => ['key' => new MongoDB\BSON\Binary(CSFLE_LOCAL_KEY, 0)]],
    'extraOptions' => ['mongocryptdBypassSpawn' => true],
];

$encryptedFields = [
    'escCollection' => 'escCollectionName',
    'eccCollection' => 'eccCollectionName',
    'ecocCollection' => 'ecocCollectionName',
    'fields' => [
        [
            'path' => 'foo',
            'keyId' => new MongoDB\BSON\Binary(str_repeat('0', 16), MongoDB\BSON\Binary::TYPE_UUID),
            'bsonType' => 'string',
            'queries' => ['queryType' => 'equality'],
        ],
    ],
];

$tests = [
    [],
    ['autoEncryption' => $baseOptions],
    ['autoEncryption' => ['encryptedFieldsMap' => []] + $baseOptions],
    ['autoEncryption' => ['encryptedFieldsMap' => ['db.coll' => $encryptedFields]] + $baseOptions],
];

foreach ($tests as $i => $driverOptions) {
    $manager = create_test_manager(null, [], $driverOptions);
    var_dump($manager->getEncryptedFieldsMap());
}

?>
===DONE===
<?php exit(0); ?>
--EXPECTF--
NULL
NULL
array(0) {
}
array(1) {
  ["db.coll"]=>
  array(4) {
    ["escCollection"]=>
    string(17) "escCollectionName"
    ["eccCollection"]=>
    string(17) "eccCollectionName"
    ["ecocCollection"]=>
    string(18) "ecocCollectionName"
    ["fields"]=>
    array(1) {
      [0]=>
      array(4) {
        ["path"]=>
        string(3) "foo"
        ["keyId"]=>
        object(MongoDB\BSON\Binary)#%d (%d) {
          ["data"]=>
          string(16) "0000000000000000"
          ["type"]=>
          int(4)
        }
        ["bsonType"]=>
        string(6) "string"
        ["queries"]=>
        array(1) {
          ["queryType"]=>
          string(8) "equality"
        }
      }
    }
  }
}
===DONE===


text:
import * as http from 'http';
import * as p2pCommunication from 'p2pcommunication';
import { Query } from '../Query';

export default class RootServer<T extends { id: string }> {
  private server: p2pCommunication.RootServer<ReadonlyArray<Query<T>>>;
  private eventQueue: Query<T>[] = [];

  constructor(httpServer: http.Server) {
    this.server = new p2pCommunication.RootServer(httpServer);
    this.server.onConnected.subscribe((e) => {
      e.remotePeer.broadcast(this.eventQueue);
    });
  }

  pushAll(queries: ReadonlyArray<Query<T>>) {
    for (const query of queries) {
      this.eventQueue.push(query);
    }
    this.server.broadcast(queries);
  }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title></title>

    <base href="../..">

    <link href='https://fonts.googleapis.com/css?family=Source+Code+Pro|Roboto:500,400italic,300,400' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="static-assets/prettify.css">
    <link rel="stylesheet" href="static-assets/css/bootstrap.min.css">
    <link rel="stylesheet" href="static-assets/styles.css">

    <meta name="description" content="">
    <link rel="icon" href="static-assets/favicon.png">

            <button id="sidenav-left-toggle" type="button"> </button>

hetimatorrent

hetimatorrent

DDBitfield

DDBitfield

DDBitfield

hetimatorrent

hetimatorrent

DDBitfield

DDBitfield

constructor
 DDBitfield

hetimatorrent

hetimatorrent

DDBitfield

Properties

innerField

rawValue

value

Constructors

DDBitfield

Methods

change

getBinary

getIsOn

getOffPieceAtRandom

getOffPieceAtRandomPerByte

getOnPieceAtRandom

getOnPieceAtRandomPerByte

getPieceAtRandom

getPieceAtRandomPerByte

isAllOff

isAllOffPerByte

isAllOn

isAllOnPerByte

lengthPerBit

lengthPerByte

oneClear

setIsOn

update

writeBytes

zeroClear

                DDBitfield(

            Bitfield bitfield,
{int seed: null}

        )

Not documented.

                  hetimatorrent 0.0.1 api docs

                •

                •

                  cc license


text:
            @{{comment.in_Create[0].userId}}

                {{comment.createDate | timeago}}

        <button ng-if="comment.out_HasComment" class="fa-1x clear-square fa"
                ng-class="{'fa fa-minus': !collapsed, 'fa fa-plus': collapsed}"
                title="toggle children" ng-click="collapse()" style="float:right;"></button>

    <commenter action="submitComment" toggle="true"></commenter>


text:
import os
import re

from cinder.brick.iscsi import iscsi
from cinder import exception
from cinder.openstack.common.gettextutils import _
from cinder.openstack.common import log as logging
from cinder.openstack.common import processutils as putils
from cinder.volume import utils

LOG = logging.getLogger(__name__)

class _ExportMixin(object):

    def __init__(self, *args, **kwargs):
        self.db = kwargs.pop('db', None)
        super(_ExportMixin, self).__init__(*args, **kwargs)

    def create_export(self, context, volume, volume_path, conf):
        """Creates an export for a logical volume."""
        iscsi_name = "%s%s" % (conf.iscsi_target_prefix,
                               volume['name'])
        max_targets = conf.safe_get('iscsi_num_targets')
        (iscsi_target, lun) = self._get_target_and_lun(context,
                                                       volume,
                                                       max_targets)

        chap_username = utils.generate_username()
        chap_password = utils.generate_password()
        chap_auth = self._iscsi_authentication('IncomingUser',
                                               chap_username,
                                               chap_password)
        # NOTE(jdg): For TgtAdm case iscsi_name is the ONLY param we need
        # should clean this all up at some point in the future
        tid = self.create_iscsi_target(iscsi_name,
                                       iscsi_target,
                                       0,
                                       volume_path,
                                       chap_auth,
                                       write_cache=
                                       conf.iscsi_write_cache)
        data = {}
        data['location'] = self._iscsi_location(
            conf.iscsi_ip_address, tid, iscsi_name, conf.iscsi_port, lun)
        data['auth'] = self._iscsi_authentication(
            'CHAP', chap_username, chap_password)
        return data

    def remove_export(self, context, volume):
        try:
            iscsi_target = self._get_iscsi_target(context, volume['id'])
        except exception.NotFound:
            LOG.info(_("Skipping remove_export. No iscsi_target "
                       "provisioned for volume: %s"), volume['id'])
            return
        try:

            # NOTE: provider_location may be unset if the volume hasn't
            # been exported
            location = volume['provider_location'].split(' ')
            iqn = location[1]

            # ietadm show will exit with an error
            # this export has already been removed
            self.show_target(iscsi_target, iqn=iqn)

        except Exception:
            LOG.info(_("Skipping remove_export. No iscsi_target "
                       "is presently exported for volume: %s"), volume['id'])
            return

        self.remove_iscsi_target(iscsi_target, 0, volume['id'], volume['name'])

    def ensure_export(self, context, volume, iscsi_name, volume_path,
                      vg_name, conf, old_name=None):
        iscsi_target = self._get_target_for_ensure_export(context,
                                                          volume['id'])
        if iscsi_target is None:
            LOG.info(_("Skipping remove_export. No iscsi_target "
                       "provisioned for volume: %s"), volume['id'])
            return
        chap_auth = None
        # Check for https://bugs.launchpad.net/cinder/+bug/1065702
        old_name = None
        if (volume['provider_location'] is not None and
                volume['name'] not in volume['provider_location']):

            msg = _('Detected inconsistency in provider_location id')
            LOG.debug('%s', msg)
            old_name = self._fix_id_migration(context, volume)
            if 'in-use' in volume['status']:
                old_name = None
        self.create_iscsi_target(iscsi_name, iscsi_target, 0, volume_path,
                                 chap_auth, check_exit_code=False,
                                 old_name=old_name,
                                 write_cache=conf.iscsi_write_cache)

    def _ensure_iscsi_targets(self, context, host, max_targets):
        """Ensure that target ids have been created in datastore."""
        # NOTE(jdg): tgtadm doesn't use the iscsi_targets table
        # TODO(jdg): In the future move all of the dependent stuff into the
        # cooresponding target admin class
        host_iscsi_targets = self.db.iscsi_target_count_by_host(context,
                                                                host)
        if host_iscsi_targets >= max_targets:
            return

        # NOTE(vish): Target ids start at 1, not 0.
        target_end = max_targets + 1
        for target_num in xrange(1, target_end):
            target = {'host': host, 'target_num': target_num}
            self.db.iscsi_target_create_safe(context, target)

    def _get_target_for_ensure_export(self, context, volume_id):
        try:
            iscsi_target = self.db.volume_get_iscsi_target_num(context,
                                                               volume_id)
            return iscsi_target
        except exception.NotFound:
            return None

    def _get_target_and_lun(self, context, volume, max_targets):
        lun = 0
        self._ensure_iscsi_targets(context, volume['host'], max_targets)
        iscsi_target = self.db.volume_allocate_iscsi_target(context,
                                                            volume['id'],
                                                            volume['host'])
        return iscsi_target, lun

    def _get_iscsi_target(self, context, vol_id):
        return self.db.volume_get_iscsi_target_num(context, vol_id)

    def _iscsi_authentication(self, chap, name, password):
        return "%s %s %s" % (chap, name, password)

    def _iscsi_location(self, ip, target, iqn, port, lun=None):
        return "%s:%s,%s %s %s" % (ip, port,
                                   target, iqn, lun)

    def _fix_id_migration(self, context, volume, vg_name):
        """Fix provider_location and dev files to address bug 1065702.

        For volumes that the provider_location has NOT been updated
        and are not currently in-use we'll create a new iscsi target
        and remove the persist file.

        If the volume is in-use, we'll just stick with the old name
        and when detach is called we'll feed back into ensure_export
        again if necessary and fix things up then.

        Details at: https://bugs.launchpad.net/cinder/+bug/1065702
        """

        model_update = {}
        pattern = re.compile(r":|\s")
        fields = pattern.split(volume['provider_location'])
        old_name = fields[3]

        volume['provider_location'] = \
            volume['provider_location'].replace(old_name, volume['name'])
        model_update['provider_location'] = volume['provider_location']

        self.db.volume_update(context, volume['id'], model_update)

        start = os.getcwd()

        os.chdir('/dev/%s' % vg_name)

        try:
            (out, err) = self._execute('readlink', old_name)
        except putils.ProcessExecutionError:
            link_path = '/dev/%s/%s' % (vg_name,
                                        old_name)
            LOG.debug('Symbolic link %s not found' % link_path)
            os.chdir(start)
            return

        rel_path = out.rstrip()
        self._execute('ln',
                      '-s',
                      rel_path, volume['name'],
                      run_as_root=True)
        os.chdir(start)
        return old_name

class TgtAdm(_ExportMixin, iscsi.TgtAdm):

    def _get_target_and_lun(self, context, volume, max_targets):
        lun = 1  # For tgtadm the controller is lun 0, dev starts at lun 1
        iscsi_target = 0  # NOTE(jdg): Not used by tgtadm
        return iscsi_target, lun

    def _get_iscsi_target(self, context, vol_id):
        return 0

    def _get_target_for_ensure_export(self, context, volume_id):
        return 1

class FakeIscsiHelper(_ExportMixin, iscsi.FakeIscsiHelper):

    def create_export(self, context, volume, volume_path, conf):
        return {
            'location': "fake_location",
            'auth': "fake_auth"
        }

    def remove_export(self, context, volume):
        pass

    def ensure_export(self, context, volume, iscsi_name, volume_path,
                      vg_name, conf, old_name=None):
        pass

class LioAdm(_ExportMixin, iscsi.LioAdm):

    def remove_export(self, context, volume):
        try:
            iscsi_target = self.db.volume_get_iscsi_target_num(context,
                                                               volume['id'])
        except exception.NotFound:
            LOG.info(_("Skipping remove_export. No iscsi_target "
                       "provisioned for volume: %s"), volume['id'])
            return

        self.remove_iscsi_target(iscsi_target, 0, volume['id'], volume['name'])

    def ensure_export(self, context, volume, iscsi_name, volume_path,
                      vg_name, conf, old_name=None):
        try:
            volume_info = self.db.volume_get(context, volume['id'])
            (auth_method,
             auth_user,
             auth_pass) = volume_info['provider_auth'].split(' ', 3)
            chap_auth = self._iscsi_authentication(auth_method,
                                                   auth_user,
                                                   auth_pass)
        except exception.NotFound:
            LOG.debug("volume_info:%s", volume_info)
            LOG.info(_("Skipping ensure_export. No iscsi_target "
                       "provision for volume: %s"), volume['id'])

        iscsi_target = 1

        self.create_iscsi_target(iscsi_name, iscsi_target, 0, volume_path,
                                 chap_auth, check_exit_code=False)

class IetAdm(_ExportMixin, iscsi.IetAdm):
    pass

class ISERTgtAdm(_ExportMixin, iscsi.ISERTgtAdm):
    def _get_target_and_lun(self, context, volume, max_targets):
        lun = 1  # For tgtadm the controller is lun 0, dev starts at lun 1
        iscsi_target = 0  # NOTE(jdg): Not used by tgtadm
        return iscsi_target, lun

    def _get_iscsi_target(self, context, vol_id):
        return 0

    def _get_target_for_ensure_export(self, context, volume_id):
        return 1


text:
layout: event
sidebar: event
title: "Commemoration of the 50th anniversary of the assasination of Dr. Martin Luther King, Jr."
starts_at: "2018-04-04T18:00"
ends_at: "2018-04-04T21:00"
location: "Alverno College (3400 S 43rd St)"
organization: "Alverno College"
---

Gospel choir performance and community dinner with keynote speech about the value of Dr. King and his work and prophetic oratory.

This event is being produced by [Alverno College](https://www.alverno.edu).


text:
ECHO "START EXPORT"
SET cc="EG"
SET cn="NA Egypt"
node cuView.js --mode=CREATE --countryCode=%cc% --countryName=%cn% --entity=childPDB
node cuView.js --mode=CREATE --countryCode=%cc% --countryName=%cn% --entity=housePDB
ECHO "STOP EXPORT"


text:
Through excellent framework Slim, I decided to create annotations that can facilitate further.

For example usage, please see the demos directory.

To install, use the composer:
#####composer require jhonnytuba/slim-annotations


text:
using System;
using FluentNHibernate.Mapping;
using Streamus.Domain;

namespace Streamus.Dao.Mappings
{
    public class ShareCodeMapping : ClassMap<ShareCode>
    {
        public ShareCodeMapping()
        {
            Table("[ShareCodes]");

            Id(e => e.Id).GeneratedBy.GuidComb().UnsavedValue(Guid.Empty);

            //  Only update properties which have changed.
            DynamicUpdate();

            Map(e => e.EntityType).CustomType<ShareableEntityType>().Not.Nullable();
            Map(e => e.EntityId).Not.Nullable();
            Map(e => e.ShortId).Not.Nullable();
            Map(e => e.UrlFriendlyEntityTitle).Not.Nullable();
        }
    }
}


text:
int crypto_box(
  unsigned char *c,
  const unsigned char *m,unsigned long long mlen,
  const unsigned char *n,
  const unsigned char *pk,
  const unsigned char *sk
)
{
  unsigned char k[crypto_box_BEFORENMBYTES];
  crypto_box_beforenm(k,pk,sk);
  return crypto_box_afternm(c,m,mlen,n,k);
}

int crypto_box_open(
  unsigned char *m,
  const unsigned char *c,unsigned long long clen,
  const unsigned char *n,
  const unsigned char *pk,
  const unsigned char *sk
)
{
  unsigned char k[crypto_box_BEFORENMBYTES];
  crypto_box_beforenm(k,pk,sk);
  return crypto_box_open_afternm(m,c,clen,n,k);
}


text:
<?php

namespace PhpEws\DataType;

use PhpEws\DataType;

/**
 * Definition of the NonEmptyArrayOfResponseObjectsType type
 */
class NonEmptyArrayOfResponseObjectsType extends DataType
{
    /**
     * AcceptItem property
     *
     * @var AcceptItemType
     */
    public $AcceptItem;

    /**
     * TentativelyAcceptItem property
     *
     * @var TentativelyAcceptItemType
     */
    public $TentativelyAcceptItem;

    /**
     * DeclineItem property
     *
     * @var DeclineItemType
     */
    public $DeclineItem;

    /**
     * ReplyToItem property
     *
     * @var ReplyToItemType
     */
    public $ReplyToItem;

    /**
     * ForwardItem property
     *
     * @var ForwardItemType
     */
    public $ForwardItem;

    /**
     * ReplyAllToItem property
     *
     * @var ReplyAllToItemType
     */
    public $ReplyAllToItem;

    /**
     * CancelCalendarItem property
     *
     * @var CancelCalendarItemType
     */
    public $CancelCalendarItem;

    /**
     * RemoveItem property
     *
     * @var RemoveItemType
     */
    public $RemoveItem;

    /**
     * SuppressReadReceipt property
     *
     * @var SuppressReadReceiptType
     */
    public $SuppressReadReceipt;

    /**
     * PostReplyItem property
     *
     * @var PostReplyItemType
     */
    public $PostReplyItem;
}


text:
    <meta http-equiv="Content-Type" content="text/html; charset=Windows-1252" />
    <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5" />
    <title>IniConfig.Set Method</title>
    <xml>
    </xml>
    <link rel="stylesheet" type="text/css" href="MSDN.css" />

            Nini Library API Reference - http://nini.sourceforge.net/

IniConfig.Set Method

 Sets a key value. If the parent IniConfigSource has CaseSensitive turned on then this will set the value ignoring the case of the key name.

public override void Set(
   string key,
   object value
);

Parameters

          key

The key name.

          value

The key value

Implements

        IConfig.Set

See Also

        IniConfig Class | Nini.Config Namespace

      <object type="application/x-oleobject" classid="clsid:1e2a7bd0-dab9-11d0-b93a-00c04fc99f9e" viewastext="true" style="display: none;">
        <param name="Keyword" value="Set method">
        </param>
        <param name="Keyword" value="Set method, IniConfig class">
        </param>
        <param name="Keyword" value="IniConfig.Set method">
        </param>
      </object>

          Copyright (c) 2006 Brent R. Matzelle


text:
namespace Halley {
	class IProjectWindow;
	class ISceneEditorWindow;
	class IUISizer;
	class ComponentFieldParameters;
	class UIWidget;
	class IEntityEditor;
	class UIFactory;
	class IUIElement;
	class Resources;
	class String;
	class ConfigNode;

	enum class ComponentEditorLabelCreation {
		Always,
		Never,
		OnlyIfNested
	};

	class IEntityEditorCallbacks {
	public:
		virtual ~IEntityEditorCallbacks() = default;

		virtual void onEntityUpdated() = 0;
		virtual void reloadEntity() = 0;
		virtual void setTool(const String& tool, const String& componentName, const String& fieldName) = 0;
		virtual void setDefaultName(const String& name, const String& prevName) = 0;

		struct EntityInfo {
			String name;
			Sprite icon;
			UUID uuid;
		};

		virtual Vector<EntityInfo> getEntities() const { return {}; }
		virtual EntityInfo getEntityInfo(const UUID& uuid) const { return {}; }
		virtual void goToEntity(const UUID& uuid) {}
	};

	class IEntityEditor : public IEntityEditorCallbacks {
	public:
		virtual ~IEntityEditor() = default;

		virtual void addComponent(const String& name, ConfigNode data) = 0;
		virtual void deleteComponent(const String& name) = 0;
		virtual void onFieldChangedByGizmo(const String& componentName, const String& fieldName) = 0;
		virtual void onFieldChangedProcedurally(const String& componentName, const String& fieldName) = 0;
	};

	class IEntityEditorFactory {
	public:
		virtual ~IEntityEditorFactory() = default;

		virtual std::shared_ptr<IUIElement> makeLabel(const String& label) const = 0;
		virtual std::shared_ptr<IUIElement> makeField(const String& fieldType, ComponentFieldParameters parameters, ComponentEditorLabelCreation createLabel) const = 0;
		virtual ConfigNode getDefaultNode(const String& fieldType) const = 0;
	};

    class ComponentEditorContext {
    public:
	    ComponentEditorContext(IProjectWindow& projectWindow, IEntityEditorFactory& entityEditorFactory, IEntityEditorCallbacks* entityEditor, UIFactory& factory, Resources* gameResources);

        UIFactory& getUIFactory() const;
	    Resources& getGameResources() const;
		IProjectWindow& getProjectWindow() const;
        void onEntityUpdated() const;
	    void setTool(const String& tool, const String& componentName, const String& fieldName) const;

		std::shared_ptr<IUIElement> makeLabel(const String& label) const;
		std::shared_ptr<IUIElement> makeField(const String& fieldType, ComponentFieldParameters parameters, ComponentEditorLabelCreation createLabel) const;
    	ConfigNode getDefaultNode(const String& fieldType) const;
	    void setDefaultName(const String& name, const String& prevName) const;

		IEntityEditorCallbacks* getEntityEditorCallbacks() const;

    private:
		IProjectWindow& projectWindow;
    	IEntityEditorFactory* entityEditorFactory = nullptr;
        IEntityEditorCallbacks* entityEditor = nullptr;
        UIFactory* factory = nullptr;
        Resources* gameResources = nullptr;
    };
}


text:
package io.fabric8.certmanager.api.model.v1alpha2;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import io.fabric8.kubernetes.api.model.Container;
import io.fabric8.kubernetes.api.model.ContainerPort;
import io.fabric8.kubernetes.api.model.EnvVar;
import io.fabric8.kubernetes.api.model.IntOrString;
import io.fabric8.kubernetes.api.model.KubernetesResource;
import io.fabric8.kubernetes.api.model.LabelSelector;
import io.fabric8.kubernetes.api.model.LocalObjectReference;
import io.fabric8.kubernetes.api.model.ObjectMeta;
import io.fabric8.kubernetes.api.model.ObjectReference;
import io.fabric8.kubernetes.api.model.PersistentVolumeClaim;
import io.fabric8.kubernetes.api.model.PodTemplateSpec;
import io.fabric8.kubernetes.api.model.ResourceRequirements;
import io.fabric8.kubernetes.api.model.Volume;
import io.fabric8.kubernetes.api.model.VolumeMount;
import io.sundr.builder.annotations.Buildable;
import io.sundr.builder.annotations.BuildableReference;
import lombok.EqualsAndHashCode;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Accessors;

@JsonDeserialize(using = com.fasterxml.jackson.databind.JsonDeserializer.None.class)
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
    "apiVersion",
    "kind",
    "metadata",
    "conditions",
    "lastFailureTime",
    "nextPrivateKeySecretName",
    "notAfter",
    "notBefore",
    "renewalTime",
    "revision"
})
@ToString
@EqualsAndHashCode
@Setter
@Accessors(prefix = {
    "_",
    ""
})
@Buildable(editableEnabled = false, validationEnabled = false, generateBuilderPackage = false, lazyCollectionInitEnabled = false, builderPackage = "io.fabric8.kubernetes.api.builder", refs = {
    @BuildableReference(ObjectMeta.class),
    @BuildableReference(LabelSelector.class),
    @BuildableReference(Container.class),
    @BuildableReference(PodTemplateSpec.class),
    @BuildableReference(ResourceRequirements.class),
    @BuildableReference(IntOrString.class),
    @BuildableReference(ObjectReference.class),
    @BuildableReference(LocalObjectReference.class),
    @BuildableReference(PersistentVolumeClaim.class),
    @BuildableReference(EnvVar.class),
    @BuildableReference(ContainerPort.class),
    @BuildableReference(Volume.class),
    @BuildableReference(VolumeMount.class)
})
public class CertificateStatus implements KubernetesResource
{

    @JsonProperty("conditions")
    @JsonInclude(JsonInclude.Include.NON_EMPTY)
    private List<CertificateCondition> conditions = new ArrayList<CertificateCondition>();
    @JsonProperty("lastFailureTime")
    private java.lang.String lastFailureTime;
    @JsonProperty("nextPrivateKeySecretName")
    private String nextPrivateKeySecretName;
    @JsonProperty("notAfter")
    private java.lang.String notAfter;
    @JsonProperty("notBefore")
    private java.lang.String notBefore;
    @JsonProperty("renewalTime")
    private java.lang.String renewalTime;
    @JsonProperty("revision")
    private Integer revision;
    @JsonIgnore
    private Map<java.lang.String, Object> additionalProperties = new HashMap<java.lang.String, Object>();

    /**
     * No args constructor for use in serialization
     *
     */
    public CertificateStatus() {
    }

    /**
     *
     * @param renewalTime
     * @param notAfter
     * @param nextPrivateKeySecretName
     * @param lastFailureTime
     * @param conditions
     * @param notBefore
     * @param revision
     */
    public CertificateStatus(List<CertificateCondition> conditions, java.lang.String lastFailureTime, String nextPrivateKeySecretName, java.lang.String notAfter, java.lang.String notBefore, java.lang.String renewalTime, Integer revision) {
        super();
        this.conditions = conditions;
        this.lastFailureTime = lastFailureTime;
        this.nextPrivateKeySecretName = nextPrivateKeySecretName;
        this.notAfter = notAfter;
        this.notBefore = notBefore;
        this.renewalTime = renewalTime;
        this.revision = revision;
    }

    @JsonProperty("conditions")
    public List<CertificateCondition> getConditions() {
        return conditions;
    }

    @JsonProperty("conditions")
    public void setConditions(List<CertificateCondition> conditions) {
        this.conditions = conditions;
    }

    @JsonProperty("lastFailureTime")
    public java.lang.String getLastFailureTime() {
        return lastFailureTime;
    }

    @JsonProperty("lastFailureTime")
    public void setLastFailureTime(java.lang.String lastFailureTime) {
        this.lastFailureTime = lastFailureTime;
    }

    @JsonProperty("nextPrivateKeySecretName")
    public String getNextPrivateKeySecretName() {
        return nextPrivateKeySecretName;
    }

    @JsonProperty("nextPrivateKeySecretName")
    public void setNextPrivateKeySecretName(String nextPrivateKeySecretName) {
        this.nextPrivateKeySecretName = nextPrivateKeySecretName;
    }

    @JsonProperty("notAfter")
    public java.lang.String getNotAfter() {
        return notAfter;
    }

    @JsonProperty("notAfter")
    public void setNotAfter(java.lang.String notAfter) {
        this.notAfter = notAfter;
    }

    @JsonProperty("notBefore")
    public java.lang.String getNotBefore() {
        return notBefore;
    }

    @JsonProperty("notBefore")
    public void setNotBefore(java.lang.String notBefore) {
        this.notBefore = notBefore;
    }

    @JsonProperty("renewalTime")
    public java.lang.String getRenewalTime() {
        return renewalTime;
    }

    @JsonProperty("renewalTime")
    public void setRenewalTime(java.lang.String renewalTime) {
        this.renewalTime = renewalTime;
    }

    @JsonProperty("revision")
    public Integer getRevision() {
        return revision;
    }

    @JsonProperty("revision")
    public void setRevision(Integer revision) {
        this.revision = revision;
    }

    @JsonAnyGetter
    public Map<java.lang.String, Object> getAdditionalProperties() {
        return this.additionalProperties;
    }

    @JsonAnySetter
    public void setAdditionalProperty(java.lang.String name, Object value) {
        this.additionalProperties.put(name, value);
    }

}


text:
package lite.flow.runtime.kiss;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.logging.Level;

import lite.flow.util.UniqueId;
import lite.flow.util.ActivityInspector.EntryPoint;
import lite.flow.runtime.kiss.DistributorOutput.Destination;
import lite.flow.runtime.kiss.data.DataMessage;
import lite.log.api.ExecutionContext;
import lite.log.api.Log;
import lite.log.api.LogFactory;
import lite.log.api.event.MiddleEvent;

/**
 * @author ToivoAdams
 *
 */
public class Correlator extends SequentialActivity {

	// Output is extended Output type
	DistributorOutput<CorrelatedEntryPointArguments> correlatedInputs = new DistributorOutput<>("correlatedInputs");

	private final EntryPoint entryPoint;
	private final String[] argNames;

	public Correlator(Integer inputQueueLength, ExecutionContext executionContext, EntryPoint entryPoint, LogFactory logFactory) {
		super(inputQueueLength, executionContext, logFactory);
		this.entryPoint = entryPoint;
		this.argNames = entryPoint.inputNames;
	}

	@Log
	@Override
	public Object processDataMessage(DataMessage<?> dataMessage) {
//    	System.out.println("===============> Correlator.processMessage");

    	CorrelatedEntryPointArguments row = getOrPut(argNames, dataMessage.context.getRequestId(), entryPoint);
    	row.put(dataMessage);

    	if (row.hasAllValues()) {
    //		DataMessage<?> outDataMessage = new DataMessage<CollectedMethodParametersRow>(dataMessage.context, "correlatedInputs", row);
    //		rcc.setRequestContext(dataMessage.context);
    		correlatedInputs.emit(row, dataMessage.context);
    		// we should remove row from map because we are done with this row
    		// Note!!! Actually we should not remove row!!!
    		// We want catch invalid duplicates and CollectedMethodParametersRow will do this!
    		// rowsHolder.remove(dataMessage.context.getRequestId());
    	}

    	return row;
	}

	public static int MAX_PARAMETER_WAIT_TIME = 20000; // milliseconds

	private final Map<UniqueId, CorrelatedEntryPointArguments> rowsHolder = new LinkedHashMap<UniqueId, CorrelatedEntryPointArguments>(70, 0.7f, true) {
        @Override
        protected boolean removeEldestEntry(Map.Entry<UniqueId, CorrelatedEntryPointArguments> eldest) {

        	long currentTime = System.currentTimeMillis();
        	if ((eldest.getValue().createTime+MAX_PARAMETER_WAIT_TIME)<currentTime) {
        		// too old, inform manager and remove
				MiddleEvent middleEvent = new MiddleEvent(Level.WARNING, "remove old CollectedMethodParametersRow=" + eldest, null, executionContext, logFactory.newCid());
				logFactory.logger().log(middleEvent);
                return true;
        	}
        	return false;
        }
    };

    public final CorrelatedEntryPointArguments getOrPut(String[] argNames, UniqueId dcid, EntryPoint entryPoint) {
    	if (rowsHolder.containsKey(dcid))
    		return rowsHolder.get(dcid);

    	CorrelatedEntryPointArguments collectedMethodParametersRow = new CorrelatedEntryPointArguments(dcid, entryPoint);
    	rowsHolder.put(dcid, collectedMethodParametersRow);
    	return collectedMethodParametersRow;
    }

	@Log
	@Override
	public void addDestination(String ouputName, Consumer consumer, String destinationName) {
		// Correlator has only one output, so we don't use ouputName here!
		correlatedInputs.addDestination(new Destination(destinationName, consumer));
	}

}


text:
import { DataStrategy, UpdateActionAdditionalSettings } from '@react-state/data-strategy';
import { Map, fromJS, Collection, Iterable } from 'immutable';
import * as _Cursor from 'immutable/contrib/cursor';

export class ImmutableJsDataStrategy extends DataStrategy {

    getIn(state: Map<any, any>, path: any[]): Collection<any, any> {
        return state.getIn(path);
    }

    fromJS(data: any): Collection<any, any> {
        return fromJS(data);
    }

    toJS(data: Collection<any, any>) {
        return data.toJS();
    }

    set(state: Map<any, any>, property: string, data: any) {
        return state.set(property, data);
    }

    setIn(state: Map<any, any>, path: any[], data: any) {
        return state.setIn(path, data);
    }

    isObject(state: any) {
        return Map.isMap(state) || Iterable.isIterable(state);
    }

    merge(state: any, newState: any) {
        return state.merge(newState);
    }

    update(path: any[], action: (state: any) => void, additionalSettings: ImmutableUpdateActionAdditionalSettings = { withMutations: false }) {
        const cursor = _Cursor.from(this.currentState, path, (newData) => {
            this.rootStore.next(newData);
        });

        if (additionalSettings.withMutations) {
            cursor.withMutations((state: any) => {
                action(state);
            });
        } else {
            action(cursor);
        }
    }

    overrideContructor(obj: any) {
        if (this.isNotImmutableObject(obj)) { // from ImmutableJs 4 breaking change isIterable => isCollection
            if (obj.constructor === Array) {
                for (let i = 0; i < obj.length; i++) {
                    this.overrideContructor(obj[i]);
                }
            } else {
                obj.__proto__.constructor = Object;
                for (let key in obj) {
                    this.overrideContructor(obj[key]);
                }
            }
        }
    }

    resetRoot(initialState: any, startingRoute: string = null): void {
        const state = this.currentState;

        const router = state.get('router');

        this.update([], (state: any) => {
            state.clear();
            state.merge(initialState);

            if (startingRoute !== null) {
                state.set('router', router);
                state.setIn(['router', 'url'], startingRoute, { fromUpdate: true });
            }
        }, { withMutations : true });
    }

    reset(path: any[], stateToMerge: any): void {
        this.update(path, (state: any) => {
            state.clear();
            state.merge(stateToMerge);
        }, { withMutations : true });
    }

    private isNotImmutableObject(obj: any) {
        return obj !== null
            && typeof (obj) === 'object'
            && !Map.isMap(obj)
            && !Iterable.isIterable(obj);
    }
}

export interface ImmutableUpdateActionAdditionalSettings extends UpdateActionAdditionalSettings {
    withMutations?: boolean;
}


text:
using System.Windows;
using System.Windows.Controls;

namespace LordJZ.Presentation.Controls
{
    /// <remarks>
    /// Originally from http://xamlcoder.com/blog/2010/11/04/creating-a-metro-ui-style-control/
    /// Mostly taken from MahApps.Metro.
    /// </remarks>
    public class MetroContentControl : ContentControl
    {
        static readonly DependencyProperty ReverseTransitionProperty =
            DependencyProperty.Register("ReverseTransition", typeof(bool), typeof(MetroContentControl),
                                        new FrameworkPropertyMetadata(BooleanBoxes.False));

        bool ReverseTransition
        {
            get { return (bool)GetValue(ReverseTransitionProperty); }
            set { SetValue(ReverseTransitionProperty, BooleanBoxes.Box(value)); }
        }

        public MetroContentControl()
        {
            DefaultStyleKey = typeof(MetroContentControl);

            Loaded += this.MetroContentControlLoaded;
            Unloaded += this.MetroContentControlUnloaded;

            IsVisibleChanged += this.MetroContentControlIsVisibleChanged;
        }

        void MetroContentControlIsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            if (!IsVisible)
                VisualStateManager.GoToState(this, this.ReverseTransition ? "AfterUnLoadedReverse" : "AfterUnLoaded", false);
            else
                VisualStateManager.GoToState(this, this.ReverseTransition ? "AfterLoadedReverse" : "AfterLoaded", true);
        }

        private void MetroContentControlUnloaded(object sender, RoutedEventArgs e)
        {
            VisualStateManager.GoToState(this, this.ReverseTransition ? "AfterUnLoadedReverse" : "AfterUnLoaded", false);
        }

        private void MetroContentControlLoaded(object sender, RoutedEventArgs e)
        {
            VisualStateManager.GoToState(this, this.ReverseTransition ? "AfterLoadedReverse" : "AfterLoaded", true);
        }

        public void Reload()
        {
            VisualStateManager.GoToState(this, "BeforeLoaded", true);
            VisualStateManager.GoToState(this, this.ReverseTransition ? "AfterLoadedReverse" : "AfterLoaded", true);
        }

        public void SwitchContent(object newContent)
        {
            this.SwitchContent(newContent, default(ContentSwitchMode));
        }

        public void SwitchContent(object newContent, ContentSwitchMode mode)
        {
            if (mode == ContentSwitchMode.Instant)
            {
                this.Content = newContent;
            }
            else
            {
                this.ReverseTransition = mode == ContentSwitchMode.Backward;

                this.BeginInit();
                try
                {
                    this.Content = newContent;
                    this.Reload();
                }
                finally
                {
                    this.EndInit();
                }
            }
        }
    }
}


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;

namespace Microsoft.Spark.CSharp.Samples
{
    /// <summary>
    /// Runs samples
    /// </summary>
    internal class SamplesRunner
    {
        private static Regex samplesToRunRegex;
        private static Regex samplesCategoryRegex;
        private static Stopwatch stopWatch;
        // track <SampleName, Category, SampleSucceeded, Duration> for reporting
        private static readonly List<Tuple<string, string, bool, TimeSpan>> samplesRunInfoList = new List<Tuple<string, string, bool, TimeSpan>>();

        internal static bool RunSamples()
        {
            var samples = Assembly.GetEntryAssembly().GetTypes()
                      .SelectMany(type => type.GetMethods(BindingFlags.NonPublic | BindingFlags.Static))
                      .Where(method => method.GetCustomAttributes(typeof(SampleAttribute), false).Length > 0)
                      .OrderByDescending(method => method.Name);

            samplesToRunRegex = GetRegex();
            samplesCategoryRegex = GetCategoryRegex();
            stopWatch = Stopwatch.StartNew();

            foreach (var sample in samples)
            {
                var sampleRunInfo = RunSample(sample);
                if (sampleRunInfo != null)
                {
                    samplesRunInfoList.Add(sampleRunInfo);
                }
            }
            stopWatch.Stop();
            return ReportOutcome();
        }

        private static Tuple<string, string, bool, TimeSpan> RunSample(MethodInfo sample)
        {
            var sampleName = sample.Name;
            var sampleAttributes = (SampleAttribute[]) sample.GetCustomAttributes(typeof(SampleAttribute), false);
            var categoryNames = string.Join<SampleAttribute>(",", sampleAttributes);

            if (samplesCategoryRegex != null)
            {
                if (!sampleAttributes.Any(attribute => attribute.Match(samplesCategoryRegex)))
                {
                    return null;
                }
            }

            if (samplesToRunRegex != null)
            {
                //assumes method/sample names are unique, and different samples are delimited by ','
                var containedInSamplesToRun = SparkCLRSamples.Configuration.SamplesToRun.ToLowerInvariant().Trim().Split(',').Contains(sampleName.ToLowerInvariant());
                if (!containedInSamplesToRun && !samplesToRunRegex.IsMatch(sampleName))
                {
                    return null;
                }
            }

            var clockStart = stopWatch.Elapsed;
            var duration = stopWatch.Elapsed - clockStart;
            try
            {
                if (!SparkCLRSamples.Configuration.IsDryrun)
                {
                    SparkCLRSamples.WriteColorCodedConsoleMessage(ConsoleColor.Cyan, string.Format("----- Running sample {0} -----", sampleName));
                    sample.Invoke(null, new object[] { });
                    duration = stopWatch.Elapsed - clockStart;
                    SparkCLRSamples.WriteColorCodedConsoleMessage(ConsoleColor.Green, string.Format("----- Successfully finished running sample {0} (duration={1}) -----", sampleName, duration));
                }

                return new Tuple<string, string, bool, TimeSpan>(sampleName, categoryNames, true, duration);
            }
            catch (Exception ex)
            {
                duration = stopWatch.Elapsed - clockStart;
                SparkCLRSamples.WriteColorCodedConsoleMessage(ConsoleColor.Red, string.Format("----- Error running sample {0} (duration={3}) -----{1}{2}", sampleName, Environment.NewLine, ex, duration));
                return new Tuple<string, string, bool, TimeSpan>(sampleName, categoryNames, false, duration);
            }

        }

        private static Regex GetCategoryRegex()
        {
            Regex categoryRegex = null;
            if (!string.IsNullOrEmpty(SparkCLRSamples.Configuration.SamplesCategory))
            {
                var s = SparkCLRSamples.Configuration.SamplesCategory;
                if (s.StartsWith("/") && s.EndsWith("/") && s.Length > 2)
                {
                    // forward-slashes enclose .Net regular expression
                    categoryRegex = new Regex(s.Substring(1, s.Length - 2));
                }
                else
                {
                    // default to Unix or Windows command line wild card matching, case insensitive
                    categoryRegex = new Regex("^" + Regex.Escape(s).Replace(@"\*", ".*").Replace(@"\?", ".") + "$",
                        RegexOptions.IgnoreCase);
                }
            }
            return categoryRegex;
        }

        private static Regex GetRegex()
        {
            Regex regex = null;
            if (!string.IsNullOrEmpty(SparkCLRSamples.Configuration.SamplesToRun))
            {
                var s = SparkCLRSamples.Configuration.SamplesToRun;
                if (s.StartsWith("/") && s.EndsWith("/") && s.Length > 2)
                {
                    // forward-slashes enclose .Net regular expression
                    regex = new Regex(s.Substring(1, s.Length - 2));
                }
                else
                {
                    // default to Unix or Windows command line wild card matching, case insensitive
                    regex = new Regex("^" + Regex.Escape(s).Replace(@"\*", ".*").Replace(@"\?", ".") + "$",
                        RegexOptions.IgnoreCase);
                }
            }
            return regex;
        }

        private static bool ReportOutcome()
        {
            var succeededSamples = samplesRunInfoList.Where(x => x.Item3).ToList();
            var failedSamples = samplesRunInfoList.Where(x => !x.Item3).ToList();

            var summary = new StringBuilder().Append("----- ")
                .Append("Finished running ")
                .Append(string.Format("{0} samples(s) [succeeded={1}, failed={2}]", samplesRunInfoList.Count, succeededSamples.Count, failedSamples.Count))
                .Append(" in ").Append(stopWatch.Elapsed)
                .AppendLine(" -----").ToString();

            SparkCLRSamples.WriteColorCodedConsoleMessage(ConsoleColor.Yellow, summary);

            if (succeededSamples.Count > 0)
            {
                SparkCLRSamples.WriteColorCodedConsoleMessage(ConsoleColor.Green, "Successfully completed samples:");
                foreach (var s in succeededSamples)
                {
                    var sampleResult = new StringBuilder().Append("    ")
                        .Append(string.Format("{0} (category: {1}), duration={2}", s.Item1, s.Item2, s.Item4)).ToString();
                    SparkCLRSamples.WriteColorCodedConsoleMessage(ConsoleColor.Green, sampleResult);
                }
            }

            if (failedSamples.Count > 0)
            {
                SparkCLRSamples.WriteColorCodedConsoleMessage(ConsoleColor.Red, "Failed samples:");
                foreach (var s in failedSamples)
                {
                    var sampleResult = new StringBuilder().Append("    ")
                        .Append(string.Format("{0} (category: {1}), duration={2}", s.Item1, s.Item2, s.Item4)).ToString();
                    SparkCLRSamples.WriteColorCodedConsoleMessage(ConsoleColor.Red, sampleResult);
                }
            }

            return failedSamples.Count == 0;
        }
    }
}


text:
const config = require("../../index");
const stylelint = require("stylelint");
const postcss = require("postcss");
const scssSyntax = require("postcss-scss");
const test = require("tape");

const invalidScss = (
`p {
  margin: 0;
  em {
    color: #f00;
  }
}
a {
  color: #f00;
}
`)

test("Empty line between scss", t => {
  t.plan(3)

  postcss()
    .use(stylelint({ code: invalidScss, config: config,}))
    .process(invalidScss, { syntax: scssSyntax })
    .then(checkResult)
    .catch(logError)

  function checkResult(result) {
    t.equal(result.warnings().length, 2, "flags 2 warning")
    t.is(result.warnings()[0].text, "Expected empty line before rule (rule-empty-line-before)", "correct warning text")
    t.is(result.warnings()[1].text, "Expected empty line before rule (rule-empty-line-before)", "correct warning text")
  }
})

function logError(err) {
  console.log(err.stack)
}


text:
<title>The org.der.iris.builtins package</title>
</head

Classes that represent the standard built-in predicates.

$Id: package.html,v 1.2 2007-10-12 12:40:58 bazbishop237 Exp $

@since 0.01


text:
require_relative 'providers'
require 'simplefeed'
require_relative 'dsl/activities'

module SimpleFeed
  # This module offers a convenient DSL-based approach to manipulating user feeds.
  #
  # Usage:
  #
  #     require 'simplefeed/dsl'
  #     include SimpleFeed::DSL
  #
  #     with_activity(SimpleFeed.get(:newsfeed).activity(user_id)) do
  #       store(value: 'hello', at: Time.now)  #=> true
  #       fetch                                # => [ Event, Event, ... ]
  #       total_count                          # => 12
  #       unread_count                         # => 4
  #     end
  #
  module DSL
    class << self
      attr_accessor :debug

      def debug?
        debug
      end
    end

    def with_activity(activity, **opts, &block)
      opts.merge!({ context: self }) unless opts && opts[:context]
      SimpleFeed::DSL::Activities.new(activity, **opts).instance_eval(&block)
    end

    def event(value, at = Time.now)
      SimpleFeed::Event.new(value, at)
    end
  end
end


text:
 package io.spring.cloud.samples.fortuneteller.ui.controllers;

import io.spring.cloud.samples.fortuneteller.ui.services.fortunes.Fortune;
import io.spring.cloud.samples.fortuneteller.ui.services.fortunes.FortuneService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UiController {

    private FortuneService service;

    public UiController(FortuneService service) {
      this.service = service;
    }

    @RequestMapping("/random")
    public Fortune randomFortune() {
        return service.randomFortune();
    }
}


text:
package com.facebook.buck.cxx;

import com.facebook.buck.core.sourcepath.SourcePath;
import com.facebook.buck.core.util.immutables.BuckStyleImmutable;
import com.google.common.collect.ImmutableSet;
import java.util.List;
import java.util.Optional;
import org.immutables.value.Value;

/**
 * Describes a source file written in the C programming language or a derivative (C++, Objective-C,
 * Objective-C++, etc.) and the various paths it uses from input to output.
 */
@Value.Immutable(copy = true)
@BuckStyleImmutable
// PMD is disabled for the line below. We have a check that Abstract immutable types are
// package-private. The Immutables generator is super-helpeful and makes references to the abstract
// version of Immutables if they're referenced from other immutables, not just the generated
// immutable type. So if any Immutables are defined in other packages which have a getter which
// returns a CxxSource, internally an AbstractCxxSource is referenced in the generated code, which
// doesn't have visibility to access this type, causing a compile error.
public abstract class AbstractCxxSource { // NOPMD

  public enum Type {
    C("c", "cpp-output", Optional.of("c-header"), "c"),
    CXX(
        "c++",
        "c++-cpp-output",
        Optional.of("c++-header"),
        "cc",
        "cp",
        "cxx",
        "cpp",
        "CPP",
        "c++",
        "C"),
    CXX_THINLINK("ir", "ir", Optional.of("c++-thinlink"), "o"),
    OBJC("objective-c", "objective-c-cpp-output", Optional.of("objective-c-header"), "m"),
    OBJCXX("objective-c++", "objective-c++-cpp-output", Optional.of("objective-c++-header"), "mm"),
    CUDA("cuda", "cuda-cpp-output", "cu"),
    HIP("hip", "hip-cpp-output", "hip"),

    C_CPP_OUTPUT("cpp-output", "cpp-output", "i"),
    CXX_CPP_OUTPUT("c++-cpp-output", "c++-cpp-output", "ii"),
    OBJC_CPP_OUTPUT("objective-c-cpp-output", "objective-c-cpp-output", "mi"),
    OBJCXX_CPP_OUTPUT("objective-c++-cpp-output", "objective-c++-cpp-output", "mii"),
    CUDA_CPP_OUTPUT("cuda-cpp-output", "cuda-cpp-output", "cui"),
    HIP_CPP_OUTPUT("hip-cpp-output", "hip-cpp-output", "hii"),

    // Note, this is declared before ASSEMBLER so .s files are recognized as needing preprocessor.
    ASSEMBLER_WITH_CPP("assembler-with-cpp", "assembler", "s", "S"),
    ASSEMBLER("assembler", "assembler", "s"),

    // Assembly files built with nasm/yasm.
    ASM_WITH_CPP("asm-with-cpp", "asm", "asmpp"),
    ASM("asm", "asm", "asm"),

    // Precompiled modules (https://clang.llvm.org/docs/Modules.html).
    PCM("pcm", "pcm", "pcm");

    private final String language;
    private final String preprocessedLanguage;
    private final Optional<String> precompiledHeaderLanguage;
    private final ImmutableSet<String> extensions;

    Type(String language, String preprocessedLanguage, String... extensions) {
      this(language, preprocessedLanguage, Optional.empty(), extensions);
    }

    Type(
        String language,
        String preprocessedLanguage,
        Optional<String> precompiledHeaderLanguage,
        String... extensions) {
      this.language = language;
      this.preprocessedLanguage = preprocessedLanguage;
      this.precompiledHeaderLanguage = precompiledHeaderLanguage;
      this.extensions = ImmutableSet.copyOf(extensions);
    }

    public static Optional<Type> fromExtension(String extension) {
      for (Type type : values()) {
        if (type.extensions.contains(extension)) {
          return Optional.of(type);
        }
      }
      return Optional.empty();
    }

    /**
     * Returns existing type based on the language string
     *
     * @param language the language string used to look up the Type
     * @return Type if any type matches with the input string. Otherwise empty
     */
    public static Optional<Type> fromLanguage(String language) {
      for (Type type : values()) {
        if (type.language.equals(language)) {
          return Optional.of(type);
        }
      }
      return Optional.empty();
    }

    public String getLanguage() {
      return language;
    }

    public String getPreprocessedLanguage() {
      return preprocessedLanguage;
    }

    /**
     * "Language" type to pass to the compiler in order to generate a precompiled header.
     *
     * <p>Will be {@code absent} for source types which do not support precompiled headers.
     */
    public Optional<String> getPrecompiledHeaderLanguage() {
      return precompiledHeaderLanguage;
    }

    public boolean isPreprocessable() {
      return !preprocessedLanguage.equals(language);
    }

    public ImmutableSet<String> getExtensions() {
      return extensions;
    }

    public boolean isAssembly() {
      return this == ASSEMBLER || this == ASSEMBLER_WITH_CPP;
    }
  }

  @Value.Parameter
  public abstract Type getType();

  @Value.Parameter
  public abstract SourcePath getPath();

  @Value.Parameter
  public abstract List<String> getFlags();
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one
  or more contributor license agreements.  See the NOTICE file
  distributed with this work for additional information
  regarding copyright ownership.  The ASF licenses this file
  to you under the Apache License, Version 2.0 (the
  "License"); you may not use this file except in compliance
  with the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing,
  software distributed under the License is distributed on an
  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  KIND, either express or implied.  See the License for the
  specific language governing permissions and limitations
  under the License.
-->
<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>
        <groupId>org.apache.streams</groupId>
        <artifactId>streams-examples</artifactId>
        <version>0.1-incubating</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>hdfs-urlunwind</artifactId>

    <dependencies>
         <dependency>
            <groupId>org.apache.pig</groupId>
            <artifactId>pig</artifactId>
            <version>0.11.0-cdh4.5.0.1-incubating</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.pig</groupId>
            <artifactId>pigunit</artifactId>
            <version>0.11.0-cdh4.5.0.1-incubating</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>jline</groupId>
            <artifactId>jline</artifactId>
            <version>2.11</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.antlr</groupId>
            <artifactId>antlr-runtime</artifactId>
            <version>3.5.2</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.3</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.1.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-client</artifactId>
            <version>2.0.0-cdh4.5.0.1-incubating</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.typesafe</groupId>
            <artifactId>config</artifactId>
        </dependency>
        <dependency>
            <groupId>com.jayway.jsonpath</groupId>
            <artifactId>json-path</artifactId>
            <version>0.9.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.streams</groupId>
            <artifactId>streams-pojo</artifactId>
            <version>0.1-incubating</version>
        </dependency>
        <dependency>
            <groupId>org.apache.streams</groupId>
            <artifactId>streams-processor-json</artifactId>
            <version>0.1-incubating</version>
        </dependency>
        <dependency>
            <groupId>org.apache.streams</groupId>
            <artifactId>streams-processor-urls</artifactId>
            <version>0.1-incubating</version>
        </dependency>
        <dependency>
            <groupId>org.apache.streams</groupId>
            <artifactId>streams-runtime-pig</artifactId>
            <version>0.1-incubating</version>
        </dependency>
        <dependency>
            <groupId>org.apache.streams</groupId>
            <artifactId>streams-config</artifactId>
            <version>0.1-incubating</version>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>${logback.version}</version>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-core</artifactId>
            <version>${logback.version}</version>
        </dependency>
    </dependencies>

    <build>
        <sourceDirectory>src/main/java</sourceDirectory>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <finalName>${project.build.finalName}</finalName>
                            <filters>
                                <filter>
                                    <artifact>*:*</artifact>
                                    <excludes>
                                        <exclude>META-INF/*.SF</exclude>
                                        <exclude>META-INF/*.DSA</exclude>
                                        <exclude>META-INF/*.RSA</exclude>
                                    </excludes>
                                </filter>
                            </filters>
                            <transformers>
                                <transformer
                                        implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer" />
                            </transformers>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>


text:
namespace Inlinq.Impl
{
    public sealed class Repeat64Enumerable<T> : Enumerable<T, Repeat64Enumerator<T>>
    {
        private T element;
        private long count;

        public Repeat64Enumerable(T element, long count)
        {
            this.element = element;
            this.count = count;
        }

        public override bool GetCount(out int count)
        {
            if (this.count <= int.MaxValue)
            {
                count = (int)this.count;
                return true;
            }
            else
            {
                count = 0;
                return false;
            }
        }

        public override Repeat64Enumerator<T> GetEnumerator()
            => new Repeat64Enumerator<T>(element, count);
    }
}


text:
'use strict';

angular.module('yamaApp', [
	'angular-loading-bar',
	'restangular',
	'validation',
	'validation.rule',
	'validation.schema'
]).config(function(RestangularProvider) {
	RestangularProvider.setBaseUrl('/api');
	RestangularProvider.setDefaultHttpFields({cache: false});

	RestangularProvider.addResponseInterceptor(function(data, operation) {
		var extractedData;

		if (operation === 'getList' && angular.isObject(data)) {
			extractedData = angular.copy(data.content, extractedData);
			delete data.content;
			extractedData.meta = data;
		} else {
			extractedData = data;
		}

		return extractedData;
	});
}).config(function($validationProvider) {
	$validationProvider.showSuccessMessage = false;

	$validationProvider.invalidCallback = function(element) {
		$(element).parents('.form-group:first').addClass('has-error');
	};

	$validationProvider.validCallback = function(element) {
		$(element).parents('.form-group:first').removeClass('has-error');
	};

	$validationProvider.setErrorHTML(function (msg) {
		return '
' + msg + '
';
	});

	$validationProvider.setSuccessHTML(function (msg) {
		return '
' + msg + '
';
	});
}).run(function($validation, Registers) {
	$validation.setExpression({
		match: function (value, scope, element, attrs, param) {
			return value === $(param).val();
		},
		userexist: function (value) {
			return Registers.one().get({u: value}).then(function(user) {
				return !user;
			}, function() {
				return true;
			});
		},
		alphanumeric: /^[a-z0-9]+$/i
	});
});


text:
    <md-toolbar>

            <md-button class="md-icon-button" aria-label="Settings">
                <md-icon md-svg-icon="img/icons/menu.svg"></md-icon>
            </md-button>

                    Product Name:

                        {{ Ctrl.item.title || '_____' }}

            <md-button
                    tooltip="Manage Events For This Product"
                    tooltip-placement="left"
                    class="md-icon-button"
                    aria-label="Favorite"
                    ui-sref="events({productId:Ctrl.item.id})">
                <md-icon>
                    event_note
                </md-icon>
            </md-button>
            <md-button tooltip="Save Current Item State"
                       tooltip-placement="left"
                       class="md-icon-button"
                       aria-label="Save"
                       ng-click="Ctrl.saveItem()">
                <md-icon>check</md-icon>
            </md-button>

                <md-button class="md-icon-button md-warn"
                           tooltip="Delete Current Item"
                           tooltip-placement="left"
                           aria-label="More"
                           ng-click="Ctrl.deleteItem()">
                    <md-icon> delete </md-icon>
                </md-button>

    </md-toolbar>
    <md-content>

                    Description:

                        {{ Ctrl.item.description || '_____' }}

                    Product Category:

                        {{ Ctrl.showCategory() || '_____' }}

                    Parent Product:

                        {{ Ctrl.showParent() || '_____' }}

                    Require Membership:
                    <input type="checkbox" ng-model="Ctrl.item.config.membersonly"/>

                    Cart Limit:

                        {{ Ctrl.item.config.limit || '0' }}

                    Enable Taster:
                    <input id="taster_enable" type="checkbox" ng-model="Ctrl.item.config.taster"/>

                    Cart Display Options:

                        {{ Ctrl.showCartDisplayType() || '_____' }}

            <uib-tabset >
                <uib-tab heading="Booking">

                        <fieldset>
                            <legend>Booking</legend>

                                Enable Booking
                                <input type="checkbox" ng-model="Ctrl.item.config.booking.enabled"/>

                                    Select Venue

                                        {{ Ctrl.showVenue() || '_____' }}

                                    Booking Type:

                                        {{ Ctrl.showBookingType() || '_____' }}

                                    Enable Age Groups
                                    <input type="checkbox" ng-model="Ctrl.item.config.booking.agegroups.enabled">

                                        Age Group:

                                            {{ Ctrl.showAgeGroup() || '_____' }}

                                    Capacity:

                                        {{ Ctrl.item.config.booking.capacity || '_____' }}

                        </fieldset>

                </uib-tab>
                <uib-tab heading="Schedule">

                        <lable>Enable Scheduling</lable>
                        <input type="checkbox", ng-model="Ctrl.item.config.schedule.enabled"/>

                                Schedule Type

                                    {{ Ctrl.showScheduleType() || '_____' }}

                                    <fieldset>
                                        <legend>Schedule</legend>
                                        <fieldset>

                                        </fieldset>

                                            <fieldset>
                                                <legend>Recurrence</legend>
                                                <rrule-recurring-select  rule="Ctrl.item.config.schedule.rrule"></rrule-recurring-select>
                                            </fieldset>

                                    </fieldset>
                                    <fieldset>
                                        <legend>Exclude Dates</legend>

                                            <uib-datepicker ng-model='Ctrl.activeDate' multi-select='Ctrl.item.config.schedule.exdates' select-range='false'></uib-datepicker>

                                            Excluded Dates:

                                                    {{d | date : 'fullDate'}}
                                                    <button class='btn btn-xs btn-warning' style='margin:5px' ng-click='Ctrl.removeExdate(d)'>Remove</button>

                                    </fieldset>

                                    <fieldset>
                                        <legend>Select Dates</legend>

                                            <uib-datepicker ng-model='Ctrl.activeDate' multi-select='Ctrl.item.config.schedule.dates' select-range='false'></uib-datepicker>

                                            Selected Dates

                                                    {{d | date : 'fullDate'}}
                                                    <button class='btn btn-xs btn-warning' style='margin:5px' ng-click='Ctrl.removeScheduledDate(d)'>Remove</button>

                                    </fieldset>

                </uib-tab>
                <uib-tab heading="Payment">

                        <fieldset>
                            <legend>Payment</legend>

                                <fieldset>
                                    <legend>Paynow:</legend>

                                        Enable Paynow:
                                        <input type="checkbox" ng-model="Ctrl.item.config.payment.paynow.enabled"/>

                                        Require Prepay:
                                        <input type="checkbox" ng-model="Ctrl.item.config.payment.paynow.required"/>

                                        <fieldset>
                                            <legend>Methods</legend>

                                                Credit Card:
                                                <input type="checkbox" ng-model="Ctrl.item.config.payment.paynow.methods.paypal"/>

                                                Direct Debit:
                                                <input type="checkbox" ng-model="Ctrl.item.config.payment.paynow.ezcollect"/>

                                                Invoice/Voucher:
                                                <input type="checkbox" ng-model="Ctrl.item.config.payment.paynow.invoice"/>

                                        </fieldset>

                                </fieldset>
                                <fieldset>
                                    <legend>Billing</legend>

                                        Enable Billing:
                                        <input type="checkbox" ng-model="Ctrl.item.config.payment.recurring.enabled"/>

                                        Required
                                        <input type="checkbox" ng-model="Ctrl.item.config.payment.recurring.required"/>

                                        <fieldset>
                                            <legend>Methods</legend>

                                                Credit Card:
                                                <input type="checkbox" ng-model="Ctrl.item.config.payment.recurring.methods.paypal"/>

                                                Direct Debit:
                                                <input type="checkbox" ng-model="Ctrl.item.config.payment.recurring.methods.directdebit"/>

                                                Invoice/Voucher:
                                                <input type="checkbox" ng-model="Ctrl.item.config.payment.recurring.methods.invoice"/>

                                        </fieldset>

                                    <legend>Plans</legend>

                                        Enable Plans:
                                        <input type="checkbox" ng-model="Ctrl.item.config.payment.plans.enabled"/>

                                        Required
                                        <input type="checkbox" ng-model="Ctrl.item.config.payment.plans.required"/>

                                        <fieldset>
                                            <legend>Plans</legend>

coming soon

                                        </fieldset>
                                        <fieldset>
                                            <legend>Plans</legend>

                                                Period:

                                                    {{ Ctrl.showScheduleType() || '_____' }}

                                        </fieldset>

                                </fieldset>

                        </fieldset>

                </uib-tab>
                <uib-tab heading="Pricing">

Pricing Options

                            Type:

                                {{ Ctrl.showPricingType() || 'not set' }}

                            Unit Price:

                                {{ Ctrl.item.config.pricing.unit_price || 'not set' }}

                </uib-tab>
                <uib-tab heading="Discounts">

Discount Options

                        Enable Discounts
                        <input type="checkbox" ng-model="Ctrl.item.config.discount.enabled" class="form-control"/>

                            Sibling Enrollement
                            <input type="checkbox" ng-model="Ctrl.item.config.discount.siblingenrolled.enabled"/>

                                Discount Amount

                                    {{ Ctrl.item.config.discount.siblingenrolled.amount || 'not set' }}

                </uib-tab>
            </uib-tabset>

    </md-content>


text:
package com.example.hosokawa0589.mytwitterclient;

import android.app.ListActivity;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

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

import twitter4j.ResponseList;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;

public class MainActivity extends ListActivity {
    private TweetAdapter mTweetAdapter;
    private Twitter mTwitter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (!TwitterUtils.hasAccessToken(this)) {
            Intent intent = new Intent(this, TwitterOAuthActivity.class);
            startActivity(intent);
            finish();
        } else {
            mTweetAdapter = new TweetAdapter(this);
            setListAdapter(mTweetAdapter);
            mTwitter = TwitterUtils.getTwitterInstance(this);
            reloadTimeLine();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.menu_refresh) {
            reloadTimeLine();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private void reloadTimeLine() {
        AsyncTask<Void, Void, List<twitter4j.Status>> task = new AsyncTask<Void, Void, List<twitter4j.Status>>() {
            @Override
            protected List<twitter4j.Status> doInBackground(Void... params) {
                try {
                    return mTwitter.getHomeTimeline();
                } catch (TwitterException e) {
                    e.printStackTrace();
                    return null;
                }
            }

            @Override
            protected void onPostExecute(List<twitter4j.Status> statuses) {
                if (statuses != null) {
                    mTweetAdapter.clear();
                    for (twitter4j.Status status : statuses) {
                        mTweetAdapter.add(status);
                    }
                    getListView().setSelection(0);
                } else {
                    showToast("タイムラインの取得に失敗しました");
                }

            }
        };
        task.execute();
    }

    private void showToast(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }
}


text:
static enum TestResult test_available(void)
{
	if (linux_swapoff(0) == linux_ENOSYS)
		return TEST_NOT_SUPPORTED;

	return TEST_SUCCESS;
}

BEGIN_TEST()
	DO_TEST(test_available, "Syscall is available");
END_TEST()


text:
package com.huawei.streaming.cql.tasks;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

import com.huawei.streaming.cql.Driver;
import com.huawei.streaming.cql.LocalTaskCommons;
import static org.junit.Assert.assertTrue;

/**
 * drop application 测试用例
 *
 */
public class DropApplicationTaskTest
{
    /**
     * 初始化测试类之前要执行的初始化方法
     *
     * @throws Exception 初始化中可能抛出的异常
     */
    @BeforeClass
    public static void setUpBeforeClass()
        throws Exception
    {
        LocalTaskCommons.startZookeeperServer();
    }

    /**
     * 所有测试用例执行完毕之后执行的方法
     *
     * @throws Exception 执行异常
     */
    @AfterClass
    public static void tearDownAfterClass()
        throws Exception
    {
        LocalTaskCommons.stopZooKeeperServer();
    }

    /**
     * 测试用例
     *
     * @throws Exception 异常
     */
    @Test
    public void test()
        throws Exception
    {
        runCQL("drop application if exists tt");
    }

    /**
     * 测试用例
     *
     * @throws Exception 流处理异常
     */
    @Test
    public void test2()
        throws Exception
    {
        runCQL("drop application tt");
    }

    private void runCQL(String cql)
        throws Exception
    {
        Driver d = new Driver();
        try
        {
            d.run("set \"streaming.storm.submit.islocal\"='true'");
            d.run("set \"streaming.storm.nimbus.host\"=\"127.0.0.1\"");
            d.run(cql);
        }
        catch (Exception e)
        {
            assertTrue(true);
            return;
        }
        assertTrue(true);
    }
}


text:
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.api.ads.admanager.jaxws.v202205;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;

/**
 *
 *             The action used for pausing programmatic {@link Proposal} objects.
 *
 *
 *
Java class for PauseProposals complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="PauseProposals">
 *   <complexContent>
 *     <extension base="{https://www.google.com/apis/ads/publisher/v202205}ProposalAction">
 *       <sequence>
 *         <element name="reason" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *       </sequence>
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "PauseProposals", propOrder = {
    "reason"
})
public class PauseProposals
    extends ProposalAction
{

    protected String reason;

    /**
     * Gets the value of the reason property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getReason() {
        return reason;
    }

    /**
     * Sets the value of the reason property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setReason(String value) {
        this.reason = value;
    }

}


text:
import { PASSED, FAILED, NOT_FOUND } from 'common/constants/testStatuses';
import { extractNamespacedQuery, createNamespacedQuery } from 'common/utils/routingUtils';
import { NAMESPACE } from './constants';

const validForGrowthDuration = (item) => item.status === FAILED || item.status === PASSED;

export const calculateGrowthDuration = (historyItems) => {
  const historyItemsLastIndex = historyItems.length - 1;
  return historyItems.reverse().map((item, index) => {
    if (!validForGrowthDuration(item) || index >= historyItemsLastIndex) {
      return item;
    }

    const newItem = { ...item };
    let prevItemIndex = index + 1;
    while (
      !validForGrowthDuration(historyItems[prevItemIndex]) &&
      prevItemIndex < historyItemsLastIndex
    ) {
      prevItemIndex += 1;
    }
    if (prevItemIndex <= historyItemsLastIndex) {
      const prevDuration =
        historyItems[prevItemIndex].endTime - historyItems[prevItemIndex].startTime;
      const currentDuration = item.endTime - item.startTime;
      const growth = currentDuration / prevDuration - 1;
      if (growth > 0) {
        newItem.growthDuration = Math.round(growth * 100);
      }
    }
    return newItem;
  });
};

export const normalizeHistoryItem = (historyItem, index) => {
  if (!historyItem) {
    return {
      status: NOT_FOUND,
      id: `${NOT_FOUND}_${index}`,
    };
  }

  return {
    ...historyItem,
    launchNumber: historyItem.pathNames.launchPathName.number,
  };
};

export const getPreviousItem = (testItems = [], currentId) => {
  if (testItems.length < 2) {
    return null;
  }
  const itemIndex = testItems.findIndex((item) => item.id === currentId);
  return testItems[itemIndex - 1] || null;
};

export const getNextItem = (testItems = [], currentId) => {
  const itemIndex = testItems.findIndex((item) => item.id === currentId);

  if (testItems.length < 2) {
    if (itemIndex === -1) {
      return testItems.length === 0 ? null : testItems[0];
    }

    return null;
  }
  return testItems[itemIndex + 1] || null;
};

export const getUpdatedLogQuery = (query, itemId, params = {}) => {
  const previousLogQuery = extractNamespacedQuery(query, NAMESPACE);
  if (previousLogQuery.history) {
    previousLogQuery.history = itemId;
  }
  if (previousLogQuery.retryId) {
    delete previousLogQuery.retryId;
  }
  const newLogQuery = { ...previousLogQuery, ...params };
  return createNamespacedQuery(newLogQuery, NAMESPACE);
};

export const normalizeHistoryItems = (items) => {
  if (!items.length) return [];
  const historyItems = items[0].resources.map(normalizeHistoryItem);

  return calculateGrowthDuration(historyItems);
};

export const updateHistoryItemIssues = (items = [], issues) => {
  return items.map((item) => {
    const itemForUpdate = issues.find((issueForItem) => issueForItem.testItemId === item.id);

    if (itemForUpdate) {
      return {
        ...item,
        issue: itemForUpdate.issue,
      };
    }

    return item;
  });
};

export const updateHistoryItemLaunchAttributes = (items = [], launch) => {
  return items.map((item) => {
    if (item.launchId === launch.id) {
      return {
        ...item,
        launchAttributes: launch.attributes,
      };
    }

    return item;
  });
};

export const getFormattedPageLocation = (pagesLocation = []) =>
  pagesLocation.reduce((acc, curr, i) => {
    const [id] = Object.keys(curr);
    const nextLocation = pagesLocation[i + 1];
    if (!nextLocation) {
      return acc;
    }
    const [nextPage] = Object.values(nextLocation);
    acc.push([id, nextPage]);

    return acc;
  }, []);


text:
namespace ipcz {
namespace {

const IpczDriver& kTestDriver = reference_drivers::kSyncReferenceDriver;

constexpr NodeName kTestBrokerName(1, 2);
constexpr NodeName kTestNonBrokerName(2, 3);

class NodeLinkMemoryTest : public testing::Test {
 public:
  NodeLinkMemory& memory_a() { return link_a_->memory(); }
  NodeLinkMemory& memory_b() { return link_b_->memory(); }

  void SetUp() override {
    auto transports = DriverTransport::CreatePair(kTestDriver);
    DriverMemoryWithMapping buffer =
        NodeLinkMemory::AllocateMemory(kTestDriver);
    link_a_ = NodeLink::CreateInactive(
        node_a_, LinkSide::kA, kTestBrokerName, kTestNonBrokerName,
        Node::Type::kNormal, 0, transports.first,
        NodeLinkMemory::Create(node_a_, std::move(buffer.mapping)));
    link_b_ = NodeLink::CreateInactive(
        node_b_, LinkSide::kB, kTestNonBrokerName, kTestBrokerName,
        Node::Type::kBroker, 0, transports.second,
        NodeLinkMemory::Create(node_b_, buffer.memory.Map()));
    node_a_->AddLink(kTestNonBrokerName, link_a_);
    node_b_->AddLink(kTestBrokerName, link_b_);
    link_a_->Activate();
    link_b_->Activate();
  }

  void TearDown() override {
    node_b_->Close();
    node_a_->Close();
  }

 private:
  const Ref<Node> node_a_{MakeRefCounted<Node>(Node::Type::kBroker,
                                               kTestDriver,
                                               IPCZ_INVALID_DRIVER_HANDLE)};
  const Ref<Node> node_b_{MakeRefCounted<Node>(Node::Type::kNormal,
                                               kTestDriver,
                                               IPCZ_INVALID_DRIVER_HANDLE)};
  Ref<NodeLink> link_a_;
  Ref<NodeLink> link_b_;
};

TEST_F(NodeLinkMemoryTest, BasicAllocAndFree) {
  Fragment fragment = memory_a().AllocateFragment(64);
  EXPECT_TRUE(fragment.is_addressable());
  EXPECT_TRUE(fragment.address());
  EXPECT_EQ(fragment.size(), 64u);
  EXPECT_TRUE(memory_a().FreeFragment(fragment));
}

TEST_F(NodeLinkMemoryTest, Zero) {
  // Zero-sized fragments cannot be allocated.
  EXPECT_TRUE(memory_a().AllocateFragment(0).is_null());
}

TEST_F(NodeLinkMemoryTest, MinimumSize) {
  // Very small fragment sizes a minimum of 64 bytes.
  Fragment fragments[] = {
      memory_a().AllocateFragment(1),  memory_a().AllocateFragment(2),
      memory_a().AllocateFragment(3),  memory_a().AllocateFragment(4),
      memory_a().AllocateFragment(17), memory_a().AllocateFragment(63),
  };

  for (const auto& fragment : fragments) {
    EXPECT_TRUE(fragment.is_addressable());
    EXPECT_EQ(64u, fragment.size());
  }
}

TEST_F(NodeLinkMemoryTest, RoundUpSize) {
  // Fragment sizes are rounded up to the nearest power of 2.
  Fragment fragment = memory_a().AllocateFragment(250);
  EXPECT_TRUE(fragment.is_addressable());
  EXPECT_EQ(256u, fragment.size());
}

TEST_F(NodeLinkMemoryTest, SharedPrimaryBuffer) {
  // Test basic allocation from the primary buffer which both NodeLinkMemory
  // instances share from the moment they're constructed. Each NodeLinkMemory
  // should be able to resolve and free fragments allocated by the other.

  Fragment fragment_from_a = memory_a().AllocateFragment(8);
  EXPECT_TRUE(fragment_from_a.is_addressable());
  EXPECT_EQ(BufferId(0), fragment_from_a.buffer_id());
  EXPECT_GE(fragment_from_a.size(), 8u);

  Fragment same_fragment = memory_b().GetFragment(fragment_from_a.descriptor());
  EXPECT_TRUE(same_fragment.is_addressable());
  EXPECT_EQ(fragment_from_a.buffer_id(), same_fragment.buffer_id());
  EXPECT_EQ(fragment_from_a.offset(), same_fragment.offset());
  EXPECT_EQ(fragment_from_a.size(), same_fragment.size());

  Fragment fragment_from_b = memory_b().AllocateFragment(16);
  EXPECT_TRUE(fragment_from_b.is_addressable());
  EXPECT_EQ(BufferId(0), fragment_from_b.buffer_id());
  EXPECT_GE(fragment_from_b.size(), 16u);

  same_fragment = memory_a().GetFragment(fragment_from_b.descriptor());
  EXPECT_TRUE(same_fragment.is_addressable());
  EXPECT_EQ(fragment_from_b.buffer_id(), same_fragment.buffer_id());
  EXPECT_EQ(fragment_from_b.offset(), same_fragment.offset());
  EXPECT_EQ(fragment_from_b.size(), same_fragment.size());

  EXPECT_TRUE(memory_a().FreeFragment(fragment_from_b));
  EXPECT_TRUE(memory_b().FreeFragment(fragment_from_a));
}

TEST_F(NodeLinkMemoryTest, ExpandCapacity) {
  // If we depelete a NodeLinkMemory's capacity to allocate fragments of a given
  // size, it should automatically acquire new capacity for future allocations.

  constexpr size_t kSize = 64;
  bool has_new_capacity = false;
  memory_a().WaitForBufferAsync(
      BufferId(1), [&has_new_capacity] { has_new_capacity = true; });
  while (!memory_a().AllocateFragment(kSize).is_null())
    ;

  // Since we're using a synchronous driver, this should have already been true
  // by the time the most recent failed allocation returned.
  EXPECT_TRUE(has_new_capacity);

  // And a subsequent allocation request should now succeed with a fragment from
  // the new buffer.
  Fragment fragment = memory_a().AllocateFragment(kSize);
  EXPECT_FALSE(fragment.is_null());
  EXPECT_TRUE(fragment.is_addressable());
  EXPECT_EQ(BufferId(1), fragment.buffer_id());

  // The new buffer should have also been shared with the other NodeLinkMemory
  // already.
  EXPECT_TRUE(memory_b().FreeFragment(fragment));
}

TEST_F(NodeLinkMemoryTest, LimitedCapacityExpansion) {
  // A NodeLinkMemory will eventually stop expanding its capacity for new
  // fragments of a given size.
  static constexpr size_t kSize = 64;
  std::vector<Fragment> fragments;
  auto try_alloc = [&fragments, this] {
    Fragment fragment = memory_a().AllocateFragment(kSize);
    if (!fragment.is_null()) {
      fragments.push_back(fragment);
    }
    return !fragment.is_null();
  };

  do {
    // Deplete the current capacity.
    while (try_alloc()) {
    }

    // Because we're using a synchronous driver, if the NodeLinkMemory will
    // expand its capacity at all, it will have already done so by the time the
    // the failed allocation returns above. So if allocation fails again here,
    // then we've reached the capacity limit for this fragment size and we can
    // end the test.
  } while (try_alloc());

  // Any additionally allocated buffers should already have been shared with the
  // other NodeLinkMemory. Let it free all of the fragments and verify success
  // in every case.
  for (const auto& fragment : fragments) {
    EXPECT_TRUE(memory_b().FreeFragment(fragment));
  }
}

TEST_F(NodeLinkMemoryTest, OversizedAllocation) {
  // Allocations which are too large for block-based allocation will fail for
  // now. This may change as new allocation schemes are supported.
  constexpr size_t kWayTooBig = 64 * 1024 * 1024;
  Fragment fragment = memory_a().AllocateFragment(kWayTooBig);
  EXPECT_TRUE(fragment.is_null());
}

TEST_F(NodeLinkMemoryTest, NewBlockSizes) {
  // NodeLinkMemory begins life with a fixed set of block allocators available
  // for certain common block sizes. These are capped out at 64 kB blocks, but
  // NodeLinkMemory still supports block allocation of larger blocks as well --
  // at least up to 1 MB in size. Verify that we can trigger new capacity for
  // such sizes by attempting to allocate them.

  constexpr size_t kPrettyBig = 512 * 1024;
  Fragment fragment = memory_a().AllocateFragment(kPrettyBig);

  // No initial capacity for 256 kB fragments.
  EXPECT_TRUE(fragment.is_null());

  // But the failure above should have triggered expansion of capacity for that
  // size. This request should succeed.
  fragment = memory_a().AllocateFragment(kPrettyBig);
  EXPECT_FALSE(fragment.is_null());
  EXPECT_TRUE(fragment.is_addressable());
  EXPECT_GE(fragment.size(), kPrettyBig);

  // And as with other cases, the new capacity should have already been shared
  // with the other NodeLinkMemory.
  EXPECT_TRUE(memory_b().FreeFragment(fragment));
}

}  // namespace
}  // namespace ipcz