text:
package tested.robots;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.lang.reflect.*;

/**
 * @author Flemming N. Larsen (original)
 */
public class ConstructorReflectionAttack extends robocode.AdvancedRobot {

	static ByteArrayOutputStream baos = new ByteArrayOutputStream();

	static {
		try {
			Field field = System.class.getField("out");

			field.setAccessible(true);
			Object obj = field.get(null);
			Method method = obj.getClass().getMethod("print", new Class[] { String.class });

			method.setAccessible(true);
			method.invoke(obj, new Object[] { "Hello World" });

		} catch (Exception e) {
			// The stack trace from the exception is redirected to a temporary buffer,
			// which is read and written out to the robot's output in the run() method.

			PrintStream ps = new PrintStream(baos);

			e.printStackTrace(ps);
			ps.flush();
		}
	}

	public void run() {
		// Write out the buffered output
		out.append(baos.toString());
	}
}


text:
package com.cloud.network.as;

import java.util.Date;
import java.util.UUID;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import org.apache.cloudstack.api.InternalIdentity;

import com.cloud.utils.db.GenericDao;

@Entity
@Table(name = "autoscale_policies")
@Inheritance(strategy = InheritanceType.JOINED)
public class AutoScalePolicyVO implements AutoScalePolicy, InternalIdentity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    long id;

    @Column(name = "uuid")
    String uuid;

    @Column(name = "domain_id")
    private long domainId;

    @Column(name = "account_id")
    private long accountId;

    @Column(name = "duration")
    private int duration;

    @Column(name = "quiet_time", updatable = true, nullable = false)
    private int quietTime;

    @Column(name = "last_quiet_time", updatable = true)
    @Temporal(value = TemporalType.TIMESTAMP)
    private Date lastQuiteTime;

    @Column(name = "action", updatable = false, nullable = false)
    private String action;

    @Column(name = GenericDao.REMOVED_COLUMN)
    protected Date removed;

    @Column(name = GenericDao.CREATED_COLUMN)
    protected Date created;

    public AutoScalePolicyVO() {
    }

    public AutoScalePolicyVO(long domainId, long accountId, int duration,
            int quietTime, Date lastQuiteTime, String action) {
        uuid = UUID.randomUUID().toString();
        this.domainId = domainId;
        this.accountId = accountId;
        this.duration = duration;
        this.quietTime = quietTime;
        this.lastQuiteTime = lastQuiteTime;
        this.action = action;
    }

    @Override
    public String toString() {
        return new StringBuilder("AutoScalePolicy[").append("id-").append(id).append("]").toString();
    }

    @Override
    public long getId() {
        return id;
    }

    @Override
    public String getUuid() {
        return uuid;
    }

    @Override
    public long getDomainId() {
        return domainId;
    }

    @Override
    public long getAccountId() {
        return accountId;
    }

    @Override
    public int getDuration() {
        return duration;
    }

    @Override
    public int getQuietTime() {
        return quietTime;
    }

    @Override
    public Date getLastQuiteTime() {
        return lastQuiteTime;
    }

    @Override
    public String getAction() {
        return action;
    }

    public Date getRemoved() {
        return removed;
    }

    public Date getCreated() {
        return created;
    }

    public void setDuration(Integer duration) {
        this.duration = duration;
    }

    public void setQuietTime(Integer quietTime) {
        this.quietTime = quietTime;
    }

    public void setLastQuiteTime(Date lastQuiteTime) {
        this.lastQuiteTime = lastQuiteTime;
    }

    @Override
    public Class<?> getEntityType() {
        return AutoScalePolicy.class;
    }

}

redpajama_set_name: RedPajamaGithub


text:
//---------------------------------------------------------------------
// <copyright file="ODataParameterReaderTestWrapper.cs" company="Microsoft">
//      Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
// </copyright>
//---------------------------------------------------------------------

namespace Microsoft.Test.Taupo.OData.Reader.Tests
{
    #region Namespaces
    using System;
    using System.Reflection;
#if !WINDOWS_PHONE
    using System.Threading.Tasks;
#endif
    using Microsoft.OData.Core;
    using Microsoft.Test.Taupo.Common;
    using Microsoft.Test.Taupo.OData.Common;
    #endregion Namespaces

    /// <summary>
    /// Wrapper for the ODataParameterReader which allows for transparent monitoring and changing
    /// of the reader behavior.
    /// </summary>
    public sealed class ODataParameterReaderTestWrapper : ODataParameterReader
    {
        /// <summary>
        /// The underlying reader to wrap.
        /// </summary>
        private readonly ODataParameterReader parameterReader;

        /// <summary>
        /// Test configuration to use.
        /// </summary>
        private readonly ReaderTestConfiguration testConfiguration;

        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="parameterReader">The reader to wrap.</param>
        /// <param name="testConfiguration">The test configuration to use.</param>
        public ODataParameterReaderTestWrapper(ODataParameterReader parameterReader, ReaderTestConfiguration testConfiguration)
        {
            ExceptionUtilities.CheckArgumentNotNull(parameterReader, "parameterReader");
            ExceptionUtilities.CheckArgumentNotNull(testConfiguration, "testConfiguration");

            this.parameterReader = parameterReader;
            this.testConfiguration = testConfiguration;
        }

        /// <summary>
        /// The underlying reader.
        /// </summary>
        public ODataParameterReader ParameterReader
        {
            get { return this.parameterReader; }
        }

        /// <summary>
        /// The current state of the reader.
        /// </summary>
        public override ODataParameterReaderState State
        {
            get { return this.parameterReader.State; }
        }

        /// <summary>
        /// The name of the current parameter that is being read.
        /// </summary>
        public override string Name
        {
            get { return this.parameterReader.Name; }
        }

        /// <summary>
        /// The value of the current parameter that is being read.
        /// </summary>
        /// <remarks>
        /// This property returns a primitive value, an ODataComplexValue or null when State is ODataParameterReaderState.Value.
        /// This property returns null when State is ODataParameterReaderState.Entry, ODataParameterReaderState.Feed or ODataParameterReaderState.Collection.
        /// </remarks>
        public override object Value
        {
            get { return this.parameterReader.Value; }
        }

        /// <summary>
        /// This method creates an <see cref="ODataReader"/> to read the entry value when the state is ODataParameterReaderState.Entry.
        /// </summary>
        /// <remarks>
        /// When the state is ODataParameterReaderState.Entry, the Name property of the <see cref="ODataParameterReader"/> returns the name of the parameter
        /// and the Value property of the <see cref="ODataParameterReader"/> returns null. Calling this method in any other state will cause an ODataException to be thrown.
        /// </remarks>
        /// <returns>Returns an <see cref="ODataReader"/> to read the entry value when the state is ODataParameterReaderState.Entry.</returns>
        public override ODataReader CreateEntryReader()
        {
            return new ODataReaderTestWrapper(this.parameterReader.CreateEntryReader(), this.testConfiguration);
        }

        /// <summary>
        /// This method creates an <see cref="ODataReader"/> to read the feed value when the state is ODataParameterReaderState.Feed.
        /// </summary>
        /// <remarks>
        /// When the state is ODataParameterReaderState.Feed, the Name property of the <see cref="ODataParameterReader"/> returns the name of the parameter
        /// and the Value property of the <see cref="ODataParameterReader"/> returns null. Calling this method in any other state will cause an ODataException to be thrown.
        /// </remarks>
        /// <returns>Returns an <see cref="ODataReader"/> to read the feed value when the state is ODataParameterReaderState.Feed.</returns>
        public override ODataReader CreateFeedReader()
        {
            return new ODataReaderTestWrapper(this.parameterReader.CreateFeedReader(), this.testConfiguration);
        }

        /// <summary>
        /// This method creates an <see cref="ODataCollectionReader"/> to read the collection value when the state is ODataParameterReaderState.Collection.
        /// </summary>
        /// <remarks>
        /// When the state is ODataParameterReaderState.Collection, the Name property of the <see cref="ODataParameterReader"/> returns the name of the parameter
        /// and the Value property of the <see cref="ODataParameterReader"/> returns null. Calling this method in any other state will cause an ODataException to be thrown.
        /// </remarks>
        /// <returns>Returns an <see cref="ODataCollectionReader"/> to read the collection value when the state is ODataParameterReaderState.Collection.</returns>
        public override ODataCollectionReader CreateCollectionReader()
        {
            return new ODataCollectionReaderTestWrapper(this.parameterReader.CreateCollectionReader(), this.testConfiguration);
        }

        /// <summary>
        /// Reads the next item from the message payload.
        /// </summary>
        /// <returns>true if more items were read; otherwise false.</returns>
        public override bool Read()
        {
            if (this.testConfiguration.Synchronous)
            {
                return this.parameterReader.Read();
            }
            else
            {
#if SILVERLIGHT || WINDOWS_PHONE
                throw new PlatformNotSupportedException("Asynchronous reading is only supported on desktop");
#else
                return this.parameterReader.ReadAsync().WaitForResult();
#endif
            }
        }

#if !WINDOWS_PHONE
        /// <summary>
        /// Asynchronously reads the next item from the message payload.
        /// </summary>
        /// <returns>A task that when completed indicates whether more items were read.</returns>
        public override Task<bool> ReadAsync()
        {
            throw new NotImplementedException("Tests should always use synchronous APIs.");
        }
#endif
    }
}


text:
package io.digdag.core;

import com.google.inject.BindingAnnotation;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

@BindingAnnotation
@Target({FIELD, PARAMETER, METHOD})
@Retention(RUNTIME)
public @interface Environment
{
}


text:
const Knex = require('./knex-builder/Knex');

module.exports = Knex;


text: define({title:"Rasti mano vietą"});


text:
package eu.seaclouds.paas;

import eu.seaclouds.paas.PaasSession.ScaleCommand;
import eu.seaclouds.paas.PaasSession.ScaleUpDownCommand;
import eu.seaclouds.paas.PaasSession.StartStopCommand;
import eu.seaclouds.paas.heroku.DeployParameters;

/**
 *
 * @author
 *
 */
public class Tests
{

	private static final String PIVOTAL = "https://api.run.pivotal.io";
	private static final String BLUEMIX = "https://api.eu-gb.bluemix.net";
	private static final String APPFOG = "";
	private static final String PRIVATE_CF = "https://api.95.211.172.243.xip.io";

	private static final String APP_NAME = "unified-paas-cloudfoundry-test";

	public static void main(String[] args)
	{
		try
		{
			//
			String heroku_apiKey = "";
		    String heroku_username = "";
		    String heroku_password = "";

		    String cf_username = "";
		    String cf_password = "";
		    String cf_api = PIVOTAL;
		    String cf_org = "";
		    String cf_space = "development";
		    boolean cf_trustSelfSignedCerts = true;

		    //
		    PaasClientFactory factory = new PaasClientFactory();
	        PaasClient client = factory.getClient("cloudfoundry"); // cloudfoundry   heroku
	        PaasSession session = null;
	        String path = Tests.class.getResource("/SampleApp1.war").getFile();

		    // HEROKU
	        /*
	        session = client.getSession(new Credentials.ApiKeyCredentials(heroku_apiKey));
		    //eu.seaclouds.paas.Module m = session.deploy(APP_NAME, new DeployParameters(path));
		    eu.seaclouds.paas.Module m = session.getModule(APP_NAME);

		    System.out.println("### >> running instances: " + m.getRunningInstances());

		    session.startStop(m, StartStopCommand.START);
		    m = session.getModule(APP_NAME);

	        System.out.println("### >> " + String.format("name='%s',  url='%s'", m.getName(), m.getUrl()));
	        System.out.println("### >> running instances: " + m.getRunningInstances());
	        */

	        // CLOUD FOUNDRY
	        session = client.getSession(
	        		new Credentials.ApiUserPasswordOrgSpaceCredentials(cf_api, cf_username, cf_password, cf_org, cf_space, cf_trustSelfSignedCerts));

	        /*
	        eu.seaclouds.paas.Module m = session.deploy(APP_NAME, new DeployParameters(path));
	        System.out.println("### >> running instances: " + m.getRunningInstances());

	        session.startStop(m, StartStopCommand.STOP);
	        Thread.sleep(5000);
	        m = session.getModule(APP_NAME);
	        System.out.println("### >> running instances: " + m.getRunningInstances());

	        session.startStop(m, StartStopCommand.START);
	        Thread.sleep(5000);
	        m = session.getModule(APP_NAME);
	        System.out.println("### >> running instances: " + m.getRunningInstances());

	        session.scaleUpDown(m, ScaleUpDownCommand.SCALE_UP_INSTANCES);
	        Thread.sleep(5000);
	        m = session.getModule(APP_NAME);
	        System.out.println("### >> running instances: " + m.getRunningInstances());

	        session.undeploy(APP_NAME);
	        */

	        eu.seaclouds.paas.Module m = session.getModule(APP_NAME);
	        //session.scaleUpDown(m, ScaleUpDownCommand.SCALE_UP_INSTANCES);
	        //session.scale(m, ScaleCommand.SCALE_INSTANCES, 0);
	        session.undeploy(APP_NAME);
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
		}
	}

}


text:
<?xml version="1.0" encoding="utf-8"?>
<Deployment xmlns="http://schemas.microsoft.com/windowsphone/2012/deployment" AppPlatformVersion="8.0">
  <DefaultLanguage xmlns="" code="en-US" />
  <App xmlns="" ProductID="{2ff15737-7c0e-4c6f-9acf-e6554c701748}" Title="Bus Catcher" RuntimeType="Silverlight" Version="1.0.0.0" Genre="apps.normal" Author="BusCatcher.Core author" Description="Sample description" Publisher="BusCatcher.Core" PublisherID="{7bc3740d-f1e6-40de-8b94-604744bdec4c}">
    <IconPath IsRelative="true" IsResource="false">icon_small.png</IconPath>
    <Capabilities>
      <Capability Name="ID_CAP_NETWORKING" />
      <Capability Name="ID_CAP_MEDIALIB_AUDIO" />
      <Capability Name="ID_CAP_MEDIALIB_PLAYBACK" />
      <Capability Name="ID_CAP_SENSORS" />
      <Capability Name="ID_CAP_WEBBROWSERCOMPONENT" />
      <Capability Name="ID_CAP_MAP" />
    </Capabilities>
    <Tasks>
      <DefaultTask Name="_default" NavigationPage="/Views/Common/ExtendedSplashScreen.xaml" />
    </Tasks>
    <Tokens>
      <PrimaryToken TokenID="BusCatcher.CoreToken" TaskName="_default">
        <TemplateIconic>
          <SmallImageURI IsRelative="true" IsResource="false">icon_small.png</SmallImageURI>
          <Count>0</Count>
          <IconImageURI IsRelative="true" IsResource="false">medium_icon.png</IconImageURI>
          <Title></Title>
          <Message></Message>
          <BackgroundColor></BackgroundColor>
          <HasLarge>false</HasLarge>
          <LargeContent1></LargeContent1>
          <LargeContent2></LargeContent2>
          <LargeContent3></LargeContent3>
          <DeviceLockImageURI IsRelative="true" IsResource="false"></DeviceLockImageURI>
        </TemplateIconic>
      </PrimaryToken>
    </Tokens>
    <ScreenResolutions>
      <ScreenResolution Name="ID_RESOLUTION_WVGA" />
      <ScreenResolution Name="ID_RESOLUTION_WXGA" />
      <ScreenResolution Name="ID_RESOLUTION_HD720P" />
    </ScreenResolutions>
  </App>
</Deployment>
<!-- WPSDK Version 8.0.9900 -->


text:
package org.wso2.developerstudio.eclipse.gmf.esb.provider;

import java.util.Collection;
import java.util.List;

import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.emf.common.notify.Notification;

import org.eclipse.emf.ecore.EStructuralFeature;

import org.eclipse.emf.edit.provider.ComposeableAdapterFactory;
import org.eclipse.emf.edit.provider.IEditingDomainItemProvider;
import org.eclipse.emf.edit.provider.IItemLabelProvider;
import org.eclipse.emf.edit.provider.IItemPropertyDescriptor;
import org.eclipse.emf.edit.provider.IItemPropertySource;
import org.eclipse.emf.edit.provider.IStructuredItemContentProvider;
import org.eclipse.emf.edit.provider.ITreeItemContentProvider;
import org.eclipse.emf.edit.provider.ItemPropertyDescriptor;
import org.eclipse.emf.edit.provider.ViewerNotification;

import org.wso2.developerstudio.eclipse.gmf.esb.EsbFactory;
import org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage;
import org.wso2.developerstudio.eclipse.gmf.esb.RuleMediator;
import org.wso2.developerstudio.eclipse.gmf.esb.RuleSourceType;

/**
 * This is the item provider adapter for a {@link org.wso2.developerstudio.eclipse.gmf.esb.RuleMediator} object.
 * <!-- begin-user-doc -->
 * <!-- end-user-doc -->
 * @generated
 */
public class RuleMediatorItemProvider extends MediatorItemProvider {
    /**
     * This constructs an instance from a factory and a notifier.
     * <!-- begin-user-doc -->
     * <!-- end-user-doc -->
     * @generated
     */
    public RuleMediatorItemProvider(AdapterFactory adapterFactory) {
        super(adapterFactory);
    }

    /**
     * This returns the property descriptors for the adapted class.
     * <!-- begin-user-doc -->
     * <!-- end-user-doc -->
     *
     * @generated NOT
     */

    @Override
    public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object) {
        RuleMediator ruleMediator = (RuleMediator) object;
        if (itemPropertyDescriptors != null) {
            itemPropertyDescriptors.clear();
        }
        super.getPropertyDescriptors(object);

        addRuleSetSourceTypePropertyDescriptor(object);
        if (ruleMediator.getRuleSetSourceType() == RuleSourceType.REGISTRY) {
            addRuleSetSourceKeyPropertyDescriptor(object);
        } else if (ruleMediator.getRuleSetSourceType() == RuleSourceType.URL) {
            addRuleSetURLPropertyDescriptor(object);
        } else {
            addRuleSetSourceCodePropertyDescriptor(object);
        }
        // addRuleSetPropertiesPropertyDescriptor(object);
        // addStatefulSessionPropertyDescriptor(object);
        // addRuleSessionPropertiesPropertyDescriptor(object);
        addFactsConfigurationPropertyDescriptor(object);
        addResultsConfigurationPropertyDescriptor(object);
        addSourceValuePropertyDescriptor(object);
        addSourceXpathPropertyDescriptor(object);
        addTargetValuePropertyDescriptor(object);
        addTargetResultXpathPropertyDescriptor(object);
        addTargetXpathPropertyDescriptor(object);
        addTargetActionPropertyDescriptor(object);
        addInputWrapperNamePropertyDescriptor(object);
        addInputNameSpacePropertyDescriptor(object);
        addOutputWrapperNamePropertyDescriptor(object);
        addOutputNameSpacePropertyDescriptor(object);
        addRuleSetTypePropertyDescriptor(object);
        addDescriptionPropertyDescriptor(object);

        return itemPropertyDescriptors;
    }

    /*
     * @Override
     * public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object) {
     * RuleMediator ruleMediator = (RuleMediator) object;
     * if (itemPropertyDescriptors != null) {
     * itemPropertyDescriptors.clear();
     * }
     * super.getPropertyDescriptors(object);
     *
     * addRuleSetURIPropertyDescriptor(object);
     * addRuleSetSourceTypePropertyDescriptor(object);
     * if (ruleMediator.getRuleSetSourceType() == RuleSourceType.REGISTRY_REFERENCE) {
     * addRuleSetSourceKeyPropertyDescriptor(object);
     * } else {
     * addRuleSetSourceCodePropertyDescriptor(object);
     * }
     * addRuleSetPropertiesPropertyDescriptor(object);
     * //addStatefulSessionPropertyDescriptor(object);
     * //addRuleSessionPropertiesPropertyDescriptor(object);
     * addFactsConfigurationPropertyDescriptor(object);
     * addResultsConfigurationPropertyDescriptor(object);
     * addSourceValuePropertyDescriptor(object);
     * addSourceXpathPropertyDescriptor(object);
     * addTargetValuePropertyDescriptor(object);
     * addTargetResultXpathPropertyDescriptor(object);
     * addTargetXpathPropertyDescriptor(object);
     * addTargetActionPropertyDescriptor(object);
     * addInputWrapperNamePropertyDescriptor(object);
     * addInputNameSpacePropertyDescriptor(object);
     * addOutputWrapperNamePropertyDescriptor(object);
     * addOutputNameSpacePropertyDescriptor(object);
     *
     * return itemPropertyDescriptors;
     * }
     */

    /**
     * This adds a property descriptor for the Rule Set URL feature.
     * <!-- begin-user-doc -->
     * <!-- end-user-doc -->
     * @generated
     */
    protected void addRuleSetURLPropertyDescriptor(Object object) {
        itemPropertyDescriptors.add
            (createItemPropertyDescriptor
                (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
                 getResourceLocator(),
                 getString("_UI_RuleMediator_RuleSetURL_feature"),
                 getString("_UI_PropertyDescriptor_description", "_UI_RuleMediator_RuleSetURL_feature", "_UI_RuleMediator_type"),
                 EsbPackage.Literals.RULE_MEDIATOR__RULE_SET_URL,
                 true,
                 false,
                 false,
                 ItemPropertyDescriptor.GENERIC_VALUE_IMAGE,
                 getString("_UI_RuleSetPropertyCategory"),
                 null));
    }

    /**
     * This adds a property descriptor for the Rule Set Source Type feature.
     * <!-- begin-user-doc -->
     * <!-- end-user-doc -->
     * @generated
     */
    protected void addRuleSetSourceTypePropertyDescriptor(Object object) {
        itemPropertyDescriptors.add
            (createItemPropertyDescriptor
                (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
                 getResourceLocator(),
                 getString("_UI_RuleMediator_ruleSetSourceType_feature"),
                 getString("_UI_PropertyDescriptor_description", "_UI_RuleMediator_ruleSetSourceType_feature", "_UI_RuleMediator_type"),
                 EsbPackage.Literals.RULE_MEDIATOR__RULE_SET_SOURCE_TYPE,
                 true,
                 false,
                 false,
                 ItemPropertyDescriptor.GENERIC_VALUE_IMAGE,
                 getString("_UI_RuleSetPropertyCategory"),
                 null));
    }

    /**
     * This adds a property descriptor for the Rule Set Source Code feature.
     * <!-- begin-user-doc -->
     * <!-- end-user-doc -->
     * @generated
     */
    protected void addRuleSetSourceCodePropertyDescriptor(Object object) {
        itemPropertyDescriptors.add
            (createItemPropertyDescriptor
                (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
                 getResourceLocator(),
                 getString("_UI_RuleMediator_ruleSetSourceCode_feature"),
                 getString("_UI_PropertyDescriptor_description", "_UI_RuleMediator_ruleSetSourceCode_feature", "_UI_RuleMediator_type"),
                 EsbPackage.Literals.RULE_MEDIATOR__RULE_SET_SOURCE_CODE,
                 true,
                 true,
                 false,
                 ItemPropertyDescriptor.GENERIC_VALUE_IMAGE,
                 getString("_UI_RuleSetPropertyCategory"),
                 null));
    }

    /**
     * This adds a property descriptor for the Rule Set Source Key feature.
     * <!-- begin-user-doc -->
     * <!-- end-user-doc -->
     * @generated
     */
    protected void addRuleSetSourceKeyPropertyDescriptor(Object object) {
        itemPropertyDescriptors.add
            (createItemPropertyDescriptor
                (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
                 getResourceLocator(),
                 getString("_UI_RuleMediator_ruleSetSourceKey_feature"),
                 getString("_UI_PropertyDescriptor_description", "_UI_RuleMediator_ruleSetSourceKey_feature", "_UI_RuleMediator_type"),
                 EsbPackage.Literals.RULE_MEDIATOR__RULE_SET_SOURCE_KEY,
                 true,
                 false,
                 false,
                 null,
                 getString("_UI_RuleSetPropertyCategory"),
                 null));
    }

    /**
     * This adds a property descriptor for the Stateful Session feature.
     * <!-- begin-user-doc -->
     * <!-- end-user-doc -->
     * @generated
     */
    protected void addStatefulSessionPropertyDescriptor(Object object) {
        itemPropertyDescriptors.add
            (createItemPropertyDescriptor
                (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
                 getResourceLocator(),
                 getString("_UI_RuleMediator_statefulSession_feature"),
                 getString("_UI_PropertyDescriptor_description", "_UI_RuleMediator_statefulSession_feature", "_UI_RuleMediator_type"),
                 EsbPackage.Literals.RULE_MEDIATOR__STATEFUL_SESSION,
                 true,
                 false,
                 false,
                 ItemPropertyDescriptor.BOOLEAN_VALUE_IMAGE,
                 getString("_UI_RuleSessionPropertyCategory"),
                 null));
    }

    /**
     * This adds a property descriptor for the Rule Session Properties feature.
     * <!-- begin-user-doc -->
     * <!-- end-user-doc -->
     * @generated
     */
    protected void addRuleSessionPropertiesPropertyDescriptor(Object object) {
        itemPropertyDescriptors.add
            (createItemPropertyDescriptor
                (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
                 getResourceLocator(),
                 getString("_UI_RuleMediator_RuleSessionProperties_feature"),
                 getString("_UI_PropertyDescriptor_description", "_UI_RuleMediator_RuleSessionProperties_feature", "_UI_RuleMediator_type"),
                 EsbPackage.Literals.RULE_MEDIATOR__RULE_SESSION_PROPERTIES,
                 true,
                 false,
                 false,
                 null,
                 getString("_UI_RuleSessionPropertyCategory"),
                 null));
    }

    /**
     * This adds a property descriptor for the Facts Configuration feature.
     * <!-- begin-user-doc -->
     * <!-- end-user-doc -->
     * @generated
     */
    protected void addFactsConfigurationPropertyDescriptor(Object object) {
        itemPropertyDescriptors.add
            (createItemPropertyDescriptor
                (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
                 getResourceLocator(),
                 getString("_UI_RuleMediator_factsConfiguration_feature"),
                 getString("_UI_PropertyDescriptor_description", "_UI_RuleMediator_factsConfiguration_feature", "_UI_RuleMediator_type"),
                 EsbPackage.Literals.RULE_MEDIATOR__FACTS_CONFIGURATION,
                 true,
                 false,
                 false,
                 null,
                 getString("_UI_InputFactsPropertyCategory"),
                 null));
    }

    /**
     * This adds a property descriptor for the Results Configuration feature.
     * <!-- begin-user-doc -->
     * <!-- end-user-doc -->
     * @generated
     */
    protected void addResultsConfigurationPropertyDescriptor(Object object) {
        itemPropertyDescriptors.add
            (createItemPropertyDescriptor
                (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
                 getResourceLocator(),
                 getString("_UI_RuleMediator_resultsConfiguration_feature"),
                 getString("_UI_PropertyDescriptor_description", "_UI_RuleMediator_resultsConfiguration_feature", "_UI_RuleMediator_type"),
                 EsbPackage.Literals.RULE_MEDIATOR__RESULTS_CONFIGURATION,
                 true,
                 false,
                 false,
                 null,
                 getString("_UI_OutputFactsPropertyCategory"),
                 null));
    }

    /**
     * This adds a property descriptor for the Source Value feature.
     * <!-- begin-user-doc -->
     * <!-- end-user-doc -->
     * @generated
     */
    protected void addSourceValuePropertyDescriptor(Object object) {
        itemPropertyDescriptors.add
            (createItemPropertyDescriptor
                (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
                 getResourceLocator(),
                 getString("_UI_RuleMediator_sourceValue_feature"),
                 getString("_UI_PropertyDescriptor_description", "_UI_RuleMediator_sourceValue_feature", "_UI_RuleMediator_type"),
                 EsbPackage.Literals.RULE_MEDIATOR__SOURCE_VALUE,
                 true,
                 false,
                 false,
                 ItemPropertyDescriptor.GENERIC_VALUE_IMAGE,
                 getString("_UI_SourcePropertyCategory"),
                 null));
    }

    /**
     * This adds a property descriptor for the Source Xpath feature.
     * <!-- begin-user-doc -->
     * <!-- end-user-doc -->
     * @generated
     */
    protected void addSourceXpathPropertyDescriptor(Object object) {
        itemPropertyDescriptors.add
            (createItemPropertyDescriptor
                (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
                 getResourceLocator(),
                 getString("_UI_RuleMediator_sourceXpath_feature"),
                 getString("_UI_PropertyDescriptor_description", "_UI_RuleMediator_sourceXpath_feature", "_UI_RuleMediator_type"),
                 EsbPackage.Literals.RULE_MEDIATOR__SOURCE_XPATH,
                 true,
                 false,
                 true,
                 null,
                 getString("_UI_SourcePropertyCategory"),
                 null));
    }

    /**
     * This adds a property descriptor for the Target Value feature.
     * <!-- begin-user-doc -->
     * <!-- end-user-doc -->
     * @generated
     */
    protected void addTargetValuePropertyDescriptor(Object object) {
        itemPropertyDescriptors.add
            (createItemPropertyDescriptor
                (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
                 getResourceLocator(),
                 getString("_UI_RuleMediator_targetValue_feature"),
                 getString("_UI_PropertyDescriptor_description", "_UI_RuleMediator_targetValue_feature", "_UI_RuleMediator_type"),
                 EsbPackage.Literals.RULE_MEDIATOR__TARGET_VALUE,
                 true,
                 false,
                 false,
                 ItemPropertyDescriptor.GENERIC_VALUE_IMAGE,
                 getString("_UI_TargetPropertyCategory"),
                 null));
    }

    /**
     * This adds a property descriptor for the Target Result Xpath feature.
     * <!-- begin-user-doc -->
     * <!-- end-user-doc -->
     * @generated
     */
    protected void addTargetResultXpathPropertyDescriptor(Object object) {
        itemPropertyDescriptors.add
            (createItemPropertyDescriptor
                (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
                 getResourceLocator(),
                 getString("_UI_RuleMediator_targetResultXpath_feature"),
                 getString("_UI_PropertyDescriptor_description", "_UI_RuleMediator_targetResultXpath_feature", "_UI_RuleMediator_type"),
                 EsbPackage.Literals.RULE_MEDIATOR__TARGET_RESULT_XPATH,
                 true,
                 false,
                 true,
                 null,
                 getString("_UI_TargetPropertyCategory"),
                 null));
    }

    /**
     * This adds a property descriptor for the Target Xpath feature.
     * <!-- begin-user-doc -->
     * <!-- end-user-doc -->
     * @generated
     */
    protected void addTargetXpathPropertyDescriptor(Object object) {
        itemPropertyDescriptors.add
            (createItemPropertyDescriptor
                (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
                 getResourceLocator(),
                 getString("_UI_RuleMediator_targetXpath_feature"),
                 getString("_UI_PropertyDescriptor_description", "_UI_RuleMediator_targetXpath_feature", "_UI_RuleMediator_type"),
                 EsbPackage.Literals.RULE_MEDIATOR__TARGET_XPATH,
                 true,
                 false,
                 true,
                 null,
                 getString("_UI_TargetPropertyCategory"),
                 null));
    }

    /**
     * This adds a property descriptor for the Target Action feature.
     * <!-- begin-user-doc -->
     * <!-- end-user-doc -->
     * @generated
     */
    protected void addTargetActionPropertyDescriptor(Object object) {
        itemPropertyDescriptors.add
            (createItemPropertyDescriptor
                (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
                 getResourceLocator(),
                 getString("_UI_RuleMediator_targetAction_feature"),
                 getString("_UI_PropertyDescriptor_description", "_UI_RuleMediator_targetAction_feature", "_UI_RuleMediator_type"),
                 EsbPackage.Literals.RULE_MEDIATOR__TARGET_ACTION,
                 true,
                 false,
                 false,
                 ItemPropertyDescriptor.GENERIC_VALUE_IMAGE,
                 getString("_UI_TargetPropertyCategory"),
                 null));
    }

    /**
     * This adds a property descriptor for the Input Wrapper Name feature.
     * <!-- begin-user-doc -->
     * <!-- end-user-doc -->
     * @generated
     */
    protected void addInputWrapperNamePropertyDescriptor(Object object) {
        itemPropertyDescriptors.add
            (createItemPropertyDescriptor
                (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
                 getResourceLocator(),
                 getString("_UI_RuleMediator_InputWrapperName_feature"),
                 getString("_UI_PropertyDescriptor_description", "_UI_RuleMediator_InputWrapperName_feature", "_UI_RuleMediator_type"),
                 EsbPackage.Literals.RULE_MEDIATOR__INPUT_WRAPPER_NAME,
                 true,
                 false,
                 false,
                 ItemPropertyDescriptor.GENERIC_VALUE_IMAGE,
                 getString("_UI_InputFactsPropertyCategory"),
                 null));
    }

    /**
     * This adds a property descriptor for the Input Name Space feature.
     * <!-- begin-user-doc -->
     * <!-- end-user-doc -->
     * @generated
     */
    protected void addInputNameSpacePropertyDescriptor(Object object) {
        itemPropertyDescriptors.add
            (createItemPropertyDescriptor
                (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
                 getResourceLocator(),
                 getString("_UI_RuleMediator_InputNameSpace_feature"),
                 getString("_UI_PropertyDescriptor_description", "_UI_RuleMediator_InputNameSpace_feature", "_UI_RuleMediator_type"),
                 EsbPackage.Literals.RULE_MEDIATOR__INPUT_NAME_SPACE,
                 true,
                 false,
                 false,
                 ItemPropertyDescriptor.GENERIC_VALUE_IMAGE,
                 getString("_UI_InputFactsPropertyCategory"),
                 null));
    }

    /**
     * This adds a property descriptor for the Output Wrapper Name feature.
     * <!-- begin-user-doc -->
     * <!-- end-user-doc -->
     * @generated
     */
    protected void addOutputWrapperNamePropertyDescriptor(Object object) {
        itemPropertyDescriptors.add
            (createItemPropertyDescriptor
                (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
                 getResourceLocator(),
                 getString("_UI_RuleMediator_OutputWrapperName_feature"),
                 getString("_UI_PropertyDescriptor_description", "_UI_RuleMediator_OutputWrapperName_feature", "_UI_RuleMediator_type"),
                 EsbPackage.Literals.RULE_MEDIATOR__OUTPUT_WRAPPER_NAME,
                 true,
                 false,
                 false,
                 ItemPropertyDescriptor.GENERIC_VALUE_IMAGE,
                 getString("_UI_OutputFactsPropertyCategory"),
                 null));
    }

    /**
     * This adds a property descriptor for the Output Name Space feature.
     * <!-- begin-user-doc -->
     * <!-- end-user-doc -->
     * @generated
     */
    protected void addOutputNameSpacePropertyDescriptor(Object object) {
        itemPropertyDescriptors.add
            (createItemPropertyDescriptor
                (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
                 getResourceLocator(),
                 getString("_UI_RuleMediator_OutputNameSpace_feature"),
                 getString("_UI_PropertyDescriptor_description", "_UI_RuleMediator_OutputNameSpace_feature", "_UI_RuleMediator_type"),
                 EsbPackage.Literals.RULE_MEDIATOR__OUTPUT_NAME_SPACE,
                 true,
                 false,
                 false,
                 ItemPropertyDescriptor.GENERIC_VALUE_IMAGE,
                 getString("_UI_OutputFactsPropertyCategory"),
                 null));
    }

    /**
     * This adds a property descriptor for the Rule Set Type feature.
     * <!-- begin-user-doc -->
     * <!-- end-user-doc -->
     * @generated
     */
    protected void addRuleSetTypePropertyDescriptor(Object object) {
        itemPropertyDescriptors.add
            (createItemPropertyDescriptor
                (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
                 getResourceLocator(),
                 getString("_UI_RuleMediator_RuleSetType_feature"),
                 getString("_UI_PropertyDescriptor_description", "_UI_RuleMediator_RuleSetType_feature", "_UI_RuleMediator_type"),
                 EsbPackage.Literals.RULE_MEDIATOR__RULE_SET_TYPE,
                 true,
                 false,
                 false,
                 ItemPropertyDescriptor.GENERIC_VALUE_IMAGE,
                 getString("_UI_RuleSetPropertyCategory"),
                 null));
    }

    /**
     * This specifies how to implement {@link #getChildren} and is used to deduce an appropriate feature for an
     * {@link org.eclipse.emf.edit.command.AddCommand}, {@link org.eclipse.emf.edit.command.RemoveCommand} or
     * {@link org.eclipse.emf.edit.command.MoveCommand} in {@link #createCommand}.
     * <!-- begin-user-doc -->
     * <!-- end-user-doc -->
     * @generated
     */

    @Override
    public Collection<? extends EStructuralFeature> getChildrenFeatures(Object object) {
        if (childrenFeatures == null) {
            super.getChildrenFeatures(object);
            childrenFeatures.add(EsbPackage.Literals.RULE_MEDIATOR__RULE_SET_SOURCE_KEY);
            childrenFeatures.add(EsbPackage.Literals.RULE_MEDIATOR__RULE_SESSION_PROPERTIES);
            childrenFeatures.add(EsbPackage.Literals.RULE_MEDIATOR__FACTS_CONFIGURATION);
            childrenFeatures.add(EsbPackage.Literals.RULE_MEDIATOR__RESULTS_CONFIGURATION);
            childrenFeatures.add(EsbPackage.Literals.RULE_MEDIATOR__CHILD_MEDIATORS_CONFIGURATION);
            childrenFeatures.add(EsbPackage.Literals.RULE_MEDIATOR__INPUT_CONNECTOR);
            childrenFeatures.add(EsbPackage.Literals.RULE_MEDIATOR__OUTPUT_CONNECTOR);
            childrenFeatures.add(EsbPackage.Literals.RULE_MEDIATOR__CHILD_MEDIATORS_OUTPUT_CONNECTOR);
            childrenFeatures.add(EsbPackage.Literals.RULE_MEDIATOR__MEDIATOR_FLOW);
        }
        return childrenFeatures;
    }

    /**
     * <!-- begin-user-doc -->
     * <!-- end-user-doc -->
     * @generated
     */

    @Override
    protected EStructuralFeature getChildFeature(Object object, Object child) {
        // Check the type of the specified child object and return the proper feature to use for
        // adding (see {@link AddCommand}) it as a child.

        return super.getChildFeature(object, child);
    }

    /**
     * This returns RuleMediator.png.
     * <!-- begin-user-doc -->
     * <!-- end-user-doc -->
     * @generated NOT
     */

    @Override
    public Object getImage(Object object) {
        return overlayImage(object, getResourceLocator().getImage("full/obj16/RuleMediator.png"));
    }

    /**
     * This returns the label text for the adapted class.
     * <!-- begin-user-doc -->
     * <!-- end-user-doc -->
     * @generated
     */

    @Override
    public String getText(Object object) {
        String label = ((RuleMediator)object).getInputWrapperName();
        return label == null || label.length() == 0 ?
            getString("_UI_RuleMediator_type") :
            getString("_UI_RuleMediator_type") + " " + label;
    }

    /**
     * This handles model notifications by calling {@link #updateChildren} to update any cached
     * children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}.
     * <!-- begin-user-doc -->
     * <!-- end-user-doc -->
     * @generated
     */

    @Override
    public void notifyChanged(Notification notification) {
        updateChildren(notification);

        switch (notification.getFeatureID(RuleMediator.class)) {
            case EsbPackage.RULE_MEDIATOR__RULE_SET_URL:
            case EsbPackage.RULE_MEDIATOR__RULE_SET_SOURCE_TYPE:
            case EsbPackage.RULE_MEDIATOR__RULE_SET_SOURCE_CODE:
            case EsbPackage.RULE_MEDIATOR__STATEFUL_SESSION:
            case EsbPackage.RULE_MEDIATOR__SOURCE_VALUE:
            case EsbPackage.RULE_MEDIATOR__TARGET_VALUE:
            case EsbPackage.RULE_MEDIATOR__TARGET_ACTION:
            case EsbPackage.RULE_MEDIATOR__INPUT_WRAPPER_NAME:
            case EsbPackage.RULE_MEDIATOR__INPUT_NAME_SPACE:
            case EsbPackage.RULE_MEDIATOR__OUTPUT_WRAPPER_NAME:
            case EsbPackage.RULE_MEDIATOR__OUTPUT_NAME_SPACE:
            case EsbPackage.RULE_MEDIATOR__RULE_SET_TYPE:
                fireNotifyChanged(new ViewerNotification(notification, notification.getNotifier(), false, true));
                return;
            case EsbPackage.RULE_MEDIATOR__RULE_SET_SOURCE_KEY:
            case EsbPackage.RULE_MEDIATOR__RULE_SESSION_PROPERTIES:
            case EsbPackage.RULE_MEDIATOR__FACTS_CONFIGURATION:
            case EsbPackage.RULE_MEDIATOR__RESULTS_CONFIGURATION:
            case EsbPackage.RULE_MEDIATOR__CHILD_MEDIATORS_CONFIGURATION:
            case EsbPackage.RULE_MEDIATOR__INPUT_CONNECTOR:
            case EsbPackage.RULE_MEDIATOR__OUTPUT_CONNECTOR:
            case EsbPackage.RULE_MEDIATOR__CHILD_MEDIATORS_OUTPUT_CONNECTOR:
            case EsbPackage.RULE_MEDIATOR__MEDIATOR_FLOW:
                fireNotifyChanged(new ViewerNotification(notification, notification.getNotifier(), true, false));
                return;
        }
        super.notifyChanged(notification);
    }

    /**
     * This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children
     * that can be created under this object.
     * <!-- begin-user-doc -->
     * <!-- end-user-doc -->
     * @generated
     */

    @Override
    protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object) {
        super.collectNewChildDescriptors(newChildDescriptors, object);

        newChildDescriptors.add
            (createChildParameter
                (EsbPackage.Literals.RULE_MEDIATOR__RULE_SET_SOURCE_KEY,
                 EsbFactory.eINSTANCE.createRegistryKeyProperty()));

        newChildDescriptors.add
            (createChildParameter
                (EsbPackage.Literals.RULE_MEDIATOR__RULE_SESSION_PROPERTIES,
                 EsbFactory.eINSTANCE.createRuleSessionProperty()));

        newChildDescriptors.add
            (createChildParameter
                (EsbPackage.Literals.RULE_MEDIATOR__FACTS_CONFIGURATION,
                 EsbFactory.eINSTANCE.createRuleFactsConfiguration()));

        newChildDescriptors.add
            (createChildParameter
                (EsbPackage.Literals.RULE_MEDIATOR__RESULTS_CONFIGURATION,
                 EsbFactory.eINSTANCE.createRuleResultsConfiguration()));

        newChildDescriptors.add
            (createChildParameter
                (EsbPackage.Literals.RULE_MEDIATOR__CHILD_MEDIATORS_CONFIGURATION,
                 EsbFactory.eINSTANCE.createRuleChildMediatorsConfiguration()));

        newChildDescriptors.add
            (createChildParameter
                (EsbPackage.Literals.RULE_MEDIATOR__INPUT_CONNECTOR,
                 EsbFactory.eINSTANCE.createRuleMediatorInputConnector()));

        newChildDescriptors.add
            (createChildParameter
                (EsbPackage.Literals.RULE_MEDIATOR__OUTPUT_CONNECTOR,
                 EsbFactory.eINSTANCE.createRuleMediatorOutputConnector()));

        newChildDescriptors.add
            (createChildParameter
                (EsbPackage.Literals.RULE_MEDIATOR__CHILD_MEDIATORS_OUTPUT_CONNECTOR,
                 EsbFactory.eINSTANCE.createRuleMediatorChildMediatorsOutputConnector()));

        newChildDescriptors.add
            (createChildParameter
                (EsbPackage.Literals.RULE_MEDIATOR__MEDIATOR_FLOW,
                 EsbFactory.eINSTANCE.createMediatorFlow()));
    }

}


text:
package com.avsystem.commons
package mongo.typed

import org.bson.{BsonArray, BsonDocument}

/**
  * Represents a MongoDB filter. In particular, this may be a [[MongoDocumentFilter]] which can be used
  * directly in database queries.
  *
  * [[MongoFilter]] may also represent a filter for a non-document value. Such filters may be used e.g. in
  * queries that apply filters on values of an array.
  *
  * @tparam T type of the filtered value
  */
sealed trait MongoFilter[T] {

  import MongoFilter._

  def on[E](prefix: MongoPropertyRef[E, T]): MongoDocumentFilter[E] =
    PropertyValueFilter(prefix, this)

  final def toBson: BsonDocument = this match {
    case docFilter: MongoDocumentFilter[T] => docFilter.toFilterBson(Opt.Empty, Set.empty)
    case opsFilter: MongoOperatorsFilter[T] => opsFilter.toOperatorsBson
  }
}

object MongoFilter {
  def creator[T: MongoFormat]: Creator[T] = new Creator(MongoFormat[T])

  class Creator[T](val format: MongoFormat[T])
    extends QueryOperatorsDsl[T, MongoOperatorsFilter[T]] with DataTypeDsl[T] {

    def SelfRef: MongoRef[T, T] =
      MongoRef.RootRef(format.assumeAdt)

    protected def wrapQueryOperators(ops: MongoQueryOperator[T]*): MongoOperatorsFilter[T] =
      MongoOperatorsFilter(ops)

    /** See [[MongoPropertyRef.satisfiesOperators]] */
    def satisfiesOperators(operators: MongoQueryOperator.Creator[T] => Seq[MongoQueryOperator[T]]): MongoOperatorsFilter[T] =
      MongoOperatorsFilter(operators(new MongoQueryOperator.Creator(format)))
  }

  private[this] val reusableEmpty = Empty()

  def empty[E]: MongoDocumentFilter[E] = reusableEmpty.asInstanceOf[MongoDocumentFilter[E]]
  def and[E](filters: MongoDocumentFilter[E]*): MongoDocumentFilter[E] = And(filters.toVector)
  def or[E](filters: MongoDocumentFilter[E]*): MongoDocumentFilter[E] = Or(filters.toVector)
  def nor[E](filters: MongoDocumentFilter[E]*): MongoDocumentFilter[E] = Nor(filters.toVector)

  final case class Empty[E]() extends MongoDocumentFilter[E]
  final case class And[E](filters: Vector[MongoDocumentFilter[E]]) extends MongoDocumentFilter[E]
  final case class Or[E](filters: Vector[MongoDocumentFilter[E]]) extends MongoDocumentFilter[E]
  final case class Nor[E](filters: Vector[MongoDocumentFilter[E]]) extends MongoDocumentFilter[E]
  //NOTE: $not is NOT allowed as a toplevel operator

  final case class PropertyValueFilter[E, T](
    property: MongoPropertyRef[E, T],
    filter: MongoFilter[T]
  ) extends MongoDocumentFilter[E]

  def subtypeFilter[E, T](prefix: MongoRef[E, T], caseFieldName: String, caseNames: List[String], negated: Boolean): MongoDocumentFilter[E] = {
    val operator = caseNames match {
      case List(single) if negated => MongoQueryOperator.Ne(single, MongoFormat[String])
      case List(single) => MongoQueryOperator.Eq(single, MongoFormat[String])
      case multiple if negated => MongoQueryOperator.Nin(multiple, MongoFormat[String])
      case multiple => MongoQueryOperator.In(multiple, MongoFormat[String])
    }
    PropertyValueFilter(MongoRef.caseNameRef(prefix, caseFieldName), MongoOperatorsFilter(Seq(operator)))
  }
}

/**
  * Represents a filter that applies a set of query operators on a value (e.g. `$$eq`, `$$lte`, etc.)
  * Every operator may be used at most once. Such filter usually translates into a BSON document that looks like this:
  *
  * {{{
  *   {"$$ne": 5, "$$gte": 0, ...more operators}
  * }}}
  *
  * @tparam T type of the filtered value
  */
final case class MongoOperatorsFilter[T](operators: Seq[MongoQueryOperator[T]]) extends MongoFilter[T] {
  def negated: MongoOperatorsFilter[T] =
    MongoOperatorsFilter(Seq(MongoQueryOperator.Not(this)))

  def unary_! : MongoOperatorsFilter[T] = negated

  def toOperatorsBson: BsonDocument = {
    val doc = new BsonDocument
    operators.foreach { op =>
      if (doc.containsKey(op.rawOperator)) {
        throw new IllegalArgumentException(s"duplicate query operator ${op.rawOperator}")
      }
      doc.put(op.rawOperator, op.toBson)
    }
    doc
  }
}

/**
  * Represents a [[https://docs.mongodb.com/manual/tutorial/query-documents/ MongoDB query document]].
  *
  * A [[MongoDocumentFilter]] is usually built by using [[MongoPropertyRef]] and its API.
  *
  * {{{
  *   case class MyEntity(id: String, number: Int) extends MongoEntity[MyEntity]
  *   object MyEntity extends MongoEntityCompanion[MyEntity]
  *
  *   val filter: MongoDocumentFilter[MyEntity] =
  *     MyEntity.ref(_.id).is("ID") && MyEntity.ref(_.number) > 8
  * }}}
  *
  * NOTE: even though you can combine filters using logical `$$and` and `$$or` operators,
  * MongoDB does not allow using the `$$not` operator on this level.
  * It may only be specified for field-level filters.
  *
  * @tparam E type of the filtered value (that must translate into a document)
  */
sealed trait MongoDocumentFilter[E] extends MongoFilter[E] {

  import MongoFilter._

  def and(other: MongoDocumentFilter[E]): MongoDocumentFilter[E] = (this, other) match {
    case (Empty(), other) => other
    case (thiz, Empty()) => thiz
    case (And(thisFilters), And(otherFilters)) => And(thisFilters ++ otherFilters)
    case (And(thisFilters), other) => And(thisFilters :+ other)
    case (thiz, And(otherFilters)) => And(thiz +: otherFilters)
    case _ => And(Vector(this, other))
  }

  def &&(other: MongoDocumentFilter[E]): MongoDocumentFilter[E] = and(other)

  def or(other: MongoDocumentFilter[E]): MongoDocumentFilter[E] = (this, other) match {
    case (Empty(), _) | (_, Empty()) => empty
    case (Or(thisFilters), Or(otherFilters)) => Or(thisFilters ++ otherFilters)
    case (Or(thisFilters), other) => Or(thisFilters :+ other)
    case (thiz, Or(otherFilters)) => Or(thiz +: otherFilters)
    case _ => Or(Vector(this, other))
  }

  def ||(other: MongoDocumentFilter[E]): MongoDocumentFilter[E] = or(other)

  final def toFilterBson(prefixPath: Opt[String], projectionRefs: Set[MongoRef[E, _]]): BsonDocument = {
    val builder = new FilterDocBuilder(prefixPath, new BsonArray)
    builder.addFilter(this)
    projectionRefs.foreach(builder.addImpliedFilters)
    builder.finalDoc
  }
}


text:
<?php

namespace Doctrine\ODM\MongoDB\Mapping\Driver;

use Doctrine\Common\Annotations\AnnotationReader;
use Doctrine\Common\Annotations\AnnotationRegistry;
use Doctrine\Common\Annotations\Reader;
use Doctrine\Common\Persistence\Mapping\ClassMetadata;
use Doctrine\Common\Persistence\Mapping\Driver\AnnotationDriver as AbstractAnnotationDriver;
use Doctrine\ODM\MongoDB\Events;
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
use Doctrine\ODM\MongoDB\Mapping\ClassMetadataInfo;
use Doctrine\ODM\MongoDB\Mapping\MappingException;

/**
 * The AnnotationDriver reads the mapping metadata from docblock annotations.
 *
 * @since       1.0
 * @author      Jonathan H. Wage <jonwage@gmail.com>
 * @author      Roman Borschel <roman@code-factory.org>
 */
class AnnotationDriver extends AbstractAnnotationDriver
{
    protected $entityAnnotationClasses = array(
        'Doctrine\\ODM\\MongoDB\\Mapping\\Annotations\\Document' => 1,
        'Doctrine\\ODM\\MongoDB\\Mapping\\Annotations\\MappedSuperclass' => 2,
        'Doctrine\\ODM\\MongoDB\\Mapping\\Annotations\\EmbeddedDocument' => 3,
    );

    /**
     * Registers annotation classes to the common registry.
     *
     * This method should be called when bootstrapping your application.
     */
    public static function registerAnnotationClasses()
    {
        AnnotationRegistry::registerFile(__DIR__ . '/../Annotations/DoctrineAnnotations.php');
    }

    /**
     * {@inheritdoc}
     */
    public function loadMetadataForClass($className, ClassMetadata $class)
    {
        /** @var $class ClassMetadataInfo */
        $reflClass = $class->getReflectionClass();

        $classAnnotations = $this->reader->getClassAnnotations($reflClass);

        $documentAnnots = array();
        foreach ($classAnnotations as $annot) {
            $classAnnotations[get_class($annot)] = $annot;

            foreach ($this->entityAnnotationClasses as $annotClass => $i) {
                if ($annot instanceof $annotClass) {
                    $documentAnnots[$i] = $annot;
                    continue 2;
                }
            }

            // non-document class annotations
            if ($annot instanceof ODM\AbstractIndex) {
                $this->addIndex($class, $annot);
            }
            if ($annot instanceof ODM\Indexes) {
                foreach (is_array($annot->value) ? $annot->value : array($annot->value) as $index) {
                    $this->addIndex($class, $index);
                }
            } elseif ($annot instanceof ODM\InheritanceType) {
                $class->setInheritanceType(constant('Doctrine\\ODM\\MongoDB\\Mapping\\ClassMetadata::INHERITANCE_TYPE_'.$annot->value));
            } elseif ($annot instanceof ODM\DiscriminatorField) {
                // $fieldName property is deprecated, but fall back for BC
                if (isset($annot->value)) {
                    $class->setDiscriminatorField($annot->value);
                } elseif (isset($annot->name)) {
                    $class->setDiscriminatorField($annot->name);
                } elseif (isset($annot->fieldName)) {
                    $class->setDiscriminatorField($annot->fieldName);
                }
            } elseif ($annot instanceof ODM\DiscriminatorMap) {
                $class->setDiscriminatorMap($annot->value);
            } elseif ($annot instanceof ODM\DiscriminatorValue) {
                $class->setDiscriminatorValue($annot->value);
            } elseif ($annot instanceof ODM\ChangeTrackingPolicy) {
                $class->setChangeTrackingPolicy(constant('Doctrine\\ODM\\MongoDB\\Mapping\\ClassMetadata::CHANGETRACKING_'.$annot->value));
            } elseif ($annot instanceof ODM\DefaultDiscriminatorValue) {
                $class->setDefaultDiscriminatorValue($annot->value);
            }

        }

        if ( ! $documentAnnots) {
            throw MappingException::classIsNotAValidDocument($className);
        }

        // find the winning document annotation
        ksort($documentAnnots);
        $documentAnnot = reset($documentAnnots);

        if ($documentAnnot instanceof ODM\MappedSuperclass) {
            $class->isMappedSuperclass = true;
        } elseif ($documentAnnot instanceof ODM\EmbeddedDocument) {
            $class->isEmbeddedDocument = true;
        }
        if (isset($documentAnnot->db)) {
            $class->setDatabase($documentAnnot->db);
        }
        if (isset($documentAnnot->collection)) {
            $class->setCollection($documentAnnot->collection);
        }
        if (isset($documentAnnot->repositoryClass) && !$class->isEmbeddedDocument) {
            $class->setCustomRepositoryClass($documentAnnot->repositoryClass);
        }
        if (isset($documentAnnot->indexes)) {
            foreach ($documentAnnot->indexes as $index) {
                $this->addIndex($class, $index);
            }
        }
        if (isset($documentAnnot->requireIndexes)) {
            $class->setRequireIndexes($documentAnnot->requireIndexes);
        }
        if (isset($documentAnnot->slaveOkay)) {
            $class->setSlaveOkay($documentAnnot->slaveOkay);
        }

        foreach ($reflClass->getProperties() as $property) {
            if (($class->isMappedSuperclass && ! $property->isPrivate())
                ||
                ($class->isInheritedField($property->name) && $property->getDeclaringClass()->name !== $class->name)) {
                continue;
            }

            $indexes = array();
            $mapping = array('fieldName' => $property->getName());
            $fieldAnnot = null;

            foreach ($this->reader->getPropertyAnnotations($property) as $annot) {
                if ($annot instanceof ODM\AbstractField) {
                    $fieldAnnot = $annot;
                }
                if ($annot instanceof ODM\AbstractIndex) {
                    $indexes[] = $annot;
                }
                if ($annot instanceof ODM\Indexes) {
                    foreach (is_array($annot->value) ? $annot->value : array($annot->value) as $index) {
                        $indexes[] = $index;
                    }
                } elseif ($annot instanceof ODM\AlsoLoad) {
                    $mapping['alsoLoadFields'] = (array) $annot->value;
                } elseif ($annot instanceof ODM\Version) {
                    $mapping['version'] = true;
                } elseif ($annot instanceof ODM\Lock) {
                    $mapping['lock'] = true;
                }
            }

            if ($fieldAnnot) {
                $mapping = array_replace($mapping, (array) $fieldAnnot);
                $class->mapField($mapping);
            }

            if ($indexes) {
                foreach ($indexes as $index) {
                    $name = isset($mapping['name']) ? $mapping['name'] : $mapping['fieldName'];
                    $keys = array($name => $index->order ?: 'asc');
                    $this->addIndex($class, $index, $keys);
                }
            }
        }

        /** @var $method \ReflectionMethod */
        foreach ($reflClass->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) {
            /* Filter for the declaring class only. Callbacks from parent
             * classes will already be registered.
             */
            if ($method->getDeclaringClass()->name !== $reflClass->name) {
                continue;
            }

            foreach ($this->reader->getMethodAnnotations($method) as $annot) {
                if ($annot instanceof ODM\AlsoLoad) {
                    $class->registerAlsoLoadMethod($method->getName(), $annot->value);
                }

                if ( ! isset($classAnnotations['Doctrine\ODM\MongoDB\Mapping\Annotations\HasLifecycleCallbacks'])) {
                    continue;
                }

                if ($annot instanceof ODM\PrePersist) {
                    $class->addLifecycleCallback($method->getName(), Events::prePersist);
                } elseif ($annot instanceof ODM\PostPersist) {
                    $class->addLifecycleCallback($method->getName(), Events::postPersist);
                } elseif ($annot instanceof ODM\PreUpdate) {
                    $class->addLifecycleCallback($method->getName(), Events::preUpdate);
                } elseif ($annot instanceof ODM\PostUpdate) {
                    $class->addLifecycleCallback($method->getName(), Events::postUpdate);
                } elseif ($annot instanceof ODM\PreRemove) {
                    $class->addLifecycleCallback($method->getName(), Events::preRemove);
                } elseif ($annot instanceof ODM\PostRemove) {
                    $class->addLifecycleCallback($method->getName(), Events::postRemove);
                } elseif ($annot instanceof ODM\PreLoad) {
                    $class->addLifecycleCallback($method->getName(), Events::preLoad);
                } elseif ($annot instanceof ODM\PostLoad) {
                    $class->addLifecycleCallback($method->getName(), Events::postLoad);
                } elseif ($annot instanceof ODM\PreFlush) {
                    $class->addLifecycleCallback($method->getName(), Events::preFlush);
                }
            }
        }
    }

    private function addIndex(ClassMetadataInfo $class, $index, array $keys = array())
    {
        $keys = array_merge($keys, $index->keys);
        $options = array();
        $allowed = array('name', 'dropDups', 'background', 'safe', 'unique', 'sparse', 'expireAfterSeconds');
        foreach ($allowed as $name) {
            if (isset($index->$name)) {
                $options[$name] = $index->$name;
            }
        }
        $options = array_merge($options, $index->options);
        $class->addIndex($keys, $options);
    }

    /**
     * Factory method for the Annotation Driver
     *
     * @param array|string $paths
     * @param Reader $reader
     * @return AnnotationDriver
     */
    public static function create($paths = array(), Reader $reader = null)
    {
        if ($reader === null) {
            $reader = new AnnotationReader();
        }
        return new self($reader, $paths);
    }
}


text:
using System;
using System.Reflection;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("DaveSexton.SettingsSwitcher")]
[assembly: AssemblyDescription("")]
[assembly: CLSCompliant(false)]
[assembly: ComVisible(false)]

internal static class AssemblyConstants
{
	public const string Version = GlobalConstants.Version;

	/// <summary>
	/// Semantic version for the assembly, indicating a prerelease package in NuGet.
	/// </summary>
	/// <remarks>
	/// <para>
	/// The specified name can be arbitrary, but its mere presence indicates a prerelease package.
	/// To indicate a release package instead, use an empty string.
	/// </para>
	/// <para>
	/// If specified, the value must include a preceding hyphen; e.g., "-alpha", "-beta", "-rc".
	/// </para>
	/// </remarks>
	/// <seealso href="http://docs.nuget.org/docs/reference/versioning#Really_brief_introduction_to_SemVer">
	/// NuGet Semantic Versioning
	/// </seealso>
	public const string PrereleaseVersion = "";
}


text:
Click on the green flag, enter the inputs provided in the "testing examples" to
see the expected output of your program.

{iframe link="https://scratch.mit.edu/projects/embed/148425996/?autostart=false"}

{panel type="help"}

# Recommended blocks

```scratch
when green flag clicked

ask [Please enter a black or white square (B for black or W for white):] and wait

say (black cards total)
```

```scratch
set [black cards total v] to [0]

change [black cards total v] by (1)
```

```scratch
repeat (5)
end

if <(answer) = [B]> then
end
```

{panel end}


text:
var express = require('express')
var router  = express.Router()

// CONTROLLERS
var postsController = require('../controllers/posts.controller.js')

// MIDDLEWARE
var globalMiddleware = require('../middleware')
var authMiddleware   = require('../middleware/authMiddleware')

// POST ROUTES ( /posts )
router
  .route('/')
    .get(globalMiddleware.test, postsController.postsGetAll)
    .post(authMiddleware.isLoggedIn, postsController.postsAddOne)

router
  .route('/new')
    .get(authMiddleware.isLoggedIn, postsController.postsRenderNew)

router
  .route('/:postId')
    .get(postsController.postsGetById)
    .put(postsController.postsUpdateById)
    .delete(postsController.postsDeleteById)

module.exports = router


text:
//
//  File: %host-readline.c
//  Summary: "Simple readline() line input handler"
//  Project: "Rebol 3 Interpreter and Run-time (Ren-C branch)"
//  Homepage: https://github.com/metaeducation/ren-c/
//
//=////////////////////////////////////////////////////////////////////////=//
//
// Copyright 2012 REBOL Technologies
// Copyright 2012-2017 Rebol Open Source Contributors
// REBOL is a trademark of REBOL Technologies
//
// See README.md and CREDITS.md for more information.
//
// 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
//
//=////////////////////////////////////////////////////////////////////////=//
//
// Processes special keys for input line editing and recall.
//
// Avoids use of complex OS libraries and GNU readline() but hardcodes some
// parts only for the common standard.
//

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h> //for read and write
#include <errno.h>

#ifndef NO_TTY_ATTRIBUTES
    #include <termios.h>
#endif

#include "sys-core.h"

// Configuration:
#define TERM_BUF_LEN 4096   // chars allowed per line
#define READ_BUF_LEN 64     // chars per read()
#define MAX_HISTORY  300    // number of lines stored

#define CHAR_LEN(c) (1 + trailingBytesForUTF8[c])

#define WRITE_CHAR(s) \
    do { \
        if (write(1, s, 1) == -1) { \
            /* Error here, or better to "just try to keep going"? */ \
        } \
    } while (0)

#define WRITE_CHARS(s,n) \
    do { \
        if (write(1, s, n) == -1) { \
            /* Error here, or better to "just try to keep going"? */ \
        } \
    } while (0)

#define WRITE_STR(s) \
    do { \
        if (write(1, s, strlen(s)) == -1) { \
            /* Error here, or better to "just try to keep going"? */ \
        } \
    } while (0)

//
// Stepping backwards in UTF8 just means to keep going back so long
// as you are looking at a byte with bit 7 set and bit 6 clear:
//
// https://stackoverflow.com/a/22257843/211160
//
#define STEP_BACKWARD(term) \
    do { \
        --term->pos; \
    } while (Is_Continuation_Byte_If_Utf8(term->buffer[term->pos]));

typedef struct term_data {
    unsigned char *buffer;
    unsigned char *residue;
    unsigned char *out;
    int pos;
    int end;
    int hist;
} STD_TERM;

// Globals:
static bool Term_Initialized = false; // Terminal init was successful
static unsigned char **Line_History; // Prior input lines
static int Line_Count; // Number of prior lines

#ifndef NO_TTY_ATTRIBUTES
static struct termios Term_Attrs;   // Initial settings, restored on exit
#endif

extern STD_TERM *Init_Terminal(void);

//
//  Init_Terminal: C
//
// Change the terminal modes to those required for proper
// REBOL console handling. Return TRUE on success.
//
STD_TERM *Init_Terminal(void)
{
#ifndef NO_TTY_ATTRIBUTES
    //
    // Good reference on termios:
    //
    // https://blog.nelhage.com/2009/12/a-brief-introduction-to-termios/
    // https://blog.nelhage.com/2009/12/a-brief-introduction-to-termios-termios3-and-stty/
    // https://blog.nelhage.com/2010/01/a-brief-introduction-to-termios-signaling-and-job-control/
    //
    struct termios attrs;

    if (Term_Initialized || tcgetattr(0, &Term_Attrs)) return NULL;

    attrs = Term_Attrs;

    // Local modes:
    attrs.c_lflag &= ~(ECHO | ICANON); // raw input

    // Input modes:
    attrs.c_iflag &= ~(ICRNL | INLCR); // leave CR an LF as is

    // Output modes:
    attrs.c_oflag |= ONLCR; // On output, emit CR LF

    // Special modes:
    attrs.c_cc[VMIN] = 1;   // min num of bytes for READ to return
    attrs.c_cc[VTIME] = 0;  // how long to wait for input

    tcsetattr(0, TCSADRAIN, &attrs);
#endif

    // Setup variables:
    Line_History = cast(
        unsigned char**,
        malloc(sizeof(char*) * (MAX_HISTORY + 2))
    );

    // Make first line as an empty string
    Line_History[0] = cast(unsigned char*, malloc(sizeof(char) * 1));
    Line_History[0][0] = '\0';
    Line_Count = 1;

    STD_TERM *term = cast(STD_TERM*, malloc(sizeof(STD_TERM)));
    memset(term, '\0', sizeof(STD_TERM));
    term->buffer = cast(unsigned char*, malloc(sizeof(char) * TERM_BUF_LEN));
    term->buffer[0] = 0;
    term->residue = cast(unsigned char*, malloc(sizeof(char) * TERM_BUF_LEN));
    term->residue[0] = 0;

    Term_Initialized = true;

    return term;
}

extern void Quit_Terminal(STD_TERM *term);

//
//  Quit_Terminal: C
//
// Restore the terminal modes original entry settings,
// in preparation for exit from program.
//
void Quit_Terminal(STD_TERM *term)
{
    int n;

    if (Term_Initialized) {
      #ifndef NO_TTY_ATTRIBUTES
        tcsetattr(0, TCSADRAIN, &Term_Attrs);
      #endif
        free(term->residue);
        free(term->buffer);
        free(term);
        for (n = 0; n < Line_Count; n++)
            free(Line_History[n]);
        free(Line_History);
    }

    Term_Initialized = false;
}

//
//  Read_Bytes_Interrupted: C
//
// Read the next "chunk" of data into the terminal buffer.  If it gets
// interrupted then return true, else false.
//
// Note that The read of bytes might end up getting only part of an encoded
// UTF-8 character.  But it's known how many bytes are expected from the
// leading byte.  Input_Char() can handle it by requesting the missing ones.
//
// Escape sequences could also *theoretically* be split, and they have no
// standard for telling how long the sequence could be.  (ESC '\0') could be a
// plain escape key--or it could be an unfinished read of a longer sequence.
// We assume this won't happen, because the escape sequences being entered
// usually happen one at a time (cursor up, cursor down).  Unlike text, these
// are not *likely* to be pasted in a batch that could overflow READ_BUF_LEN
// and be split up.
//
static bool Read_Bytes_Interrupted(STD_TERM *term, unsigned char *buf, int len)
{
    // If we have leftovers:
    //
    if (term->residue[0]) {
        int end = LEN_BYTES(term->residue);
        if (end < len)
            len = end;
        strncpy(s_cast(buf), s_cast(term->residue), len); // terminated below
        memmove(term->residue, term->residue + len, end - len); // remove
        term->residue[end - len] = '\0';
    }
    else {
        if ((len = read(0, buf, len)) < 0) {
            if (errno == EINTR)
                return true; // Ctrl-C or similar, see sigaction()/SIGINT

            WRITE_STR("\r\nI/O terminated\r\n");
            Quit_Terminal(term); // something went wrong
            exit(100);
        }
    }

    buf[len] = '\0';

    return false; // not interrupted, note we could return `len` if needed
}

//
//  Write_Char: C
//
// Write out repeated number of chars.
// Unicode: not used
//
static void Write_Char(unsigned char c, int n)
{
    unsigned char buf[4];

    buf[0] = c;
    for (; n > 0; n--)
        WRITE_CHAR(buf);
}

//
//  Store_Line: C
//
// Makes a copy of the current buffer and store it in the
// history list. Returns the copied string.
//
static void Store_Line(STD_TERM *term)
{
    term->buffer[term->end] = 0;
    term->out = cast(unsigned char*, malloc(sizeof(char) * (term->end + 1)));
    strcpy(s_cast(term->out), s_cast(term->buffer));

    // If max history, drop older lines (but not [0] empty line):
    if (Line_Count >= MAX_HISTORY) {
        free(Line_History[1]);
        memmove(
            Line_History + 1,
            Line_History + 2,
            (MAX_HISTORY - 2) * sizeof(char*)
        );
        Line_Count = MAX_HISTORY - 1;
    }

    Line_History[Line_Count] = term->out;
    ++Line_Count;
}

//
//  Recall_Line: C
//
// Set the current buffer to the contents of the history
// list at its current position. Clip at the ends.
// Return the history line index number.
// Unicode: ok
//
static void Recall_Line(STD_TERM *term)
{
    if (term->hist < 0) term->hist = 0;

    if (term->hist == 0)
        Write_Char(BEL, 1); // bell

    if (term->hist >= Line_Count) {
        // Special case: no "next" line:
        term->hist = Line_Count;
        term->buffer[0] = '\0';
        term->pos = term->end = 0;
    }
    else {
        // Fetch prior line:
        strcpy(s_cast(term->buffer), s_cast(Line_History[term->hist]));
        term->pos = term->end = LEN_BYTES(term->buffer);
    }
}

//
//  Clear_Line: C
//
// Clear all the chars from the current position to the end.
// Reset cursor to current position.
// Unicode: not used
//
static void Clear_Line(STD_TERM *term)
{
    Write_Char(' ', term->end - term->pos); // wipe prior line
    Write_Char(BS, term->end - term->pos); // return to position
}

//
//  Home_Line: C
//
// Reset cursor to home position.
// Unicode: ok
//
static void Home_Line(STD_TERM *term)
{
    while (term->pos > 0) {
        STEP_BACKWARD(term);
        Write_Char(BS, 1);
    }
}

//
//  End_Line: C
//
// Move cursor to end position.
// Unicode: not used
//
static void End_Line(STD_TERM *term)
{
    int len = term->end - term->pos;

    if (len > 0) {
        WRITE_CHARS(term->buffer+term->pos, len);
        term->pos = term->end;
    }
}

//
//  Strlen_UTF8: C
//
//  Count the character length (not byte length) of a UTF-8 string.
//  !!! Used to calculate the correct number of BS to us in Show_Line().
//      Would stepping through the UTF-8 string be better?
//
static int Strlen_UTF8(unsigned char *buffer, int byte_count)
{
    int char_count = 0;
    int i = 0;
        for(i = 0 ; i < byte_count ; i++)
            if (not Is_Continuation_Byte_If_Utf8(buffer[i]))
                char_count++;

        return char_count;
}

//
//  Show_Line: C
//
// Refresh a line from the current position to the end.
// Extra blanks can be specified to erase chars off end.
// If blanks is negative, stay at end of line.
// Reset the cursor back to current position.
// Unicode: ok
//
static void Show_Line(STD_TERM *term, int blanks)
{
    int len;

    // Clip bounds:
    if (term->pos < 0) term->pos = 0;
    else if (term->pos > term->end) term->pos = term->end;

    if (blanks >= 0) {
        len = term->end - term->pos;
        WRITE_CHARS(term->buffer+term->pos, len);
    }
    else {
        WRITE_CHARS(term->buffer, term->end);
        blanks = -blanks;
        len = 0;
    }

    Write_Char(' ', blanks);

    // return to original position or end
    Write_Char(BS,  blanks);
    Write_Char(BS,  Strlen_UTF8(term->buffer+term->pos, len));
}

//
//  Insert_Char_Null_If_Interrupted: C
//
// * Insert a char at the current position.
// * Adjust end position.
// * Redisplay the line.
//
static const unsigned char *Insert_Char_Null_If_Interrupted(
    STD_TERM *term,
    unsigned char *buf,
    int limit,
    const unsigned char *cp
){
    int encoded_len = 1 + trailingBytesForUTF8[*cp];

    if (term->end < TERM_BUF_LEN - encoded_len) { // avoid buffer overrun

        if (term->pos < term->end) { // open space for it:
            memmove(
                term->buffer + term->pos + encoded_len, // dest pointer
                term->buffer + term->pos, // source pointer
                encoded_len + term->end - term->pos // length
            );
        }

        int i;
        for (i = 0; i < encoded_len; ++i) {
            if (*cp == '\0') {
                //
                // Premature end, the UTF-8 data must have gotten split on
                // a buffer boundary.  Refill the buffer with another read,
                // where the remaining UTF-8 characters *should* be found.
                //
                if (Read_Bytes_Interrupted(term, buf, limit - 1))
                    return NULL; // signal interruption

                cp = buf;
            }

            WRITE_CHAR(cp);
            term->buffer[term->pos] = *cp;
            term->end++;
            term->pos++;
            ++cp;
        }

        Show_Line(term, 0);
    }

    return cp;
}

//
//  Delete_Char: C
//
// Delete a char at the current position. Adjust end position.
// Redisplay the line. Blank out extra char at end.
// Unicode: ok
//
static void Delete_Char(STD_TERM *term, bool back)
{
    if (term->pos == term->end and not back)
        return; // Ctrl-D at end of line

    if (term->pos == 0 and back)
        return; // backspace at beginning of line

    if (back)
        STEP_BACKWARD(term);

    int encoded_len = 1 + trailingBytesForUTF8[term->buffer[term->pos]];
    int len = encoded_len + term->end - term->pos;

    if (term->pos >= 0 && len > 0) {
        memmove(
            term->buffer + term->pos,
            term->buffer + term->pos + encoded_len,
            len
        );
        if (back)
            Write_Char(BS, 1);

        term->end -= encoded_len;
        Show_Line(term, 1);
    }
    else
        term->pos = 0;
}

//
//  Move_Cursor: C
//
// Move cursor right or left by one char.
// Unicode: not yet supported!
//
static void Move_Cursor(STD_TERM *term, int count)
{
    if (count < 0) {
        if (term->pos > 0) {
            STEP_BACKWARD(term);
            Write_Char(BS, 1);
        }
    }
    else {
        if (term->pos < term->end) {
            int encoded_len = CHAR_LEN(term->buffer[term->pos]);
            WRITE_CHARS(term->buffer + term->pos, encoded_len);
            term->pos += encoded_len;
        }
    }
}

// When an unrecognized key is hit, people may want to know that at least the
// keypress was received.  Or not.  For now just give a message in the debug
// build.
//
// !!! In the future, this might do something more interesting to get the
// BINARY! information for the key sequence back up out of the terminal, so
// that people could see what the key registered as on their machine and
// configure their console to respond to it.
//
inline static void Unrecognized_Key_Sequence(const unsigned char* cp)
{
    UNUSED(cp);

#if !defined(NDEBUG)
    WRITE_STR("[KEY?]");
#endif
}

extern int Read_Line(STD_TERM *term, unsigned char *result, int limit);

//
//  Read_Line: C
//
// Read a line (as a sequence of bytes) from the terminal.  Handles line
// editing and line history recall.
//
// !!! The line history is slated to be moved into userspace HOST-CONSOLE
// code, storing STRING!s in Rebol BLOCK!s.  Do not invest heavily in
// editing of that part of this code.
//
// Returns number of bytes in line.  If a plain ESC is pressed, then the
// result will be 0.  All successful results have at least a line feed, which
// will be returned as part of the data.
//
int Read_Line(STD_TERM *term, unsigned char *result, int limit)
{
    term->pos = 0;
    term->end = 0;
    term->hist = Line_Count;
    term->out = 0;
    term->buffer[0] = 0;

restart:;
    //
    // See notes on why Read_Bytes_Interrupted() can wind up splitting UTF-8
    // encodings (which can happen with pastes of text), and this is handled
    // by Insert_Char_Null_If_Interrupted().
    //
    // Also see notes there on why escape sequences are anticipated to come
    // in one at a time.  Hence unrecognized escape sequences jump up here to
    // `restart`.  Thus, hitting an unknown escape sequence and a character
    // very fast after it may discard that character.
    //
    unsigned char buf[READ_BUF_LEN]; // always '\0' terminated, hence `- 1`
    const unsigned char *cp = buf;

    if (Read_Bytes_Interrupted(term, buf, READ_BUF_LEN - 1))
        goto return_halt;

    while (*cp != '\0') {
        if (
            (*cp >= 32 && *cp < 127) // 32 is space, 127 is DEL(ete)
            || *cp > 127 // high-bit set UTF-8 start byte
        ){
            //
            // ASCII printable character or UTF-8
            //
            // https://en.wikipedia.org/wiki/ASCII
            // https://en.wikipedia.org/wiki/UTF-8
            //
            // Inserting a character may consume multiple bytes...and if the
            // buffer end was reached on a partial input of a UTF-8 character,
            // it may need to do its own read in order to get the missing
            // bytes and reset the buffer pointer.  So it can adjust cp even
            // backwards, if such a read is done.
            //
            cp = Insert_Char_Null_If_Interrupted(term, buf, READ_BUF_LEN, cp);
            if (cp == NULL)
                goto return_halt;

            continue;
        }

        if (*cp == ESC && cp[1] == '\0') {
            //
            // Plain Escape - Cancel Current Input (...not Halt Script)
            //
            // There are two distinct ways we want INPUT to be canceled.  One
            // is in a way that a script can detect, and continue running:
            //
            //    print "Enter filename (ESC to return to main menu):"
            //    if not filename: input [
            //       return 'go-to-main-menu
            //    ]
            //
            // The other kind of aborting would stop the script from running
            // further entirely...and either return to the REPL or exit the
            // Rebol process.  By near-universal convention in programming,
            // this is Ctrl-C (SIGINT - Signal Interrupt).  ESC seems like
            // a reasonable choice for the other.
            //
            // The way the notice of abort is wound up to the INPUT command
            // through the (deprecated) R3-Alpha "OS Host" is by a convention
            // that aborted lines will be an escape char and a terminator.
            //
            // The convention here seems to be that there's a terminator after
            // the length returned.
            //
            goto return_blank;

            // !!! See notes in the Windows Terminal usage of ReadConsole()
            // about how ESC cannot be overridden when using ENABLE_LINE_INPUT
            // to do anything other than clear the line.  Ctrl-D is used
            // there instead.
        }

        if (*cp == ESC && cp[1] == '[') {
            //
            // CSI Escape Sequences, VT100/VT220 Escape Sequences, etc:
            //
            // https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_sequences
            // http://ascii-table.com/ansi-escape-sequences-vt-100.php
            // http://aperiodic.net/phil/archives/Geekery/term-function-keys.html
            //
            // While these are similar in beginning with ESC and '[', the
            // actual codes vary.  HOME in CSI would be (ESC '[' '1' '~').
            // But to HOME in VT100, it can be as simple as (ESC '[' 'H'),
            // although there can be numbers between the '[' and 'H'.
            //
            // There's not much in the way of "rules" governing the format of
            // sequences, though official CSI codes always fit this pattern
            // with the following sequence:
            //
            //    the ESC then the '[' ("the CSI")
            //    one of `0-9:;<=>?` ("parameter byte")
            //    any number of `!"# $%&'()*+,-./` ("intermediate bytes")
            //    one of `@A-Z[\]^_`a-z{|}~` ("final byte")
            //
            // But some codes might look like CSI codes while not actually
            // fitting that rule.  e.g. the F8 function key on my machine
            // generates (ESC '[' '1' '9' '~'), which is a VT220 code
            // conflicting with the CSI interpretation of HOME above.
            //
            // Note: This kind of conflict confuses "linenoise", leading F8 to
            // jump to the beginning of line and display a tilde:
            //
            // https://github.com/antirez/linenoise

            cp += 2; // skip ESC and '['

            switch (*cp) {
              case 'A': // up arrow (VT100)
                term->hist -= 2;
                goto down_arrow;

              down_arrow:;
              case 'B': { // down arrow (VT100)
                int len = term->end;

                ++term->hist;

                Home_Line(term);
                Recall_Line(term);

                if (len <= term->end)
                    len = 0;
                else
                    len = term->end - len;

                Show_Line(term, len - 1); // len < 0 (stay at end)
                break; }

              case 'D': // left arrow (VT100)
                Move_Cursor(term, -1);
                break;

              case 'C': // right arrow (VT100)
                Move_Cursor(term, 1);
                break;

              case '1': // home (CSI) or higher function keys (VT220)
                if (cp[1] != '~') {
                    Unrecognized_Key_Sequence(cp - 2);
                    goto restart;
                }
                Home_Line(term);
                ++cp; // remove 1, the ~ is consumed after the switch
                break;

              case '4': // end (CSI)
                if (cp[1] != '~') {
                    Unrecognized_Key_Sequence(cp - 2);
                    goto restart;
                }
                End_Line(term);
                ++cp; // remove 4, the ~ is consumed after the switch
                break;

              case '3': // delete (CSI)
                if (cp[1] != '~') {
                    Unrecognized_Key_Sequence(cp - 2);
                    goto restart;
                }
                Delete_Char(term, false);
                ++cp; // remove 3, the ~ is consumed after the switch
                break;

              case 'H': // home (VT100)
                Home_Line(term);
                break;

              case 'F': // end !!! (in what standard?)
                End_Line(term);
                break;

              case 'J': // erase to end of screen (VT100)
                Clear_Line(term);
                break;

              default:
                Unrecognized_Key_Sequence(cp - 2);
                goto restart;
            }

            ++cp;
            continue;
        }

        if (*cp == ESC) {
            //
            // non-CSI Escape Sequences
            //
            // http://ascii-table.com/ansi-escape-sequences-vt-100.php

            ++cp;

            switch (*cp) {
              case 'H':   // !!! "home" (in what standard??)
              #if !defined(NDEBUG)
                rebJumps(
                    "FAIL {ESC H: please report your system info}",
                    rebEND
                );
              #endif
                Home_Line(term);
                break;

              case 'F':   // !!! "end" (in what standard??)
              #if !defined(NDEBUG)
                rebJumps(
                    "FAIL {ESC F: please report your system info}",
                    rebEND
                );
              #endif
                End_Line(term);
                break;

              case '\0':
                assert(false); // plain escape handled earlier for clarity
                goto unrecognized;

              unrecognized:;
              default:
                Unrecognized_Key_Sequence(cp - 1);
                goto restart;
            }

            ++cp;
            continue;
        }

        // C0 control codes and Bash-inspired Shortcuts
        //
        // https://en.wikipedia.org/wiki/C0_and_C1_control_codes
        // https://ss64.com/bash/syntax-keyboard.html
        //
        switch (*cp) {
          case BS: // backspace (C0)
          case DEL: // delete (C0)
            Delete_Char(term, true);
            break;

          case CR: // carriage return (C0)
            if (cp[1] == LF)
                ++cp; // disregard the CR character, else treat as LF
            goto line_feed;

          line_feed:;
          case LF: // line feed (C0)
            WRITE_STR("\r\n");
            Store_Line(term);
            ++cp;
            goto line_end_reached;

          case 1: // CTRL-A, Beginning of Line (bash)
            Home_Line(term);
            break;

          case 2: // CTRL-B, Backward One Character (bash)
            Move_Cursor(term, -1);
            break;

          case 3: // CTRL-C, Interrupt (ANSI, <signal.h> is standard C)
            //
            // It's theoretically possible to clear the termios `c_lflag` ISIG
            // in order to receive literal Ctrl-C, but we don't want to get
            // involved at that level.  Using sigaction() on SIGINT and
            // causing EINTR is how we would like to be triggering HALT.
            //
            rebJumps(
                "FAIL {Unexpected literal Ctrl-C in console}",
                rebEND
            );

          case 4: // CTRL-D, Synonym for Cancel Input (Windows Terminal Garbage)
            //
            // !!! In bash this is "Delete Character Under the Cursor".  But
            // the Windows Terminal forces our hands to not use Escape for
            // canceling input.  See notes regarding ReadConsole() along with
            // ENABLE_LINE_INPUT.
            //
            // If one is forced to choose only one thing, it makes more sense
            // to make this compatible with the Windows console so there's
            // one shortcut you can learn that works on both platforms.
            // Though ideally it would be configurable--and it could be, if
            // the Windows version had to manage the edit buffer with as
            // much manual code as this POSIX version does.
            //
          #if 0
            Delete_Char(term, false);
            break
          #else
            goto return_blank;
          #endif

          case 5: // CTRL-E, End of Line (bash)
            End_Line(term);
            break;

          case 6: // CTRL-F, Forward One Character (bash)
            Move_Cursor(term, 1);
            break;

          default:
            Unrecognized_Key_Sequence(cp);
            goto restart;
        }

        ++cp;
    }

    if (term->out == 0)
        goto restart;

return_blank:
    //
    // INPUT has a display invariant that the author of the code expected
    // a newline to be part of what the user contributed.  To keep the visual
    // flow in the case of a cancellation key that didn't have a newline, we
    // have to throw one in.
    //
    WRITE_STR("\r\n");
    result[0] = ESC;
    result[1] = '\0';
    return 1;

return_halt:
    WRITE_STR("\r\n"); // see note above on INPUT's display invariant
    result[0] = '\0';
    return 0;

line_end_reached:
    // Not at end of input? Save any unprocessed chars:
    if (*cp != '\0') {
        if (LEN_BYTES(term->residue) + LEN_BYTES(cp) >= TERM_BUF_LEN - 1) {
            //
            // avoid overrun
        }
        else
            strcat(s_cast(term->residue), cs_cast(cp));
    }

    // Fill the output buffer:
    int len = LEN_BYTES(term->out); // length of IO read
    if (len >= limit - 1)
        len = limit - 2;
    strncpy(s_cast(result), s_cast(term->out), limit);
    result[len++] = LF;
    result[len] = '\0';
    return len;
}


text:
// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com

/* DictionaryCounterDouble.cs -- simple dictionary to count values
 * Ars Magna project, http://arsmagna.ru
 * -------------------------------------------------------
 * Status: poor
 */

#region Using directives

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

using JetBrains.Annotations;

using Newtonsoft.Json;

#endregion

namespace AM.Collections
{
    /// <summary>
    /// Simple dictionary to count values.
    /// </summary>
    [PublicAPI]
    public sealed class DictionaryCounterDouble<TKey>
        : Dictionary<TKey, double>
    {
        #region Properties

        /// <summary>
        /// Gets the total.
        /// </summary>
        [JsonIgnore]
        public double Total
        {
            get
            {
                lock (SyncRoot)
                {
                    double result = 0.0;
                    foreach (double value in Values)
                    {
                        result += value;
                    }

                    return result;
                }
            }
        }

        #endregion

        #region Construction

        /// <summary>
        /// Initializes a new instance of the
        /// <see cref="DictionaryCounterDouble{TKey}"/> class.
        /// </summary>
        public DictionaryCounterDouble()
        {
        }

        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="comparer">The comparer.</param>
        public DictionaryCounterDouble
            (
                [NotNull] IEqualityComparer<TKey> comparer
            )
            : base(comparer)
        {
        }

        /// <summary>
        /// Initializes a new instance of the
        /// <see cref="DictionaryCounterDouble{TKey}"/> class.
        /// </summary>
        /// <param name="capacity">The capacity.</param>
        public DictionaryCounterDouble(int capacity)
            : base(capacity)
        {
        }

        /// <summary>
        /// Initializes a new instance of the
        /// <see cref="DictionaryCounterDouble{TKey}"/> class.
        /// </summary>
        /// <param name="dictionary">The dictionary.</param>
        public DictionaryCounterDouble
            (
                [NotNull] DictionaryCounterDouble<TKey> dictionary
            )
            : base(dictionary)
        {
        }

        #endregion

        #region Private members

        private object SyncRoot => ((ICollection)this).SyncRoot;

        #endregion

        #region Public methods

        /// <summary>
        /// Augments the specified key.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <param name="increment">The value.</param>
        /// <returns>New value for given key.</returns>
        public double Augment
            (
                [NotNull] TKey key,
                double increment
            )
        {
            lock (SyncRoot)
            {
                TryGetValue(key, out double result);
                result += increment;
                this[key] = result;

                return result;
            }
        }

        /// <summary>
        /// Get accumulated value for the specified key.
        /// </summary>
        public double GetValue
            (
                [NotNull] TKey key
            )
        {
            lock (SyncRoot)
            {
                TryGetValue(key, out double result);

                return result;
            }
        }

        /// <summary>
        /// Increment the specified key.
        /// </summary>
        public double Increment
            (
                [NotNull] TKey key
            )
        {
            return Augment(key, 1.0);
        }

        #endregion
    }
}


text:
g_ResourceRoot = getResourceRootElement(getThisResource())

addEvent("onRequestChecksumOfFile", true)
addEventHandler("onRequestChecksumOfFile", g_ResourceRoot,
	function(player, filename)
		local file = fileOpen(filename)
		local buffer = ""
		while not fileIsEOF(file) do
		    buffer = buffer..fileRead(file, 500)
		end
		fileClose(file)
		checksum = sha256(buffer)
		triggerClientEvent(player, "onClientRequestChecksumOfFile", g_ResourceRoot, checksum,filename)
	end
)

addEvent("onRequestDownload",true)
addEventHandler("onRequestDownload", g_ResourceRoot,
	function(player,filename)
		local file = fileOpen(filename)
		local buffer = ""
		while not fileIsEOF(file) do
		    buffer = buffer..fileRead(file, 500)
		end
		triggerLatentClientEvent(player,"onClientDownloaded", 1*10^8,g_ResourceRoot, buffer,filename) -- 0.1MB/s
	end
)


text:
<!DOCTYPE html>

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

    <title>Aleister Venosa - n montano</title>
    <meta name="description" content="Moptop had written a new Call of Cthulhu mission and Montano was very      excited. But just as they began to play, he and his character were sent to a bathr...">

    <link href='https://fonts.googleapis.com/css?family=Roboto+Mono|Roboto:300,400,900,400italic' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="/css/main.css">
    <link rel="canonical" href="http://erikradio.github.io/2011/08/Aleister-Venosa">
    <link rel="alternate" type="application/rss+xml" title="n montano" href="http://erikradio.github.io/feed.xml">

        *

Aleister Venosa

<time datetime="2011-08-01T00:00:00-05:00" itemprop="datePublished">Aug 1, 2011</time>

Moptop had written a new Call of Cthulhu mission and Montano was very
      excited. But just as they began to play, he and his character were sent to a bathroom where
      they were confronted by a large glowing head. The head lifted him and his character up and
      threw them into a shower where they were pulverized by excruciatingly painful electric
      rays.  He realized he was being killed off. "Sorry," said Moptop as he entered the
      room. "This mission just really didn't fit your character."

© erik radio 2016