text:
class SelectBuilder < ActionView::Helpers::FormBuilder

  # We don't have h() here because this module is not included in ActionView::Base.
  def h(str)
    ERB::Util.html_escape(str)
  end

  def country_choices
    @@country_choices ||= Country.ordered.map {|c| [h(c.name), c.id]}
  end

  def country_selector(method = :country_id, options = {}, html_options = {})
    options[:selected] = Country.spain.id unless @object && @object.send(method)
    select method, country_choices, options, html_options
  end

  def customer_choices(account)
    account.customers_ordered.map {|c| [h(c.name), c.id]}
  end

  def customer_selector(account, method = :customer_id, options = {}, html_options = {})
    select method, customer_choices(account), options, html_options
  end

  def salesman_choices(account)
    account.salesmen_ordered.map {|s| [h(s.name), s.id]}
  end

  def salesman_selector(account, method = :salesman_id, options = {}, html_options = {})
    select method, salesman_choices(account), options, html_options
  end

  def status_choices(account)
    account.statuses_ordered.map {|c| [h(c.name), c.id]}
  end

  def status_selector(account, method = :status_id, options = {}, html_options = {})
    select method, status_choices(account), options, html_options
  end
end


text:
module DTKModule
  def self.execute(attributes)
    DTKModule.wrap(attributes, all_types: true) do |all_attributes|
      DTK::Response::Ok.new(success: true)
    end
  end
end

redpajama_set_name: RedPajamaGithub


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

    Copyright 2017 StreamSets Inc.

    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.

-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>com.streamsets</groupId>
    <artifactId>streamsets-datacollector-hdp-stagelib-base</artifactId>
    <version>3.8.0-SNAPSHOT</version>
    <relativePath>../hdp-stagelib-base</relativePath>
  </parent>
  <artifactId>streamsets-datacollector-hdp_2_6-lib</artifactId>
  <version>3.8.0-SNAPSHOT</version>
  <description>StreamSets Data Collector HDP 2.6.0 Lib</description>
  <name>StreamSets Data Collector HDP 2.6.0 Lib</name>
  <packaging>jar</packaging>

  <properties>
    <hadoop.version>2.7.3.2.6.2.1-1</hadoop.version>
    <hbase.version>1.1.2.2.6.2.1-1</hbase.version>
    <scala.version>2.11.11</scala.version>
    <kafka.version>0.10.1.2.6.2.1-1</kafka.version>
    <spark.version>2.1.0.2.6.0.45-1</spark.version>
    <zk-client.version>0.5-1</zk-client.version>
    <avro.version>1.7.7</avro.version>
    <h2.version>1.4.187</h2.version>
    <httpclient.version>4.5.1</httpclient.version>
    <thrift.version>0.9.3</thrift.version>
    <protobuf.version>2.5.0</protobuf.version>
    <aws.java.sdk.version>1.11.134</aws.java.sdk.version>
  </properties>

  <dependencies>
    <!-- HDP's hadoop-aws brings in its own aws-sdk-core which has incompatible jackson dependencies. So instead
    manually add the sdk-bundle (which has relocated package names) -->
    <dependency>
      <groupId>com.amazonaws</groupId>
      <artifactId>aws-java-sdk-bundle</artifactId>
      <scope>compile</scope>
      <version>${aws.java.sdk.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.hadoop</groupId>
      <artifactId>hadoop-aws</artifactId>
      <version>${hadoop.version}</version>
      <exclusions>
        <exclusion>
          <groupId>com.fasterxml.jackson.core</groupId>
          <artifactId>jackson-core</artifactId>
        </exclusion>
        <exclusion>
          <groupId>com.fasterxml.jackson.core</groupId>
          <artifactId>jackson-databind</artifactId>
        </exclusion>
        <exclusion>
          <groupId>com.fasterxml.jackson.core</groupId>
          <artifactId>jackson-annotations</artifactId>
        </exclusion>
        <exclusion>
          <groupId>org.apache.hadoop</groupId>
          <artifactId>hadoop-common</artifactId>
        </exclusion>
        <exclusion>
          <groupId>com.amazonaws</groupId>
          <artifactId>aws-java-sdk-s3</artifactId>
        </exclusion>
        <exclusion>
          <groupId>com.amazonaws</groupId>
          <artifactId>aws-java-sdk</artifactId>
        </exclusion>
        <exclusion>
          <groupId>com.amazonaws</groupId>
          <artifactId>aws-java-sdk-core</artifactId>
        </exclusion>
        <exclusion>
          <groupId>com.amazonaws</groupId>
          <artifactId>aws-java-sdk-kms</artifactId>
        </exclusion>
      </exclusions>
    </dependency>
    <dependency>
      <groupId>org.scala-lang</groupId>
      <artifactId>scala-library</artifactId>
      <version>${scala.version}</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.spark</groupId>
      <artifactId>spark-streaming-kafka-0-10_2.11</artifactId>
      <version>${spark.version}</version>
      <scope>compile</scope>
    </dependency>

    <!-- Provided Dependencies -->
    <dependency>
      <groupId>com.streamsets</groupId>
      <artifactId>streamsets-datacollector-api</artifactId>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>io.dropwizard.metrics</groupId>
      <artifactId>metrics-core</artifactId>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>com.streamsets</groupId>
      <artifactId>streamsets-datacollector-sdk</artifactId>
      <version>${project.version}</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>com.streamsets</groupId>
      <artifactId>streamsets-datacollector-cluster-bootstrap-api</artifactId>
      <scope>provided</scope>
    </dependency>

    <!-- Compile Dependencies -->
    <dependency>
      <groupId>com.streamsets</groupId>
      <artifactId>streamsets-datacollector-hdfs-protolib</artifactId>
    </dependency>

    <dependency>
      <groupId>com.streamsets</groupId>
      <artifactId>streamsets-datacollector-mapreduce-protolib</artifactId>
    </dependency>

    <dependency>
      <groupId>com.streamsets</groupId>
      <artifactId>streamsets-datacollector-cluster-hdfs-protolib</artifactId>
      <version>${project.version}</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.avro</groupId>
      <artifactId>avro-mapred</artifactId>
      <version>${avro.version}</version>
      <classifier>hadoop2</classifier>
    </dependency>
    <dependency>
      <groupId>org.apache.avro</groupId>
      <artifactId>avro</artifactId>
      <version>${avro.version}</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
    </dependency>
    <dependency>
      <groupId>org.apache.hadoop</groupId>
      <artifactId>hadoop-client</artifactId>
      <version>${hadoop.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient</artifactId>
      <version>${httpclient.version}</version>
    </dependency>

    <!-- This MUST appear after hdfs-protolib as we override classes from hadoop-common
         which is a transitive dependency of this one. -->
    <dependency>
      <groupId>org.apache.hadoop</groupId>
      <artifactId>hadoop-azure</artifactId>
      <version>${hadoop.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.hadoop</groupId>
      <artifactId>hadoop-azure-datalake</artifactId>
      <version>${hadoop.version}</version>
    </dependency>

    <!-- HBase related -->
    <dependency>
      <groupId>com.streamsets</groupId>
      <artifactId>streamsets-datacollector-hbase-protolib</artifactId>
      <version>${project.version}</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>com.streamsets</groupId>
      <artifactId>streamsets-datacollector-sdc-hbase-0_98</artifactId>
      <version>${project.version}</version>
      <scope>compile</scope>
      <exclusions>
        <exclusion>
          <groupId>org.apache.hbase</groupId>
          <artifactId>hbase-client</artifactId>
        </exclusion>
        <exclusion>
          <groupId>org.htrace</groupId>
          <artifactId>htrace-core</artifactId>
        </exclusion>
      </exclusions>
    </dependency>
    <dependency>
      <groupId>org.apache.hbase</groupId>
      <artifactId>hbase-client</artifactId>
      <version>${hbase.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.hbase</groupId>
      <artifactId>hbase-testing-util</artifactId>
      <version>${hbase.version}</version>
      <scope>test</scope>
    </dependency>

    <!-- Kafka related -->
    <dependency>
      <groupId>com.streamsets</groupId>
      <artifactId>streamsets-datacollector-sdc-kafka-10</artifactId>
      <version>${project.version}</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>com.streamsets</groupId>
      <artifactId>streamsets-datacollector-sdc-kafka-10</artifactId>
      <version>${project.version}</version>
      <type>test-jar</type>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.streamsets</groupId>
      <artifactId>streamsets-datacollector-cluster-kafka-protolib</artifactId>
      <version>${project.version}</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>com.streamsets</groupId>
      <artifactId>streamsets-datacollector-kafka_source-protolib</artifactId>
      <version>${project.version}</version>
    </dependency>
    <dependency>
      <groupId>com.streamsets</groupId>
      <artifactId>streamsets-datacollector-kafka_multisource-0_10-protolib</artifactId>
      <version>${project.version}</version>
    </dependency>
    <dependency>
      <groupId>com.streamsets</groupId>
      <artifactId>streamsets-datacollector-kafka_target-protolib</artifactId>
      <version>${project.version}</version>
    </dependency>
    <dependency>
      <groupId>com.streamsets</groupId>
      <artifactId>streamsets-datacollector-kafka-common</artifactId>
      <version>${project.version}</version>
      <type>test-jar</type>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.kafka</groupId>
      <artifactId>kafka_2.11</artifactId>
      <version>${kafka.version}</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>com.101tec</groupId>
      <artifactId>zkclient</artifactId>
      <version>${zk-client.version}</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.kafka</groupId>
      <artifactId>kafka_2.11</artifactId>
      <version>${kafka.version}</version>
      <classifier>test</classifier>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.kafka</groupId>
      <artifactId>kafka-clients</artifactId>
      <version>${kafka.version}</version>
      <classifier>test</classifier>
      <scope>test</scope>
    </dependency>

    <!-- Test dependencies-->
    <dependency>
      <groupId>com.streamsets</groupId>
      <artifactId>streamsets-datacollector-stagesupport</artifactId>
      <type>test-jar</type>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.streamsets</groupId>
      <artifactId>streamsets-datacollector-commonlib</artifactId>
      <version>${project.version}</version>
      <type>test-jar</type>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.streamsets</groupId>
      <artifactId>streamsets-datacollector-dir-spooler-protolib</artifactId>
      <type>test-jar</type>
      <version>${project.version}</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.google.protobuf</groupId>
      <artifactId>protobuf-java</artifactId>
      <version>${protobuf.version}</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.bouncycastle</groupId>
      <artifactId>bcprov-jdk15on</artifactId>
      <version>${bouncycastle.version}</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.h2database</groupId>
      <artifactId>h2</artifactId>
      <version>${h2.version}</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.hadoop</groupId>
      <artifactId>hadoop-minicluster</artifactId>
      <version>${hadoop.version}</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.mockito</groupId>
      <artifactId>mockito-core</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.powermock</groupId>
      <artifactId>powermock-module-junit4</artifactId>
      <version>${powermock.version}</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.powermock</groupId>
      <artifactId>powermock-api-mockito</artifactId>
      <version>${powermock.version}</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.streamsets</groupId>
      <artifactId>streamsets-testing</artifactId>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>

    <plugins>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>build-helper-maven-plugin</artifactId>
        <executions>
          <execution>
            <id>add-test-source</id>
            <phase>generate-test-sources</phase>
            <goals>
              <goal>add-test-source</goal>
            </goals>
            <configuration>
              <sources>
                <source>${basedir}/../hdfs-protolib/src/test/java</source>
                <source>${basedir}/../mapreduce-protolib/src/test/java</source>
                <source>${basedir}/../hbase-protolib/src/test/java</source>
                <source>${basedir}/../kafka_source-protolib/src/test/java</source>
                <source>${basedir}/../kafka_multisource-protolib/src/test/java</source>
                <source>${basedir}/../kafka_target-protolib/src/test/java</source>
                <source>${basedir}/../cluster-hdfs-protolib/src/test/java</source>
              </sources>
            </configuration>
          </execution>
          <execution>
            <id>add-test-resources</id>
            <phase>generate-test-resources</phase>
            <goals>
              <goal>add-test-resource</goal>
            </goals>
            <configuration>
              <resources>
                <resource>
                  <directory>${basedir}/../hdfs-protolib/src/test/resources</directory>
                </resource>
                <resource>
                  <directory>${basedir}/../mapreduce-protolib/src/test/resources</directory>
                </resource>
                <resource>
                  <directory>${basedir}/../hbase-protolib/src/test/resources</directory>
                </resource>
                <resource>
                  <directory>${basedir}/../kafka_source-protolib/src/test/resources</directory>
                </resource>
                <resource>
                  <directory>${basedir}/../kafka_multisource-protolib/src/test/resources</directory>
                </resource>
                <resource>
                  <directory>${basedir}/../kafka_target-protolib/src/test/resources</directory>
                </resource>
                <resource>
                  <directory>${basedir}/../cluster-hdfs-protolib/src/test/resources</directory>
                </resource>
              </resources>
            </configuration>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-deploy-plugin</artifactId>
        <version>2.8.2</version>
        <configuration>
          <skip>true</skip>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>


text:
using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Razor;
using Microsoft.CSharp;

namespace Mios.Mail.Templating {
	[Serializable]
	public class RazorTemplateFactoryException : Exception {
		public RazorTemplateFactoryException() {}
		public RazorTemplateFactoryException(string messageFormat, params object[] parameters) : base(String.Format(messageFormat,parameters)) { }
		public RazorTemplateFactoryException(string message) : base(message) { }
		public RazorTemplateFactoryException(string message, Exception inner) : base(message, inner) { }
		protected RazorTemplateFactoryException( SerializationInfo info, StreamingContext context) : base(info, context) {}
	}

	public class RazorTemplateFactory {
		public IList<string> NamespaceImports { get; protected set; }
		public IList<string> AssemblyReferences { get; protected set; }
		public RazorTemplateFactory() {
			NamespaceImports = new List<string>();
			AssemblyReferences = new List<string>();
		}
		public RazorTemplate<T> CreateTemplate<T>(TextReader sourceReader) {
			return CreateTemplateImpl<RazorTemplate<T>>(sourceReader, NamespaceImports, AssemblyReferences);
		}
		public RazorHtmlTemplate<T> CreateHtmlTemplate<T>(TextReader sourceReader) {
			return CreateTemplateImpl<RazorHtmlTemplate<T>>(sourceReader, NamespaceImports, AssemblyReferences);
		}
		public DynamicRazorTemplate CreateDynamicTemplate(TextReader sourceReader) {
			return CreateTemplateImpl<DynamicRazorTemplate>(sourceReader, NamespaceImports, AssemblyReferences);
		}
		public DynamicRazorHtmlTemplate CreateDynamicHtmlTemplate(TextReader sourceReader) {
			return CreateTemplateImpl<DynamicRazorHtmlTemplate>(sourceReader, NamespaceImports, AssemblyReferences);
		}

		private static T CreateTemplateImpl<T>(TextReader sourceReader, IEnumerable<string> namespaceImports, IEnumerable<string> assemblyReferences) where T : class {
			var host = new RazorEngineHost(new CSharpRazorCodeLanguage());
			host.DefaultBaseClass = typeof(T).FullName;
			host.NamespaceImports.Add("System");
			foreach(var ns in namespaceImports)
				host.NamespaceImports.Add(ns);
			var result = new RazorTemplateEngine(host).GenerateCode(sourceReader);
			var templateAssembly = CompileTemplate(result.GeneratedCode, assemblyReferences);
			var typeName = host.DefaultNamespace+"."+host.DefaultClassName;
			return InstantiateTemplate<T>(templateAssembly, typeName);
		}

		private static Assembly CompileTemplate(CodeCompileUnit codeCompileUnit, IEnumerable<string> assemblyReferences) {
			var codeProvider = new CSharpCodeProvider();
			var parameters = new CompilerParameters(
				AppDomain.CurrentDomain.GetAssemblies()
					.Where(t => !t.IsDynamic)
					.Concat(new[] { Assembly.Load("Microsoft.CSharp, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a") })
					.Concat(assemblyReferences.Select(t => Assembly.Load(t)))
					.Select(t => t.Location)
					.Distinct()
					.ToArray()
			);
			parameters.GenerateInMemory = true;
			var results = codeProvider.CompileAssemblyFromDom(parameters,codeCompileUnit);
			if(results.Errors.HasErrors) {
				var err = results.Errors
					.OfType<CompilerError>()
					.First(ce => !ce.IsWarning);
				throw new RazorTemplateFactoryException(
					"Error Compiling Template: ({0}, {1}) {2}",
					err.Line, err.Column, err.ErrorText);
			}
			return results.CompiledAssembly;
		}

		private static T InstantiateTemplate<T>(Assembly templateAssembly, string typeName) where T: class {
			var templateType = templateAssembly.GetType(typeName);
			if(templateType == null) {
				throw new RazorTemplateFactoryException(
					"Could not find requested type {0} in assembly {1}",
					typeName, templateAssembly.FullName);
			}
			var template = Activator.CreateInstance(templateType) as T;
			if(template == null) {
				throw new RazorTemplateFactoryException(
					"Could not construct template or it does not inherit from {0}",
					typeof(T).Name);
			}
			return template;
		}
	}
}


text:
import React from 'react'
import PropTypes from 'prop-types'

import AreaChartComponent from './AreaChartComponent'
import BarChartComponent from './BarChartComponent'
import LineChartComponent from './LineChartComponent'

const ReChartsComponent = ({ type }) => {
  if (type === 'areaChart') return <AreaChartComponent />
  if (type === 'barChart') return <BarChartComponent />
  return <LineChartComponent />
}

ReChartsComponent.propTypes = {
  type: PropTypes.string,
}

export default ReChartsComponent


text:
#import <Foundation/Foundation.h>
#import "VLCMediaList.h"
#import "VLCTime.h"

/* Meta Dictionary Keys */
/**
 * Standard dictionary keys for retreiving meta data.
 */
extern NSString *const VLCMetaInformationTitle;          /* NSString */
extern NSString *const VLCMetaInformationArtist;         /* NSString */
extern NSString *const VLCMetaInformationGenre;          /* NSString */
extern NSString *const VLCMetaInformationCopyright;      /* NSString */
extern NSString *const VLCMetaInformationAlbum;          /* NSString */
extern NSString *const VLCMetaInformationTrackNumber;    /* NSString */
extern NSString *const VLCMetaInformationDescription;    /* NSString */
extern NSString *const VLCMetaInformationRating;         /* NSString */
extern NSString *const VLCMetaInformationDate;           /* NSString */
extern NSString *const VLCMetaInformationSetting;        /* NSString */
extern NSString *const VLCMetaInformationURL;            /* NSString */
extern NSString *const VLCMetaInformationLanguage;       /* NSString */
extern NSString *const VLCMetaInformationNowPlaying;     /* NSString */
extern NSString *const VLCMetaInformationPublisher;      /* NSString */
extern NSString *const VLCMetaInformationEncodedBy;      /* NSString */
extern NSString *const VLCMetaInformationArtworkURL;     /* NSString */
extern NSString *const VLCMetaInformationArtwork;        /* NSImage  */
extern NSString *const VLCMetaInformationTrackID;        /* NSString */

/* Notification Messages */
/**
 * Available notification messages.
 */
extern NSString *const VLCMediaMetaChanged;  //< Notification message for when the media's meta data has changed

// Forward declarations, supresses compiler error messages
@class VLCMediaList;
@class VLCMedia;

enum {
    VLCMediaStateNothingSpecial,        //< Nothing
    VLCMediaStateBuffering,             //< Stream is buffering
    VLCMediaStatePlaying,               //< Stream is playing
    VLCMediaStateError,                 //< Can't be played because an error occurred
};
typedef NSInteger VLCMediaState;

/**
 * Informal protocol declaration for VLCMedia delegates.  Allows data changes to be
 * trapped.
 */
@protocol VLCMediaDelegate
// TODO: SubItemAdded/SubItemRemoved implementation.  Not sure if we really want to implement this.
///**
// * Delegate method called whenever a sub item has been added to the specified VLCMedia.
// * \param aMedia The media resource that has received the new sub item.
// * \param childMedia The new sub item added.
// * \param index Location of the new subitem in the aMedia's sublist.
// */
// - (void)media:(VLCMedia *)media addedSubItem:(VLCMedia *)childMedia atIndex:(int)index;

///**
// * Delegate method called whenever a sub item has been removed from the specified VLCMedia.
// * \param aMedia The media resource that has had a sub item removed from.
// * \param childMedia The sub item removed.
// * \param index The previous location of the recently removed sub item.
// */
// - (void)media:(VLCMedia *)aMedia removedSubItem:(VLCMedia *)childMedia atIndex:(int)index;

/**
 * Delegate method called whenever the meta has changed for the receiver.
 * \param aMedia The media resource whose meta data has been changed.
 * \param oldValue The old meta data value.
 * \param key The key of the value that was changed.
 */
- (void)media:(VLCMedia *)aMedia metaValueChangedFrom:(id)oldValue forKey:(NSString *)key __attribute__((deprecated));

/**
 * Delegate method called whenever the media's meta data was changed for whatever reason
 * \note this is called more often than mediaDidFinishParsing, so it may be less efficient
 * \param aMedia The media resource whose meta data has been changed.
 */
- (void)mediaMetaDataDidChange:(VLCMedia *)aMedia;

/**
 * Delegate method called whenever the media was parsed.
 * \param aMedia The media resource whose meta data has been changed.
 */

- (void)mediaDidFinishParsing:(VLCMedia *)aMedia;
@end

/**
 * Defines files and streams as a managed object.  Each media object can be
 * administered seperately.  VLCMediaPlayer or VLCMediaList must be used
 * to execute the appropriate playback functions.
 * \see VLCMediaPlayer
 * \see VLCMediaList
 */
@interface VLCMedia : NSObject
{
    void *                p_md;              //< Internal media descriptor instance
    NSURL *               url;               //< URL (MRL) for this media resource
    VLCMediaList *        subitems;          //< Sub list of items
    VLCTime *             length;            //< Cached duration of the media
    NSMutableDictionary * metaDictionary;    //< Meta data storage
    id                    delegate;          //< Delegate object
    BOOL                  isArtFetched;      //< Value used to determine of the artwork has been parsed
    BOOL                  areOthersMetaFetched; //< Value used to determine of the other meta has been parsed
    BOOL                  isArtURLFetched;   //< Value used to determine of the other meta has been preparsed
    VLCMediaState         state;             //< Current state of the media
    BOOL                  isParsed;
}

/* Factories */
/**
 * Manufactures a new VLCMedia object using the URL specified.
 * \param anURL URL to media to be accessed.
 * \return A new VLCMedia object, only if there were no errors.  This object will be automatically released.
 * \see initWithMediaURL
 */
+ (id)mediaWithURL:(NSURL *)anURL;

/**
 * Manufactures a new VLCMedia object using the path specified.
 * \param aPath Path to the media to be accessed.
 * \return A new VLCMedia object, only if there were no errors.  This object will be automatically released.
 * \see initWithPath
 */
+ (id)mediaWithPath:(NSString *)aPath;

/**
 * TODO
 * \param aName TODO
 * \return a new VLCMedia object, only if there were no errors.  This object
 * will be automatically released.
 * \see initAsNodeWithName
 */
+ (id)mediaAsNodeWithName:(NSString *)aName;

/* Initializers */
/**
 * Initializes a new VLCMedia object to use the specified URL.
 * \param aPath Path to media to be accessed.
 * \return A new VLCMedia object, only if there were no errors.
 */
- (id)initWithURL:(NSURL *)anURL;

/**
 * Initializes a new VLCMedia object to use the specified path.
 * \param aPath Path to media to be accessed.
 * \return A new VLCMedia object, only if there were no errors.
 */
- (id)initWithPath:(NSString *)aPath;

/**
 * TODO
 * \param aName TODO
 * \return A new VLCMedia object, only if there were no errors.
 */
- (id)initAsNodeWithName:(NSString *)aName;

/**
 * Returns an NSComparisonResult value that indicates the lexical ordering of
 * the receiver and a given meda.
 * \param media The media with which to compare with the receiver.
 * \return NSOrderedAscending if the URL of the receiver precedes media in
 * lexical ordering, NSOrderedSame if the URL of the receiver and media are
 * equivalent in lexical value, and NSOrderedDescending if the URL of the
 * receiver follows media. If media is nil, returns NSOrderedDescending.
 */
- (NSComparisonResult)compare:(VLCMedia *)media;

/* Properties */
/**
 * Receiver's delegate.
 */
@property (assign) id delegate;

/**
 * A VLCTime object describing the length of the media resource, only if it is
 * available.  Use lengthWaitUntilDate: to wait for a specified length of time.
 * \see lengthWaitUntilDate
 */
@property (retain, readonly) VLCTime * length;

/**
 * Returns a VLCTime object describing the length of the media resource,
 * however, this is a blocking operation and will wait until the preparsing is
 * completed before returning anything.
 * \param aDate Time for operation to wait until, if there are no results
 * before specified date then nil is returned.
 * \return The length of the media resource, nil if it couldn't wait for it.
 */
- (VLCTime *)lengthWaitUntilDate:(NSDate *)aDate;

/**
 * Determines if the media has already been preparsed.
 */
@property (readonly) BOOL isParsed;

/**
 * The URL for the receiver's media resource.
 */
@property (retain, readonly) NSURL * url;

/**
 * The receiver's sub list.
 */
@property (retain, readonly) VLCMediaList * subitems;

/**
 * get meta property for key
 * \note for performance reasons, fetching the metaDictionary will be faster!
 * \see metaDictionary
 * \see dictionary keys above
 */
- (NSString *)metadataForKey:(NSString *)key;

/**
 * set meta property for key
 * \param metadata to set as NSString
 * \param metadata key
 * \see dictionary keys above
 */
- (void)setMetadata:(NSString *)data forKey:(NSString *)key;

/**
 * Save the previously changed metadata
 * \return true if saving was successful
 */
- (BOOL)saveMetadata;

/**
 * The receiver's meta data as a NSDictionary object.
 */
@property (retain, readonly) NSDictionary * metaDictionary;

/**
 * The receiver's state, such as Playing, Error, NothingSpecial, Buffering.
 */
@property (readonly) VLCMediaState state;

/**
 * returns a bool whether is the media is expected to play fluently on this
 * device or not. It always returns YES on a Mac.*/
- (BOOL)isMediaSizeSuitableForDevice;

/**
 * Tracks information NSDictionary Possible Keys
 */

/**
 * \returns a NSNumber
 */
extern NSString *const VLCMediaTracksInformationCodec;

/**
 * \returns a NSNumber
 */
extern NSString *const VLCMediaTracksInformationId;
/**
 * \returns a NSString
 * \see VLCMediaTracksInformationTypeAudio
 * \see VLCMediaTracksInformationTypeVideo
 * \see VLCMediaTracksInformationTypeText
 * \see VLCMediaTracksInformationTypeUnknown
 */
extern NSString *const VLCMediaTracksInformationType;

/**
 * \returns a NSNumber
 */
extern NSString *const VLCMediaTracksInformationCodecProfile;
/**
 * \returns a NSNumber
 */
extern NSString *const VLCMediaTracksInformationCodecLevel;

/**
 * \returns the bitrate as NSNumber
 */
extern NSString *const VLCMediaTracksInformationBitrate;
/**
 * \returns the language as NSString
 */
extern NSString *const VLCMediaTracksInformationLanguage;
/**
 * \returns the description as NSString
 */
extern NSString *const VLCMediaTracksInformationDescription;

/**
 * \returns the audio channel number as NSNumber
 */
extern NSString *const VLCMediaTracksInformationAudioChannelsNumber;
/**
 * \returns the audio rate as NSNumber
 */
extern NSString *const VLCMediaTracksInformationAudioRate;

/**
 * \returns the height as NSNumber
 */
extern NSString *const VLCMediaTracksInformationVideoHeight;
/**
 * \returns the width as NSNumber
 */
extern NSString *const VLCMediaTracksInformationVideoWidth;

/**
 * \returns the source aspect ratio as NSNumber
 */
extern NSString *const VLCMediaTracksInformationSourceAspectRatio;
/**
 * \returns the source aspect ratio denominator as NSNumber
 */
extern NSString *const VLCMediaTracksInformationSourceAspectRatioDenominator;

/**
 * \returns the frame rate as NSNumber
 */
extern NSString *const VLCMediaTracksInformationFrameRate;
/**
 * \returns the frame rate denominator as NSNumber
 */
extern NSString *const VLCMediaTracksInformationFrameRateDenominator;

/**
 * \returns the text encoding as NSString
 */
extern NSString *const VLCMediaTracksInformationTextEncoding;

/**
 * Tracks information NSDictionary values for
 * VLCMediaTracksInformationType
 */
extern NSString *const VLCMediaTracksInformationTypeAudio;
extern NSString *const VLCMediaTracksInformationTypeVideo;
extern NSString *const VLCMediaTracksInformationTypeText;
extern NSString *const VLCMediaTracksInformationTypeUnknown;

/**
 * Returns the tracks information.
 *
 * This is an array of NSDictionary representing each track.
 * It can contain the following keys:
 *
 * \see VLCMediaTracksInformationCodec
 * \see VLCMediaTracksInformationId
 * \see VLCMediaTracksInformationType
 *
 * \see VLCMediaTracksInformationCodecProfile
 * \see VLCMediaTracksInformationCodecLevel
 *
 * \see VLCMediaTracksInformationBitrate
 * \see VLCMediaTracksInformationLanguage
 * \see VLCMediaTracksInformationDescription
 *
 * \see VLCMediaTracksInformationAudioChannelsNumber
 * \see VLCMediaTracksInformationAudioRate
 *
 * \see VLCMediaTracksInformationVideoHeight
 * \see VLCMediaTracksInformationVideoWidth
 *
 * \see VLCMediaTracksInformationSourceAspectRatio
 * \see VLCMediaTracksInformationSourceAspectDenominator
 *
 * \see VLCMediaTracksInformationFrameRate
 * \see VLCMediaTracksInformationFrameRateDenominator
 *
 * \see VLCMediaTracksInformationTextEncoding
 */

- (NSArray *)tracksInformation;

/**
 * Start asynchronously to parse the media.
 * This will attempt to fetch the meta data and tracks information.
 *
 * This is automatically done when an accessor requiring parsing
 * is called.
 *
 * \see -[VLCMediaDelegate mediaDidFinishParsing:]
 */
- (void)parse;

/**
 * Trigger a synchronous parsing of the media
 * the selector won't return until parsing finished
 */
- (void)synchronousParse;

/**
 * Add options to the media, that will be used to determine how
 * VLCMediaPlayer will read the media. This allow to use VLC advanced
 * reading/streaming options in a per-media basis
 *
 * The options are detailed in vlc --long-help, for instance "--sout-all"
 * And on the web: http://wiki.videolan.org/VLC_command-line_help
*/
- (void) addOptions:(NSDictionary*) options;

/**
 * Getter for statistics information
 * Returns a NSDictionary with NSNumbers for values.
 *
 */
- (NSDictionary*) stats;

#pragma mark - individual stats

/**
 * returns the number of bytes read by the current input module
 * \return a NSInteger with the raw number of bytes
 */
- (NSInteger)numberOfReadBytesOnInput;
/**
 * returns the current input bitrate. may be 0 if the buffer is full
 * \return a float of the current input bitrate
 */
- (float)inputBitrate;

/**
 * returns the number of bytes read by the current demux module
 * \return a NSInteger with the raw number of bytes
 */
- (NSInteger)numberOfReadBytesOnDemux;
/**
 * returns the current demux bitrate. may be 0 if the buffer is empty
 * \return a float of the current demux bitrate
 */
- (float)demuxBitrate;

/**
 * returns the total number of decoded video blocks in the current media session
 * \return a NSInteger with the total number of decoded blocks
 */
- (NSInteger)numberOfDecodedVideoBlocks;
/**
 * returns the total number of decoded audio blocks in the current media session
 * \return a NSInteger with the total number of decoded blocks
 */
- (NSInteger)numberOfDecodedAudioBlocks;

/**
 * returns the total number of displayed pictures during the current media session
 * \return a NSInteger with the total number of displayed pictures
 */
- (NSInteger)numberOfDisplayedPictures;
/**
 * returns the total number of pictures lost during the current media session
 * \return a NSInteger with the total number of lost pictures
 */
- (NSInteger)numberOfLostPictures;

/**
 * returns the total number of played audio buffers during the current media session
 * \return a NSInteger with the total number of played audio buffers
 */
- (NSInteger)numberOfPlayedAudioBuffers;
/**
 * returns the total number of audio buffers lost during the current media session
 * \return a NSInteger with the total number of displayed pictures
 */
- (NSInteger)numberOfLostAudioBuffers;

/**
 * returns the total number of packets sent during the current media session
 * \return a NSInteger with the total number of sent packets
 */
- (NSInteger)numberOfSentPackets;
/**
 * returns the total number of raw bytes sent during the current media session
 * \return a NSInteger with the total number of sent bytes
 */
- (NSInteger)numberOfSentBytes;
/**
 * returns the current bitrate of sent bytes
 * \return a float of the current bitrate of sent bits
 */
- (float)streamOutputBitrate;
/**
 * returns the total number of corrupted data packets during current sout session
 * \note value is 0 on non-stream-output operations
 * \return a NSInteger with the total number of corrupted data packets
 */
- (NSInteger)numberOfCorruptedDataPackets;
/**
 * returns the total number of discontinuties during current sout session
 * \note value is 0 on non-stream-output operations
 * \return a NSInteger with the total number of discontinuties
 */
- (NSInteger)numberOfDiscontinuties;

@end


text:
//
//  POOLikedViewController.m
//  OutputFaceBookData
//
//  Created by Oleh Petrunko on 11.04.16.
//  Copyright © 2016 Oleh Petrunko. All rights reserved.
//

#import "POOLikedViewController.h"
#import "StringLocalizer.h"

static NSString *MyIdentifier = @"LikedCellIdentifier";

@interface POOLikedViewController ()

@property (strong, nonatomic) NSArray *someArray;

@end

@implementation POOLikedViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self buildHeader];
    self.someArray = [NSArray arrayWithObjects:@"1",@"2",@"3",@"4", nil];
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

#pragma mark - TableView delegat and datasource
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.someArray.count;
    }

- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault  reuseIdentifier:MyIdentifier];
    }

    if ((self.someArray.count - 1) == indexPath.row ) {
        cell.backgroundColor = [[self class] colorWithPatternImage];
        cell.accessoryView = [[UIImageView alloc]initWithImage:
                              [UIImage imageNamed:@"DarkArrow"]];
        cell.textLabel.text = [@"invaiteFriends" localized];
    }
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    cell.textLabel.text = @"Test String";

    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {

    UILabel *lable = [[UILabel alloc] init];
    lable.numberOfLines = 0;
    lable.lineBreakMode = NSLineBreakByWordWrapping;
    lable.text = [@"FooterTitle" localized];
    lable.textAlignment = NSTextAlignmentCenter;
    lable.textColor = [UIColor colorWithRed:100.0f/255.0f green:109.0f/255.0f blue:122.0f/255.0f alpha:1.0f];
    lable.font  = [UIFont fontWithName:@"HelveticaNeue-Medium" size:20];
    [lable setBackgroundColor:[[self class] colorWithPatternImage]];

    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, lable.frame.size.height - 2.0, tableView.frame.size.width, 2)];

    lineView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"SepparationLine"]];
    [lable addSubview:lineView];

    return lable;
}

+ (UIColor *)colorWithPatternImage {
    return [UIColor colorWithPatternImage:[UIImage imageNamed: @"Background"]];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 140;
}

#pragma mark - UI
- (void)buildHeader {
    [self.navigationController.navigationBar setBackgroundImage:[[UIImage imageNamed:@"Header"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, 0) resizingMode:UIImageResizingModeStretch] forBarPosition:UIBarPositionTopAttached barMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.topItem.title = [@"Liked" localized];
    [self.navigationController.navigationBar setTitleTextAttributes:
     @{NSForegroundColorAttributeName:[UIColor whiteColor]}];

    [self creatLeftHeaderButton];
    [self creatRightHeaderButton];

}

- (void)creatLeftHeaderButton {
    UIImage *headerButtonImg = [UIImage imageNamed:@"TopButton"];

    UIButton *edit = [UIButton buttonWithType:UIButtonTypeCustom];
    edit.bounds = CGRectMake( 0, 0, headerButtonImg.size.width, headerButtonImg.size.height );
    [edit setBackgroundImage:headerButtonImg forState:UIControlStateNormal];
    [edit setTitle:[@"POOLikedViewController.editButton" localized] forState:UIControlStateNormal];
    edit.titleLabel.font = [UIFont fontWithName:@"Helvetica" size:14];
    [edit addTarget:self action:@selector(edit) forControlEvents:UIControlEventTouchUpInside];

    UIBarButtonItem *customCancelButton = [[UIBarButtonItem alloc] initWithCustomView:edit];
    self.navigationController.topViewController.navigationItem.leftBarButtonItem = customCancelButton;
}

- (void)edit {

}

- (void)creatRightHeaderButton {
    UIImage *headerButtonImg = [UIImage imageNamed:@"AddBackGround"];

    UIButton *add = [UIButton buttonWithType:UIButtonTypeCustom];
    add.bounds = CGRectMake( 0, 0, headerButtonImg.size.width, headerButtonImg.size.height );
    [add setBackgroundImage:headerButtonImg forState:UIControlStateNormal];
    [add setImage:[UIImage imageNamed:@"Add"] forState:UIControlStateNormal];
    [add setTitle:@"" forState:UIControlStateNormal];
    add.titleLabel.font = [UIFont fontWithName:@"Helvetica" size:14];
    [add addTarget:self action:@selector(add) forControlEvents:UIControlEventTouchUpInside];

    UIBarButtonItem *customCancelButton = [[UIBarButtonItem alloc] initWithCustomView:add];
    self.navigationController.topViewController.navigationItem.rightBarButtonItem = customCancelButton;
}

- (void)add {

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


text:
GPP_FLAGS = --std=gnu++11 -msse -I../MamdaniMatrix -O3 -ffast-math -msse3 -Wno-unused-result

MSCProj.bin: Main.cpp ../MamdaniMatrix/mamdani.ixx
	g++ $(GPP_FLAGS) Main.cpp -o MSCProj.bin

../MamdaniMatrix/mamdani.ixx: ../MamdaniMatrix/gen_cleaned.pl
	sh -c 'cd ../MamdaniMatrix/ && perl ./gen_cleaned.pl'

clean:
	rm -f MSCProj.bin


text:
<?php

namespace temple\web\html\bootstrap;

/**
 * Description of AbstractComponent
 *
 * @author florent
 */
abstract class AbstractComponent extends \temple\web\html\AbstractFrameworkComponent implements Component {

	/**
	 * @var \temple\web\html\HTMLNode
	 */
	private $help ;

	public function __construct($nodeType, $cssClass = null) {
		parent::__construct($nodeType) ;
		$this->addCssClass($cssClass) ;
	}

	/**
	 *
	 * @param type $cssClass
	 * @param array $complements
	 * @return AbstractComponent
	 */
	public final function addCompositeCssClass($cssBaseClass, CssVariant $variant = null) {
		if($cssBaseClass) {
			$variant_ = _dif($variant, CssVariant::$_) ;
			$this->addCssClass($variant_->compose($cssBaseClass)) ;
		}
		return $this ;
	}

	public final function getTitle() {
		return $this->getAttribute('title') ;
	}

	public function getName() {
		return $this->getAttribute('name') ;
	}

	/**
	 *
	 * @param string $name
	 * @return AbstractComponent
	 */
	public final function setName($name) {
		return $this->setAttribute('name', $name) ;
	}

	/**
	 *
	 * @param mixed $help
	 * @return \temple\web\html\bootstrap\AbstractComponent
	 */
	public function setHelp($help) {
		$this->help = $help ? ComponentFactory::createComponent('small', 'help-block', $help) : null ;
		return $this ;
	}

	public function render() {
		parent::render();
		if(isset($this->help)) {
			$this->help->render() ;
		}
	}

	/**
	 *
	 * @param type $nodeName
	 * @param type $cssClass
	 * @param type $content
	 * @return \temple\web\html\HTMLNode
	 */
	protected final function createHTMLNode($nodeName, $cssClass = null, $content = null) {
		return ComponentFactory::createComponent($nodeName, $cssClass, $content) ;
	}

	/**
	 *
	 * @return AbstractComponent
	 */
	public final function pullLeft() {
		return $this->addCssClass('pull-left') ;
	}

	/**
	 *
	 * @return AbstractComponent
	 */
	public final function pullRight() {
		return $this->addCssClass('pull-right') ;
	}

}


text:
//---------------------------------------------------------------------------
//
// Copyright (C) Microsoft Corporation.  All rights reserved.
//
//---------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Text;

namespace System.Windows.Controls
{
    /// <summary>
    /// This structure encapsulate the cell information necessary when clipboard content is prepared
    /// </summary>
    public struct DataGridClipboardCellContent
    {
        /// <summary>
        /// Creates a new DataGridClipboardCellValue structure containing information about DataGrid cell
        /// </summary>
        /// <param name="row">DataGrid row item containing the cell</param>
        /// <param name="column">DataGridColumn containing the cell</param>
        /// <param name="value">DataGrid cell value</param>
        public DataGridClipboardCellContent(object item, DataGridColumn column, object content)
        {
            _item = item;
            _column = column;
            _content = content;
        }

        /// <summary>
        /// DataGrid row item containing the cell
        /// </summary>
        public object Item
        {
            get { return _item; }
        }

        /// <summary>
        /// DataGridColumn containing the cell
        /// </summary>
        public DataGridColumn Column
        {
            get { return _column; }
        }

        /// <summary>
        /// Cell content
        /// </summary>
        public object Content
        {
            get { return _content; }
        }

        /// <summary>
        /// Field-by-field comparison to avoid reflection-based ValueType.Equals
        /// </summary>
        /// <param name="data"/>
        /// <returns>True iff this and data are equal</returns>
        public override bool Equals(object data)
        {
            DataGridClipboardCellContent clipboardCellContent;
            if (data is DataGridClipboardCellContent)
            {
                clipboardCellContent = (DataGridClipboardCellContent)data;

                return
                    (_column == clipboardCellContent._column) &&
                    (_content == clipboardCellContent._content) &&
                    (_item == clipboardCellContent._item);
            }

            return false;
        }

        /// <summary>
        /// Return a deterministic hash code
        /// </summary>
        /// <returns>Hash value</returns>
        public override int GetHashCode()
        {
            return ((_column == null ? 0 : _column.GetHashCode()) ^
                (_content == null ? 0 : _content.GetHashCode()) ^
                (_item == null ? 0 : _item.GetHashCode()));
        }

        /// <summary>
        /// Field-by-field comparison to avoid reflection-based ValueType.Equals
        /// </summary>
        /// <param name="clipboardCellContent1"/>
        /// <param name="clipboardCellContent2"/>
        /// <returns>True iff clipboardCellContent1 and clipboardCellContent2 are equal</returns>
        public static bool operator ==(
            DataGridClipboardCellContent clipboardCellContent1,
            DataGridClipboardCellContent clipboardCellContent2)
        {
            return
                (clipboardCellContent1._column == clipboardCellContent2._column) &&
                (clipboardCellContent1._content == clipboardCellContent2._content) &&
                (clipboardCellContent1._item == clipboardCellContent2._item);
        }

        /// <summary>
        /// Field-by-field comparison to avoid reflection-based ValueType.Equals
        /// </summary>
        /// <param name="clipboardCellContent1"/>
        /// <param name="clipboardCellContent2"/>
        /// <returns>True iff clipboardCellContent1 and clipboardCellContent2 are NOT equal</returns>
        public static bool operator !=(
            DataGridClipboardCellContent clipboardCellContent1,
            DataGridClipboardCellContent clipboardCellContent2)
        {
            return
                (clipboardCellContent1._column != clipboardCellContent2._column) ||
                (clipboardCellContent1._content != clipboardCellContent2._content) ||
                (clipboardCellContent1._item != clipboardCellContent2._item);
        }

        private object _item;
        private DataGridColumn _column;
        private object _content;
    }
}


text:
package com.gemstone.gemfire.internal.memcached;

import java.io.IOException;
import java.net.Socket;
import java.nio.ByteBuffer;

import com.gemstone.gemfire.LogWriter;
import com.gemstone.gemfire.cache.Cache;
import com.gemstone.gemfire.cache.CacheClosedException;
import com.gemstone.gemfire.internal.memcached.commands.ClientError;
import com.gemstone.gemfire.memcached.GemFireMemcachedServer;
import com.gemstone.gemfire.memcached.GemFireMemcachedServer.Protocol;

/**
 * One instance of ConnectionHandle is created for each
 * client that connects to {@link GemFireMemcachedServer}
 * and is responsible for reading requests and sending
 * responses to this client.
 *
 *
 * @author Swapnil Bawaskar
 *
 */
public class ConnectionHandler implements Runnable {

  private final Socket socket;

  private final Cache cache;

  private final Protocol protocol;

  private static LogWriter logger;

  public ConnectionHandler(Socket socket, Cache cache, Protocol protocol) {
    this.socket = socket;
    this.cache = cache;
    this.protocol = protocol;
    if (logger == null) {
      logger = this.cache.getLogger();
    }
  }

  public void run() {
    RequestReader request = new RequestReader(this.socket, this.protocol);
    while(!Thread.currentThread().isInterrupted()) {
      try {
        Command command = request.readCommand();
        if (logger.fineEnabled()) {
          logger.fine("processing command:"+command);
        }
        ByteBuffer reply = command.getCommandProcessor().processCommand(
            request, this.protocol, cache);
        if (reply != null) {
          request.sendReply(reply);
        }
        if (command == Command.QUIT || command == Command.QUITQ) {
          socket.close();
          break;
        }
      } catch (ClientError e) {
        request.sendException(e);
      } catch (IllegalArgumentException e) {
        // thrown by Command.valueOf() when there is no matching command
        request.sendException(e);
      } catch (CacheClosedException cc) {
        Thread.currentThread().interrupt();
      } catch (IOException e) {
        Thread.currentThread().interrupt();
      }
    }
    logger.fine("Connection handler "+Thread.currentThread().getName()+" terminating");
  }

  protected static LogWriter getLogger() {
    return logger;
  }
}


text:
#ifndef SkGpuFenceSync_DEFINED
#define SkGpuFenceSync_DEFINED

#include "SkTypes.h"

typedef void* SkPlatformGpuFence;

/*
 * This class provides an interface to interact with fence syncs. A fence sync is an object that the
 * client can insert into the GPU command stream, and then at any future time, wait until all
 * commands that were issued before the fence have completed.
 */
class SkGpuFenceSync {
public:
    virtual SkPlatformGpuFence SK_WARN_UNUSED_RESULT insertFence() const = 0;
    virtual bool waitFence(SkPlatformGpuFence) const = 0;
    virtual void deleteFence(SkPlatformGpuFence) const = 0;

    virtual ~SkGpuFenceSync() {}
};

#endif


text:
- [DB Grid](dbGrid/dbGrid.md) (DB grid plugin)
- [colInherit.js](colInherit.md) (Column inheritance plugin)
- [columnResize.js](columnResize.md) (Column resize plugin)
- [columnsShowHideControl.js](columnsShowHideControl.md)
- [columnsShowHide.js](columnsShowHide.md)
- [jquery.tableFilterMin](tableFilterMin.md)
- [jquery.theadFixed](theadFixed.md)


text:
package com.s4game.server.stage.modelinit;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import com.s4game.core.data.accessor.cache.IEntityCacheModelLoader;
import com.s4game.core.event.IEventHandler;
import com.s4game.server.stage.StageModuleInfo;
import com.s4game.server.stage.command.StageCommands;
import com.s4game.server.stage.dao.cache.RoleStageCacheModelLoader;
import com.s4game.server.stage.event.subscribe.StageRoleCreateHandler;
import com.s4game.server.stage.event.subscribe.StageRoleLogoutHandler;
import com.s4game.server.stage.service.IStageService;
import com.s4game.server.stage.share.moduleinit.AbsStageModuleInit;

/**
 *
 * @Author zeusgooogle@gmail.com
 * @sine   2015年7月17日 下午3:40:59
 *
 */
@Component
public class StageModuleInit extends AbsStageModuleInit {

    @Resource
    private RoleStageCacheModelLoader roleStageCacheModelLoader;

    @Resource
    private StageRoleCreateHandler stageRoleCreateHandler;

    @Resource
    private StageRoleLogoutHandler stageRoleLogoutHandler;

    @Resource
    private IStageService stageService;

    @Override
    protected InCmd getInCmd() {
        String[] cmd = new String[] {
                    StageCommands.INNER_LEAVE_STAGE,
                    StageCommands.INNER_ENTER_STAGE,

                    //关卡
                    StageCommands.CHECKPOINT_EXPIRE_CHECK,
                    StageCommands.CHECKPOINT_FORCE_CHECK,
                    StageCommands.CHECKPOINT_CHELLENGE_RESULT,
                    StageCommands.CHECKPOINT_LEAVE
        };

        return new InCmd(StageModuleInfo.MODULE_NAME, StageModuleInfo.MODULE_NAME_ABBR, cmd);
    }

    protected IEntityCacheModelLoader[] getEntityCacheModelLoaders() {
        return new IEntityCacheModelLoader[] { this.roleStageCacheModelLoader };
    }

    protected IEventHandler[] getEventHandlers() {
        return new IEventHandler[] { this.stageRoleCreateHandler, this.stageRoleLogoutHandler };
    }

}


text:
using System;

namespace P03.RangeExceptions
{
    public class StartUp
    {
        static void Main()
        {
            const int start = 0;
            const int end = 100;

            DateTime LowerDate = new DateTime(1980, 1, 1);
            DateTime UpperDate = new DateTime(2013, 12, 31);

            try
            {
                int wrongNumber = 150;

                if (wrongNumber < start || wrongNumber > end)
                {
                    throw new InvalidRangeException<int>("Wrong", start, end);
                }

                DateTime wrongDate = new DateTime(2015, 10, 15);

                if (wrongDate < LowerDate || wrongDate > UpperDate)
                {
                    throw new InvalidRangeException<DateTime>("Date out of range!", LowerDate, UpperDate);
                }
            }

            catch (InvalidRangeException<int> ex)
            {
                Console.WriteLine($"Wrong number entered. Number must be in range {ex.LowerLimit} - {ex.UpperLimit}");
            }

            catch (InvalidRangeException<DateTime> ex)
            {
                Console.WriteLine($"Wrong date entered. Date must be in range {ex.LowerLimit:dd/MM/yyyy} - {ex.UpperLimit:dd/MM/yyyy}");
            }
        }
    }
}


text:
<!DOCTYPE html>

		<meta charset="UTF-8">
        <meta name="dpl-info" content="status=complete" />
		<title>文字计数器</title>

        <link href="../../Controls/Core/assets/styles/Base.css" rel="stylesheet" type="text/css" />
        <link href="../../Controls/Suggest/assets/styles/CharCounter.css" rel="stylesheet" type="text/css" />


text:
'use strict';
var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');

var BennettGenerator = module.exports = function BennettGenerator(args, options, config) {
  yeoman.generators.Base.apply(this, arguments);
  this.appName = path.basename(process.cwd());
  this.on('end', function () {
    this.installDependencies({ skipInstall: options['skip-install'] });
  });

  this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json')));
};

util.inherits(BennettGenerator, yeoman.generators.Base);

BennettGenerator.prototype.app = function app() {
  this.mkdir('public/vendor');
  this.mkdir('public/images');
  this.mkdir('public/javascripts');
  this.mkdir('public/stylesheets');
  this.mkdir('routes');
  this.mkdir('tests');
  this.mkdir('views');
  this.mkdir('views/home');
  this.mkdir('views/layouts');
  this.template('_package.json', 'package.json');
  this.template('_bower.json', 'bower.json');
};

BennettGenerator.prototype.projectfiles = function projectfiles() {
  this.copy('_testem.json', 'testem.json');
  this.copy('bowerrc', '.bowerrc');
  this.copy('gitignore', '.gitignore');
  this.copy('_app.js', 'app.js');
  this.copy('editorconfig', '.editorconfig');
  this.copy('Gruntfile.js', 'Gruntfile.js');
  this.copy('jshintrc', '.jshintrc');
  this.copy('routes/index.js', 'routes/index.js');
  this.copy('views/home/index.jade', 'views/home/index.jade');
  this.copy('views/layouts/main.jade', 'views/layouts/main.jade');
  this.copy('javascripts/common.js', 'public/javascripts/common.js');
  this.copy('stylesheets/main.sass', 'public/stylesheets/main.sass');
  this.copy('stylesheets/_vars.sass', 'public/stylesheets/_vars.sass');
  this.copy('tests/_index', 'tests/index.mustache');
};


text:
<?php

namespace Sideclick\CoreBundle\Twig;

use Symfony\Component\DependencyInjection\ContainerInterface;

use Symfony\Component\Intl\Intl;

/**
 * Class SideclickUrlizeExtension
 *
 * Registers a custom filter called urlize which replaces URLs in plan text
 * with clickable links
 *
 * @package Sideclick\CoreBundle\Twig
 */
class SideclickCountryNameExtension extends \Twig_Extension
{

    public function getFilters()
    {
        return array(

            new \Twig_SimpleFilter('countryName', array($this, 'countryNameFilter')),
        );
    }

    /**
     * a custom filter called urlize which replaces URLs in plan text
     * with clickable links
     *
     * @param $string
     * @return mixed
     */
    public function countryNameFilter($countryCode){
        return Intl::getRegionBundle()->getCountryName($countryCode);
    }

    public function getName()
    {
        return 'sc_country_name_extension';
    }
}


text:
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Xml.Serialization;

namespace Gwent.NET.Model.Serialization
{
    public class GwintSummonFlag
    {
        [XmlIgnore]
        [Key, Column(Order = 0)]
        public long SummonerCardId { get; set; }

        [XmlAttribute("id")]
        [Key, Column(Order = 1)]
        public long SummonCardId { get; set; }

        [XmlIgnore]
        [ForeignKey("SummonCardId")]
        public virtual Card SummonCard { get; set; }

        [XmlIgnore]
        [InverseProperty("SummonFlags")]
        [ForeignKey("SummonerCardId")]
        public virtual Card SummonerCard { get; set; }

        [XmlIgnore]
        [Timestamp]
        public byte[] RowVersion { get; set; }
    }
}


text:
layout: media
title: "Kapustin Etude Op. 40 No. 6 - Pastorale"
modified:
categories: recording
excerpt:
tags: []
image:
  feature:
  teaser:
  thumb:
date: 2014-12-01T22:09:06-05:00
---

<iframe width="560" height="315" src="//www.youtube.com/embed/gEuiHwrpSU4" frameborder="0" allowfullscreen></iframe>


text:
package com.morcinek.android.codegenerator.codegeneration.providers.resources;

import com.google.common.collect.Sets;
import com.morcinek.android.codegenerator.extractor.model.Resource;

import java.util.Set;

public class BButtonProvider extends AbstractResourceProvider {

    public BButtonProvider(Resource resource) {
        super(resource);
    }

    @Override
    public Set<String> provideInterface() {
        return null;
    }

    @Override
    public Set<String> provideAssignment() {
        return null;
    }

    @Override
    public Set<String> provideField() {
        return null;
    }

    @Override
    public Set<String> provideMethod() {
        return Sets.newHashSet("BButton");
    }
}


text:
"""
FILE: sample_attachments_async.py

DESCRIPTION:
    This sample demonstrates FarmBeats' capability of storing arbitrary files
    in context to the various farm hierarchy objects.
    We first attach some files onto a farmer and a farm, and then download all
    existing attachments for the farmer onto a local directory.

USAGE:
    ```python sample_attachments_async.py```

    Set the environment variables with your own values before running the sample:
    - `AZURE_TENANT_ID`: The tenant ID of your active directory application.
    - `AZURE_CLIENT_ID`: The client ID of your active directory application.
    - `AZURE_CLIENT_SECRET`: The client secret of your active directory application.
    - `FARMBEATS_ENDPOINT`: The FarmBeats endpoint that you want to run these samples on.
"""

from typing import Dict
from azure.core.exceptions import ResourceNotFoundError
from azure.identity.aio import DefaultAzureCredential
from azure.agrifood.farming.aio import FarmBeatsClient
from azure.agrifood.farming.models import Farmer
from pathlib import Path
import asyncio
import os
from dotenv import load_dotenv

async def sample_attachments_async():

    farmbeats_endpoint = os.environ['FARMBEATS_ENDPOINT']

    credential = DefaultAzureCredential()

    client = FarmBeatsClient(
        endpoint=farmbeats_endpoint,
        credential=credential
    )

    farmer_id = "contoso-farmer"
    farm_id = "contoso-farm"
    attachment_on_farmer_id = "contoso-farmer-attachment-1"
    attachment_on_farm_id = "contoso-farm-attachment-1"
    attachment_on_farmer_file_path = "../test.txt"
    attachment_on_farm_file_path = "../test.txt"

    if not (os.path.isfile(attachment_on_farmer_file_path) and
            os.path.isfile(attachment_on_farm_file_path)):
        raise SystemExit(
            "Please provide the paths to the files you want to upload."
    )

    # Ensure farmer exists, create if necessary.
    print(f"Create/updating farmer with id {farmer_id}...", end=" ", flush=True)
    await client.farmers.create_or_update(
        farmer_id=farmer_id,
        farmer=Farmer()
    )
    print("Done!")

    # Ensure farm exists, create if necessary.
    print(f"Create/updating farm with id {farm_id}...", end=" ", flush=True)
    await client.farms.create_or_update(
        farmer_id=farmer_id,
        farm_id=farm_id,
        farm=Farmer()
    )
    print("Done!")

    # Create attachment on farmer
    try:
        print(f"Checking if attachment with id {attachment_on_farmer_id} already exists "
            f"on farmer with id {farmer_id}...", end=" ", flush=True)
        await client.attachments.get(
            farmer_id=farmer_id,
            attachment_id=attachment_on_farmer_id
        )
        print("Attachment already exists. Not updating file.")

    except ResourceNotFoundError:
        print("Attachment doesn't exist")
        print("Creating attachment...", end=" ", flush=True)

        # Open file with buffering set to 0, to get a IO object.
        file_to_attach_on_farmer = open(
            attachment_on_farmer_file_path,
            "rb",
            buffering=0)

        await client.attachments.create_or_update(
            farmer_id=farmer_id,
            attachment_id=attachment_on_farmer_id,
            resource_id= farmer_id,
            resource_type="Farmer",
            file=file_to_attach_on_farmer)

        print("Done!")

    # Create attachment with farm
    try:
        print(f"Checking if attachment with id {attachment_on_farm_id} already exists " +
            f"on farm with id {farm_id}...", end=" ", flush=True)
        await client.attachments.get(
            farmer_id=farmer_id,
            attachment_id=attachment_on_farm_id
        )
        print("Attachment already exists. Not updating file.")

    except ResourceNotFoundError:
        print("Attachment doesn't exist")
        print("Creating attachment...", end=" ", flush=True)

        # Open file with buffering set to 0, to get a IO object.
        file_to_attach_on_farm = open(
            attachment_on_farm_file_path,
            "rb",
            buffering=0)

        await client.attachments.create_or_update(
            farmer_id=farmer_id,
            attachment_id=attachment_on_farm_id,
            resource_id= farm_id,
            resource_type="Farm",
            file=file_to_attach_on_farm)

        print("Done!")

    print("Proceeding to download all attachments on the farmer. " +
        "Press enter to continue...")
    input()

    print("Getting a list of all attachments " +
        f"on the farmer with id {farmer_id}...", end=" ", flush=True)
    farmer_attachments = client.attachments.list_by_farmer_id(
        farmer_id=farmer_id,
    )
    print("Done!")

    # Using a semaphore to limit the number of concurrent downloads.
    semaphore =  asyncio.Semaphore(2)

    print("Downloading attachments with a maximum concurrency "+
        "of two downloads at a time...")

    # Setting up a async function (a coroutine) to download each attachment
    async def download(attachment, semaphore):
        async with semaphore:
            downloaded_attachment = await client.attachments.download(
                farmer_id=farmer_id,
                attachment_id=attachment_on_farmer_id
            )
            out_path = Path(
                "../data/attachments/" +
                f"{attachment.resource_type}/{attachment.resource_id}" +
                f"/{attachment.id}/{attachment.original_file_name}"
            )

            # Make sure the dirs to the output path exists
            out_path.parent.mkdir(parents=True, exist_ok=True)

            print(f"Saving attachment id {attachment.id} to {out_path.resolve()}")
            with open(
                    out_path,
                    'wb'
                    ) as out_file:
                async for bits in downloaded_attachment:
                        out_file.write(bits)

    await asyncio.gather(
        *[download(attachment, semaphore) async for attachment in farmer_attachments]
    )

    print("Done!")

    await client.close()
    await credential.close()

if __name__ == "__main__":

    load_dotenv()

    asyncio.run(sample_attachments_async())


text:
---
layout: post
title:  RTD and UDF Examples - GigaSpaces-Excel Integration
categories: SBP
parent: excel-that-scales-solution.html
weight: 700
---

{% tip %}
**Summary:** {% excerpt %}Basic and advanced code examples for using RTD and UDF with the GigaSpaces-Excel integration.{% endexcerpt %}

**Author**: Pini Cohen, GigaSpaces

**Recently tested with GigaSpaces version**: XAP.NET 6.6

**Contents:**

{% toc minLevel=1|maxLevel=1|type=flat|separator=pipe %}

{% endtip %}

# Overview

This section includes basic and advanced code examples for using the GigaSpaces-Excel integration with Microsoft Excel User-Defined Functions (UDF) and Real-Time Data (RTD).

# Basic Examples

{% toczone minLevel=2|maxLevel=2|type=flat|separator=pipe|location=top %}

## HelloUDF -- Performing Excel Functions in Space

{% highlight java %}
using System;
using System.Runtime.InteropServices;
using Microsoft.Win32;

using GigaSpaces.Core;
using System.Configuration;

using HelloCommon;

//-----------------------------------------------------------
// This class demonstrate how to build a UDF wrapper of a GigaSpaces .NET proxy.
//
// We show how to wrap space operations to be used from within
// the Excel spreadsheet as a regular Excel functions
//
// All public methods are exposed to the Excel user and after the class is registered and added as an "add-in" will apear in the Excel functions list
//-----------------------------------------------------------
namespace HelloUDF
{
    [ClassInterface(ClassInterfaceType.AutoDual), ComVisible(true)] //required to tag a C# class a UDF
    public class HelloUDF
    {
        private ISpaceProxy _proxy;

        public HelloUDF()
        {
            SpaceInit();
        }

        public String AddMsg(int id, string msg)
        {
            String output;

            HelloMsg theMsg = new HelloMsg();
            theMsg.ID = id;
            theMsg.MSG = msg;
            theMsg.STATUS = "working";

            try
            {
                _proxy.Update<HelloMsg>(theMsg,
                                        null, //no transactions
                                        long.MaxValue, 0, //lease and write timeouts
                                        UpdateModifiers.UpdateOrWrite);

                output = "["+ theMsg.ToString() + "] was written to the space";
            }
            catch (Exception e)
            {
                output = e.Message;
            }
            return output;
        }

        public String SetToDone(int id)
        {
            String output;

            HelloMsg theMsg = new HelloMsg();
            theMsg.ID = id;
            theMsg.STATUS = "done";

            try
            {
                _proxy.Update<HelloMsg>(theMsg,
                                        null, //no transactions
                                        long.MaxValue, 0, //lease and write timeouts
                                        UpdateModifiers.PartialUpdate);
                output = "setting Messgae ID " + id + " to done...";
            }
            catch (Exception e)
            {
                output = e.Message;
            }
            return output;
        }

        [ComRegisterFunctionAttribute] //required to tag a C# class a UDF
        public static void RegisterFunction(Type type)
        {
            Registry.ClassesRoot.CreateSubKey(GetSubKeyName(type));
        }

        [ComUnregisterFunctionAttribute] //required to tag a C# class a UDF
        public static void UnregisterFunction(Type type)
        {
            Registry.ClassesRoot.DeleteSubKey(GetSubKeyName(type), false);
        }

        private static string GetSubKeyName(Type type) //required to tag a C# class a UDF
        {
            string s = @"CLSID\{" + type.GUID.ToString().ToUpper() + @"}\Programmable";
            return s;
        }

        private bool SpaceInit()
        {
            try
            {
                string url = ConfigurationManager.AppSettings["SpaceUrl"]; //an environment variable read from the excel.exe.config file
                _proxy = SpaceProxyProviderFactory.Instance.FindSpace(url);
                _proxy.OptimisticLocking = true;
                return true;
            }
            catch (Exception ex)
            {
                ex.ToString();
                return false;
            }
        }
    }
}
{% endhighlight %}

## HelloRTD -- Loading Data from Space to Excel

{% highlight java %}
using System;
using System.Configuration;
using System.Runtime.InteropServices;//<-- For our interop attributes.
using Microsoft.Office.Interop.Excel;

using GigaSpaces.Core;
using GigaSpaces.Core.Events;

using HelloCommon;

//-----------------------------------------------------------
// This class demonstrate how to build a RTD wrapper to "push" data from
// GigaSpaces to the Excel spreadsheet
//
// We show how to register on a notification for a change, and then push
// this change to a cell in Excel
//
//  Usage of the RTD function within Excel:
//  =RTD("HelloRTD",,)
//
//-----------------------------------------------------------

namespace HelloRTD
{
	[ComVisible(true), ProgId("HelloRTD")] //the name of the progId parameter in the RTD excel function
	public class TestRTD : IRtdServer//this is the interface any C# class must implement to become a RTD
	{
		private IRTDUpdateEvent _xlRTDUpdate; //the type of object to link between this runtime and the Excel
		private ISpaceProxy _proxy; //space proxy
		private int _topicID; //Excel cell id to which we will "wire" the notification
		private string _eventData; //the data we receive from the space upon notification
		IEventRegistration _eventReg; //store the space notification as local object to de-register

		#region IRTD Members
		/**
         * this method is called by Excel when the RTD server start (the first time the workbook calls =RTD(...)
		 * here we should creat the connection to the space
         * CallbackObject - the link between this runtime and the Excel
        */
		public int ServerStart(IRTDUpdateEvent CallbackObject)
		{
			// Hold a reference to the callback object.
			_xlRTDUpdate = CallbackObject;

			bool isConnected = SpaceInit(); //connect to the space

			//All is well, return 1.
			return (isConnected ? 1 : 0);
		}
		/**
		 * called when closing the Excel
		 * */
		public void ServerTerminate()
		{
			clean();
		}
		/**
		 * topicID - unique ID of the cell in the Excel
		 * RTDparms - must have at least one parameter
		 * getNewValues - used by the Excel, no need change
		 */
		public object ConnectData(int topicID, ref Array RTDparms, ref bool getNewValues)
		{
			// Registering for notifications on status "done"
			HelloMsg notifyTemplate = new HelloMsg();
			notifyTemplate.STATUS = "done";
			_eventReg = _proxy.DefaultDataEventSession.AddListener
						<HelloMsg>(notifyTemplate, Space_DataChanged);

			//store the cell this RTD is written in
			_topicID = topicID;
			return "This cell is listening for msg with status 'done' ...";
		}
		/**
		 * called when deleteing the RTD function from Excel
		 */

		public void DisconnectData(int topicID)
		{
			clean();
		}
		/**
		 * called by the Excel when _xlRTDUpdate.UpdateNotify() is called
		 * since we call UpdateNotify in each space event,
		 * RefreshData is called for each event seperately
		 *
		 * topicCount = tell the excel how many cells we updated
		 * */
		public Array RefreshData(ref int topicCount)
		{
			// This method returns a two-dimensional array of Variant values.
			// The first dimension represents a list of topic IDs;
			// these topic IDs map to the TopicID parameter in the ConnectData method above.
			// This is how Excel associates topics with data.
			// The second dimension represents the values associated with the topic IDs.

			//1st dimention is always 2 - since we have topic and value
			//2nd dimention is the number of cells we want to update in the Excel
			//    as a result of this specific event
			//
			//  |topicID(0,0)|topicID(0,1)|topicID(0,2)|... topicID(0,n)|
			//  |value1 (1,0)|value2 (1,1)|value3 (1,2)|... valueN (1,n)|
			//
			// n = the number of cells we update in each event
			//

			//since we always update a single cell, we build the following array
			object[,] result = new object[2, 1];
			result[0, 0] = _topicID;
			result[1, 0] = _eventData;

			topicCount = 1;
			return result;
		}

		public int Heartbeat()
		{
			return 1; // the RTD server is up and running, 0 indicates error
		}

		#endregion

		/**
         * calleback by GigaSpaces when event occured
         * EventArgs is the data of the event
         */

		private void Space_DataChanged(object sender, SpaceDataEventArgs<HelloMsg> e)
		{
			//store in the _receivedData the data we got from the event
			_eventData = "Message ID: " + e.Object.ID + " ('" + e.Object.MSG + "') was set to Done!";
			//Tell Excel that we have updates. Then the Excel calls back to RefreshData
			_xlRTDUpdate.UpdateNotify();
		}

		private bool SpaceInit()
		{
			try
			{
				string url = ConfigurationManager.AppSettings["SpaceUrl"];
				_proxy = SpaceProxyProviderFactory.Instance.FindSpace(url);
				_proxy.OptimisticLocking = true;
				return true;
			}
			catch (Exception ex)
			{
				System.Console.Write(ex);
				return false;
			}

		}

		private void clean()
		{
			try
			{
				//remove the event
				if (_eventReg != null)
				{
					_proxy.DefaultDataEventSession.RemoveListener(_eventReg);
					_eventReg = null;
				}
				// Clear the RTDUpdateEvent reference.
				_xlRTDUpdate = null;
			}
			catch (Exception ex)
			{
				System.Console.Write(ex);
			}
		}
	}
}
{% endhighlight %}

## HelloMsg

{% highlight java %}
using System.Text;

using GigaSpaces.Core.Metadata;

namespace HelloCommon
{
	[SpaceClass(IncludeProperties = IncludeMembers.Public, IncludeFields = IncludeMembers.None)]

	public class HelloMsg
	{
		private int _id;
		private string _msg;
		private string _status;

		public HelloMsg()
		{
			_id = -1;
		}

		// NullValue instructs the space to consider a value as null when an object instance is  used as a template
		[SpaceID, SpaceRouting, SpaceProperty(Index = SpaceIndexType.Basic, NullValue = -1)]
		public int ID
		{
			get { return _id; }
			set { _id = value; }
		}

		public string MSG
		{
			get { return _msg; }
			set { _msg = value; }
		}

		public string STATUS
		{
			get { return _status; }
			set { _status = value; }
		}

		public override string ToString()
		{
			StringBuilder builder = new StringBuilder();
			builder.Append("Id:" + ID +
							" ,Msg: " + MSG +
							" ,Status: " + STATUS);
			return builder.ToString();
		}
	}
}
{% endhighlight %}

## RTDSample -- Loading Data from Space to Excel

{% highlight java %}
using System;
using System.Collections;
using System.Text;
using System.Runtime.InteropServices;//<-- For our interop attributes.

using Microsoft.Office.Interop.Excel;
using GigaSpaces.Core;
using GigaSpaces.Core.Exceptions;
using GigaSpaces.Core.Events;
using System.Collections.Generic;
using System.Configuration;

//-----------------------------------------------------------
// This class demonstrate how to build a RTD wrapper to "push" data from
// GigaSpaces to the Excel spreadsheet
//
// We show how to register on a notification of a tick change, and then push
// the tick value to the Excel
//
//  Usage of the RTD function within Excel:
//  =RTD("GSFeader",,[the tick symbol we want to monitor])
//
//-----------------------------------------------------------
namespace GSStreamer
{
    [ComVisible(true), ProgId("GSFeeder")] //the name of the progId parameter in the RTD excel function
    public class GSStreamer : IRtdServer//this is the interface any C# class must implement to become a RTD
    {
        private IRTDUpdateEvent _xlRTDUpdate;
        private ISpaceProxy _proxy;
        private Dictionary<int, TopicTick> _topicIDTable; //used to map between the Excel cellID and the returned data
        private Dictionary<string, TopicTick> _tickTable;

        public GSStreamer()
        {
            _topicIDTable = new Dictionary<int, TopicTick>();
            _tickTable = new Dictionary<string, TopicTick>();
        }

        #region IRTD Members
		//this method is called by Excel when the RTD server start (the first time the workbook calls =RTD(...)
		//here we should creat the connection to the space
        public int ServerStart(IRTDUpdateEvent CallbackObject)
        {
            // Hold a reference to the callback object.
            _xlRTDUpdate = CallbackObject;

            bool isConnected = SpaceInit();

            //All is well, return 1.
            return (isConnected ? 1 : 0);
        }
        public void ServerTerminate()
        {
            // Clear the RTDUpdateEvent reference.
            _xlRTDUpdate = null;
        }

        //this method is called by Excel for every =RTD(...) execution
		//the topicID is a unique identifier for every cell in the excel, we use it to map where to notify back to
		public object ConnectData(int topicID, ref Array RTDparms, ref bool getNewValues)
        {
            string symbol = (string)RTDparms.GetValue(0);
            // Reading from the Space
            string tickInfo = ReadTick(symbol);

            // Registering for notifications using the space proxy
            TickInfo.TickInfo notifyTemplate = new TickInfo.TickInfo();
            notifyTemplate.Symbol = symbol;
            IEventRegistration eventReg = _proxy.DefaultDataEventSession.AddListener<TickInfo.TickInfo>(notifyTemplate, Space_TickChanged);

            //creating a new topic (which has a referance to the listner) and store it locally
            TopicTick tp = new TopicTick(topicID, symbol, eventReg);

            if (!_tickTable.ContainsKey(symbol))
                _tickTable.Add(symbol, tp);
            if (!_topicIDTable.ContainsKey(topicID))
                _topicIDTable.Add(topicID, tp);

            return (object)tickInfo;
        }
		//this method is called by the Excel when a user erase and RTD method from a given cell.
        public void DisconnectData(int topicID)
        {
            try
            {
                TopicTick tp = _topicIDTable[topicID];
                _topicIDTable.Remove(tp.TopicID);
                _tickTable.Remove(tp.symbol);
                _proxy.DefaultDataEventSession.RemoveListener(tp.EventReg);
            }
            catch (Exception ex)
            {
                ex.ToString();
            }
        }

        public Array RefreshData(ref int topicCount)
        {
            // This method returns a two-dimensional array of Variant values.
            // The first dimension represents a list of topic IDs;
            // these topic IDs map to the TopicID parameter in the ConnectData method above.
            // This is how Excel associates topics with data.
            // The second dimension represents the values associated with the topic IDs.

            object[,] result = new object[2, _topicIDTable.Count];

            //build a array of all the topics that changed to send the Excel
            foreach (TopicTick tp in _topicIDTable.Values)
            {
                if (tp.Changed)
                {
                    tp.Changed = false;
                    result[0, topicCount] = tp.TopicID;
                    result[1, topicCount] = ReadTick(tp.symbol); // we can use the symbol attribute: symbol.Pono instead of reading from space
                    topicCount++;  //Tell Excel how many topics we updated.
                }
            }

            //Return the updates.
            return result;
        }

        public int Heartbeat()
        {
            return 1; // the RTD server is up and running, 0 indicates error
        }

        #endregion

        //this method is invoked when a tick has changed
        private void Space_TickChanged(object sender, SpaceDataEventArgs<TickInfo.TickInfo> e)
        {
            //bookmark the tick that was changed
            _tickTable[e.Pono.Symbol].Changed = true;
            //Tell Excel that we have updates,
            //as a result the excel will call the RefreshData function
            _xlRTDUpdate.UpdateNotify();
        }

        private bool SpaceInit()
        {
            try
            {
                string url = ConfigurationManager.AppSettings["SpaceUrl"]; //an environment variable read from the excel.exe.config file
                _proxy = SpaceProxyProviderFactory.Instance.FindSpace(url);
                _proxy.OptimisticLocking = true;
                return true;
            }
            catch (Exception ex)
            {
                ex.ToString();
                return false;
            }
        }

        private string ReadTick(String symbol)
        {
            // reading the Person Data from the Spaces

            TickInfo.TickInfo template = new TickInfo.TickInfo();
            template.Symbol = symbol;

            TickInfo.TickInfo tick = _proxy.Read<TickInfo.TickInfo>(template);

            if (tick == null)
                return ("Not Exist");
            else
                return tick.ToString();
        }

        private class TopicTick
        {
            public int TopicID;
            public bool Changed;
            public string symbol;
            public IEventRegistration EventReg;

            public TopicTick(int topicId, string symbol, IEventRegistration eventReg)
            {
                this.TopicID = topicId;
                this.Changed = false;
                this.symbol = symbol;
                this.EventReg = eventReg;
            }
        }
    }
}
{% endhighlight %}

## TickInfo

{% highlight java %}
using System;
using System.Collections.Generic;
using System.Text;

using GigaSpaces.Core.Metadata;

namespace TickInfo
{
    // SpaceClass(IncludeProperties = IncludeMembers.Public) instructs the space to take only public properties
    // SpaceClass(IncludeFields = IncludeMembers.None) instructs the space not to take any fields
    [SpaceClass(IncludeProperties = IncludeMembers.Public, IncludeFields = IncludeMembers.None)]
    public class TickInfo
    {
        private string _symbol;
        private double _open;
        private double _close;
        private double _last;

        // SpaceID is used to indicate a unique field value. This field value is used to generate the Entry UID
        // SpaceProperty(Index = SpaceIndexType.Basic) is used indicate an indexed field
        [SpaceID, SpaceRouting, SpaceProperty(Index = SpaceIndexType.Basic)]
        public string Symbol
        {
            get { return _symbol; }
            set { _symbol = value; }
        }
        [SpaceProperty(NullValue = -1)]
        public double Open
        {
            get { return _open; }
            set { _open = value; }
        }
        [SpaceProperty(NullValue = -1)]
        public double Close
        {
            get { return _close; }
            set { _close = value; }
        }
        [SpaceProperty(NullValue = -1)]
        public double Last
        {
            get { return _last; }
            set { _last = value; }
        }

        public TickInfo()
        {
            this._open = -1;
            this._close = -1;
            this._last = -1;
        }

        public override string ToString()
        {
            StringBuilder builder = new StringBuilder();
            builder.Append(" Symbol: " + Symbol);
            builder.Append(" Open: " + Open.ToString());
            builder.Append(" Close: " + Close.ToString());
            builder.Append(" Last: " + Last.ToString());
            return builder.ToString();
        }
    }
}
{% endhighlight %}

{% endtoczone %}

# What's Next?

{% refer %}[Write Your First RTD/UDF Application](./writing-your-first-rtd-or-udf-application.html){% endrefer %}
{% refer %}[See the Market-Data Example](./gigaspaces-excel-market-data-example.html){% endrefer %}
{% refer %}Back to The [Excel that Scales Solution](./excel-that-scales-solution.html) section{% endrefer %}


text:
class Superhero < ActiveRecord::Base
  # Fields
  field :superhero_name, :as => :string
  field :age, :as => :integer
end


text:
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ui.treeStructure.filtered;

import com.intellij.ide.util.treeView.AbstractTreeBuilder;
import com.intellij.ide.util.treeView.AbstractTreeStructure;
import com.intellij.ide.util.treeView.AbstractTreeUi;
import com.intellij.ide.util.treeView.NodeDescriptor;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.util.ActionCallback;
import com.intellij.openapi.util.Disposer;
import com.intellij.ui.speedSearch.ElementFilter;
import com.intellij.ui.treeStructure.PatchedDefaultMutableTreeNode;
import com.intellij.ui.treeStructure.Tree;
import com.intellij.util.ui.tree.TreeUtil;
import com.intellij.util.ui.update.MergingUpdateQueue;
import com.intellij.util.ui.update.Update;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.concurrency.AsyncPromise;
import org.jetbrains.concurrency.Promise;
import org.jetbrains.concurrency.Promises;

import javax.swing.*;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import java.util.Comparator;

/**
 * @deprecated use {@link com.intellij.ui.tree.AsyncTreeModel} and {@link com.intellij.ui.tree.StructureTreeModel} instead.
 */
@ApiStatus.ScheduledForRemoval(inVersion = "2020.3")
@Deprecated
public class FilteringTreeBuilder extends AbstractTreeBuilder {

  private Object myLastSuccessfulSelect;
  private final Tree myTree;

  private MergingUpdateQueue myRefilterQueue;

  public FilteringTreeBuilder(Tree tree,
                              ElementFilter<?> filter,
                              AbstractTreeStructure structure,
                              @Nullable Comparator<? super NodeDescriptor<?>> comparator) {
    super(tree,
          (DefaultTreeModel)tree.getModel(),
          structure instanceof FilteringTreeStructure ? structure
                                                      : new FilteringTreeStructure(filter, structure),
          comparator);

    myTree = tree;
    initRootNode();

    if (filter instanceof ElementFilter.Active) {
      ((ElementFilter.Active)filter).addListener(new ElementFilter.Listener() {
        @NotNull
        @Override
        public Promise<?> update(final Object preferredSelection, final boolean adjustSelection, final boolean now) {
          return refilter(preferredSelection, adjustSelection, now);
        }
      }, this);
    }

    myTree.getSelectionModel().addTreeSelectionListener(new TreeSelectionListener() {
      @Override
      public void valueChanged(TreeSelectionEvent e) {
        TreePath newPath = e.getNewLeadSelectionPath();
        if (newPath != null) {
          Object element = getElementFor(newPath.getLastPathComponent());
          if (element != null) {
            myLastSuccessfulSelect = element;
          }
        }
      }
    });
  }

  @Override
  public boolean isAlwaysShowPlus(NodeDescriptor nodeDescriptor) {
    return false;
  }

  @Override
  public boolean isAutoExpandNode(NodeDescriptor nodeDescriptor) {
    return true;
  }

  protected final DefaultMutableTreeNode createChildNode(final NodeDescriptor childDescr) {
    return new PatchedDefaultMutableTreeNode(childDescr);
  }

  public void setFilteringMerge(int gap, @Nullable JComponent modalityStateComponent) {
    if (myRefilterQueue != null) {
      Disposer.dispose(myRefilterQueue);
      myRefilterQueue = null;
    }

    if (gap >= 0) {
      JComponent stateComponent = modalityStateComponent;
      if (stateComponent == null) {
        stateComponent = myTree;
      }

      myRefilterQueue = new MergingUpdateQueue("FilteringTreeBuilder", gap, false, stateComponent, this, myTree);
      myRefilterQueue.setRestartTimerOnAdd(true);
    }
  }

  protected boolean isSelectable(Object nodeObject) {
    return true;
  }

  /**
   * @deprecated use {@link #refilter(Object, boolean, boolean)}
   */
  @NotNull
  @Deprecated
  @ApiStatus.ScheduledForRemoval(inVersion = "2021.3")
  public ActionCallback refilter() {
    return Promises.toActionCallback(refilter(null, true, false));
  }

  @SuppressWarnings("UnusedReturnValue")
  @NotNull
  public Promise<?> refilterAsync() {
    return refilter(null, true, false);
  }

  @NotNull
  public Promise<?> refilter(@Nullable final Object preferredSelection, final boolean adjustSelection, final boolean now) {
    if (myRefilterQueue != null) {
      myRefilterQueue.cancelAllUpdates();
    }

    AsyncPromise<?> result = new AsyncPromise<>();
    final Runnable afterCancelUpdate = new Runnable() {
      @Override
      public void run() {
        if (myRefilterQueue == null || now) {
          refilterNow(preferredSelection, adjustSelection)
            .onSuccess(o -> result.setResult(null));
        }
        else {
          myRefilterQueue.queue(new Update(this) {
            @Override
            public void run() {
              refilterNow(preferredSelection, adjustSelection);
            }

            @Override
            public void setRejected() {
              super.setRejected();
              result.setResult(null);
            }
          });
        }
      }
    };

    if (!isDisposed()) {
      if (!ApplicationManager.getApplication().isUnitTestMode()) {
        AbstractTreeUi ui = getUi();
        if (ui != null) ui.cancelUpdate().doWhenProcessed(afterCancelUpdate);
      }
      else {
        afterCancelUpdate.run();
      }
    }

    return result;
  }

  @NotNull
  protected Promise<?> refilterNow(Object preferredSelection, boolean adjustSelection) {
    final ActionCallback selectionDone = new ActionCallback();

    getFilteredStructure().refilter();
    AbstractTreeUi ui = getUi();
    if (ui != null) ui.updateSubtree(ui.getRootNode(), false);
    final Runnable selectionRunnable = () -> {
      revalidateTree();

      Object toSelect = preferredSelection != null ? preferredSelection : myLastSuccessfulSelect;

      if (adjustSelection && toSelect != null) {
        final FilteringTreeStructure.FilteringNode nodeToSelect = getFilteredStructure().getVisibleNodeFor(toSelect);

        if (nodeToSelect != null) {
          select(nodeToSelect, () -> {
            if (getSelectedElements().contains(nodeToSelect)) {
              myLastSuccessfulSelect = getOriginalNode(nodeToSelect);
            }
            selectionDone.setDone();
          });
        }
        else {
          TreeUtil.ensureSelection(myTree);
          selectionDone.setDone();
        }
      }
      else {
        selectionDone.setDone();
      }
    };
    if (!ApplicationManager.getApplication().isUnitTestMode()) {
      queueUpdate().doWhenProcessed(selectionRunnable);
    }
    else {
      selectionRunnable.run();
    }

    AsyncPromise<?> result = new AsyncPromise<>();
    selectionDone
      .doWhenDone(new Runnable() {
      @Override
      public void run() {
        if (!ApplicationManager.getApplication().isUnitTestMode()) {
          scrollSelectionToVisible(new Runnable() {
            @Override
            public void run() {
              getReady(this)
              .doWhenDone(() -> result.setResult(null))
              .doWhenRejected(s -> result.setError(s));
            }
          }, false);
        }
        else {
          result.setResult(null);
        }
      }
    })
      .doWhenRejected(() -> result.cancel(true));
    return result;
  }

  public void revalidateTree() {
    revalidateTree(myTree);
  }

  public static void revalidateTree(Tree tree) {
    TreeUtil.invalidateCacheAndRepaint(tree.getUI());
  }

  private FilteringTreeStructure getFilteredStructure() {
    return ((FilteringTreeStructure)getTreeStructure());
  }

  public FilteringTreeStructure.FilteringNode getVisibleNodeFor(Object nodeObject) {
    FilteringTreeStructure structure = getFilteredStructure();
    return structure != null ? structure.getVisibleNodeFor(nodeObject) : null;
  }

  public Object getOriginalNode(Object node) {
    return ((FilteringTreeStructure.FilteringNode)node).getDelegate();
  }

  @Override
  protected Object transformElement(Object object) {
    return getOriginalNode(object);
  }

  @Nullable
  public Object getElementFor(Object node) {
    AbstractTreeUi ui = getUi();
    return ui == null ? null : ui.getElementFor(node);
  }

  @Override
  public void cleanUp() {
    super.cleanUp();
    myLastSuccessfulSelect = null;
    myRefilterQueue.cancelAllUpdates();
  }
}