text:
[![Gitter](https://badges.gitter.im/php-cache/cache.svg)](https://gitter.im/php-cache/cache?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)
[![Latest Stable Version](https://poser.pugx.org/cache/hierarchical-cache/v/stable)](https://packagist.org/packages/cache/hierarchical-cache)
[![Total Downloads](https://poser.pugx.org/cache/hierarchical-cache/downloads)](https://packagist.org/packages/cache/hierarchical-cache)
[![Monthly Downloads](https://poser.pugx.org/cache/hierarchical-cache/d/monthly.png)](https://packagist.org/packages/cache/hierarchical-cache)
[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](LICENSE)

This is an implementation for the PSR-6 for an hierarchical cache architecture.

If you have a cache key like `|users|:uid|followers|:fid|likes` where `:uid` and `:fid` are arbitrary integers. You
 may flush all followers by flushing `|users|:uid|followers`.

It is a part of the PHP Cache organisation. To read about features like tagging and hierarchy support please read
the shared documentation at [www.php-cache.com](http://www.php-cache.com).

### Install

```bash
composer require cache/hierarchical-cache
```

### Use

Read the [documentation on usage](http://www.php-cache.com/en/latest/hierarchy/).

### Implement

Read the [documentation on implementation](http://www.php-cache.com/en/latest/implementing-cache-pools/hierarchy/).

### Contribute

Contributions are very welcome! Send a pull request to the [main repository](https://github.com/php-cache/cache) or
report any issues you find on the [issue tracker](http://issues.php-cache.com).


text:
using System;
using System.Linq;
using Microsoft.Azure;
using Microsoft.WindowsAzure.Management.SiteRecovery.Models;

namespace Microsoft.WindowsAzure.Management.SiteRecovery.Models
{
    /// <summary>
    /// The response model for the recoveryplan object.
    /// </summary>
    public partial class RecoveryPlanResponse : AzureOperationResponse
    {
        private RecoveryPlan _recoveryPlan;

        /// <summary>
        /// Optional. The recoveryplan object for the given recoveryplan ID.
        /// </summary>
        public RecoveryPlan RecoveryPlan
        {
            get { return this._recoveryPlan; }
            set { this._recoveryPlan = value; }
        }

        /// <summary>
        /// Initializes a new instance of the RecoveryPlanResponse class.
        /// </summary>
        public RecoveryPlanResponse()
        {
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>PinkWink - Articles</title>
    <description>Robot, Data Science, AI, Engineer</description>
    <link>
    https://pinkwink.github.io/</link>

      <item>
        <title>Let's meet daVinci, a world-famous surgical robot, using ROS RViz.</title>

          <description>
The original copy of this post is on the PinkWink written in Korean.

</description>

        <pubDate>Tue, 07 Nov 2017 17:00:00 +0900</pubDate>
        <link>
        https://pinkwink.github.io//Lets_meet_daVinci_a_world-famous_surgical_robot_using_ROS_RViz</link>
        <guid isPermaLink="true">https://pinkwink.github.io//Lets_meet_daVinci_a_world-famous_surgical_robot_using_ROS_RViz</guid>
      </item>

      <item>
        <title>Two-Rotor System Controller Design using T-S Fuzzy Model</title>

          <description>
The original of this post is PinkWink. Some of the contents have been revised while moving the post written in Korean.

</description>

        <pubDate>Thu, 02 Nov 2017 17:00:00 +0900</pubDate>
        <link>
        https://pinkwink.github.io//two-rotor-system-controller-design-using-T-S-Fuzzy</link>
        <guid isPermaLink="true">https://pinkwink.github.io//two-rotor-system-controller-design-using-T-S-Fuzzy</guid>
      </item>

      <item>
        <title>The Purpose of Education</title>

          <description>
As I engage in the so-called "bull sessions" around and about the school, I too often find that most college men have a misconception of the purpose of education. Most of the "brethren" think that education should equip them with the proper instruments of exploitation so that they can forever trample over the masses. Still others think that education should furnish them with noble ends rather than means to an end.

</description>

        <pubDate>Sun, 12 Dec 1948 19:18:00 +0900</pubDate>
        <link>
        https://pinkwink.github.io//the-purpose-of-education</link>
        <guid isPermaLink="true">https://pinkwink.github.io//the-purpose-of-education</guid>
      </item>

  </channel>
</rss>


text:
exports.run = async (client, message, args, level) => { // eslint-disable-line no-unused-vars
	const msg = await message.channel.send('Ping?');
	msg.edit(`Pong! Latency is ${msg.createdTimestamp - message.createdTimestamp}ms. API Latency is ${Math.round(client.ping)}ms`);
};

exports.conf = {
	enabled: true,
	guildOnly: false,
	aliases: [],
	permLevel: 0
};

exports.help = {
	name: 'ping',
	category: 'Miscelaneous',
	description: 'For checking response time',
	usage: 'ping'
};


text:
package org.ow2.chameleon.rose.zookeeper.test;

import static org.apache.zookeeper.CreateMode.EPHEMERAL;
import static org.apache.zookeeper.CreateMode.PERSISTENT;
import static org.ops4j.pax.exam.CoreOptions.felix;
import static org.ops4j.pax.exam.CoreOptions.mavenBundle;
import static org.ops4j.pax.exam.CoreOptions.options;
import static org.ops4j.pax.exam.CoreOptions.provision;
import static org.ops4j.pax.exam.CoreOptions.systemProperty;
import static org.osgi.framework.Constants.OBJECTCLASS;
import static org.osgi.service.log.LogService.LOG_DEBUG;
import static org.osgi.service.log.LogService.LOG_WARNING;
import static org.osgi.service.remoteserviceadmin.RemoteConstants.ENDPOINT_ID;
import static org.osgi.service.remoteserviceadmin.RemoteConstants.SERVICE_IMPORTED_CONFIGS;
import static org.ow2.chameleon.rose.ImporterService.ENDPOINT_CONFIG_PREFIX;
import static org.ow2.chameleon.rose.zookeeper.ZookeeperManager.computePath;
import static org.junit.Assert.assertTrue;

import java.io.IOException;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import org.apache.felix.ipojo.Factory;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.ZooDefs.Ids;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.ops4j.pax.exam.CoreOptions;
import org.ops4j.pax.exam.Inject;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.OptionUtils;
import org.ops4j.pax.exam.junit.Configuration;
import org.ops4j.pax.exam.junit.JUnit4TestRunner;
import org.ops4j.pax.exam.junit.JUnitOptions;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
import org.osgi.service.remoteserviceadmin.EndpointDescription;
import org.osgi.service.remoteserviceadmin.ExportReference;
import org.ow2.chameleon.json.JSONService;
import org.ow2.chameleon.rose.ImporterService;
import org.ow2.chameleon.rose.RoseMachine;
import org.ow2.chameleon.testing.helpers.IPOJOHelper;
import org.ow2.chameleon.testing.helpers.OSGiHelper;

@RunWith(JUnit4TestRunner.class)
public class RegistryServerTest {
	private static final String PROP_JABSORB_URL = "org.jabsorb.url";
	protected static final String SERVLETNAME = "/JSONRPC";
	private static final String HTTP_PORT = "2170";
	private static final String ZOOKEEPER_HOST = "127.0.0.1";

	private RoseMachine rose;

	@Inject
	protected BundleContext context;

	protected OSGiHelper osgi;

	protected IPOJOHelper ipojo;

	private ZooKeeper keeper;

	private JSONService json;

	@Before
	public void setUp() {
		osgi = new OSGiHelper(context);
		ipojo = new IPOJOHelper(context);
		ipojo.createComponentInstance("RoSe_machine");
		Dictionary<String, String> props = new Hashtable<String, String>();
		props.put("connection", "127.0.0.1/rose");
		ipojo.createComponentInstance("RoSe_registry.zookeeper", props);
		rose = (RoseMachine) osgi.getServiceObject(RoseMachine.class.getName(), null);
		json = (JSONService) osgi.getServiceObject(JSONService.class.getName(),null);

	}

	@After
	public void tearDown() {
		osgi.dispose();
		ipojo.dispose();
	}

	/**
	 * Mockito bundles
	 */
	@Configuration
	public static Option[] mockitoBundle() {
		return options(JUnitOptions.mockitoBundles());
	}

	@Configuration
	public static Option[] configure() {
		Option[] platform = options(felix());

		Option[] bundles = options(provision(
				mavenBundle().groupId("org.apache.felix")
						.artifactId("org.apache.felix.ipojo")
						.versionAsInProject(),
				mavenBundle().groupId("org.ow2.chameleon.testing")
						.artifactId("osgi-helpers").versionAsInProject(),
				mavenBundle().groupId("org.osgi")
						.artifactId("org.osgi.compendium").versionAsInProject(),
				mavenBundle().groupId("org.slf4j").artifactId("slf4j-api")
						.versionAsInProject(),
				mavenBundle().groupId("org.slf4j").artifactId("slf4j-simple")
						.versionAsInProject(),
				mavenBundle().groupId("org.ow2.chameleon.rose")
						.artifactId("rose-core").versionAsInProject(),
				mavenBundle().groupId("org.ow2.chameleon.rose.registry")
						.artifactId("zookeeper-registry").versionAsInProject(),
				mavenBundle().groupId("org.jabsorb")
						.artifactId("org.ow2.chameleon.commons.jabsorb")
						.versionAsInProject(),
				mavenBundle().groupId("org.apache.felix")
						.artifactId("org.apache.felix.http.jetty")
						.versionAsInProject(),
				mavenBundle().groupId("org.apache.httpcomponents")
						.artifactId("httpcore-osgi").versionAsInProject(),
				mavenBundle().groupId("org.apache.httpcomponents")
						.artifactId("httpclient-osgi").versionAsInProject(),
				mavenBundle().groupId("commons-logging")
						.artifactId("org.ow2.chameleon.commons.logging")
						.versionAsInProject(),
				mavenBundle()
						.groupId("org.apache.cxf.dosgi")
						.artifactId(
								"cxf-dosgi-ri-discovery-distributed-zookeeper-wrapper")
						.versionAsInProject(),
				mavenBundle().groupId("org.apache.log4j")
						.artifactId("com.springsource.org.apache.log4j")
						.versionAsInProject(),
				mavenBundle().groupId("org.ow2.chameleon.json")
						.artifactId("json-service-json.org").versionAsInProject()

		));

		Option[] r = OptionUtils.combine(platform, bundles);

		return r;
	}

	protected <T> EndpointDescription createEndpoint(String endpointId,
			Class<T> klass) {

		Map<String, Object> props = new HashMap<String, Object>();
		props.put(PROP_JABSORB_URL, "http://localhost:" + HTTP_PORT
				+ SERVLETNAME);
		props.put(ENDPOINT_ID, endpointId);
		props.put(OBJECTCLASS, new String[] { klass.getName() });
		props.put(SERVICE_IMPORTED_CONFIGS, "jsonrpc");
		EndpointDescription desc = new EndpointDescription(props);
		return desc;
	}

	@Test
	public void test() throws InvalidSyntaxException, InterruptedException {
		connectToZookeeper();
		waitForIt(200);
		createNode("server1");
		EndpointDescription desc = createEndpoint("dummyEndpoint1",
				this.getClass());
		putToZookeeper("server1","endpoint1", desc);
		waitForIt(500);
		assertTrue((rose.containsRemote(desc)));
		waitForIt(200);
		clearZookeeper();
		waitForIt(200);
	}

	private void createNode(String node) {
		byte[] data = {0};
		try {
			keeper.create("/rose/"+node, data,ZooDefs.Ids.OPEN_ACL_UNSAFE, PERSISTENT);
			for (String b : keeper.getChildren("/rose", false)) {
				System.err.println(b);
			}
		} catch (KeeperException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

	}

	private void clearZookeeper() {
		try {
			for (String node : keeper.getChildren("/rose",null)) {
				for (String endpoint : keeper.getChildren("/rose/"+node, false)) {
					keeper.delete("/rose/"+node+"/"+endpoint, -1);
				}
				keeper.delete("/rose/"+node, -1);
			}
		} catch (KeeperException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

	}

	private void putToZookeeper(String node, String endpoint, EndpointDescription endpointDesc) {
		String desc = json.toJSON(endpointDesc.getProperties());
		try {
			keeper.create("/rose/"+node+"/"+endpoint, desc.getBytes(),
					ZooDefs.Ids.OPEN_ACL_UNSAFE, PERSISTENT);
		} catch (KeeperException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

	}

	private void connectToZookeeper() {
		try {
			keeper = new ZooKeeper(ZOOKEEPER_HOST, 40000, null);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

    public static void waitForIt(int time){
        try {
            Thread.sleep(time);
        } catch (InterruptedException e) {
            assert false;
        }
    }

}


text:
ErrorPageMiddlewareWebSite
===

This web site illustrates how to register error page middleware.


text:
using System;

namespace SharpDoc.Model
{
    /// <summary>
    /// An enum documentation.
    /// </summary>
    public class NEnum : NType
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="NEnum"/> class.
        /// </summary>
        public NEnum()
        {
            TypeName = "enum";
            Category = "Enumeration";
        }
    }
}


text:
package org.apache.druid.segment;

import com.google.common.collect.ImmutableList;
import org.apache.druid.collections.StupidPool;
import org.apache.druid.java.util.common.DateTimes;
import org.apache.druid.java.util.common.Intervals;
import org.apache.druid.java.util.common.granularity.Granularities;
import org.apache.druid.query.QueryPlus;
import org.apache.druid.query.QueryRunner;
import org.apache.druid.query.QueryRunnerTestHelper;
import org.apache.druid.query.Result;
import org.apache.druid.query.TableDataSource;
import org.apache.druid.query.aggregation.CountAggregatorFactory;
import org.apache.druid.query.dimension.DefaultDimensionSpec;
import org.apache.druid.query.spec.MultipleIntervalSegmentSpec;
import org.apache.druid.query.topn.DimensionAndMetricValueExtractor;
import org.apache.druid.query.topn.NumericTopNMetricSpec;
import org.apache.druid.query.topn.TopNQuery;
import org.apache.druid.query.topn.TopNQueryConfig;
import org.apache.druid.query.topn.TopNQueryQueryToolChest;
import org.apache.druid.query.topn.TopNQueryRunnerFactory;
import org.apache.druid.query.topn.TopNResultValue;
import org.apache.druid.segment.incremental.IncrementalIndex;
import org.apache.druid.timeline.SegmentId;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

public class MapVirtualColumnTopNTest
{
  @Rule
  public ExpectedException expectedException = ExpectedException.none();

  private QueryRunner<Result<TopNResultValue>> runner;

  @Before
  public void setup() throws IOException
  {
    final IncrementalIndex incrementalIndex = MapVirtualColumnTestBase.generateIndex();

    final TopNQueryRunnerFactory factory = new TopNQueryRunnerFactory(
        new StupidPool<>("map-virtual-column-test", () -> ByteBuffer.allocate(1024)),
        new TopNQueryQueryToolChest(
            new TopNQueryConfig(),
            QueryRunnerTestHelper.noopIntervalChunkingQueryRunnerDecorator()
        ),
        QueryRunnerTestHelper.NOOP_QUERYWATCHER
    );

    runner = QueryRunnerTestHelper.makeQueryRunner(
        factory,
        SegmentId.dummy("index1"),
        new IncrementalIndexSegment(incrementalIndex, SegmentId.dummy("index1")),
        "incremental"
    );
  }

  @Test
  public void testWithMapColumn()
  {
    final TopNQuery query = new TopNQuery(
        new TableDataSource(QueryRunnerTestHelper.dataSource),
        VirtualColumns.create(
            ImmutableList.of(
                new MapVirtualColumn("keys", "values", "params")
            )
        ),
        new DefaultDimensionSpec("params", "params"), // params is the map type
        new NumericTopNMetricSpec("count"),
        1,
        new MultipleIntervalSegmentSpec(ImmutableList.of(Intervals.of("2011/2012"))),
        null,
        Granularities.ALL,
        ImmutableList.of(new CountAggregatorFactory("count")),
        null,
        null
    );

    expectedException.expect(UnsupportedOperationException.class);
    expectedException.expectMessage("Map column doesn't support getRow()");
    runner.run(QueryPlus.wrap(query), new HashMap<>()).toList();
  }

  @Test
  public void testWithSubColumn()
  {
    final TopNQuery query = new TopNQuery(
        new TableDataSource(QueryRunnerTestHelper.dataSource),
        VirtualColumns.create(
            ImmutableList.of(
                new MapVirtualColumn("keys", "values", "params")
            )
        ),
        new DefaultDimensionSpec("params.key3", "params.key3"), // params.key3 is string
        new NumericTopNMetricSpec("count"),
        2,
        new MultipleIntervalSegmentSpec(ImmutableList.of(Intervals.of("2011/2012"))),
        null,
        Granularities.ALL,
        ImmutableList.of(new CountAggregatorFactory("count")),
        null,
        null
    );

    final List<Result<TopNResultValue>> result = runner.run(QueryPlus.wrap(query), new HashMap<>()).toList();
    final List<Result<TopNResultValue>> expected = Collections.singletonList(
        new Result<>(
            DateTimes.of("2011-01-12T00:00:00.000Z"),
            new TopNResultValue(
                ImmutableList.of(
                    new DimensionAndMetricValueExtractor(MapVirtualColumnTestBase.mapOf("count", 2L, "params.key3", null)),
                    new DimensionAndMetricValueExtractor(MapVirtualColumnTestBase.mapOf("count", 1L, "params.key3", "value3"))
                )
            )
        )
    );

    Assert.assertEquals(expected, result);
  }
}


text:
package uk.gov.hmrc.ct.ct600.v2.calculations

import org.scalatest.{Matchers, WordSpec}
import uk.gov.hmrc.ct.ct600._
import uk.gov.hmrc.ct.ct600.v2._

class Ct600FinalisationCalculatorSpec extends WordSpec with Matchers {

  "Ct600FinalisationCalculator - computeTaxPayable" should {

    "return taxPayable when incomeTaxDeductedFromGrossIncome > profitsChargeable" in new Ct600FinalisationCalculator {
      computeTaxPayable(b70 = B70(BigDecimal("1000")), b79 = B79(None),
        b84 = B84(1500)) shouldBe B86(BigDecimal(0))
    }

    "return taxPayable when incomeTaxDeductedFromGrossIncome = 0 and profitsChargeable = 0" in new Ct600FinalisationCalculator {
      computeTaxPayable(b70 = B70(BigDecimal("0")), b79 = B79(None),
        b84 = B84(0)) shouldBe B86(BigDecimal(0))
    }

    "return taxPayable when incomeTaxDeductedFromGrossIncome < profitsChargeable" in new Ct600FinalisationCalculator {
      computeTaxPayable(b70 = B70(BigDecimal("1000")), b79 = B79(None),
        b84 = B84(450)) shouldBe B86(BigDecimal(550))
    }

    "return taxPayable when incomeTaxDeductedFromGrossIncome < profitsChargeable, with decimal values" in new Ct600FinalisationCalculator {
      computeTaxPayable(b70 = B70(BigDecimal("1000.80")), b79 = B79(None),
        b84 = B84(BigDecimal("450.30"))) shouldBe B86(BigDecimal("550.50"))
    }

    "return taxPayable when (incomeTaxDeductedFromGrossIncome + taxPayableUnderS419) < profitsChargeable, with decimal values" in new Ct600FinalisationCalculator {
      computeTaxPayable(b70 = B70(BigDecimal("440.30")), b79 = B79(Option(BigDecimal("10.10"))),
        b84 = B84(BigDecimal("450.30"))) shouldBe B86(BigDecimal("0.10"))
    }
  }

  "Ct600FinalisationCalculator - computeTaxRepayable" should {

    "return taxRepayable when incomeTaxDeductedFromGrossIncome > profitsChargeable" in new Ct600FinalisationCalculator {
      computeTaxRepayable(b70 = B70(BigDecimal("1000")), b79 = B79(None),
        b84 = B84(1500)) shouldBe B85(BigDecimal(500))
    }

    "return taxRepayable when incomeTaxDeductedFromGrossIncome > profitsChargeable, with decimal values" in new Ct600FinalisationCalculator {
      computeTaxRepayable(b70 = B70(BigDecimal("1000.30")), b79 = B79(None),
        b84 = B84(BigDecimal("1500.80"))) shouldBe B85(BigDecimal("500.50"))
    }

    "return taxRepayable when incomeTaxDeductedFromGrossIncome = 0 and profitsChargeable = 0" in new Ct600FinalisationCalculator {
      computeTaxRepayable(b70 = B70(BigDecimal("0")), b79 = B79(None),
        b84 = B84(0)) shouldBe B85(BigDecimal(0))
    }

    "return taxRepayable when incomeTaxDeductedFromGrossIncome < profitsChargeable" in new Ct600FinalisationCalculator {
      computeTaxRepayable(b70 = B70(BigDecimal("1000")), b79 = B79(None),
        b84 = B84(450)) shouldBe B85(BigDecimal(0))
    }

    "return taxRepayable when (incomeTaxDeductedFromGrossIncome + taxPayableUnderS419) > profitsChargeable, with decimal values" in new Ct600FinalisationCalculator {
      computeTaxRepayable(b70 = B70(BigDecimal("1000.30")), b79 = B79(Option(BigDecimal("10.10"))),
        b84 = B84(BigDecimal("1500.80"))) shouldBe B85(BigDecimal("490.40"))
    }
  }
}


text:
<?php
namespace Google\Service\AdExchangeSeller\AdunitsCustomchannels;

/**
 * The "customchannels" collection of methods.
 * Typical usage is:
 *  <code>
 *   $adexchangesellerService = new Google_Service_AdExchangeSeller(...);
 *   $customchannels = $adexchangesellerService->customchannels;
 *  </code>
 */
class Resource extends \Google\Service\Resource
{

  /**
   * List all custom channels which the specified ad unit belongs to.
   * (customchannels.listAdunitsCustomchannels)
   *
   * @param string $adClientId
   * Ad client which contains the ad unit.
   * @param string $adUnitId
   * Ad unit for which to list custom channels.
   * @param array $optParams Optional parameters.
   *
   * @opt_param string pageToken
   * A continuation token, used to page through custom channels. To retrieve the next page, set this
    * parameter to the value of "nextPageToken" from the previous response.
   * @opt_param string maxResults
   * The maximum number of custom channels to include in the response, used for paging.
   * @return \Google\Service\AdExchangeSeller\CustomChannels
   */
  public function listAdunitsCustomchannels($adClientId, $adUnitId, $optParams = array())
  {
    $params = array('adClientId' => $adClientId, 'adUnitId' => $adUnitId);
    $params = array_merge($params, $optParams);
    return $this->call('list', array($params), "\Google\Service\AdExchangeSeller\CustomChannels");
  }
}


text:
A js slideshow where thumbnails slide like a diaphragm to make room for the main picture.

View demo: https://quinten.github.io/slidesurface/


text:
create table foo (a char(10), b varchar(10));
insert into foo values ('1234567890', '1234567890');

-- should give an error (constant expressions cannot be used as function index)
create index i_foo_trans_a_b on foo (translate(a, b, null));
drop index i_foo_trans_a_b on foo;

create index i_foo_trans_a_b on foo (translate(a, null, b));
drop index i_foo_trans_a_b on foo;

create index i_foo_trans_a_b on foo (translate(null, a, b));
drop index i_foo_trans_a_b on foo;

-- should work
create index i_foo_trans_a_b on foo (translate(a, a, b));
drop index i_foo_trans_a_b on foo;

-- should return null and give no error
select translate(a, b, null) from foo;
select translate(a, null, b) from foo;
select translate(null, a, b) from foo;

drop foo;

-- should give an error (constant expressions cannot be used as function index)
create table foo (a int);
create index idx on foo(5);
drop foo;


text:
package main

import (
	"strings"
)

const (
	// fileDepMkTemplate holds a template for file-based
	// dependency tracking make file.
	fileDepMkTemplate = `# generated by !!!DEPS_GEN_APP_NAME!!!

define _DEPS_GEN_GET_ALL_FILES_
!!!DEPS_GEN_FILES_GENERATOR!!!
endef

_DEPS_GEN_ALL_FILES_STORED_ := !!!DEPS_GEN_ALL_FILES_STORED!!!

_DEPS_GEN_SPACE_ :=
_DEPS_GEN_SPACE_ +=

_DEPS_GEN_F1_ := $(sort $(strip $(_DEPS_GEN_ALL_FILES_STORED_)))
_DEPS_GEN_F2_ := $(sort $(strip $(call _DEPS_GEN_GET_ALL_FILES_)))

ifeq ($(_DEPS_GEN_F1_),$(_DEPS_GEN_F2_))

!!!DEPS_GEN_TARGET!!!: $(_DEPS_GEN_ALL_FILES_STORED_)

else

# invalidate the target
!!!DEPS_GEN_TARGET!!!: _DEPS_GEN_INVALIDATE_
.PHONY: _DEPS_GEN_INVALIDATE_

endif

$(call undefine-namespaces,_DEPS_GEN)
`

	// kvStoredPrefix is used to prefix the variable name we want
	// to store (so actual variable checked at runtime is FOO and
	// its stored value from previous run is $(kvStoredPrefix)FOO.
	kvStoredPrefix = "_DEPS_GEN_STORED_"
	// kvDepMkTemplate holds a template for key-value-based
	// dependency tracking make file.
	kvDepMkTemplate = `# generated by !!!DEPS_GEN_APP_NAME!!!
_DEPS_GEN_VARIABLES_ := !!!DEPS_GEN_VARIABLES!!!
!!!DEPS_GEN_STORED_VALUES!!!
_DEPS_GEN_DO_INVALIDATE_ := no

$(foreach v,$(_DEPS_GEN_VARIABLES_), \
        $(if $(call equal,$($v),$(!!!DEPS_GEN_STORED_PREFIX!!!$v)), \
                , \
                $(eval _DEPS_GEN_DO_INVALIDATE_ := yes)))

ifeq ($(_DEPS_GEN_DO_INVALIDATE_),yes)

# invalidate the target
!!!DEPS_GEN_TARGET!!!: _DEPS_GEN_INVALIDATE_
.PHONY: _DEPS_GEN_INVALIDATE_

endif

$(call undefine-namespaces,_DEPS_GEN)
`
)

// GenerateFileDeps returns contents of make file describing
// dependencies of given target on given files and checking if files
// weren't added or removed in directories where given files are.
func GenerateFileDeps(target, filesGenerator string, files []string) string {
	return replacePlaceholders(fileDepMkTemplate,
		"DEPS_GEN_APP_NAME", appName(),
		"DEPS_GEN_FILES_GENERATOR", filesGenerator,
		"DEPS_GEN_ALL_FILES_STORED", strings.Join(files, " "),
		"DEPS_GEN_TARGET", target,
	)
}

func GenerateKvDeps(target string, keysValues map[string]string) string {
	variables := make([]string, 0, len(keysValues))
	storedValues := make([]string, 0, len(keysValues))
	for k, v := range keysValues {
		variables = append(variables, k)
		storedValues = append(storedValues, kvStoredPrefix+k+" := "+v)
	}

	return replacePlaceholders(kvDepMkTemplate,
		"DEPS_GEN_APP_NAME", appName(),
		"DEPS_GEN_VARIABLES", strings.Join(variables, " "),
		"DEPS_GEN_STORED_VALUES", strings.Join(storedValues, "\n"),
		"DEPS_GEN_STORED_PREFIX", kvStoredPrefix,
		"DEPS_GEN_TARGET", target,
	)
}


text:
{% extends "public_layout.html" %}

{% block header %}

About Facture

{% endblock %}
{% block content %}

Lo crem ipsum dolor

  Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tempore eligendi itaque accusamus officia nihil quae, omnis deleniti quas facere eius accusantium dolor fugit obcaecati explicabo tenetur deserunt tempora assumenda asperiores.

Lorem ipsum

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aspernatur, eum.

{% endblock %}


text:
package nl.nn.adapterframework.processors;

import nl.nn.adapterframework.core.SenderException;
import nl.nn.adapterframework.core.TimeOutException;
import nl.nn.adapterframework.parameters.ParameterResolutionContext;
import nl.nn.adapterframework.senders.SenderWrapperBase;

/**
 * Interface for handlers in SenderWrapper processor chain.
 *
 * @author  Gerrit van Brakel
 * @since   4.11
 * @version $Id$
 */
public interface SenderWrapperProcessor {

	public String sendMessage(SenderWrapperBase senderWrapperBase, String correlationID, String message, ParameterResolutionContext prc) throws SenderException, TimeOutException;

}


text:
A simple CLI for interacting with OS X reminders.

## Usage:

#### Show all lists

```
$ reminders show-lists
Soon
Eventually
```

#### Show reminders on a specific list

```
$ reminders show Soon
0 Write README
1 Ship reminders-cli
```

#### Complete an item on a list

```
$ reminders complete Soon 0
Completed 'Write README'
$ reminders show Soon
0 Ship reminders-cli
```

#### Add a reminder to a list

```
$ reminders add Soon Go to sleep
$ reminders show Soon
0 Ship reminders-cli
1 Go to sleep
```

## Installation:

#### With [Homebrew](http://brew.sh/)

```
$ brew install keith/formulae/reminders-cli
```

**NOTE** You must have Xcode 7.3.1 installed at
`/Applications/Xcode.app` for this to work correctly. If this isn't the
case you should build manually as described below.

#### Manually

Download the latest release from
[here](https://github.com/keith/reminders-cli/releases)

```
$ tar -zxvf reminders.tar.gz
$ mv reminders /usr/local/bin
$ rm reminders.tar.gz
```

#### Building manually

Install [swiftenv](https://github.com/kylef/swiftenv/)

```
$ cd reminders-cli
$ swiftenv install
$ swift build --configuration release
$ cp .build/release/reminders /usr/local/bin/reminders
```


text:
require 'optparse'

class QuerySummary
  def initialize(query)
    @calls = 1
	@averageQueryTime = query.query_time
	@averageLockTime = query.lock_time
	@averageRowsSent = query.rows_sent.to_f
	@averageRowsExamined = query.rows_examined.to_f
	@sql = query.sql
  end

  def calls
    return @calls
  end

  def rows_examined
    return @averageRowsExamined
  end

  def lock_time
    return @averageLockTime
  end

  def query_time
    return @averageQueryTime
  end

  def rows_sent
    return @averageRowsSent
  end

  def row_efficiency
    if @rowsExamined > 0
	  return @rowsSent.to_f / @rowsExamined.to_f
	end
	return 1.0
  end

  def sql
    return @sql
  end

  def adjust_average(xbar, n, x)
    return xbar + ((x - xbar) / n)
  end

  def add_query(query)
    @calls += 1
	@averageQueryTime = adjust_average(@averageQueryTime, @calls.to_f, query.query_time)
	@averageLockTime = adjust_average(@averageLockTime, @calls.to_f, query.lock_time)
	@averageRowsSent = adjust_average(@averageRowsSent, @calls.to_f, query.rows_sent.to_f)
	@averageRowsExamined = adjust_average(@averageRowsExamined, @calls.to_f, query.rows_examined.to_f)
  end

  def row_efficiency
    if @averageRowsExamined > 0.0
	  return @averageRowsSent / @averageRowsExamined
	end
	return 1.0
  end

  def is_valid (options)
    return @calls >= options[:minCalls] &&
	  @averageQueryTime >= options[:minQuery] &&
	  @averageLockTime >= options[:minLock] &&
	  @averageRowsSent >= options[:minRowsSent] &&
	  @averageRowsExamined >= options[:minRowsExamined] &&
	  row_efficiency <= options[:maxRowEfficiency]
  end
end

class Query
  def initialize(queryTime, lockTime, rowsSent, rowsExamined)
    @queryTime = queryTime.to_f
	@lockTime = lockTime.to_f
	@rowsSent = rowsSent.to_i
	@rowsExamined = rowsExamined.to_i
	@sql = nil
  end

  def rows_examined
    return @rowsExamined
  end

  def lock_time
    return @lockTime
  end

  def query_time
    return @queryTime
  end

  def rows_sent
    return @rowsSent
  end

  def row_efficiency
    if @rowsExamined > 0
	  return @rowsSent.to_f / @rowsExamined.to_f
	end
	return 1.0
  end

  def sql
    return @sql
  end

  def add_sql(line)
    if @sql != nil
	  @sql = @sql + '\n' + line
	else
      @sql = line
	end
  end

  def to_s
    return @sql
  end
end

def processFile (fileName, state)
  File.open(fileName, "r") do |file|
    file.each_line { |line| processLine(line, state) }
  end
end

def processLine (line, state)
  if line =~ /\#/
	if line =~ /\# Query_time:/
      # query start
	  matches = /\# Query_time\: (.+)  Lock_time\: (.+) Rows_sent\: (.+)  Rows_examined\: (.+)/.match(line)
	  state[:query] = Query.new(matches[1], matches[2], matches[3], matches[4]);
	else
	  query = state[:query]
	  if query != nil
	    summary = state[:summaries][query.sql.hash]
		if summary == nil
		  summary = QuerySummary.new(query)
		  state[:summaries][query.sql.hash] = summary
		else
		  summary.add_query(query)
		end
	  end
	  state[:query] = nil
	end
  elsif state[:query] != nil
    if line =~ /^SET timestamp/ || line =~ /^use/
	else
      # query sql
	  query = state[:query]
	  query.add_sql(line)
	end
  end
end

def sortSummaries(summaries, method)
  summaries.sort! {|x, y| x.send(method) <=> y.send(method) }
end

#===========================
# parse command line options
#===========================
options = {}
optparse = OptionParser.new do |opts|
  opts.banner = "Usage: sqa.rb [options] file1 file2 ..."

  # default options
  options[:count] = 10
  options[:minCalls] = 1
  options[:minQuery] = 0.0
  options[:minLock] = 0.0
  options[:minRowsSent] = 0.0
  options[:minRowsExamined] = 0.0
  options[:maxRowEfficiency] = 1.0
  options[:sort] = :calls
  options[:ascending] = false

  # count
  opts.on('--count NUMBER', Integer, 'Number of items to report.') do |n|
    options[:count] = n
  end

  # minimum calls
  opts.on('--min-calls NUMBER', Integer, 'Minimum number of calls.') do |n|
    options[:minCalls] = n
  end

  # minimum query time
  opts.on('--min-query SECONDS', Float, 'Minimum average query time in seconds; can be in fraction of seconds.') do |d|
    options[:minQuery] = d
  end

  # minimum lock time
  opts.on('--min-lock SECONDS', Float, 'Minimum average lock time in seconds; can be in fraction of seconds.') do |d|
    options[:minLock] = d
  end

  # minimum rows sent
  opts.on('--min-rows-sent NUMBER', Float, 'Minimum average number of rows returned.') do |d|
    options[:minRowsSent] = d
  end

  # minimum rows examined
  opts.on('--min-rows-examined NUMBER', Float, 'Minimum average number of rows examined.') do |d|
    options[:minRowsExamined] = d
  end

  # minimum lock time
  opts.on('--max-row-efficiency PERCENT', Float, 'Maxinum row efficiency as expressed as a percentage.') do |d|
    options[:maxRowEfficiency] = d / 100.0
  end

  # sort ascending
  opts.on('-a', '--sort-ascend TYPE', 'How the items in the report are sorted. TYPE is one of calls, query, lock, sent, examine, or eff') do |s|
    options[:ascending] = true
    options[:sort] = :calls if s == 'calls';
    options[:sort] = :query_time if s == 'query';
    options[:sort] = :lock_time if s == 'lock';
    options[:sort] = :rows_sent if s == 'sent';
    options[:sort] = :rows_examined if s == 'examine';
    options[:sort] = :row_efficiency if s == 'eff';
  end

  # sort descending
  opts.on('-d', '--sort-descend TYPE', 'How the items in the report are sorted. TYPE is one of calls, query, lock, sent, examine, or eff') do |s|
    options[:ascending] = false
    options[:sort] = :calls if s == 'calls';
    options[:sort] = :query_time if s == 'query';
    options[:sort] = :lock_time if s == 'lock';
    options[:sort] = :rows_sent if s == 'sent';
    options[:sort] = :rows_examined if s == 'examine';
    options[:sort] = :row_efficiency if s == 'eff';
  end

  # help
  opts.on( '-?', '--help', 'Display this screen' ) do
    puts opts
	exit
  end
end
optparse.parse!

#====================
# data initialization
#====================
state = {:query => nil, :summaries => {} }

#==============================================
# process files and accumulate query statistics
#==============================================
ARGV.each { |fileName| processFile(fileName, state) }

#=========================================
# select and sort results based on options
#=========================================
selectedSummaries = []
state[:summaries].each do |entry|
  summary = entry[1]
  selectedSummaries << summary if summary.is_valid(options)
end

sortSummaries(selectedSummaries, options[:sort])
if options[:ascending] == false
  selectedSummaries.reverse!
end

#===============
# output results
#===============
n = options[:count] - 1
puts "Calls  Query Time  Lock Time  Rows Sent  Rows Examined  Efficiency  SQL"
selectedSummaries[0..n].each_with_index do |summary, index|
  args = [summary.calls, summary.query_time, summary.lock_time, summary.rows_sent, summary.rows_examined, summary.row_efficiency * 100.0, index]
  puts "%5d  %10.3f  %9.3f  %9.2f  %13.2f  %10.1f  [%d] Below" % args
end

selectedSummaries[0..n].each_with_index do |summary, index|
  puts ""
  puts "[#{index}] SQL Statement:"
  puts summary.sql
end


text:
package org.apache.cassandra.tools;

import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.exceptions.ConfigurationException;

public final class Util
{
    private Util()
    {
    }

    /**
     * This is used by standalone tools to force static initialization of DatabaseDescriptor, and fail if configuration
     * is bad.
     */
    public static void initDatabaseDescriptor()
    {
        try
        {
            DatabaseDescriptor.toolInitialization();
        }
        catch (Throwable e)
        {
            boolean logStackTrace = !(e instanceof ConfigurationException) || ((ConfigurationException) e).logStackTrace;
            System.out.println("Exception (" + e.getClass().getName() + ") encountered during startup: " + e.getMessage());

            if (logStackTrace)
            {
                e.printStackTrace();
                System.exit(3);
            }
            else
            {
                System.err.println(e.getMessage());
                System.exit(3);
            }
        }
    }
}


text:
require 'whois/record/parser/base_icann_compliant'

module Whois
  class Record
    class Parser

      # Parser for the whois.donuts.com server.
      #
      # @see Whois::Record::Parser::Example
      #   The Example parser for the list of all available methods.
      #
      class WhoisDonutsCo < BaseIcannCompliant
        self.scanner = Scanners::BaseIcannCompliant, {
            pattern_available: /^Domain not found\.\n/
        }

        property_supported :domain_id do
          node('Domain ID')
        end

        property_supported :expires_on do
          node('Registry Expiry Date') do |value|
            Time.parse(value)
          end
        end

        property_supported :registrar do
          return unless node('Sponsoring Registrar')
          Record::Registrar.new(
              id:           node('Sponsoring Registrar IANA ID'),
              name:         node('Sponsoring Registrar'),
              organization: node('Sponsoring Registrar')
          )
        end

        private

        def build_contact(element, type)
          if (contact = super)
            contact.id = node("#{element} ID")
          end
          contact
        end

      end

    end
  end
end