text:
-- phpMyAdmin SQL Dump
-- version 3.4.10.1deb1
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Jun 08, 2013 at 12:23 AM
-- Server version: 5.5.31
-- PHP Version: 5.3.10-1ubuntu3.6

SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;

--
-- Database: `savalize`
--

-- --------------------------------------------------------

--
-- Table structure for table `admin_account`
--

CREATE TABLE IF NOT EXISTS `admin_account` (
  `id` int(3) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(30) NOT NULL,
  `username` varchar(20) NOT NULL,
  `email` varchar(30) NOT NULL,
  `password` varchar(20) NOT NULL,
  `is_deleted` binary(1) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

-- --------------------------------------------------------

--
-- Table structure for table `brand`
--

CREATE TABLE IF NOT EXISTS `brand` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(30) NOT NULL,
  `confirmed` binary(1) NOT NULL,
  `is_deleted` binary(1) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

-- --------------------------------------------------------

--
-- Table structure for table `category`
--

CREATE TABLE IF NOT EXISTS `category` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(30) NOT NULL,
  `confirmed` binary(1) NOT NULL DEFAULT '0',
  `is_deleted` binary(1) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

-- --------------------------------------------------------

--
-- Table structure for table `company`
--

CREATE TABLE IF NOT EXISTS `company` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(30) NOT NULL,
  `username` varchar(20) NOT NULL,
  `password` int(11) NOT NULL,
  `email` varchar(30) NOT NULL,
  `telphone` varchar(15) NOT NULL,
  `country` varchar(20) NOT NULL,
  `city` varchar(20) NOT NULL,
  `region` varchar(20) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

-- --------------------------------------------------------

--
-- Table structure for table `history`
--

CREATE TABLE IF NOT EXISTS `history` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `category_id` int(10) unsigned NOT NULL,
  `product_id` int(11) unsigned NOT NULL,
  `brand_id` int(11) unsigned NOT NULL,
  `company_id` int(10) unsigned NOT NULL,
  `price` int(10) unsigned NOT NULL,
  `user_id` int(11) unsigned NOT NULL,
  `date` date NOT NULL,
  PRIMARY KEY (`id`),
  KEY `category_id` (`category_id`),
  KEY `company_id` (`company_id`),
  KEY `user_id` (`user_id`),
  KEY `product_id` (`product_id`),
  KEY `brand_id` (`brand_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

-- --------------------------------------------------------

--
-- Table structure for table `product`
--

CREATE TABLE IF NOT EXISTS `product` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(30) NOT NULL,
  `category_id` int(10) unsigned NOT NULL,
  `confirmed` binary(1) NOT NULL DEFAULT '0',
  `is_deleted` binary(1) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `category_id` (`category_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

-- --------------------------------------------------------

--
-- Table structure for table `product_brand`
--

CREATE TABLE IF NOT EXISTS `product_brand` (
  `product_id` int(11) unsigned NOT NULL,
  `brand_id` int(11) unsigned NOT NULL,
  PRIMARY KEY (`product_id`,`brand_id`),
  KEY `product_id` (`product_id`),
  KEY `brand_id` (`brand_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

-- --------------------------------------------------------

--
-- Table structure for table `product_rating`
--

CREATE TABLE IF NOT EXISTS `product_rating` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) unsigned NOT NULL,
  `product_id` int(11) unsigned NOT NULL,
  `brand_id` int(10) unsigned NOT NULL,
  `rating` int(1) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `user_id` (`product_id`,`brand_id`),
  UNIQUE KEY `user_id_2` (`user_id`),
  KEY `brand_id` (`brand_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

-- --------------------------------------------------------

--
-- Table structure for table `user_account`
--

CREATE TABLE IF NOT EXISTS `user_account` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `fname` varchar(30) NOT NULL,
  `lname` varchar(30) NOT NULL,
  `username` varchar(20) NOT NULL,
  `password` varchar(30) NOT NULL,
  `email` varchar(40) NOT NULL,
  `country` varchar(30) NOT NULL,
  `city` varchar(30) NOT NULL,
  `region` varchar(30) NOT NULL,
  `age` int(5) unsigned NOT NULL,
  `martal_status` varchar(15) NOT NULL,
  `car` binary(1) NOT NULL DEFAULT '0',
  `salary` int(10) unsigned NOT NULL,
  `linked_to` int(11) unsigned NOT NULL,
  `created_at` date NOT NULL,
  `updated_at` date NOT NULL,
  PRIMARY KEY (`id`),
  KEY `linked_to` (`linked_to`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

-- --------------------------------------------------------

--
-- Table structure for table `user_notification`
--

CREATE TABLE IF NOT EXISTS `user_notification` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `content` text NOT NULL,
  `user_id` int(11) unsigned NOT NULL,
  PRIMARY KEY (`id`),
  KEY `user_id` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

--
-- Constraints for dumped tables
--

--
-- Constraints for table `history`
--
ALTER TABLE `history`
  ADD CONSTRAINT `history_ibfk_2` FOREIGN KEY (`category_id`) REFERENCES `category` (`id`),
  ADD CONSTRAINT `history_ibfk_3` FOREIGN KEY (`company_id`) REFERENCES `company` (`id`),
  ADD CONSTRAINT `history_ibfk_4` FOREIGN KEY (`user_id`) REFERENCES `user_account` (`id`),
  ADD CONSTRAINT `history_ibfk_5` FOREIGN KEY (`product_id`) REFERENCES `product` (`id`),
  ADD CONSTRAINT `history_ibfk_6` FOREIGN KEY (`brand_id`) REFERENCES `brand` (`id`);

--
-- Constraints for table `product`
--
ALTER TABLE `product`
  ADD CONSTRAINT `product_ibfk_1` FOREIGN KEY (`category_id`) REFERENCES `category` (`id`);

--
-- Constraints for table `product_brand`
--
ALTER TABLE `product_brand`
  ADD CONSTRAINT `product_brand_ibfk_2` FOREIGN KEY (`brand_id`) REFERENCES `brand` (`id`),
  ADD CONSTRAINT `product_brand_ibfk_3` FOREIGN KEY (`product_id`) REFERENCES `product` (`id`);

--
-- Constraints for table `product_rating`
--
ALTER TABLE `product_rating`
  ADD CONSTRAINT `product_rating_ibfk_1` FOREIGN KEY (`product_id`) REFERENCES `product` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  ADD CONSTRAINT `product_rating_ibfk_2` FOREIGN KEY (`brand_id`) REFERENCES `brand` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  ADD CONSTRAINT `product_rating_ibfk_3` FOREIGN KEY (`user_id`) REFERENCES `user_account` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;

--
-- Constraints for table `user_account`
--
ALTER TABLE `user_account`
  ADD CONSTRAINT `user_account_ibfk_1` FOREIGN KEY (`linked_to`) REFERENCES `user_account` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;

--
-- Constraints for table `user_notification`
--
ALTER TABLE `user_notification`
  ADD CONSTRAINT `user_notification_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `user_account` (`id`);

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;


text:
namespace Abacaxi.Graphs
{
    using JetBrains.Annotations;

    /// <summary>
    ///     Defines a 2-D coordinate to be used when manipulating matrices.
    /// </summary>
    [PublicAPI]
    public struct Cell
    {
        /// <summary>
        ///     Gets the X coordinate.
        /// </summary>
        /// <value>
        ///     The X coordinate.
        /// </value>
        public int X { get; }

        /// <summary>
        ///     Gets the Y coordinate.
        /// </summary>
        /// <value>
        ///     The Y coordinate.
        /// </value>
        public int Y { get; }

        /// <summary>
        ///     Initializes a new instance of the <see cref="Cell" /> struct.
        /// </summary>
        /// <param name="x">The X coordinate.</param>
        /// <param name="y">The Y coordinate.</param>
        public Cell(int x, int y)
        {
            X = x;
            Y = y;
        }

        /// <summary>
        ///     Determines whether the specified <see cref="object" />, is equal to this instance.
        /// </summary>
        /// <param name="obj">The <see cref="object" /> to compare with this instance.</param>
        /// <returns>
        ///     <c>true</c> if the specified <see cref="object" /> is equal to this instance; otherwise, <c>false</c>.
        /// </returns>
        public override bool Equals([CanBeNull] object obj)
        {
            if (obj == null ||
                obj.GetType() != GetType())
            {
                return false;
            }

            var co = (Cell) obj;
            return co.X == X && co.Y == Y;
        }

        /// <summary>
        ///     Returns a hash code for this instance.
        /// </summary>
        /// <returns>
        ///     A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
        /// </returns>
        public override int GetHashCode()
        {
            return X.GetHashCode() ^ Y.GetHashCode();
        }

        /// <summary>
        ///     Returns a <see cref="string" /> that represents this instance.
        /// </summary>
        /// <returns>
        ///     A <see cref="string" /> that represents this instance.
        /// </returns>
        public override string ToString()
        {
            return $"({X}, {Y})";
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.gazzax.labs.jena.nosql.cassandra;

import static org.gazzax.labs.jena.nosql.cassandra.Table.C_OPS;
import static org.gazzax.labs.jena.nosql.cassandra.Table.OC_PS;
import static org.gazzax.labs.jena.nosql.cassandra.Table.O_SPC;
import static org.gazzax.labs.jena.nosql.cassandra.Table.PO_SC;
import static org.gazzax.labs.jena.nosql.cassandra.Table.PO_SC_INDEX_P;
import static org.gazzax.labs.jena.nosql.cassandra.Table.SC_OP;
import static org.gazzax.labs.jena.nosql.cassandra.Table.SPC_O;
import static org.gazzax.labs.jena.nosql.cassandra.Table.SPC_O_INDEX_PC;
import static org.gazzax.labs.jena.nosql.cassandra.Table.S_POC;

import java.util.Map;

import org.gazzax.labs.jena.nosql.cassandra.dao.Cassandra2xBidirectionalMapDAO;
import org.gazzax.labs.jena.nosql.cassandra.dao.Cassandra2xMapDAO;
import org.gazzax.labs.jena.nosql.cassandra.dao.CassandraTripleIndexDAO;
import org.gazzax.labs.jena.nosql.fwk.InitialisationException;
import org.gazzax.labs.jena.nosql.fwk.configuration.Configuration;
import org.gazzax.labs.jena.nosql.fwk.dictionary.TopLevelDictionary;
import org.gazzax.labs.jena.nosql.fwk.dictionary.node.TransientNodeDictionary;
import org.gazzax.labs.jena.nosql.fwk.ds.GraphDAO;
import org.gazzax.labs.jena.nosql.fwk.ds.MapDAO;
import org.gazzax.labs.jena.nosql.fwk.factory.ClientShutdownHook;
import org.gazzax.labs.jena.nosql.fwk.factory.StorageLayerFactory;

import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.ConsistencyLevel;
import com.datastax.driver.core.HostDistance;
import com.datastax.driver.core.KeyspaceMetadata;
import com.datastax.driver.core.Metadata;
import com.datastax.driver.core.PoolingOptions;
import com.datastax.driver.core.ProtocolOptions.Compression;
import com.datastax.driver.core.QueryOptions;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.SocketOptions;
import com.datastax.driver.core.policies.LoadBalancingPolicy;
import com.datastax.driver.core.policies.Policies;
import com.datastax.driver.core.policies.ReconnectionPolicy;
import com.datastax.driver.core.policies.RetryPolicy;
import com.hp.hpl.jena.graph.Node;

/**
 * Concrete factory for creating Cassandra-backed domain and data access objects.
 *
 * @author Andrea Gazzarini
 * @since 1.0
 */
public class CassandraStorageLayerFactory extends StorageLayerFactory {

	private Session session;
	private Cluster cluster;
	private TopLevelDictionary dictionary;
	private int deletionBatchSize;

	@Override
	public <K, V> MapDAO<K, V> getMapDAO(
			final Class<K> keyClass,
			final Class<V> valueClass,
			final boolean isBidirectional,
			final String name) {

		final CoDec<K> k = CoDec.get(keyClass);
		final CoDec<V> v = CoDec.get(valueClass);

		return isBidirectional
				? new Cassandra2xBidirectionalMapDAO<K, V>(
						session,
						name,
						k,
						v)
				: new Cassandra2xMapDAO<K, V>(
						session,
						name,
						k,
						v);
	}

	@Override
	public GraphDAO<byte[][], byte[][]> getGraphDAO(final Node name) {
		return new CassandraTripleIndexDAO(session, deletionBatchSize);
	}

	@Override
	public GraphDAO<byte[][], byte[][]> getGraphDAO() {
		return new CassandraTripleIndexDAO(session, deletionBatchSize);
	}

	@Override
	public void accept(final Configuration<Map<String, Object>> configuration) {
		deletionBatchSize = configuration.getParameter("delete-batch-size", Integer.valueOf(1000));

		final String hosts = configuration.getParameter("cassandra-contact-points", "localhost");

		final Cluster.Builder builder = Cluster.builder()
				.addContactPoints(hosts.split(","))
				.withLoadBalancingPolicy(configureLoadBalancingPolicy(configuration))
				.withQueryOptions(configureQueryOptions(configuration))
				.withPoolingOptions(configurePoolingOptions(configuration))
				.withReconnectionPolicy(configureReconnectionPolicy(configuration))
				.withRetryPolicy(configureRetryPolicy(configuration))
				.withSocketOptions(configureSocketOptions(configuration));

		final Compression compression = configureCompression(configuration);

		if (compression != null) {
			builder.withCompression(compression);
		}

		final String keyspaceName = configuration.getParameter("keyspace-name", "C2XDB");
		final Boolean createSchema = configuration.getParameter("create-schema", Boolean.TRUE);

		cluster = builder.build();
		final Metadata metadata = cluster.getMetadata();
		final KeyspaceMetadata keyspaceMetadata = metadata.getKeyspace(keyspaceName);

		session = cluster.connect();

		if (keyspaceMetadata == null) {
			createKeyspace(keyspaceName, configuration);
			session.execute("USE " + keyspaceName);
			if (createSchema) {
				createSchema(configuration);
			}
		} else {
			session.execute("USE " + keyspaceName);
		}

		dictionary = new TransientNodeDictionary("TEST_DICTIONARY", new TransientNodeDictionary("NEVER_USED"), 1000000);
//				new CacheNodectionary(
//					"TopLevelCacheDictionary",
//					new KnownURIsDictionary(
//						"KnownURIsDictionary",
//						new ThreeTieredNodeDictionary(
//								"ThreeTieredDictionary",
//								new CacheStringDictionary(
//										"NamespacesCacheDictionary",
//										new PersistentStringDictionary("NamespacesDictionary", "DICT_NAMESPACES"),
//										configuration.getParameter("namespaces-id-cache-size", Integer.valueOf(1000)),
//										configuration.getParameter("namespaces-value-cache-size", Integer.valueOf(1000)),
//										false),
//								new TransientStringDictionary("LocalNamesDictionary"),
//								new CacheNodectionary(
//										"LiteralsAndBNodesCacheDictionary",
//										new TransientNodeDictionary(
//												"LiteralAndBNodesDictionary",
//												new PersistentNodeDictionary("LongLiteralsDictionary"),
//												configuration.getParameter("long-literals-threshold", Integer.valueOf(1000))),
//										configuration.getParameter("literals-bnodes-id-cache-size", Integer.valueOf(50000)),
//										configuration.getParameter("literals-bnodes-value-cache-size", Integer.valueOf(50000)),
//										true))),
//					configuration.getParameter("known-uris-id-cache-size", Integer.valueOf(2000)),
//					configuration.getParameter("known-uris-value-cache-size", Integer.valueOf(2000)),
//					true);
		try {
			dictionary.initialise(this);
		} catch (InitialisationException e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public TopLevelDictionary getDictionary() {
		return dictionary;
	}

	@Override
	public ClientShutdownHook getClientShutdownHook() {
		return new CassandraClientShutdownHook(session, dictionary);
	}

	@Override
	public String getInfo() {
		return "Jena-nosql Apache Cassandra binding";
	}

	/**
	 * Creates necessary schema.
	 *
	 * @param configuration the storage configuration.
	 */
	private void createSchema(final Configuration<Map<String, Object>> configuration) {
		final StringBuilder options = new StringBuilder()
				.append(" WITH compaction = {'class': '")
				.append(configuration.getParameter("compaction-strategy", "SizeTieredCompactionStrategy"))
				.append("'}")
				.append(" AND compression = {'sstable_compression' : '")
				.append(configuration.getParameter("compression-strategy", "LZ4Compressor"))
				.append("'}")
				.append(" AND caching = '")
				.append(configuration.getParameter("caching-strategy", "keys_only"))
				.append("'");

		session.execute("CREATE TABLE " + S_POC + "(s BLOB, p BLOB, o BLOB, c BLOB, PRIMARY KEY (s, p, o, c)) " + options);
		session.execute("CREATE TABLE " + O_SPC + "(o BLOB, s BLOB, p BLOB, c BLOB, PRIMARY KEY (o, s, p, c)) " + options);
		session.execute("CREATE TABLE " + PO_SC + "(p BLOB, o BLOB, s BLOB, c BLOB, p_index BLOB, PRIMARY KEY ((p, o), s, c)) " + options);
		session.execute("CREATE INDEX " + PO_SC_INDEX_P + " ON " + PO_SC + "(p_index)");

		session.execute("CREATE TABLE " + OC_PS + "(o BLOB, c BLOB, p BLOB, s BLOB, PRIMARY KEY ((o, c), p, s)) " + options);
		session.execute("CREATE TABLE " + C_OPS + "(c BLOB, o BLOB, p BLOB, s BLOB, PRIMARY KEY (c, o, p, s)) " + options);
		session.execute("CREATE TABLE " + SC_OP + "(s BLOB, c BLOB, o BLOB, p BLOB, PRIMARY KEY ((s, c), o, p)) " + options);

		session.execute("CREATE TABLE " + SPC_O + "(s BLOB, p BLOB, c BLOB, o BLOB, pc_index BLOB, PRIMARY KEY ((s, p, c), o)) " + options);
		session.execute("CREATE INDEX " + SPC_O_INDEX_PC + " ON " + SPC_O + "(pc_index)");
	}

	/**
	 * Creates a keyspace with the given name and configuration.
	 *
	 * @param name the keyspace name.
	 * @param configuration the configuration.
	 */
	void createKeyspace(final String name, final Configuration<Map<String, Object>> configuration) {
		session.execute(
				new StringBuilder()
					.append("CREATE KEYSPACE ")
					.append(name)
					.append(" WITH replication = {'class': '")
					.append(configuration.getParameter("replication-factor-strategy", "SimpleStrategy"))
					.append("', 'replication_factor': ")
					.append(configuration.getParameter("replication-factor", 1))
					.append("}")
					.toString());
	}

	/**
	 * Returns the compression options according with a given configuration.
	 *
	 * @param configuration the configuration.
	 * @return the compression options according with a given configuration.
	 */
	private Compression configureCompression(final Configuration<Map<String, Object>> configuration) {
		Compression compression = null;
		try {
			final String compressionOption = configuration.getParameter("transport-compression", null);
			if (compressionOption != null) {
				compression = Compression.valueOf(compressionOption);
			}
		} catch (final Exception e) {
			// Ignore and don't set the compression.
		}
		return compression;
	}

	/**
	 * Returns the load balancing policy according with a given configuration.
	 *
	 * @param configuration the configuration.
	 * @return the load balancing policy according with a given configuration.
	 */
	private LoadBalancingPolicy configureLoadBalancingPolicy(final Configuration<Map<String, Object>> configuration) {
		LoadBalancingPolicy lbPolicy = Policies.defaultLoadBalancingPolicy();
		try {
			final String lbPolicyClassName = configuration.getParameter("load-balancing-policy-class-name", null);
			if (lbPolicyClassName != null) {
				lbPolicy = (LoadBalancingPolicy) Class.forName(lbPolicyClassName).newInstance();
			}
		} catch (final Exception ignore) {
			// just use the default value.
		}
		return lbPolicy;
	}

	/**
	 * Creates the pooling options for this factory.
	 *
	 * @param configuration the configuration.
	 * @return the pooling options for this factory.
	 */
	private PoolingOptions configurePoolingOptions(final Configuration<Map<String, Object>> configuration) {
		final PoolingOptions poolingOptions = new PoolingOptions();

		Integer value = configuration.getParameter("local_core_connections_per_host", null);
		if (value != null) {
			poolingOptions.setCoreConnectionsPerHost(HostDistance.LOCAL, value);
		}

		value = configuration.getParameter("local_max_connections_per_host", null);
		if (value != null) {
			poolingOptions.setMaxConnectionsPerHost(HostDistance.LOCAL, value);
		}

		value = configuration.getParameter("local_max_simultaneous_request_per_connection_threshold", null);
		if (value != null) {
			poolingOptions.setMaxSimultaneousRequestsPerConnectionThreshold(HostDistance.LOCAL, value);
		}

		value = configuration.getParameter("local_min_simultaneous_request_per_connection_threshold", null);
		if (value != null) {
			poolingOptions.setMinSimultaneousRequestsPerConnectionThreshold(HostDistance.LOCAL, value);
		}

		value = configuration.getParameter("remote_core_connections_per_host", null);
		if (value != null) {
			poolingOptions.setCoreConnectionsPerHost(HostDistance.REMOTE, value);
		}

		value = configuration.getParameter("remote_max_connections_per_host", null);
		if (value != null) {
			poolingOptions.setMaxConnectionsPerHost(HostDistance.REMOTE, value);
		}

		value = configuration.getParameter("remote_max_simultaneous_request_per_connection_threshold", null);
		if (value != null) {
			poolingOptions.setMaxSimultaneousRequestsPerConnectionThreshold(HostDistance.REMOTE, value);
		}

		value = configuration.getParameter("remote_min_simultaneous_request_per_connection_threshold", null);
		if (value != null) {
			poolingOptions.setMinSimultaneousRequestsPerConnectionThreshold(HostDistance.REMOTE, value);
		}

		return poolingOptions;
	}

	/**
	 * Creates the query options for this factory.
	 *
	 * @param configuration the configuration.
	 * @return the query options for this factory.
	 */
	private QueryOptions configureQueryOptions(final Configuration<Map<String, Object>> configuration) {
		final QueryOptions queryOptions = new QueryOptions();

		queryOptions.setConsistencyLevel(
					ConsistencyLevel.valueOf(
							configuration.getParameter(
									"consistency_level",
									"ONE")));

		queryOptions.setSerialConsistencyLevel(
					ConsistencyLevel.valueOf(
							configuration.getParameter(
									"serial_consistency_level",
									"ONE")));

		queryOptions.setFetchSize(configuration.getParameter(
						"fetch_size",
						1000));

		return queryOptions;
	}

	/**
	 * Returns the reconnection balancing policy according with a given configuration.
	 *
	 * @param configuration the configuration.
	 * @return the reconnection balancing policy according with a given configuration.
	 */
	private ReconnectionPolicy configureReconnectionPolicy(final Configuration<Map<String, Object>> configuration) {
		ReconnectionPolicy reconnectionPolicy = Policies.defaultReconnectionPolicy();
		try {
			final String reconnectionPolicyClassName = configuration.getParameter("reconnection_policy", null);
			if (reconnectionPolicyClassName != null) {
				reconnectionPolicy = (ReconnectionPolicy) Class.forName(reconnectionPolicyClassName).newInstance();
			}
		} catch (final Exception ignore) {
			// ignore and just use the default value.
		}
		return reconnectionPolicy;
	}

	/**
	 * Returns the retry balancing policy according with a given configuration.
	 *
	 * @param configuration the configuration.
	 * @return the retry balancing policy according with a given configuration.
	 */
	private RetryPolicy configureRetryPolicy(final Configuration<Map<String, Object>> configuration) {
		RetryPolicy retryPolicy = Policies.defaultRetryPolicy();
		try {
			final String retryPolicyClassName = configuration.getParameter("retry_policy", null);
			if (retryPolicyClassName != null) {
				retryPolicy = (RetryPolicy) Class.forName(retryPolicyClassName).newInstance();
			}
		} catch (final Exception ignore) {
			// just use the default value.
		}
		return retryPolicy;
	}

	/**
	 * Creates the socket options for this factory.
	 *
	 * @param configuration the configuration.
	 * @return the socket options for this factory.
	 */
	private SocketOptions configureSocketOptions(final Configuration<Map<String, Object>> configuration) {
		final SocketOptions socketOptions = new SocketOptions();

		socketOptions.setConnectTimeoutMillis(
				configuration.getParameter(
						"connect_timeout_millis",
						SocketOptions.DEFAULT_CONNECT_TIMEOUT_MILLIS));

		socketOptions.setReadTimeoutMillis(
				configuration.getParameter(
						"read_timeout_millis",
						SocketOptions.DEFAULT_READ_TIMEOUT_MILLIS));

		final Boolean keepAlive = configuration.getParameter("keep_alive", null);
		if (keepAlive != null) {
			socketOptions.setKeepAlive(keepAlive);
		}

		final Integer soLinger = configuration.getParameter("so_linger", null);
		if (soLinger != null) {
			socketOptions.setSoLinger(soLinger);
		}

		final Integer receiveBufferSize = configuration.getParameter("receive_buffer_size", null);
		if (receiveBufferSize != null) {
			socketOptions.setReceiveBufferSize(receiveBufferSize);
		}

		final Boolean tcpNoDelay = configuration.getParameter("tcp_no_delay", null);
		if (tcpNoDelay != null) {
			socketOptions.setTcpNoDelay(tcpNoDelay);
		}

		final Boolean reuseAddress = configuration.getParameter("reuse_address", null);
		if (reuseAddress != null) {
			socketOptions.setReuseAddress(reuseAddress);
		}

		return socketOptions;
	}
}


text:
author: Jeff Van Campen
comments: true
date: 2014-08-21 06:58:26+00:00
layout: post
slug: festina-lente
title: Festina lente
wordpress_id: 1341
category: notes
tags:
- Bill Telepan
- diligence
- festina lente
- haste
- speed
- Stef Lewandowski
- urgency
---

I always say, 'Look, I'd rather you take an extra minute or two and slow up service to get it right.' Because the one minute behind you are now is going to become six minutes behind because we're going to have to redo the plate.

Bill Telepan explaining [one of the principles of mise-en-place](http://www.npr.org/blogs/thesalt/2014/08/11/338850091/for-a-more-ordered-life-organize-like-a-chef): speed up to slow down.

I read this a day or so before I read Stef Lewandowski's essay on [makefulness](https://medium.com/@stef/makefulness-737559ecb440), in which he discusses the Latin phrase _festina lente_:

There are many historical and cultural references to the flow state, yet many people seem to be unfamiliar with it. If we go back to Roman times, we have the concept of festina lente — which roughly translates as "make haste slowly", and gave rise to the idea of "slow is smooth, smooth is fast". The phrase has its roots in military strategy—by going slowly you make progress, whereas rushing ahead recklessly could result in casualties. It has adapted over time and many people now take it to mean that it is important to balance urgency and diligence, and that a state of flow is where that occurs on a personal level.

I like the idea of balancing urgency and diligence. Putting too much emphasis on urgency is almost always counterproductive. This is about prioritization: taking time to do the things the things that matter, rather thank trying to do everything in as little time as possible.


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using ColossalFramework.UI;
using UnityEngine;

namespace CommonShared.Utils
{
    /// <summary>
    /// Contains various utilities regarding atlases.
    /// </summary>
    public static class AtlasUtils
    {
        /// <summary>
        /// Creates a new <see cref="UITextureAtlas"/> from a PNG file.
        /// </summary>
        /// <param name="fileName">The PNG file name of the texture.</param>
        /// <param name="atlasName">The name of the <see cref="UITextureAtlas"/>.</param>
        /// <param name="shaderName">The name of the <see cref="Shader"/>.</param>
        /// <param name="spriteSize">The size of each sprite.</param>
        /// <param name="spriteGrid">The size of the sprite grid.</param>
        /// <param name="spriteNames">The names of the sprites.</param>
        /// <returns>The generated <see cref="UITextureAtlas"/>.</returns>
        public static UITextureAtlas CreateAtlas(string fileName, string atlasName, string shaderName, Vector2 spriteSize, Vector2 spriteGrid, string[][] spriteNames)
        {
            Shader shader = Shader.Find(shaderName);
            if (shader == null)
            {
                return null;
            }

            // Setup
            Texture2D texture = new Texture2D((int)(spriteSize.x * spriteGrid.x), (int)(spriteSize.y * spriteGrid.y), TextureFormat.ARGB32, false);
            byte[] textureBytes = File.ReadAllBytes(fileName);
            texture.LoadImage(textureBytes);
            FixTransparency(texture);

            Material material = new Material(shader);
            material.mainTexture = texture;

            UITextureAtlas atlas = ScriptableObject.CreateInstance<UITextureAtlas>();
            atlas.name = atlasName;
            atlas.material = material;

            // Sprites
            for (int y = 0; y < spriteGrid.y; y++)
            {
                for (int x = 0; x < spriteGrid.x; x++)
                {
                    if (y < spriteNames.Length && x < spriteNames[y].Length && !string.IsNullOrEmpty(spriteNames[y][x]))
                    {
                        Rect spriteRect = new Rect(
                            x * spriteSize.x / texture.width,
                            1 - ((y + 1) * spriteSize.y / texture.height),
                            spriteSize.x / texture.width,
                            spriteSize.y / texture.height
                        );

                        UITextureAtlas.SpriteInfo spriteInfo = new UITextureAtlas.SpriteInfo()
                        {
                            name = spriteNames[y][x],
                            texture = texture,
                            region = spriteRect
                        };
                        atlas.AddSprite(spriteInfo);
                    }
                }
            }

            return atlas;
        }

        /// <summary>
        /// Copy the values of adjacent pixels to transparent pixels color info, to remove the white border artifact when importing transparent .PNGs.
        /// </summary>
        /// <param name="texture">The texture.</param>
        /// <remarks>Source at http://answers.unity3d.com/questions/238922/png-transparency-has-white-borderhalo.html. </remarks>
        private static void FixTransparency(this Texture2D texture)
        {
            Color32[] pixels = texture.GetPixels32();
            int w = texture.width;
            int h = texture.height;

            for (int y = 0; y < h; y++)
            {
                for (int x = 0; x < w; x++)
                {
                    int idx = y * w + x;
                    Color32 pixel = pixels[idx];
                    if (pixel.a == 0)
                    {
                        bool done = false;
                        if (!done && x > 0) done = TryAdjacent(ref pixel, pixels[idx - 1]);        // Left pixel
                        if (!done && x < w - 1) done = TryAdjacent(ref pixel, pixels[idx + 1]);    // Right pixel
                        if (!done && y > 0) done = TryAdjacent(ref pixel, pixels[idx - w]);        // Top pixel
                        if (!done && y < h - 1) done = TryAdjacent(ref pixel, pixels[idx + w]);    // Bottom pixel
                        pixels[idx] = pixel;
                    }
                }
            }

            texture.SetPixels32(pixels);
            texture.Apply();
        }

        private static bool TryAdjacent(ref Color32 pixel, Color32 adjacent)
        {
            if (adjacent.a == 0) return false;

            pixel.r = adjacent.r;
            pixel.g = adjacent.g;
            pixel.b = adjacent.b;
            return true;
        }
    }
}


text:
    <form class="lockscreen animated flipInY" action="#/dashboard">

 SmartAdmin

John Doe   Locked

                    john.doe@smartadmin.com

                    <input class="form-control" type="password" placeholder="Password">

                        <button class="btn btn-primary" type="submit">

                        </button>

                    Logged as someone else?  Click here

            Copyright SmartAdmin 2014-2020.

    </form>


text:
typedef NS_ENUM(AUParameterAddress, AKCostelloReverbParameter) {
    AKCostelloReverbParameterFeedback,
    AKCostelloReverbParameterCutoffFrequency,
    AKCostelloReverbParameterRampDuration
};

#ifndef __cplusplus

AKDSPRef createCostelloReverbDSP(int channelCount, double sampleRate);

#else

#import "AKSoundpipeDSPBase.hpp"

class AKCostelloReverbDSP : public AKSoundpipeDSPBase {
private:
    struct InternalData;
    std::unique_ptr<InternalData> data;

public:
    AKCostelloReverbDSP();

    float feedbackLowerBound = 0.0;
    float feedbackUpperBound = 1.0;
    float cutoffFrequencyLowerBound = 12.0;
    float cutoffFrequencyUpperBound = 20000.0;

    float defaultFeedback = 0.6;
    float defaultCutoffFrequency = 4000.0;

    int defaultRampDurationSamples = 10000;

    // Uses the ParameterAddress as a key
    void setParameter(AUParameterAddress address, float value, bool immediate) override;

    // Uses the ParameterAddress as a key
    float getParameter(AUParameterAddress address) override;

    void init(int channelCount, double sampleRate) override;

    void deinit() override;

    void process(AUAudioFrameCount frameCount, AUAudioFrameCount bufferOffset) override;
};

#endif


text:
'use strict';

var assert = require('assert');
var yaml   = require('../../');

describe('Resolving explicit tags on empty nodes', function () {
  it('!!binary', function () {
    assert.throws(function () { yaml.load('!!binary'); }, yaml.YAMLException);
  });

  it('!!bool', function () {
    assert.throws(function () { yaml.load('!!bool'); }, yaml.YAMLException);
  });

  it('!!float', function () {
    assert.throws(function () { yaml.load('!!float'); }, yaml.YAMLException);
  });

  it('!!int', function () {
    assert.throws(function () { yaml.load('!!int'); }, yaml.YAMLException);
  });

  it('!!map', function () {
    assert.deepStrictEqual(yaml.load('!!map'), {});
  });

  it('!!merge', function () {
    assert.doesNotThrow(function () { yaml.load('? !!merge\n: []'); });
  });

  it('!!null', function () {
    // Fetch null from an array to reduce chance that null is returned because of another bug
    assert.strictEqual(yaml.load('- !!null')[0], null);
  });

  it('!!omap', function () {
    assert.deepStrictEqual(yaml.load('!!omap'), []);
  });

  it('!!pairs', function () {
    assert.deepStrictEqual(yaml.load('!!pairs'), []);
  });

  it('!!seq', function () {
    assert.deepStrictEqual(yaml.load('!!seq'), []);
  });

  it('!!set', function () {
    assert.deepStrictEqual(yaml.load('!!set'), {});
  });

  it('!!str', function () {
    assert.strictEqual(yaml.load('!!str'), '');
  });

  it('!!timestamp', function () {
    assert.throws(function () { yaml.load('!!timestamp'); }, yaml.YAMLException);
  });
});


text:
#include <ztest.h>
#include "lifo_usage.h"
#include <kernel.h>

#define STACK_SIZE (1024 + CONFIG_TEST_EXTRA_STACKSIZE)
#define LIST_LEN 2

struct k_lifo lifo, plifo;
static ldata_t data[LIST_LEN];
struct k_lifo timeout_order_lifo;

static struct k_thread tdata, tdata1;
static K_THREAD_STACK_DEFINE(tstack, STACK_SIZE);
static K_THREAD_STACK_DEFINE(tstack1, STACK_SIZE);

static struct k_sem start_sema, wait_sema;
void test_thread_pend_and_timeout(void *p1, void *p2, void *p3);

struct scratch_lifo_packet {
	void *link_in_lifo;
	void *data_if_needed;
};

struct reply_packet {
	void *link_in_lifo;
	int32_t reply;
};

struct timeout_order_data {
	void *link_in_lifo;
	struct k_lifo *klifo;
	k_ticks_t timeout;
	int32_t timeout_order;
	int32_t q_order;
};

static struct k_lifo lifo_timeout[2];

struct timeout_order_data timeout_order_data[] = {
	{0, &lifo_timeout[0], 20, 2, 0},
	{0, &lifo_timeout[0], 40, 4, 1},
	{0, &lifo_timeout[0], 0, 0, 2},
	{0, &lifo_timeout[0], 10, 1, 3},
	{0, &lifo_timeout[0], 30, 3, 4},
};

struct timeout_order_data timeout_order_data_mult_lifo[] = {
	{0, &lifo_timeout[1], 0, 0, 0},
	{0, &lifo_timeout[0], 30, 3, 1},
	{0, &lifo_timeout[0], 50, 5, 2},
	{0, &lifo_timeout[1], 80, 8, 3},
	{0, &lifo_timeout[1], 70, 7, 4},
	{0, &lifo_timeout[0], 10, 1, 5},
	{0, &lifo_timeout[0], 60, 6, 6},
	{0, &lifo_timeout[0], 20, 2, 7},
	{0, &lifo_timeout[1], 40, 4, 8},
};

#define NUM_SCRATCH_LIFO_PACKETS 20
#define TIMEOUT_ORDER_NUM_THREADS	ARRAY_SIZE(timeout_order_data_mult_lifo)
#define TSTACK_SIZE			(1024 + CONFIG_TEST_EXTRA_STACKSIZE)
#define LIFO_THREAD_PRIO		-5

struct scratch_lifo_packet scratch_lifo_packets[NUM_SCRATCH_LIFO_PACKETS];

struct k_lifo scratch_lifo_packets_lifo;

static k_tid_t tid[TIMEOUT_ORDER_NUM_THREADS];
static K_THREAD_STACK_ARRAY_DEFINE(ttstack,
		TIMEOUT_ORDER_NUM_THREADS, TSTACK_SIZE);
static struct k_thread ttdata[TIMEOUT_ORDER_NUM_THREADS];

static void *get_scratch_packet(void)
{
	void *packet = k_lifo_get(&scratch_lifo_packets_lifo, K_NO_WAIT);

	zassert_true(packet != NULL, NULL);
	return packet;
}

static void put_scratch_packet(void *packet)
{
	k_lifo_put(&scratch_lifo_packets_lifo, packet);
}

static void thread_entry_nowait(void *p1, void *p2, void *p3)
{
	void *ret;

	ret = k_lifo_get((struct k_lifo *)p1, K_FOREVER);

	/* data pushed at last should be read first */
	zassert_equal(ret, (void *)&data[1], NULL);

	ret = k_lifo_get((struct k_lifo *)p1, K_FOREVER);

	zassert_equal(ret, (void *)&data[0], NULL);

	k_sem_give(&start_sema);
}

static bool is_timeout_in_range(uint32_t start_time, uint32_t timeout)
{
	uint32_t stop_time, diff;

	stop_time = k_cycle_get_32();
	diff = (uint32_t)k_cyc_to_ns_floor64(stop_time -
					start_time) / NSEC_PER_USEC;
	diff = diff / USEC_PER_MSEC;
	return timeout <= diff;
}

static int test_multiple_threads_pending(struct timeout_order_data *test_data,
					 int test_data_size)
{
	int ii;

	for (ii = 0; ii < test_data_size; ii++) {
		tid[ii] = k_thread_create(&ttdata[ii], ttstack[ii], TSTACK_SIZE,
				test_thread_pend_and_timeout,
				&test_data[ii], NULL, NULL,
				LIFO_THREAD_PRIO, K_INHERIT_PERMS, K_NO_WAIT);
	}

	for (ii = 0; ii < test_data_size; ii++) {
		struct timeout_order_data *data =
			k_lifo_get(&timeout_order_lifo, K_FOREVER);

		if (data->timeout_order == ii) {
			TC_PRINT(" thread (q order: %d, t/o: %d, lifo %p)\n",
				 data->q_order, (int) data->timeout,
				 data->klifo);
		} else {
			zassert_equal(data->timeout_order, ii, " *** thread %d "
				      "woke up, expected %d\n",
				      data->timeout_order, ii);
			return TC_FAIL;
		}
	}

	return TC_PASS;
}

static void thread_entry_wait(void *p1, void *p2, void *p3)
{
	k_lifo_put((struct k_lifo *)p1, (void *)&data[0]);

	k_lifo_put((struct k_lifo *)p1, (void *)&data[1]);
	k_sem_give(&wait_sema);
}

/**
 * @addtogroup kernel_lifo_tests
 * @{
 */

/**
 * @brief try getting data on lifo with special timeout value,
 * return result in lifo
 *
 *
 * @see k_lifo_put()
 */
static void test_thread_timeout_reply_values(void *p1, void *p2, void *p3)
{
	struct reply_packet *reply_packet = (struct reply_packet *)p1;

	reply_packet->reply =
		!!k_lifo_get(&lifo_timeout[0], K_NO_WAIT);

	k_lifo_put(&timeout_order_lifo, reply_packet);
}

/**
 * @see k_lifo_put()
 */
static void test_thread_timeout_reply_values_wfe(void *p1, void *p2, void *p3)
{
	struct reply_packet *reply_packet = (struct reply_packet *)p1;

	reply_packet->reply =
		!!k_lifo_get(&lifo_timeout[0], K_FOREVER);

	k_lifo_put(&timeout_order_lifo, reply_packet);
}

/**
 * @brief A thread sleeps then puts data on the lifo
 *
 * @see k_lifo_put()
 */
static void test_thread_put_timeout(void *p1, void *p2, void *p3)
{
	uint32_t timeout = *((uint32_t *)p2);

	k_msleep(timeout);
	k_lifo_put((struct k_lifo *)p1, get_scratch_packet());
}

/**
 * @brief Test last in, first out queue using LIFO
 * @see k_sem_init(), k_lifo_put(), k_lifo_get()
 */
static void test_lifo_nowait(void)
{
	k_lifo_init(&lifo);

	k_sem_init(&start_sema, 0, 1);

	/* put some data on lifo */
	k_lifo_put(&lifo, (void *)&data[0]);

	k_tid_t tid = k_thread_create(&tdata, tstack, STACK_SIZE,
				      thread_entry_nowait, &lifo, NULL, NULL,
				      K_PRIO_PREEMPT(0), 0, K_NO_WAIT);

	k_lifo_put(&lifo, (void *)&data[1]);

	/* Allow another thread to read lifo */
	k_sem_take(&start_sema, K_FOREVER);
	k_thread_abort(tid);
}

/**
 * @brief Test pending reader in LIFO
 * @see k_lifo_init(), k_lifo_get(), k_lifo_put()
 */
static void test_lifo_wait(void)
{
	int *ret;

	k_lifo_init(&plifo);
	k_sem_init(&wait_sema, 0, 1);

	k_tid_t tid = k_thread_create(&tdata1, tstack1, STACK_SIZE,
				      thread_entry_wait, &plifo, NULL, NULL,
				      K_PRIO_PREEMPT(0), 0, K_NO_WAIT);

	ret = k_lifo_get(&plifo, K_FOREVER);

	zassert_equal(ret, (void *)&data[0], NULL);

	k_sem_take(&wait_sema, K_FOREVER);

	ret = k_lifo_get(&plifo, K_FOREVER);

	zassert_equal(ret, (void *)&data[1], NULL);

	k_thread_abort(tid);
}

/**
 * @brief Test reading empty LIFO
 * @see k_lifo_get()
 */
static void test_timeout_empty_lifo(void)
{
	void *packet;

	uint32_t start_time, timeout;

	timeout = 10U;

	start_time = k_cycle_get_32();

	packet = k_lifo_get(&lifo_timeout[0], K_MSEC(timeout));

	zassert_equal(packet, NULL, NULL);

	zassert_true(is_timeout_in_range(start_time, timeout), NULL);

	/* Test empty lifo with timeout of K_NO_WAIT */
	packet = k_lifo_get(&lifo_timeout[0], K_NO_WAIT);
	zassert_equal(packet, NULL, NULL);
}

/**
 * @brief Test read and write operation in LIFO with timeout
 * @see k_lifo_put(), k_lifo_get()
 */
static void test_timeout_non_empty_lifo(void)
{
	void *packet, *scratch_packet;

	/* Test k_lifo_get with K_NO_WAIT */
	scratch_packet = get_scratch_packet();
	k_lifo_put(&lifo_timeout[0], scratch_packet);
	packet = k_lifo_get(&lifo_timeout[0], K_NO_WAIT);
	zassert_true(packet != NULL, NULL);
	put_scratch_packet(scratch_packet);

	 /* Test k_lifo_get with K_FOREVER */
	scratch_packet = get_scratch_packet();
	k_lifo_put(&lifo_timeout[0], scratch_packet);
	packet = k_lifo_get(&lifo_timeout[0], K_FOREVER);
	zassert_true(packet != NULL, NULL);
}

/**
 * @brief Test LIFO with timeout
 * @see k_lifo_put(), k_lifo_get()
 */
static void test_timeout_lifo_thread(void)
{
	void *packet, *scratch_packet;
	static volatile struct reply_packet reply_packet;
	uint32_t start_time, timeout;

	/*
	 * Test lifo with some timeout and child thread that puts
	 * data on the lifo on time
	 */
	timeout = 10U;
	start_time = k_cycle_get_32();

	tid[0] = k_thread_create(&ttdata[0], ttstack[0], TSTACK_SIZE,
				test_thread_put_timeout, &lifo_timeout[0],
				&timeout, NULL,
				LIFO_THREAD_PRIO, K_INHERIT_PERMS, K_NO_WAIT);

	packet = k_lifo_get(&lifo_timeout[0], K_MSEC(timeout + 10));
	zassert_true(packet != NULL, NULL);
	zassert_true(is_timeout_in_range(start_time, timeout), NULL);
	put_scratch_packet(packet);

	/*
	 * Test k_lifo_get with timeout of K_NO_WAIT and the lifo
	 * should be filled be filled by the child thread based on
	 * the data availability on another lifo. In this test child
	 * thread does not find data on lifo.
	 */
	tid[0] = k_thread_create(&ttdata[0], ttstack[0], TSTACK_SIZE,
				test_thread_timeout_reply_values,
				 (void *)&reply_packet, NULL, NULL,
				LIFO_THREAD_PRIO, K_INHERIT_PERMS, K_NO_WAIT);

	k_yield();
	packet = k_lifo_get(&timeout_order_lifo, K_NO_WAIT);
	zassert_true(packet != NULL, NULL);
	zassert_false(reply_packet.reply, NULL);

	/*
	 * Test k_lifo_get with timeout of K_NO_WAIT and the lifo
	 * should be filled be filled by the child thread based on
	 * the data availability on another lifo. In this test child
	 * thread does find data on lifo.
	 */
	scratch_packet = get_scratch_packet();
	k_lifo_put(&lifo_timeout[0], scratch_packet);

	tid[0] = k_thread_create(&ttdata[0], ttstack[0], TSTACK_SIZE,
				test_thread_timeout_reply_values,
				(void *)&reply_packet, NULL, NULL,
				LIFO_THREAD_PRIO, K_INHERIT_PERMS, K_NO_WAIT);

	k_yield();
	packet = k_lifo_get(&timeout_order_lifo, K_NO_WAIT);
	zassert_true(packet != NULL, NULL);
	zassert_true(reply_packet.reply, NULL);
	put_scratch_packet(scratch_packet);

	/*
	 * Test k_lifo_get with timeout of K_FOREVER and the lifo
	 * should be filled be filled by the child thread based on
	 * the data availability on another lifo. In this test child
	 * thread does find data on lifo.
	 */
	scratch_packet = get_scratch_packet();
	k_lifo_put(&lifo_timeout[0], scratch_packet);

	tid[0] = k_thread_create(&ttdata[0], ttstack[0], TSTACK_SIZE,
				test_thread_timeout_reply_values_wfe,
				(void *)&reply_packet, NULL, NULL,
				LIFO_THREAD_PRIO, K_INHERIT_PERMS, K_NO_WAIT);

	packet = k_lifo_get(&timeout_order_lifo, K_FOREVER);
	zassert_true(packet != NULL, NULL);
	zassert_true(reply_packet.reply, NULL);
	put_scratch_packet(scratch_packet);
}

/**
 * @brief a thread pends on a lifo then times out
 * @see k_lifo_put(), k_lifo_get()
 */
void test_thread_pend_and_timeout(void *p1, void *p2, void *p3)
{
	struct timeout_order_data *d = (struct timeout_order_data *)p1;
	uint32_t start_time;
	void *packet;

	start_time = k_cycle_get_32();
	packet = k_lifo_get(d->klifo, K_MSEC(d->timeout));
	zassert_true(packet == NULL, NULL);
	zassert_true(is_timeout_in_range(start_time, d->timeout), NULL);

	k_lifo_put(&timeout_order_lifo, d);
}

/**
 * @brief Test multiple pending readers in LIFO
 * @details test multiple threads pending on the same lifo
 * with different timeouts
 * @see k_lifo_get()
 */
static void test_timeout_threads_pend_on_lifo(void)
{
	int32_t rv, test_data_size;

	/*
	 * Test multiple threads pending on the same
	 * lifo with different timeouts
	 */
	test_data_size = ARRAY_SIZE(timeout_order_data);
	rv = test_multiple_threads_pending(timeout_order_data, test_data_size);
	zassert_equal(rv, TC_PASS, NULL);
}

/**
 * @brief Test LIFO initialization with various parameters
 * @see k_lifo_init(), k_lifo_put()
 */
static void test_para_init(void)
{
	intptr_t ii;

	/* Init  kernel objects*/
	k_lifo_init(&lifo_timeout[0]);

	k_lifo_init(&lifo_timeout[0]);

	k_lifo_init(&timeout_order_lifo);

	k_lifo_init(&scratch_lifo_packets_lifo);

	/* Fill Scratch LIFO*/

	for (ii = 0; ii < NUM_SCRATCH_LIFO_PACKETS; ii++) {
		scratch_lifo_packets[ii].data_if_needed = (void *)ii;
		k_lifo_put(&scratch_lifo_packets_lifo,
				(void *)&scratch_lifo_packets[ii]);
	}

	for (int i = 0; i < LIST_LEN; i++) {
		data[i].data = i + 1;
	}
}

/**
 * @}
 */

/** test case main entry */
void test_main(void)
{
	test_para_init();

	ztest_test_suite(test_lifo_usage,
			 ztest_unit_test(test_lifo_nowait),
			 ztest_1cpu_unit_test(test_lifo_wait),
			 ztest_1cpu_unit_test(test_timeout_empty_lifo),
			 ztest_unit_test(test_timeout_non_empty_lifo),
			 ztest_1cpu_unit_test(test_timeout_lifo_thread),
			 ztest_1cpu_unit_test(test_timeout_threads_pend_on_lifo));
	ztest_run_test_suite(test_lifo_usage);
}


text:
<?php

namespace Zend\Filter\Compress;

use Archive_Tar;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use Zend\Filter\Exception;

/**
 * Compression adapter for Tar
 *
 * @category   Zend
 * @package    Zend_Filter
 */
class Tar extends AbstractCompressionAlgorithm
{
    /**
     * Compression Options
     * array(
     *     'archive'  => Archive to use
     *     'target'   => Target to write the files to
     * )
     *
     * @var array
     */
    protected $options = array(
        'archive'  => null,
        'target'   => '.',
        'mode'     => null,
    );

    /**
     * Class constructor
     *
     * @param array $options (Optional) Options to set
     * @throws Exception\ExtensionNotLoadedException if Archive_Tar component not available
     */
    public function __construct($options = null)
    {
        if (!class_exists('Archive_Tar')) {
            throw new Exception\ExtensionNotLoadedException(
                'This filter needs PEAR\'s Archive_Tar component. '
                . 'Ensure loading Archive_Tar (registering autoload or require_once)');
        }

        parent::__construct($options);
    }

    /**
     * Returns the set archive
     *
     * @return string
     */
    public function getArchive()
    {
        return $this->options['archive'];
    }

    /**
     * Sets the archive to use for de-/compression
     *
     * @param  string $archive Archive to use
     * @return Tar
     */
    public function setArchive($archive)
    {
        $archive = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, (string) $archive);
        $this->options['archive'] = $archive;

        return $this;
    }

    /**
     * Returns the set target path
     *
     * @return string
     */
    public function getTarget()
    {
        return $this->options['target'];
    }

    /**
     * Sets the target path to use
     *
     * @param  string $target
     * @return Tar
     * @throws Exception\InvalidArgumentException if target path does not exist
     */
    public function setTarget($target)
    {
        if (!file_exists(dirname($target))) {
            throw new Exception\InvalidArgumentException("The directory '$target' does not exist");
        }

        $target = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, (string) $target);
        $this->options['target'] = $target;
        return $this;
    }

    /**
     * Returns the set compression mode
     *
     * @return string
     */
    public function getMode()
    {
        return $this->options['mode'];
    }

    /**
     * Compression mode to use
     *
     * Either Gz or Bz2.
     *
     * @param string $mode
     * @return Tar
     * @throws Exception\InvalidArgumentException for invalid $mode values
     * @throws Exception\ExtensionNotLoadedException if bz2 mode selected but extension not loaded
     * @throws Exception\ExtensionNotLoadedException if gz mode selected but extension not loaded
     */
    public function setMode($mode)
    {
        $mode = ucfirst(strtolower($mode));
        if (($mode != 'Bz2') && ($mode != 'Gz')) {
            throw new Exception\InvalidArgumentException("The mode '$mode' is unknown");
        }

        if (($mode == 'Bz2') && (!extension_loaded('bz2'))) {
            throw new Exception\ExtensionNotLoadedException('This mode needs the bz2 extension');
        }

        if (($mode == 'Gz') && (!extension_loaded('zlib'))) {
            throw new Exception\ExtensionNotLoadedException('This mode needs the zlib extension');
        }

        $this->options['mode'] = $mode;
        return $this;
    }

    /**
     * Compresses the given content
     *
     * @param  string $content
     * @return string
     * @throws Exception\RuntimeException if unable to create temporary file
     * @throws Exception\RuntimeException if unable to create archive
     */
    public function compress($content)
    {
        $archive = new Archive_Tar($this->getArchive(), $this->getMode());
        if (!file_exists($content)) {
            $file = $this->getTarget();
            if (is_dir($file)) {
                $file .= DIRECTORY_SEPARATOR . "tar.tmp";
            }

            $result = file_put_contents($file, $content);
            if ($result === false) {
                throw new Exception\RuntimeException('Error creating the temporary file');
            }

            $content = $file;
        }

        if (is_dir($content)) {
            // collect all file infos
            foreach (new RecursiveIteratorIterator(
                        new RecursiveDirectoryIterator($content, RecursiveDirectoryIterator::KEY_AS_PATHNAME),
                        RecursiveIteratorIterator::SELF_FIRST
                    ) as $directory => $info
            ) {
                if ($info->isFile()) {
                    $file[] = $directory;
                }
            }

            $content = $file;
        }

        $result  = $archive->create($content);
        if ($result === false) {
            throw new Exception\RuntimeException('Error creating the Tar archive');
        }

        return $this->getArchive();
    }

    /**
     * Decompresses the given content
     *
     * @param  string $content
     * @return string
     * @throws Exception\RuntimeException if unable to find archive
     * @throws Exception\RuntimeException if error occurs decompressing archive
     */
    public function decompress($content)
    {
        $archive = $this->getArchive();
        if (empty($archive) || !file_exists($archive)) {
            throw new Exception\RuntimeException('Tar Archive not found');
        }

        $archive = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, realpath($content));
        $archive = new Archive_Tar($archive, $this->getMode());
        $target  = $this->getTarget();
        if (!is_dir($target)) {
            $target = dirname($target) . DIRECTORY_SEPARATOR;
        }

        $result = $archive->extract($target);
        if ($result === false) {
            throw new Exception\RuntimeException('Error while extracting the Tar archive');
        }

        return $target;
    }

    /**
     * Returns the adapter name
     *
     * @return string
     */
    public function toString()
    {
        return 'Tar';
    }
}


text:
package com.speedment.common.codegenxml.internal.view;

import static org.junit.jupiter.api.Assertions.assertTrue;

import com.speedment.common.codegen.Generator;
import com.speedment.common.codegenxml.Document;
import org.junit.jupiter.api.Test;

final class DocumentViewTest {

    @Test
    void transform() {
        final Generator generator = Generator.forJava();

        final DocumentView documentView = new DocumentView();
        final Document document = Document.of();

        assertTrue(documentView.transform(generator, document).isPresent());
    }
}


text:
/*************************************************************************/
/*  godot_rect3.h                                                        */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                    http://www.godotengine.org                         */
/*************************************************************************/
/* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2017 Godot Engine contributors (cf. AUTHORS.md)    */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/
#ifndef GODOT_RECT3_H
#define GODOT_RECT3_H

#ifdef __cplusplus
extern "C" {
#endif

#include <stdint.h>

#ifndef GODOT_CORE_API_GODOT_RECT3_TYPE_DEFINED
#define GODOT_CORE_API_GODOT_RECT3_TYPE_DEFINED
typedef struct godot_rect3 {
	uint8_t _dont_touch_that[24];
} godot_rect3;
#endif

#include "../godot.h"
#include "godot_plane.h"
#include "godot_vector3.h"

void GDAPI godot_rect3_new(godot_rect3 *r_dest, const godot_vector3 *p_pos, const godot_vector3 *p_size);

godot_string GDAPI godot_rect3_as_string(const godot_rect3 *p_self);

godot_real GDAPI godot_rect3_get_area(const godot_rect3 *p_self);

godot_bool GDAPI godot_rect3_has_no_area(const godot_rect3 *p_self);

godot_bool GDAPI godot_rect3_has_no_surface(const godot_rect3 *p_self);

godot_bool GDAPI godot_rect3_intersects(const godot_rect3 *p_self, const godot_rect3 *p_with);

godot_bool GDAPI godot_rect3_encloses(const godot_rect3 *p_self, const godot_rect3 *p_with);

godot_rect3 GDAPI godot_rect3_merge(const godot_rect3 *p_self, const godot_rect3 *p_with);

godot_rect3 GDAPI godot_rect3_intersection(const godot_rect3 *p_self, const godot_rect3 *p_with);

godot_bool GDAPI godot_rect3_intersects_plane(const godot_rect3 *p_self, const godot_plane *p_plane);

godot_bool GDAPI godot_rect3_intersects_segment(const godot_rect3 *p_self, const godot_vector3 *p_from, const godot_vector3 *p_to);

godot_bool GDAPI godot_rect3_has_point(const godot_rect3 *p_self, const godot_vector3 *p_point);

godot_vector3 GDAPI godot_rect3_get_support(const godot_rect3 *p_self, const godot_vector3 *p_dir);

godot_vector3 GDAPI godot_rect3_get_longest_axis(const godot_rect3 *p_self);

godot_int GDAPI godot_rect3_get_longest_axis_index(const godot_rect3 *p_self);

godot_real GDAPI godot_rect3_get_longest_axis_size(const godot_rect3 *p_self);

godot_vector3 GDAPI godot_rect3_get_shortest_axis(const godot_rect3 *p_self);

godot_int GDAPI godot_rect3_get_shortest_axis_index(const godot_rect3 *p_self);

godot_real GDAPI godot_rect3_get_shortest_axis_size(const godot_rect3 *p_self);

godot_rect3 GDAPI godot_rect3_expand(const godot_rect3 *p_self, const godot_vector3 *p_to_point);

godot_rect3 GDAPI godot_rect3_grow(const godot_rect3 *p_self, const godot_real p_by);

godot_vector3 GDAPI godot_rect3_get_endpoint(const godot_rect3 *p_self, const godot_int p_idx);

godot_bool GDAPI godot_rect3_operator_equal(const godot_rect3 *p_self, const godot_rect3 *p_b);

#ifdef __cplusplus
}
#endif

#endif // GODOT_RECT3_H


text:
#ifndef __ASM_SPINLOCK_TYPES_H
#define __ASM_SPINLOCK_TYPES_H

typedef struct {
	volatile unsigned int slock;
} arch_spinlock_t;

#define __ARCH_SPIN_LOCK_UNLOCKED__	0
#define __ARCH_SPIN_LOCK_LOCKED__	1

#define __ARCH_SPIN_LOCK_UNLOCKED	{ __ARCH_SPIN_LOCK_UNLOCKED__ }
#define __ARCH_SPIN_LOCK_LOCKED		{ __ARCH_SPIN_LOCK_LOCKED__ }

/*
 * Unlocked     : 0x0100_0000
 * Read lock(s) : 0x00FF_FFFF to 0x01  (Multiple Readers decrement it)
 * Write lock   : 0x0, but only if prior value is "unlocked" 0x0100_0000
 */
typedef struct {
	volatile unsigned int	counter;
#ifndef CONFIG_ARC_HAS_LLSC
	arch_spinlock_t		lock_mutex;
#endif
} arch_rwlock_t;

#define __ARCH_RW_LOCK_UNLOCKED__	0x01000000
#define __ARCH_RW_LOCK_UNLOCKED		{ .counter = __ARCH_RW_LOCK_UNLOCKED__ }

#endif


text:
#include <aws/pinpoint/model/DeleteAppResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>

#include <utility>

using namespace Aws::Pinpoint::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;

DeleteAppResult::DeleteAppResult()
{
}

DeleteAppResult::DeleteAppResult(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
  *this = result;
}

DeleteAppResult& DeleteAppResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
  JsonView jsonValue = result.GetPayload().View();
  m_applicationResponse = jsonValue;

  return *this;
}


text:
     Note: Starting with v0.39.0, Prometheus Operator requires use of Kubernetes v1.16.x and up.

This documentation is for an alpha feature.

# Monitoring Kubernetes Ingress with Ambassador
[Ambassador](https://getambassador.io/) is a popular open-source API gateway for Kubernetes. Built on [Envoy Proxy](https://envoyproxy.io), Ambassador natively exposes statistics that give you better insight to what is happening at the edge of your Kubernetes cluster. In this guide we will:

* Create a simple Kubernetes application
* Deploy Ambassador as your Kubernetes ingress controller
* Use the Prometheus Operator to deploy and manage our Prometheus instance
* Examine some metrics related to the performance of Kubernetes application at the edge

## Prerequisites
* A Kubernetes Cluster
* The [Kubernetes command line tool](https://kubernetes.io/docs/tasks/tools/install-kubectl/)

## Deploy and Expose an Application on Kubernetes
First, we need an application running on Kubernetes for our users to access. You can deploy any application you would like but, for simplicity, we will use a [sample application](https://getambassador.io/user-guide/getting-started#3-creating-your-first-service) provided by the Ambassador team.

We can quickly deploy this application using `kubectl`:

```
kubectl apply -f https://getambassador.io/yaml/tour/tour.yaml
```

Check the application's status and wait for it to start running:

```
$ kubectl get po --selector=app=tour

NAME                    READY   STATUS    RESTARTS   AGE
tour-6df995489d-lc9hs   2/2     Running   0          1m
```

Now that we have an application running in Kubernetes, we need to expose it to the outside world. We will do this with Ambassador to take advantage of Envoy's robust metrics generation.

1. Deploy Ambassador to your cluster with `kubectl`:

    ```
    kubectl apply -f https://getambassador.io/yaml/ambassador/ambassador-rbac.yaml
    ```
    Ambassador is now running in your cluster and is ready to start routing traffic to your application.

2. Expose Ambassador to the internet.

    ```
    kubectl apply -f https://getambassador.io/yaml/ambassador/ambassador-service.yaml
    ```
    This will create a `LoadBalancer` service in Kubernetes which will automatically create a cloud load balancer if you are running in cloud-managed Kubernetes.

    Kubernetes will automatically assign the load balancer's IP address as the `EXTERNAL_IP` of the service. You can view this with `kubectl`:

    ```
    $ kubectl get svc ambassador

    NAME         TYPE           CLUSTER-IP      EXTERNAL-IP      PORT(S)       AGE
    ambassador   LoadBalancer   10.96.110.170   34.233.165.XXX   80:33241/TCP  87m
    ```
    **Note:** If you are running in a different Kubernetes environment that does not automatically create a load balancer (like minikube), you can still access Ambassador using the `NodePort` of the service (33241 in this example).

3. Route traffic to your application

    You configure Ambassador to expose your application using [annotations](https://getambassador.io/reference/configuration/) on the Kubernetes service of the application like the one below.

    ```yaml
    ---
    apiVersion: v1
    kind: Service
    metadata:
      name: tour
      annotations:
        getambassador.io/config: |
          ---
          apiVersion: ambassador/v1
          kind: Mapping
          name: tour-ui_mapping
          prefix: /
          service: tour:5000
    spec:
      ports:
      - name: ui
        port: 5000
        targetPort: 5000
      selector:
        app: tour
    ```

    The example application above was deployed with a pre-configured annotation to expose it. You can can now access this application using the `EXTERNAL_IP` above and going to http://{AMBASSADOR_EXTERNAL_IP}/ from a web-browser.

You now have an application running in Kubernetes and exposed to the internet.

## Deploy Prometheus
Now that we have an application running and exposed by Ambassador, we need to configure Prometheus to scrape the metrics from Ambassador. The Prometheus Operator gives us a way to deploy and manage Prometheus deployments using Kubernetes-style resources

The Prometheus Operator creates Kubernetes Custom Resource Definitions (CRDs) so we can manage our Prometheus deployment using Kubernetes-style declarative YAML manifests. To deploy the Prometheus Operator, you can clone the [repository](https://github.com/prometheus-operator/prometheus-operator) and follow the instructions in the README. You can also just create it with `kubectl`:

```
kubectl apply -f https://raw.githubusercontent.com/prometheus-operator/prometheus-operator/master/bundle.yaml
```

Once the Prometheus operator is running, we need to create a Prometheus instance. The Prometheus Operator manages Prometheus deployments with the `Prometheus` CRD. To create a Prometheus instance and Kubernetes service, copy the following YAML to a file called `prometheus.yaml` and deploy it with `kubectl`:

```yaml
---
apiVersion: v1
kind: Service
metadata:
  name: prometheus
  annotations:
    getambassador.io/config: |
       ---
       apiVersion: ambassador/v1
       kind: Mapping
       name: prometheus_mapping
       prefix: /prometheus/
       service: prometheus:9090
spec:
  type: ClusterIP
  ports:
  - name: web
    port: 9090
    protocol: TCP
    targetPort: 9090
  selector:
    prometheus: prometheus
---
apiVersion: monitoring.coreos.com/v1
kind: Prometheus
metadata:
  name: prometheus
spec:
  externalUrl: http://{AMBASSADOR_EXTERNAL_IP}/prometheus
  routePrefix: /prometheus
  ruleSelector:
    matchLabels:
      app: prometheus-operator
  serviceAccountName: prometheus-operator
  serviceMonitorSelector:
    matchLabels:
      app: ambassador
  resources:
    requests:
      memory: 400Mi
```

**Note:** The `externalUrl` and `routePrefix` fields allows for you to route requests to Prometheus through Ambassador on the `/prometheus` path. Replace `{AMBASSADOR_EXTERNAL_IP}` with the value from above.

```
kubectl apply -f prometheus.yaml
```
We now have Prometheus running in the cluster and exposed through Ambassador. View the Prometheus UI by going to http://{AMBASSADOR_EXTERNAL_IP}/prometheus/graph from a web browser.

Finally, we need tell Prometheus where to scrape metrics from. The Prometheus Operator easily manages this using a `ServiceMonitor` CRD. To tell Prometheus to scrape metrics from Ambassador's `/metrics` endpoint, we will use the Ambassador admin service and port `ambassador-admin`(8877). Copy the following YAML to a file called `ambassador-monitor.yaml` and apply it with `kubectl`:

```yaml
---
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
  name: ambassador-monitor
  namespace: monitoring
  labels:
    app: ambassador
spec:
  namespaceSelector:
    matchNames:
    - default
  selector:
    matchLabels:
      service: ambassador-admin
  endpoints:
  - port: ambassador-admin
```

```
kubectl apply -f ambassador-monitor.yaml
```

Prometheus will now be configured to collect metrics from the `ambassadr-admin` Kubernetes service with the internal address: `http://ambassador-admin:8877/metrics`.

## Examining Ingress Metrics

If you go to `http://{AMBASSADOR_EXTERNAL_IP}/prometheus/targets` from a web browser you will now see `ambassador-monitor` as a target for Prometheus to scrape metrics from Ambassador. Clicking on the drop down menu at `http://{AMBASSADOR_EXTERNAL_IP}/prometheus/graph`, you can see the various ingress-related metrics output by Envoy.

Envoy's metrics data model is remarkably similar to that of Prometheus and uses the same three kinds of statistics (`Counters`, `Gauges`, and `Histograms`). This allows for Envoy to export dynamic and data-rich statistics that are immediately useable by Prometheus's analytical functions.

**Notable Metrics:**

| Metric Category | Notable Metrics | Description |
| --------------- | --------------- | ----------- |
| envoy_http_downstream_rq | envoy_http_downstream_rq_http1_total

 envoy_http_downstream_rq_http1_total

 envoy_http_downstream_rq_total

 envoy_http_downstream_rq_xx | Statistics regarding traffic from the internet, to each Ambassador instance. Tracking this will give you insight into how each pod is performing for various requests. |
| envoy_cluster_upstream_rq | envoy_cluster_upstream_rq

 envoy_cluster_upstream_rq_xx

 envoy_cluster_upstream_rq_total

 envoy_cluster_upstream_rq_retry | Statistics regarding traffic from Envoy to each upstream service. Tracking this will give you insight to how the request is performing after reaching Ambassador. It will help you pinpoint whether failures are happening in Ambassador or the upstream service. |

Envoy collects many more statistics including some regarding rate limiting, circuit breaking, and distributed tracing. See the [Envoy's documentation](https://envoyproxy.io/docs/envoy/latest/configuration/http/http_conn_man/stats) for more information on the metrics envoy collects.


text:
#ifndef FFW_SYS_UI_GROUP
#define FFW_SYS_UI_GROUP

#include "uiWidget.hpp"

/*!
 * @ingroup User-Interface
 */
namespace ffw{
	/*!
	 * @memberof ffw
	 * @ingroup User-Interface
	 * @inherit uiWidget
	 */
	class FFW_API uiGroup: public uiWidget{
	public:
		/*!
		 * @memberof uiGroup
		 * @ingroup User-Interface
		 */
		uiGroup(void* Handle, int ID, int PosX, int PosY, int Width, int Height, const std::wstring& Label);
		~uiGroup();

		static const size_t hash;
	};
};
#endif


text:
<refentry id="targets.filename">
<refmeta>
<refentrytitle>targets.filename</refentrytitle>
<refmiscinfo role="type">string</refmiscinfo>
</refmeta>
<refnamediv>
<refname>targets.filename</refname>
<refpurpose>Name of cross reference targets data file</refpurpose>
</refnamediv>
<refsynopsisdiv> <src:fragment id="targets.filename.frag">
<xsl:param name="targets.filename" select="'target.db'"/>
</src:fragment>
</refsynopsisdiv>
<refsect1>
<title>Description</title>
<para>
In order to resolve olinks efficiently, the stylesheets can
generate an external data file containing information about
all potential cross reference endpoints in a document.
This parameter lets you change the name of the generated
file from the default name <filename>target.db</filename>.
The name must agree with that used in the target database
used to resolve olinks during processing.
See also <parameter>target.database.document</parameter>.
</para>
</refsect1>
</refentry>


text:
@class NSArray, NSDictionary, NSString;

@interface USUXMSchema : NSObject
{
    NSArray *_tags;
    NSArray *_arrayRepresentation;
    NSDictionary *_variablesForTags;
    NSString *_schemaHash;
}

+ (id)sharedSchema;
+ (id)arrayRepresentation;
+ (id)tags;
+ (id)schemaHash;
+ (id)schemaForTag:(id)arg1;
@property(retain, nonatomic) NSString *schemaHash; // @synthesize schemaHash=_schemaHash;
@property(retain, nonatomic) NSDictionary *variablesForTags; // @synthesize variablesForTags=_variablesForTags;
@property(retain, nonatomic) NSArray *arrayRepresentation; // @synthesize arrayRepresentation=_arrayRepresentation;
@property(retain, nonatomic) NSArray *tags; // @synthesize tags=_tags;
- (void).cxx_destruct;
- (id)schemaFilePath;
- (void)loadUXMVariables;
- (id)schemaForTag:(id)arg1;
- (id)copyWithZone:(struct _NSZone *)arg1;

@end


text:
apt_repository "nginx" do
  uri          "ppa:nginx/stable"
  distribution node["lsb"]["codename"]
end

package "nginx" do
  options %(-o Dpkg::Options::="--force-confdef")
  version node["nginx"]["version"]
end

directory node["nginx"]["dir"] do
  owner "root"
  group "root"
  mode "0755"
  recursive true
end

directory node["nginx"]["log_dir"] do
  owner "www-data"
  group "adm"
  mode "0755"
  recursive true
end

%w[sites-available sites-enabled].each do |vhost_dir|
  directory "#{node["nginx"]["dir"]}/#{vhost_dir}" do
    owner  "root"
    group  "root"
    mode   "0755"
    action :create
  end
end

service "nginx" do
  supports status: true, restart: true, reload: true, stop: true
  provider Chef::Provider::Service::Init::Debian
  action [:enable]
end

# Remove other default sites
file "#{node["nginx"]["dir"]}/conf.d/default" do
  action :delete
  notifies :restart, "service[nginx]"
end

cookbook_file "#{node["nginx"]["dir"]}/mime.types" do
  source "mime.types"
  owner "root"
  group "root"
  mode  "0644"
end

template "nginx.conf" do
  path "#{node["nginx"]["dir"]}/nginx.conf"
  source "nginx.conf.erb"
  owner "root"
  group "root"
  mode  "0644"
  notifies :start, "service[nginx]"
end

# Ensure default site is disabled if necessary
%w[enabled].each do |dir|
  file "#{node["nginx"]["dir"]}/sites-#{dir}/default" do
    action :delete
    manage_symlink_source true
    only_if { node["nginx"]["skip_default_site"] }
    notifies :reload, "service[nginx]"
  end
end

nginx_site "default" do
  action [:create, :enable]
  host node["hostname"]
  root "/usr/share/nginx/html"
  not_if { node["nginx"]["skip_default_site"] }
  notifies :reload, "service[nginx]"
end


text:
@echo off
cscript "%~dp0\deploy.js" %1 -emulate //nologo


text:
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using ControlzEx.Theming;

namespace TinyLittleMvvm.Demo.ViewModels {
    public class SampleFlyoutViewModel : DialogViewModel {
        private AccentColorMenuData _currentAccentColor;

        public SampleFlyoutViewModel() {
            AccentColors = ThemeManager.Current.Themes
                .GroupBy(x => x.ColorScheme)
                .Select(a => new AccentColorMenuData {
                    Name = a.Key,
                    ColorBrush = a.First().ShowcaseBrush
                })
                .ToList();
            var theme = ThemeManager.Current.DetectTheme(Application.Current);
            _currentAccentColor = AccentColors.SingleOrDefault(accent => accent.Name == theme?.ColorScheme) ?? AccentColors.First();

            OkCommand = new RelayCommand(OnOk, () => !HasErrors);
            CancelCommand = new RelayCommand(Close);
        }

        public List<AccentColorMenuData> AccentColors { get; }

        public AccentColorMenuData CurrentAccentColor {
            get { return _currentAccentColor; }
            set {
                if (_currentAccentColor != value) {
                    _currentAccentColor = value;
                    ThemeManager.Current.ChangeThemeColorScheme(Application.Current, value.Name);
                }
            }
        }

        public ICommand OkCommand { get; }

        public ICommand CancelCommand { get; }

        private void OnOk() {
            Close();
        }
    }

    public class AccentColorMenuData {
        public string Name { get; set; } = null!;
        public Brush ColorBrush { get; set; } = null!;
    }
}


text:
package com.sequenceiq.environment.parameters.v1.converter;

import java.util.Optional;

import org.springframework.stereotype.Component;

import com.sequenceiq.cloudbreak.common.mappable.CloudPlatform;
import com.sequenceiq.environment.environment.domain.Environment;
import com.sequenceiq.environment.parameter.dto.AwsDiskEncryptionParametersDto;
import com.sequenceiq.environment.parameter.dto.AwsParametersDto;
import com.sequenceiq.environment.parameter.dto.ParametersDto;
import com.sequenceiq.environment.parameter.dto.ParametersDto.Builder;
import com.sequenceiq.environment.parameters.dao.domain.AwsParameters;
import com.sequenceiq.environment.parameters.dao.domain.BaseParameters;

@Component
public class AwsEnvironmentParametersConverter extends BaseEnvironmentParametersConverter {

    @Override
    protected BaseParameters createInstance() {
        return new AwsParameters();
    }

    @Override
    public CloudPlatform getCloudPlatform() {
        return CloudPlatform.AWS;
    }

    @Override
    protected void postConvert(BaseParameters baseParameters, Environment environment, ParametersDto parametersDto) {
        super.postConvert(baseParameters, environment, parametersDto);
        AwsParameters awsParameters = (AwsParameters) baseParameters;
        Optional<AwsParametersDto> awsParametersDto = Optional.of(parametersDto)
                .map(ParametersDto::getAwsParametersDto);
        awsParameters.setS3guardTableName(awsParametersDto
                .map(AwsParametersDto::getS3GuardTableName)
                .orElse(null));
        awsParameters.setS3guardTableCreation(awsParametersDto
                .map(AwsParametersDto::getDynamoDbTableCreation)
                .orElse(null));
        awsParameters.setFreeIpaSpotPercentage(awsParametersDto
                .map(AwsParametersDto::getFreeIpaSpotPercentage)
                .orElse(0));
        awsParameters.setFreeIpaSpotMaxPrice(awsParametersDto
                .map(AwsParametersDto::getFreeIpaSpotMaxPrice)
                .orElse(null));
        awsParameters.setEncryptionKeyArn(awsParametersDto
                .map(AwsParametersDto::getAwsDiskEncryptionParametersDto)
                .map(AwsDiskEncryptionParametersDto::getEncryptionKeyArn)
                .orElse(null));
    }

    @Override
    protected void postConvertToDto(Builder builder, BaseParameters source) {
        super.postConvertToDto(builder, source);
        AwsParameters awsParameters = (AwsParameters) source;
        builder.withAwsParametersDto(AwsParametersDto.builder()
                .withDynamoDbTableName(awsParameters.getS3guardTableName())
                .withDynamoDbTableCreation(awsParameters.getS3guardTableCreation())
                .withFreeIpaSpotPercentage(awsParameters.getFreeIpaSpotPercentage())
                .withFreeIpaSpotMaxPrice(awsParameters.getFreeIpaSpotMaxPrice())
                .withAwsDiskEncryptionParametersDto(AwsDiskEncryptionParametersDto.builder()
                        .withEncryptionKeyArn(awsParameters.getEncryptionKeyArn())
                        .build())
                .build());
    }
}


text:
require('ember-bootstrap/mixins/item_selection_support');
require('ember-bootstrap/mixins/item_view_href_support');

var get = Ember.get, set = Ember.set, A = Ember.A;
var Bootstrap = window.Bootstrap;

Bootstrap.Pagination = Ember.CollectionView.extend({
  tagName: 'ul',
  classNames: ['pagination'],
  itemTitleKey: 'title',
  itemHrefKey: 'href',
  init: function() {
    this._super();
    if (!this.get('content')) {
      this.set('content', new A([]));
    }
  },
  itemViewClass: Ember.View.extend(Bootstrap.ItemSelectionSupport, Bootstrap.ItemViewHrefSupport, {
    classNameBindings: ['content.disabled'],
    template: Ember.Handlebars.compile('<a {{bindAttr href="view.href"}}>{{view.title}}</a>')
  })
});