text:
package org.springframework.cloud.dataflow.server.db.migration;

import java.sql.Connection;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.cloud.dataflow.core.ApplicationType;
import org.springframework.cloud.dataflow.registry.support.AppResourceCommon;
import org.springframework.cloud.deployer.resource.maven.MavenProperties;
import org.springframework.cloud.deployer.resource.support.DelegatingResourceLoader;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.util.ObjectUtils;

/**
 * Base implementation for a {@link SqlCommand} copying data from
 * {@code URI_REGISTRY} table into {@code app_registration} table.
 *
 * @author Janne Valkealahti
 *
 */
public abstract class AbstractMigrateUriRegistrySqlCommand extends SqlCommand {

	private static final Logger logger = LoggerFactory.getLogger(AbstractMigrateUriRegistrySqlCommand.class);

	@Override
	public void handle(JdbcTemplate jdbcTemplate, Connection connection) {
		boolean migrate = false;
		try {
			jdbcTemplate.execute("select 1 from URI_REGISTRY");
			migrate = true;
			logger.info("Detected URI_REGISTRY, migrating");
		} catch (Exception e) {
			logger.info("Didn't detected URI_REGISTRY, skipping migration from URI_REGISTRY to app_registration");
		}

		if (migrate) {
			updateAppRegistration(jdbcTemplate, createAppRegistrationMigrationData(jdbcTemplate));
			dropUriRegistryTable(jdbcTemplate);
		}
	}

	@Override
	public boolean canHandleInJdbcTemplate() {
		return true;
	}

	/**
	 * Update app registration. Actual database implementation of this method is
	 * required to insert data based on list of
	 * {@code AppRegistrationMigrationData}'s and keep {@code hibernate_sequence}
	 * up-to-date.
	 *
	 * @param jdbcTemplate the jdbc template
	 * @param data the data
	 */
	protected abstract void updateAppRegistration(JdbcTemplate jdbcTemplate, List<AppRegistrationMigrationData> data);

	/**
	 * Creates a migration data from URI_REGISTRY table to get inserted
	 * into app_registration table. We're working on a raw data level
	 * thus no use hibernate, spring repositories nor entity classes.
	 *
	 * @param jdbcTemplate the jdbc template
	 * @return the list
	 */
	protected List<AppRegistrationMigrationData> createAppRegistrationMigrationData(JdbcTemplate jdbcTemplate) {
		Map<String, AppRegistrationMigrationData> data = new HashMap<>();
		// to get version using same existing logic
		AppResourceCommon arc = new AppResourceCommon(new MavenProperties(), new DelegatingResourceLoader());
		// track that we only add default version for one by just giving it to first one
		// just to be on a safe side
		Collection<String> defaultVersions = new HashSet<>();

		// format for old URI_REGISTRY is:
		// +-------------------------------+-------------------------------------------------------------------------------------------------+
		// | NAME                          | URI                                                                                |
		// +-------------------------------+-------------------------------------------------------------------------------------------------+
		// | processor.bridge              | maven://org.springframework.cloud.stream.app:bridge-processor-rabbit:2.0.1.RELEASE              |
		// | processor.bridge.metadata     | maven://org.springframework.cloud.stream.app:bridge-processor-rabbit:jar:metadata:2.0.1.RELEASE |
		//
		// this needs to go to a new app_registration table structure where
		// uri and metadata and other fields are within same record.
		// AppRegistrationMigrationData is base of that info which then
		// gets actually updates with updateAppRegistration method.

		jdbcTemplate.query("select NAME, URI from URI_REGISTRY", rs -> {
			AppRegistrationMigrationData armd;
			String name = rs.getString(1);
			String uri = rs.getString(2);
			// we assume i.e processor.bridge and processor.bridge.metadata belong together
			String[] split = name.split("\\.");
			if (split.length == 2 || split.length == 3) {
				String key = split[0] + split[1];
				armd = data.getOrDefault(key, new AppRegistrationMigrationData());
				if (!defaultVersions.contains(key)) {
					armd.setDefaultVersion(true);
					defaultVersions.add(key);
				}
				if (split.length == 2) {
					// we got *.* first
					armd.setName(split[1]);
					armd.setType(ApplicationType.valueOf(split[0]).ordinal());
					armd.setUri(uri);
					try {
						armd.setVersion(arc.getResourceVersion(arc.getResource(uri)));
					}
					catch (Exception e) {
						logger.warn("Skipping URI_REGISTRY item {} migration with URI {} due to lack of version number in the URI", name, uri, e);
					}
				}
				else {
					// we got *.*.metadata first
					armd.setName(split[1]);
					armd.setType(ApplicationType.valueOf(split[0]).ordinal());
					armd.setMetadataUri(uri);
				}
				// either *.* or *.*.metadata, put it to map, either initial
				// insert or update
				data.put(key, armd);
			}
		});
		// if we skipper version errors, filter those out
		return data.values().stream().filter(i -> !ObjectUtils.isEmpty(i.getVersion())).collect(Collectors.toList());
	}

	/**
	 * Drop uri registry table.
	 *
	 * @param jdbcTemplate the jdbc template
	 */
	protected void dropUriRegistryTable(JdbcTemplate jdbcTemplate) {
		jdbcTemplate.execute("drop table URI_REGISTRY");
	}

	/**
	 * Raw migration data from uri registry into app registration.
	 */
	protected static class AppRegistrationMigrationData {

		private String name;
		private int type;
		private String version;
		private String uri;
		private String metadataUri;
		private boolean defaultVersion;

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}

		public int getType() {
			return type;
		}

		public void setType(int type) {
			this.type = type;
		}

		public String getVersion() {
			return version;
		}

		public void setVersion(String version) {
			this.version = version;
		}

		public String getUri() {
			return uri;
		}

		public void setUri(String uri) {
			this.uri = uri;
		}

		public String getMetadataUri() {
			return metadataUri;
		}

		public void setMetadataUri(String metadataUri) {
			this.metadataUri = metadataUri;
		}

		public boolean isDefaultVersion() {
			return defaultVersion;
		}

		public void setDefaultVersion(boolean defaultVersion) {
			this.defaultVersion = defaultVersion;
		}
	}
}


text:
  A nngraph unit that maps features ids to embeddings. When using multiple
  features this can be the concatenation or the sum of each individual embedding.
]]
local FeaturesEmbedding, parent = torch.class('onmt.FeaturesEmbedding', 'nn.Container')

function FeaturesEmbedding:__init(dicts, dimExponent, dim, merge)
  parent.__init(self)

  self.net = self:_buildModel(dicts, dimExponent, dim, merge)
  self:add(self.net)
end

function FeaturesEmbedding:_buildModel(dicts, dimExponent, dim, merge)
  local inputs = {}
  local output

  if merge == 'sum' then
    self.outputSize = dim
  else
    self.outputSize = 0
  end

  for i = 1, #dicts do
    local feat = nn.Identity()() -- batchSize
    table.insert(inputs, feat)

    local vocabSize = dicts[i]:size()
    local embSize

    if merge == 'sum' then
      embSize = self.outputSize
    else
      embSize = math.floor(vocabSize ^ dimExponent)
      self.outputSize = self.outputSize + embSize
    end

    local emb = nn.LookupTable(vocabSize, embSize)(feat)

    if not output then
      output = emb
    elseif merge == 'sum' then
      output = nn.CAddTable()({output, emb})
    else
      output = nn.JoinTable(2)({output, emb})
    end
  end

  return nn.gModule(inputs, {output})
end

function FeaturesEmbedding:updateOutput(input)
  self.output = self.net:updateOutput(input)
  return self.output
end

function FeaturesEmbedding:updateGradInput(input, gradOutput)
  return self.net:updateGradInput(input, gradOutput)
end

function FeaturesEmbedding:accGradParameters(input, gradOutput, scale)
  self.net:accGradParameters(input, gradOutput, scale)
end

redpajama_set_name: RedPajamaGithub


text:
<?php declare(strict_types=1);

namespace Yay;

interface Result {
	function as(string $label = '') : self;
	function withMeta(Map $meta) : self;
	function meta() : Map;
}


text:
package org.jdesktop.animation.timing.interpolation;

/**
 * Interface that defines the single {@link #interpolate(float)} method. This interface is
 * implemented by built-in interpolators. Applications may choose to implement their own
 * Interpolator to get custom interpolation behavior.
 *
 * @author Chet
 */
public interface Interpolator
{
   /**
    * This function takes an input value between 0 and 1 and returns another value, also between 0
    * and 1. The purpose of the function is to define how time (represented as a (0-1) fraction of
    * the duration of an animation) is altered to derive different value calculations during an
    * animation.
    *
    * @param fraction a value between 0 and 1, representing the elapsed fraction of a time interval
    *                 (either an entire animation cycle or an interval between two KeyTimes,
    *                 depending on where this Interpolator has been set)
    * @return a value between 0 and 1.  Values outside of this boundary may be clamped to the
    *         interval [0,1] and cause undefined results.
    */
   float interpolate(float fraction);
}


text:
/*
 * Modified from {@link org.elasticsearch.plugin.transport.memcached.MemcachedPlugin}
 */

package org.elasticsearch.plugin.transport.redis;

import org.elasticsearch.common.component.LifecycleComponent;
import org.elasticsearch.common.inject.Module;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.redis.RedisServer;
import org.elasticsearch.redis.RedisServerModule;
import org.elasticsearch.plugins.AbstractPlugin;

import java.util.Collection;

import static org.elasticsearch.common.collect.Lists.newArrayList;

/**
 */
public class RedisTransportPlugin extends AbstractPlugin {

    private final Settings settings;

    public RedisTransportPlugin(Settings settings) {
        this.settings = settings;
    }

    @Override
    public String name() {
        return "transport-redis";
    }

    @Override
    public String description() {
        return "Exports Elasticsearch APIs over redis";
    }

    @Override
    public Collection<Class<? extends Module>> modules() {
        Collection<Class<? extends Module>> modules = newArrayList();
        if (settings.getAsBoolean("redis.enabled", true)) {
            modules.add(RedisServerModule.class);
        }
        return modules;
    }

    @Override
    public Collection<Class<? extends LifecycleComponent>> services() {
        Collection<Class<? extends LifecycleComponent>> services = newArrayList();
        if (settings.getAsBoolean("redis.enabled", true)) {
            services.add(RedisServer.class);
        }
        return services;
    }
}


text:
def inorder_traversal(root)
  path = []
  return path if root.nil?
  stack = []
  while !stack.empty? || !root.nil?
    if !root.nil?
      stack.push(root)
      root = root.left
    else
      root = stack.pop
      path.push(root.val)
      root = root.right
    end
  end
  path
end


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

#ifndef DIP_ACCUMULATORS_H
#define DIP_ACCUMULATORS_H

#include <cmath>
#include <numeric>
#include <limits>

#include "diplib/library/types.h"

/// \file
/// \brief Classes for on-line computation of data statistics.
/// See \ref numeric.

namespace dip {

/// \addtogroup numeric

/// \brief `StatisticsAccumulator` computes population statistics by accumulating the first four central moments.
///
/// Samples are added one by one, using the `Push` method. Other members are used to retrieve estimates of
/// the population statistics based on the samples seen up to that point. Formula used to compute population
/// statistics are corrected, though the standard deviation, skewness and excess kurtosis are not unbiased
/// estimators. The accumulator uses a stable algorithm to prevent catastrophic cancellation.
///
/// It is possible to accumulate samples in different objects (e.g. when processing with multiple threads),
/// and add the accumulators together using the `+` operator.
///
/// \see VarianceAccumulator, FastVarianceAccumulator, CovarianceAccumulator, DirectionalStatisticsAccumulator, MinMaxAccumulator, MomentAccumulator
///
/// !!! literature
///     - Code modified from [John D. Cook](http://www.johndcook.com/blog/skewness_kurtosis/)
///       ([Wikipedia](https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance) has the same code).
///     - T. B. Terriberry, ["Computing higher-order moments online"](http://people.xiph.org/~tterribe/notes/homs.html), 2008.
///     - Philippe P. Pébay, "Formulas for Robust, One-Pass Parallel Computation of Covariances and Arbitrary-Order Statistical Moments",
///       Technical Report [SAND2008-6212](https://www.osti.gov/biblio/1028931), Sandia National Laboratories, September 2008.
///     - Wikipedia: ["Skewness", section "Sample skewness"](https://en.wikipedia.org/wiki/Skewness#Sample_skewness).
///     - Wikipedia: ["Kurtosis", section "Sample kurtosis"](https://en.wikipedia.org/wiki/Kurtosis#Sample_kurtosis).
class DIP_NO_EXPORT StatisticsAccumulator {
   public:
      /// Reset the accumulator, leaving it as if newly allocated.
      void Reset() {
         n_ = 0;
         m1_ = 0.0;
         m2_ = 0.0;
         m3_ = 0.0;
         m4_ = 0.0;
      }

      /// Add a sample to the accumulator
      void Push( dfloat x ) {
         ++n_;
         dfloat n = static_cast< dfloat >( n_ );
         dfloat delta = x - m1_;
         dfloat term1 = delta / n;
         dfloat term2 = term1 * term1;
         dfloat term3 = delta * term1 * ( n - 1 );
         m4_ += term3 * term2 * ( n * n - 3.0 * n + 3 ) + 6.0 * term2 * m2_ - 4.0 * term1 * m3_;
         m3_ += term3 * term1 * ( n - 2 ) - 3.0 * term1 * m2_; // old value used for m4_ calculation
         m2_ += term3; // old value used for m3_ and m4_ calculation.
         m1_ += term1;
      }

      /// Combine two accumulators
      StatisticsAccumulator& operator+=( StatisticsAccumulator const& b ) {
         dfloat an = static_cast< dfloat >( n_ );
         dfloat an2 = an * an;
         dfloat bn = static_cast< dfloat >( b.n_ );
         dfloat bn2 = bn * bn;
         dfloat xn2 = an * bn;
         n_ += b.n_;
         dfloat nn = static_cast< dfloat >( n_ );
         dfloat n2 = nn * nn;
         dfloat delta = b.m1_ - m1_;
         dfloat delta2 = delta * delta;
         m4_ += b.m4_ + delta2 * delta2 * xn2 * ( an2 - xn2 + bn2 ) / ( n2 * nn )
               + 6.0 * delta2 * ( an2 * b.m2_ + bn2 * m2_ ) / n2
               + 4.0 * delta * ( an * b.m3_ - bn * m3_ ) / nn;
         m3_ += b.m3_ + delta * delta2 * xn2 * ( an - bn ) / n2
                + 3.0 * delta * ( an * b.m2_ - bn * m2_ ) / nn;
         m2_ += b.m2_ + delta2 * xn2 / nn;
         m1_ += bn * delta / nn;
         return *this;
      }

      /// Number of samples
      dip::uint Number() const {
         return n_;
      }
      /// Unbiased estimator of population mean
      dfloat Mean() const {
         return m1_;
      }
      /// Unbiased estimator of population variance
      dfloat Variance() const {
         dfloat n = static_cast< dfloat >( n_ );
         return ( n_ > 1 ) ? ( m2_ / ( n - 1 )) : ( 0.0 );
      }
      /// Estimator of population standard deviation (it is not possible to derive an unbiased estimator)
      dfloat StandardDeviation() const {
         return std::sqrt( Variance() );
      }
      /// \brief Estimator of population skewness. This estimator is unbiased only for symmetric distributions
      /// (it is not possible to derive an unbiased estimator).
      dfloat Skewness() const {
         if(( n_ > 2 ) && ( m2_ != 0 )) {
            dfloat n = static_cast< dfloat >( n_ );
            return (( n * n ) / (( n - 1 ) * ( n - 2 ))) * ( m3_ / ( n * std::pow( Variance(), 1.5 )));
         }
         return 0;
      }
      /// \brief Estimator of population excess kurtosis. This estimator is only unbiased for normally
      /// distributed data (it is not possible to derive an unbiased estimator).
      dfloat ExcessKurtosis() const {
         if( n_ > 3 && ( m2_ != 0 )) {
            dfloat n = static_cast< dfloat >( n_ );
            return ( n - 1 ) / (( n - 2 ) * ( n - 3 )) * (( n + 1 ) * n * m4_ / ( m2_ * m2_ ) - 3 * ( n - 1 ));
         }
         return 0;
      }

   private:
      dip::uint n_ = 0; // number of values x collected
      dfloat m1_ = 0.0;   // mean of values x
      dfloat m2_ = 0.0;   // sum of (x-mean(x))^2  --  `m2_ / n_` is second order central moment
      dfloat m3_ = 0.0;   // sum of (x-mean(x))^3  --  `m3_ / n_` is third order central moment
      dfloat m4_ = 0.0;   // sum of (x-mean(x))^4  --  `m4_ / n_` is fourth order central moment
};

/// \brief Combine two accumulators
/// \relates dip::StatisticsAccumulator
inline StatisticsAccumulator operator+( StatisticsAccumulator lhs, StatisticsAccumulator const& rhs ) {
   lhs += rhs;
   return lhs;
}

/// \brief `VarianceAccumulator` computes mean and standard deviation by accumulating the first two
/// central moments.
///
/// Samples are added one by one, using the `Push` method. Other members are used to retrieve estimates of
/// the population statistics based on the samples seen up to that point. Formula used to compute population
/// statistics are corrected, though the standard deviation is not an unbiased estimator. The accumulator
/// uses a stable algorithm to prevent catastrophic cancellation. If catastrophic cancellation is unlikely
/// or not important, use the faster \ref dip::FastVarianceAccumulator.
///
/// It is possible to accumulate samples in different objects (e.g. when processing with multiple threads),
/// and add the accumulators together using the `+` operator.
///
/// It is also possible to remove a sample from the accumulator, using the `Pop` method. It is assumed that the
/// particular value passed to this method had been added previously to the accumulator. If this is not the case,
/// resulting means and variances are no longer correct.
///
/// \see StatisticsAccumulator, FastVarianceAccumulator, CovarianceAccumulator, DirectionalStatisticsAccumulator, MinMaxAccumulator, MomentAccumulator
///
/// !!! literature
///     - Donald E. Knuth, "The Art of Computer Programming, Volume 2: Seminumerical Algorithms", 3^rd^ Ed., 1998.
class DIP_NO_EXPORT VarianceAccumulator {
   public:
      /// Reset the accumulator, leaving it as if newly allocated.
      void Reset() {
         n_ = 0;
         m1_ = 0.0;
         m2_ = 0.0;
      }

      /// Add a sample to the accumulator
      void Push( dfloat x ) {
         ++n_;
         dfloat delta = x - m1_;
         m1_ += delta / static_cast< dfloat >( n_ );
         m2_ += delta * ( x - m1_ );
      }

      /// Remove a sample from the accumulator
      void Pop( dfloat x ) {
         if( n_ > 0 ) {
            dfloat delta = x - m1_;
            m1_ = ( m1_ * static_cast< dfloat >( n_ ) - x ) / static_cast< dfloat >( n_ - 1 );
            m2_ -= delta * ( x - m1_ );
            --n_;
         }
      }

      /// Combine two accumulators
      VarianceAccumulator& operator+=( VarianceAccumulator const& b ) {
         dfloat oldn = static_cast< dfloat >( n_ );
         n_ += b.n_;
         dfloat n = static_cast< dfloat >( n_ );
         dfloat bn = static_cast< dfloat >( b.n_ );
         dfloat delta = b.m1_ - m1_;
         m1_ += bn * delta / n;
         m2_ += b.m2_ + delta * delta * ( oldn * bn ) / n;
         return *this;
      }

      /// Number of samples
      dip::uint Number() const {
         return n_;
      }
      /// Unbiased estimator of population mean
      dfloat Mean() const {
         return m1_;
      }
      /// Unbiased estimator of population variance
      dfloat Variance() const {
         dfloat n = static_cast< dfloat >( n_ );
         return ( n_ > 1 ) ? ( m2_ / ( n - 1 )) : ( 0.0 );
      }
      /// Estimator of population standard deviation (it is not possible to derive an unbiased estimator)
      dfloat StandardDeviation() const {
         return std::sqrt( Variance() );
      }

   private:
      dip::uint n_ = 0; // number of values x collected
      dfloat m1_ = 0.0;   // mean of values x
      dfloat m2_ = 0.0;   // sum of (x-mean(x))^2  --  `m2_ / n_` is second order central moment
};

/// \brief Combine two accumulators
/// \relates dip::VarianceAccumulator
inline VarianceAccumulator operator+( VarianceAccumulator lhs, VarianceAccumulator const& rhs ) {
   lhs += rhs;
   return lhs;
}

/// \brief `FastVarianceAccumulator` computes mean and standard deviation by accumulating the sum of sample
/// values and the sum of the square of sample values.
///
/// Samples are added one by one, using the `Push` method. Other members are used to retrieve estimates of
/// the population statistics based on the samples seen up to that point. Formula used to compute population
/// statistics are corrected, though the standard deviation is not an unbiased estimator. The accumulator
/// uses a simple algorithm that could result in catastrophic cancellation if the variance is very small with
/// respect to the mean; use \ref dip::VarianceAccumulator to prevent it.
///
/// It is possible to accumulate samples in different objects (e.g. when processing with multiple threads),
/// and add the accumulators together using the `+` operator.
///
/// It is also possible to remove a sample from the accumulator, using the `Pop` method. It is assumed that the
/// particular value passed to this method had been added previously to the accumulator. If this is not the case,
/// resulting means and variances are no longer correct.
///
/// \see StatisticsAccumulator, VarianceAccumulator, CovarianceAccumulator, DirectionalStatisticsAccumulator, MinMaxAccumulator, MomentAccumulator
class DIP_NO_EXPORT FastVarianceAccumulator {
   public:
      /// Reset the accumulator, leaving it as if newly allocated.
      void Reset() {
         n_ = 0;
         m1_ = 0.0;
         m2_ = 0.0;
      }

      /// Add a sample to the accumulator
      void Push( dfloat x ) {
         ++n_;
         m1_ += x;
         m2_ += x * x;
      }

      /// Remove a sample from the accumulator
      void Pop( dfloat x ) {
         if( n_ > 0 ) {
            --n_;
            m1_ -= x;
            m2_ -= x * x;
         }
      }

      /// Combine two accumulators
      FastVarianceAccumulator& operator+=( FastVarianceAccumulator const& b ) {
         n_ += b.n_;
         m1_ += b.m1_;
         m2_ += b.m2_;
         return *this;
      }

      /// Number of samples
      dip::uint Number() const {
         return n_;
      }
      /// Unbiased estimator of population mean
      dfloat Mean() const {
         return m1_ / static_cast< dfloat >( n_ );
      }
      /// Unbiased estimator of population variance
      dfloat Variance() const {
         dfloat n = static_cast< dfloat >( n_ );
         return ( n_ > 1 ) ? (( m2_ - ( m1_ * m1_ ) / n ) / ( n - 1 )) : ( 0.0 );
      }
      /// Estimator of population standard deviation (it is not possible to derive an unbiased estimator)
      dfloat StandardDeviation() const {
         return std::sqrt( Variance() );
      }

   private:
      dip::uint n_ = 0; // number of values x collected
      dfloat m1_ = 0.0; // sum of x
      dfloat m2_ = 0.0; // sum of x^2
};

/// \brief Combine two accumulators
/// \relates dip::FastVarianceAccumulator
inline FastVarianceAccumulator operator+( FastVarianceAccumulator lhs, FastVarianceAccumulator const& rhs ) {
   lhs += rhs;
   return lhs;
}

/// \brief `CovarianceAccumulator` computes covariance and correlation of pairs of samples by accumulating the
/// first two central moments and cross-moments.
///
/// Samples are added one pair at the time, using the `Push` method. Other members are used to retrieve the results.
/// The accumulator uses a stable algorithm to prevent catastrophic cancellation.
///
/// The covariance matrix is formed by
///
/// ```text
/// | cov.VarianceX()   cov.Covariance() |
/// | cov.Covariance()  cov.VarianceY()  |
/// ```
///
/// The `Regression` method returns the parameters to the least squares fit of the equation $y = a + bx$,
/// where $x$ is the first sample in each pair and $y$ is the second (this is linear regression), $a$ is the
/// intercept and $b$ is the slope. The `Slope` method computes only the slope component.
///
/// It is possible to accumulate samples in different objects (e.g. when processing with multiple threads),
/// and add the accumulators together using the `+` operator.
///
/// \see StatisticsAccumulator, VarianceAccumulator, FastVarianceAccumulator, DirectionalStatisticsAccumulator, MinMaxAccumulator, MomentAccumulator
///
/// !!! literature
///     - Wikipedia: ["Algorithms for calculating variance", section "Covariance"](https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Covariance).
class DIP_NO_EXPORT CovarianceAccumulator {
      // TODO: rewrite this for arbitrary number of variables
   public:
      /// Reset the accumulator, leaving it as if newly allocated.
      void Reset() {
         n_ = 0;
         meanx_ = 0;
         m2x_ = 0;
         meany_ = 0;
         m2y_ = 0;
         C_ = 0;
      }

      /// Add a pair of samples to the accumulator
      void Push( dfloat x, dfloat y ) {
         ++n_;
         dfloat dx = x - meanx_;
         meanx_ += dx / static_cast< dfloat >( n_ );
         m2x_ += dx * ( x - meanx_ );
         dfloat dy = y - meany_;
         meany_ += dy / static_cast< dfloat >( n_ );
         dfloat dy_new = y - meany_;
         m2y_ += dy * dy_new;
         C_ += dx * dy_new;
      }

      /// Combine two accumulators
      CovarianceAccumulator& operator+=( const CovarianceAccumulator& other ) {
         if( n_ == 0 ) {
            *this = other; // copy over the data
         } else if( other.n_ > 0 ) {
            dip::uint intN = n_ + other.n_;
            dfloat N = static_cast< dfloat >( intN );
            dfloat dx = other.meanx_ - meanx_;
            dfloat dy = other.meany_ - meany_;
            meanx_ = ( static_cast< dfloat >( n_ ) * meanx_ + static_cast< dfloat >( other.n_ ) * other.meanx_ ) / N;
            meany_ = ( static_cast< dfloat >( n_ ) * meany_ + static_cast< dfloat >( other.n_ ) * other.meany_ ) / N;
            dfloat fN = static_cast< dfloat >( n_ * other.n_ ) / N;
            m2x_ += other.m2x_ + dx * dx * fN;
            m2y_ += other.m2y_ + dy * dy * fN;
            C_ += other.C_ + dx * dy * fN;
            n_ = intN;
         }
         return *this;
      }

      /// Number of samples
      dip::uint Number() const {
         return n_;
      }
      /// Unbiased estimator of population mean for first variable
      dfloat MeanX() const {
         return meanx_;
      }
      /// Unbiased estimator of population mean for second variable
      dfloat MeanY() const {
         return meany_;
      }
      /// Unbiased estimator of population variance for first variable
      dfloat VarianceX() const {
         dfloat n = static_cast< dfloat >( n_ );
         return ( n_ > 1 ) ? ( m2x_ / ( n - 1 )) : ( 0.0 );
      }
      /// Unbiased estimator of population variance for second variable
      dfloat VarianceY() const {
         dfloat n = static_cast< dfloat >( n_ );
         return ( n_ > 1 ) ? ( m2y_ / ( n - 1 )) : ( 0.0 );
      }
      /// Estimator of population standard deviation for first variable (it is not possible to derive an unbiased estimator)
      dfloat StandardDeviationX() const {
         return std::sqrt( VarianceX() );
      }
      /// Estimator of population standard deviation for second variable (it is not possible to derive an unbiased estimator)
      dfloat StandardDeviationY() const {
         return std::sqrt( VarianceY() );
      }
      /// Unbiased estimator of population covariance
      dfloat Covariance() const {
         dfloat n = static_cast< dfloat >( n_ );
         return ( n_ > 1 ) ? ( C_ / ( n - 1.0 )) : ( 0.0 );
      }
      /// Estimator of correlation between the two variables
      dfloat Correlation() const {
         dfloat S = std::sqrt( m2x_ * m2y_ );
         return (( n_ > 1 ) && ( S != 0.0 )) ? ( C_ / S ) : ( 0.0 );
      }
      /// Computes the slope of the regression line
      dfloat Slope() const {
         //dfloat stdX = StandardDeviationX();
         //return ( stdX != 0.0 ) ? ( Correlation() * StandardDeviationY() / stdX ) : ( 0.0 );
         return ( m2x_ != 0.0 ) ? ( C_ / m2x_ ) : ( 0.0 );
      }
      /// Copying type for backward compatibility.
      using RegressionResult = dip::RegressionParameters;
      /// Computes the slope and intercept of the regression line
      RegressionResult Regression() const {
         RegressionResult out;
         out.slope = Slope();
         out.intercept = meany_ - out.slope * meanx_;
         return out;
      };

   private:
      dip::uint n_ = 0;
      dfloat meanx_ = 0;
      dfloat m2x_ = 0;
      dfloat meany_ = 0;
      dfloat m2y_ = 0;
      dfloat C_ = 0;
};

/// \brief `DirectionalStatisticsAccumulator` computes directional mean and standard deviation by accumulating
/// a unit vector with the input value as angle.
///
/// Samples are added one by one, using the `Push` method. Other members are used to retrieve estimates of
/// the sample statistics based on the samples seen up to that point.
///
/// It is possible to accumulate samples in different objects (e.g. when processing with multiple threads),
/// and add the accumulators together using the `+` operator.
///
/// \see StatisticsAccumulator, VarianceAccumulator, FastVarianceAccumulator, CovarianceAccumulator, MinMaxAccumulator, MomentAccumulator
class DIP_NO_EXPORT DirectionalStatisticsAccumulator {
   public:
      /// Reset the accumulator, leaving it as if newly allocated.
      void Reset() {
         n_ = 0;
         sum_ = { 0.0, 0.0 };
      }

      /// Add a sample to the accumulator
      void Push( dfloat x ) {
         ++n_;
         sum_ += dcomplex{ std::cos( x ), std::sin( x ) };
      }

      /// Combine two accumulators
      DirectionalStatisticsAccumulator& operator+=( DirectionalStatisticsAccumulator const& b ) {
         n_ += b.n_;
         sum_ += b.sum_;
         return *this;
      }

      /// Number of samples
      dip::uint Number() const {
         return n_;
      }
      /// Unbiased estimator of population mean
      dfloat Mean() const {
         return std::arg( sum_ );
      }
      /// Unbiased estimator of population variance
      dfloat Variance() const {
         dfloat n = static_cast< dfloat >( n_ );
         return ( n_ > 0 ) ? ( 1.0 - std::abs( sum_ ) / n ) : ( 0.0 );
      }
      /// Estimator of population standard deviation (it is not possible to derive an unbiased estimator)
      dfloat StandardDeviation() const {
         dfloat n = static_cast< dfloat >( n_ );
         return ( n_ > 0 ) ? ( std::sqrt( std::max( -2.0 * std::log( std::abs( sum_ ) / n ), 0.0 ))) : ( 0.0 );
         // If `abs(sum_)/n` is 1, rounding error can put it over 1, making `log()` positive, which causes
         // `sqrt(-2*log(...))` to be NaN. Hence the `max(..., 0)`, which prevents negative inputs to `sqrt()`.
      }

   private:
      dip::uint n_ = 0; // number of values x collected
      dcomplex sum_ = { 0.0, 0.0 }; // sum of values exp(i x)
};

/// \brief Combine two accumulators
/// \relates dip::DirectionalStatisticsAccumulator
inline DirectionalStatisticsAccumulator operator+( DirectionalStatisticsAccumulator lhs, DirectionalStatisticsAccumulator const& rhs ) {
   lhs += rhs;
   return lhs;
}

/// \brief `MinMaxAccumulator` computes minimum and maximum values of a sequence of values.
///
/// Samples are added one by one or two by two, using the `Push` method. Other members are used to retrieve the results.
///
/// It is possible to accumulate samples in different objects (e.g. when processing with multiple threads),
/// and add the accumulators together using the `+` operator.
///
/// \see StatisticsAccumulator, VarianceAccumulator, FastVarianceAccumulator, CovarianceAccumulator, DirectionalStatisticsAccumulator, MomentAccumulator
class DIP_NO_EXPORT MinMaxAccumulator {
   public:
      /// Reset the accumulator, leaving it as if newly allocated.
      void Reset() {
         min_ = std::numeric_limits< dfloat >::max();
         max_ = std::numeric_limits< dfloat >::lowest();
      }

      /// Add a sample to the accumulator
      void Push( dfloat x ) {
         max_ = std::max( max_, x );
         min_ = std::min( min_, x );
      }

      /// \brief Add two samples to the accumulator. Prefer this over adding one value at the time.
      void Push( dfloat x, dfloat y ) {
         if( x > y ) {
            max_ = std::max( max_, x );
            min_ = std::min( min_, y );
         } else { // y >= x
            max_ = std::max( max_, y );
            min_ = std::min( min_, x );
         }
      }

      /// Combine two accumulators
      MinMaxAccumulator& operator+=( MinMaxAccumulator const& other ) {
         min_ = std::min( min_, other.min_ );
         max_ = std::max( max_, other.max_ );
         return *this;
      }

      /// Minimum value seen so far
      dfloat Minimum() const {
         return min_;
      }

      /// Maximum value seen so far
      dfloat Maximum() const {
         return max_;
      }

   private:
      dfloat min_ = std::numeric_limits< dfloat >::max();
      dfloat max_ = std::numeric_limits< dfloat >::lowest();
};

/// \brief Combine two accumulators
/// \relates dip::MinMaxAccumulator
inline MinMaxAccumulator operator+( MinMaxAccumulator lhs, MinMaxAccumulator const& rhs ) {
   lhs += rhs;
   return lhs;
}

/// \brief `MomentAccumulator` accumulates the zeroth order moment, the first order normalized moments, and the
/// second order normalized central moments, in `N` dimensions.
///
/// Samples are added one by one, using the `Push` method. Other members are used to retrieve the moments.
///
/// It is possible to accumulate samples in different objects (e.g. when processing with multiple threads),
/// and add the accumulators together using the `+` operator.
///
/// \see StatisticsAccumulator, VarianceAccumulator, FastVarianceAccumulator, CovarianceAccumulator, DirectionalStatisticsAccumulator, MinMaxAccumulator
class DIP_NO_EXPORT MomentAccumulator {
   public:
      /// The constructor determines the dimensionality for the object.
      MomentAccumulator( dip::uint N ) {
         DIP_THROW_IF( N < 1, E::PARAMETER_OUT_OF_RANGE );
         m0_ = 0.0;
         m1_.resize( N, 0.0 );
         m2_.resize( N * ( N + 1 ) / 2, 0.0 );
      }

      /// Reset the accumulator, leaving it as if newly allocated.
      void Reset() {
         m0_ = 0.0;
         m1_.fill( 0.0 );
         m2_.fill( 0.0 );
      }

      /// \brief Add a sample to the accumulator. `pos` must have `N` dimensions.
      void Push( FloatArray const& pos, dfloat weight ) {
         dip::uint N = m1_.size();
         DIP_ASSERT( pos.size() == N );
         m0_ += weight;
         dip::uint kk = 0;
         for( dip::uint ii = 0; ii < N; ++ii ) {
            m1_[ ii ] += pos[ ii ] * weight;
            for( dip::uint jj = 0; jj <= ii; ++jj ) {
               m2_[ kk ] += pos[ ii ] * pos[ jj ] * weight;
               ++kk;
            }
         }
      }

      /// Combine two accumulators
      MomentAccumulator& operator+=( MomentAccumulator const& b ) {
         m0_ += b.m0_;
         m1_ += b.m1_;
         m2_ += b.m2_;
         return *this;
      }

      /// Sum of weights (zeroth order moment)
      dfloat Sum() const {
         return m0_;
      }

      /// First order moments, normalized
      FloatArray FirstOrder() const {
         if( m0_ == 0 ) {
            return FloatArray( m1_.size(), 0.0 );
         }
         FloatArray out = m1_;
         for( dfloat& v : out ) {
            v /= m0_;
         }
         return out;
      }

      /// \brief Second order central moment tensor, normalized
      ///
      /// The moments are stored in the same order as symmetric tensors are stored in an image
      /// (see \ref dip::Tensor::Shape). That is, fist are the main diagonal elements, then the elements
      /// above the diagonal, column-wise. This translates to:
      ///
      /// - 2D: xx, yy, xy
      /// - 3D: xx, yy, zz, xy, xz, yz
      /// - 4D: xx, yy, zz, tt, xy, xz, yz, xt, yt, zt
      /// - etc.
      ///
      /// The second order moment tensor (inertia tensor) is defined as
      ///
      /// $$ I = \Sigma_k m_k ((\vec{r_k} \cdot \vec{r_k}) E - \vec{r_k} \otimes \vec{r_k}) $$
      ///
      /// where $E$ is the identity matrix ( $E = \Sigma_i \vec{e_i} \otimes \vec{e_i}$ ), $m_k$
      /// is the weight of point $k$, and $\vec{r_k} = (x_k, y_k, \ldots)$ is its position relative to the
      /// center of mass. In 2D, this leads to
      ///
      /// \begin{eqnarray*}
      ///       I_{xx} & = & \mathbin{\phantom{-}}\Sigma_k m_k y_k^2
      ///    \\ I_{yy} & = & \mathbin{\phantom{-}}\Sigma_k m_k x_k^2
      ///    \\ I_{xy} & = &                   -  \Sigma_k m_k x_k y_k
      /// \end{eqnarray*}
      ///
      /// In 3D, it leads to
      ///
      /// \begin{eqnarray*}
      ///       I_{xx} & = & \mathbin{\phantom{-}}\Sigma_k m_k y_k^2 + \Sigma_k m_k z_k^2
      ///    \\ I_{yy} & = & \mathbin{\phantom{-}}\Sigma_k m_k x_k^2 + \Sigma_k m_k z_k^2
      ///    \\ I_{zz} & = & \mathbin{\phantom{-}}\Sigma_k m_k x_k^2 + \Sigma_k m_k y_k^2
      ///    \\ I_{xy} & = &                   -  \Sigma_k m_k x_k y_k
      ///    \\ I_{xz} & = &                   -  \Sigma_k m_k x_k z_k
      ///    \\ I_{yz} & = &                   -  \Sigma_k m_k y_k z_k
      /// \end{eqnarray*}
      ///
      /// In 1D the tensor is always 0, see \ref PlainSecondOrder for a useful result in 1D.
      ///
      /// Note that here we normalize each components by the sum of weights. This makes the tensor invariant
      /// to scaling of the weights (e.g. scaling the image intensity).
      FloatArray SecondOrder() const {
         FloatArray out( m2_.size(), 0.0 ); // output tensor
         if( m0_ != 0 ) {
            dip::uint N = m1_.size();
            FloatArray m1 = FirstOrder(); // normalized first order moments
            FloatArray m2( N, 0.0 );      // normalized second order central moments, diagonal elements
            for( dip::uint ii = 0, kk = 0; ii < N; ++ii, kk += 1 + ii ) {
               m2[ ii ] = m2_[ kk ] / m0_ - m1[ ii ] * m1[ ii ];
            }
            for( dip::uint ii = 0; ii < N; ++ii ) {
               dfloat acc = 0.0;
               for( dip::uint jj = 0; jj < N; ++jj ) {
                  if( jj != ii ) {
                     acc += m2[ jj ];
                  }
               }
               out[ ii ] = acc;
            }
            for( dip::uint ii = 1, kk = N, ll = 1; ii < N; ++ii, ++ll ) {
               for( dip::uint jj = 0; jj < ii; ++jj, ++kk, ++ll ) {
                  out[ kk ] = m1[ ii ] * m1[ jj ] - m2_[ ll ] / m0_;
               }
            }
         }
         return out;
      }

      /// \brief Plain second order central moments, normalized
      ///
      /// Sometimes one just needs the normalized central moments directly, not in tensor form.
      /// Here we return them, in the same order as described above for \ref SecondOrder. Each of
      /// the components are defined by
      ///
      /// $$ M_{ij} = \frac{\Sigma_k m_k r_{ki} r_{kj}}{\Sigma_k m_k} $$
      ///
      /// with $m_k$ the weight of point $k$, and $\vec{r_k} = (r_{k1}, r_{k2}, \ldots)$ its position
      /// relative to the center of mass.
      ///
      /// The normalization makes the moments invariant to scaling of the weights (e.g. scaling of the
      /// image intensity). Divide each component by \ref "Sum" (the zeroth order moment) to obtain
      /// size-invariant second order moments.
      FloatArray PlainSecondOrder() const {
         FloatArray out( m2_.size(), 0.0 ); // output tensor
         if( m0_ != 0 ) {
            dip::uint N = m1_.size();
            FloatArray m1 = FirstOrder(); // normalized first order moments
            for( dip::uint ii = 0, kk = 0; ii < N; ++ii, kk += 1 + ii ) {
               out[ ii ] = m2_[ kk ] / m0_ - m1[ ii ] * m1[ ii ];
            }
            for( dip::uint ii = 1, kk = N, ll = 1; ii < N; ++ii, ++ll ) {
               for( dip::uint jj = 0; jj < ii; ++jj, ++kk, ++ll ) {
                  out[ kk ] = m2_[ ll ] / m0_ - m1[ ii ] * m1[ jj ];
               }
            }
         }
         return out;
      }

   private:
      dfloat m0_;       // zeroth order moments accumulated here (sum of weights)
      FloatArray m1_;   // first order moments accumulated here (N values)
      FloatArray m2_;   // second order moments accumulated here (N*(N+1)/2 values)
      // Second order moments are stored column-wise, after removing the symmetric elements below the main diagonal:
      //  - 2D: xx, xy, yy
      //  - 3D: xx, xy, yy, xz, yz, zz
      //  - 4D: xx, xy, yy, xz, yz, zz, xt, yt, zt, tt
      //  - etc.
      // Note that this order is different from the one we use for the output. This is more convenient in computation,
      // the output order matches that of pixel storage.
};

/// \brief Combine two accumulators
/// \relates dip::MomentAccumulator
inline MomentAccumulator operator+( MomentAccumulator lhs, MomentAccumulator const& rhs ) {
   lhs += rhs;
   return lhs;
}

/// \endgroup

} // namespace dip

#endif // DIP_ACCUMULATORS_H


text:
You can configure AnyCable-Go via CLI options, e.g.:

```sh
$ anycable-go --rpc_host=localhost:50051 --headers=cookie \
              --redis_url=redis://localhost:6379/5 --redis_channel=__anycable__ \
              --host=localhost --port=8080
```

Or via the corresponding environment variables (i.e. `ANYCABLE_RPC_HOST`, `ANYCABLE_REDIS_URL`, etc.).

## Primary settings

Here is the list of the most commonly used configuration parameters.

**NOTE:** To see all available options run `anycable-go -h`.

---

**--host**, **--port** (`ANYCABLE_HOST`, `ANYCABLE_PORT` or `PORT`)

Server host and port (default: `"localhost:8080"`).

**--rpc_host** (`ANYCABLE_RPC_HOST`)

RPC service address (default: `"localhost:50051"`).

**--headers** (`ANYCABLE_HEADERS`)

Comma-separated list of headers to proxy to RPC (default: `"cookie"`).

**--proxy-cookies** (`ANYCABLE_PROXY_COOKIES`)

Comma-separated list of cookies to proxy to RPC (default: all cookies).

**--allowed_origins** (`ANYCABLE_ALLOWED_ORIGINS`)

Comma-separated list of hostnames to check the Origin header against during the WebSocket Upgrade.
Supports wildcards, e.g., `--allowed_origins=*.evilmartians.io,www.evilmartians.com`.

**--broadcast_adapter** (`ANYCABLE_BROADCAST_ADAPTER`, default: `redis`)

[Broadcasting adapter](../ruby/broadcast_adapters.md) to use. Available options: `redis` (default), `nats`, and `http`.

When HTTP adapter is used, AnyCable-Go accepts broadcasting requests on `:8090/_broadcast`.

**--http_broadcast_port** (`ANYCABLE_HTTP_BROADCAST_PORT`, default: `8090`)

You can specify on which port to receive broadcasting requests (NOTE: it could be the same port as the main HTTP server listens to).

**--http_broadcast_secret** (`ANYCABLE_HTTP_BROADCAST_SECRET`)

Authorization secret to protect the broadcasting endpoint (see [Ruby docs](../ruby/broadcast_adapters.md#securing-http-endpoint)).

**--redis_url** (`ANYCABLE_REDIS_URL` or `REDIS_URL`)

Redis URL for pub/sub (default: `"redis://localhost:6379/5"`).

**--redis_channel** (`ANYCABLE_REDIS_CHANNEL`)

Redis channel for broadcasting (default: `"__anycable__"`).

**--nats_servers** (`ANYCABLE_NATS_SERVERS`)

The list of [NATS][] servers to connect to (default: `"nats://localhost:4222"`).

**--nats_channel** (`ANYCABLE_NATS_CHANNEL`)

NATS channel for broadcasting (default: `"__anycable__"`).

**--log_level** (`ANYCABLE_LOG_LEVEL`)

Logging level (default: `"info"`).

**--debug** (`ANYCABLE_DEBUG`)

Enable debug mode (more verbose logging).

## TLS

To secure your `anycable-go` server provide the paths to SSL certificate and private key:

```sh
anycable-go --port=443 -ssl_cert=path/to/ssl.cert -ssl_key=path/to/ssl.key

=> INFO time context=http Starting HTTPS server at 0.0.0.0:443
```

If your RPC server requires TLS you can enable it via `--rpc_enable_tls` (`ANYCABLE_RPC_ENABLE_TLS`).

## Concurrency settings

AnyCable-Go uses a single Go gRPC client\* to communicate with AnyCable RPC servers (see [the corresponding PR](https://github.com/anycable/anycable-go/pull/88)). We limit the number of concurrent RPC calls to avoid flooding servers (and getting `ResourceExhausted` exceptions in response).

\* A single _client_ doesn't necessary mean a single connection; a Go gRPC client could maintain multiple HTTP2 connections, for example, when using [DNS-based load balancing](../deployment/load_balancing).

We limit the number of concurrent RPC calls at the application level (to prevent RPC servers overload). By default, the concurrency limit is equal to **28**, which is intentionally less than the default RPC size (see [Ruby configuration](../ruby/configuration.md#concurrency-settings)): there is a tiny lag between the times when the response is received by the client and the corresponding worker is returned to the pool. Thus, whenever you update the concurrency settings, make sure that the AnyCable-Go value is _slightly less_ than the AnyCable-RPC one.

You can change this value via `--rpc_concurrency` (`ANYCABLE_RPC_CONCURRENCY`) parameter.

## Disconnect events settings

AnyCable-Go notifies an RPC server about disconnected clients asynchronously with a rate limit. We do that to allow other RPC calls to have higher priority (because _live_ clients are usually more important) and to avoid load spikes during mass disconnects (i.e., when a server restarts).

That could lead to the situation when the _disconnect queue_ is overwhelmed, and we cannot perform all the `Disconnect` calls during server shutdown. Thus, **RPC server may not receive all the disconnection events** (i.e., `disconnect` and `unsubscribed` callbacks in your code).

If you rely on `disconnect` callbacks in your code, you can tune the default disconnect queue settings to provide better guarantees\*:

**--disconnect_rate** (`ANYCABLE_DISCONNECT_RATE`)

The max number of `Disconnect` calls per-second (default: 100).

**--disconnect_timeout** (`ANYCABLE_DISCONNECT_TIMEOUT`)

The number of seconds to wait before forcefully shutting down a disconnect queue during the server graceful shutdown (default: 5).

Thus, the default configuration can handle a backlog of up to 500 calls. By increasing both values, you can reduce the number of lost disconnect notifications.

If your application code doesn't rely on `disconnect` / `unsubscribe` callbacks, you can disable `Disconnect` calls completely (to avoid unnecessary load) by setting `--disable_disconnect` option or `ANYCABLE_DISABLE_DISCONNECT` env var.

\* It's (almost) impossible to guarantee that `disconnect` callbacks would be called for 100%. There is always a chance of a server crash or `kill -9` or something worse. Consider an alternative approach to tracking client states (see [example](https://github.com/anycable/anycable/issues/99#issuecomment-611998267)).

## GOMAXPROCS

We use [automaxprocs][] to automatically set the number of OS threads to match Linux container CPU quota in a virtualized environment, not a number of _visible_ CPUs (which is usually much higher).

This feature is enabled by default. You can opt-out by setting `GOMAXPROCS=0` (in this case, the default Go mechanism of defining the number of threads is used).

You can find the actual value for GOMAXPROCS in the starting logs:

```sh
INFO 2022-06-30T03:31:21.848Z context=main Starting AnyCable 1.2.0-c4f1c6e (with mruby 1.2.0 (2015-11-17)) (pid: 39705, open file limit: 524288, gomaxprocs: 8)
```

[automaxprocs]: https://github.com/uber-go/automaxprocs
[NATS]: https://nats.io


text:
package com.oefenmod;

import com.oefenmod.block.ModBlocks;
import com.oefenmod.crafting.ModCrafting;
import com.oefenmod.item.ModItems;

import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;

public class CommonProxy {

	public void preInit(FMLPreInitializationEvent e)
	{
		ModItems.init();
		ModBlocks.init();
		ModCrafting.init();
	}

	public void init(FMLInitializationEvent e)
	{

	}

	public void postInit(FMLPostInitializationEvent e)
	{

	}
}


text:
Generate secure, site-specific passwords from a secret master password. Since no database is used, passwords are available offline everywhere and anywhere.

![Screenshot](Screenshot.png)

---

### How to Use

**Enter the Name of the Service.**
Passcode uses the name of the service (domain) to cryptographically generate unique passwords.

**Enter your Master Password.**
This keeps your passwords secure and different from anyone else's for the same given domain. This is only password you'll ever need to remember.

**Generate!**
By combining the domain and master password, then running it through an encrpytion algorithm, a unique passcode is generated for you to use for that service.

---

**Secure by Design.**
Passcode was designed to be secure from the start. User information is not stored on a server. In fact, no data ever leaves the app running on the device itself.

**It's Algorithmic.**
To generate passwords, Passcode uses a standard SHA-256 encrpytion algorithm. This means that when Passcode is given the same input, it gives the same output. Already using a generated passcode and need to retrieve it? Simply generate it again. Since the algorithm is one-way, the master password cannot be retrieved given the outputted password.

**It's Ubiquitous.**
Since Passcode algorithmically generates passcodes, and doesn't rely on servers and networks to sync them, all your passwords are available at all times—even when not connected to the internet.

**Available Multi-Platform.**
No matter what computing platform you're on, Your passwords are available. Passcode is available natively for iOS, and Android. Browser extensions are available for Firefox, Chrome, and Safari. A website is available for easy access on any computer. Even a command-line application is available.

**Free & Open Source.**
The source code for Passcode, and all its applications is available for free. Because of this, Passcode will always be free and support for new platforms is easily added.


text:
#pragma once

#include "sgx_error.h"
#include "sgx_eid.h"     /* sgx_enclave_id_t */

#ifndef TRUE
# define TRUE 1
#endif

#ifndef FALSE
# define FALSE 0
#endif

#if defined(_MSC_VER)
#define TOKEN_FILENAME   "Enclave.token"
#define ENCLAVE_FILENAME "Enclave.signed.dll"
#elif defined(__GNUC__)
#define TOKEN_FILENAME   "enclave.token"
#define ENCLAVE_FILENAME "enclave.signed.so"
#endif

void print_error_message(sgx_status_t ret);
int initialize_enclave(sgx_enclave_id_t *eid);

#if defined(_MSC_VER)
int query_sgx_status();
#endif

#if defined(__cplusplus)
extern "C" {
#endif

//extern sgx_enclave_id_t global_eid;    /* global enclave id */

typedef struct _sgx_errlist_t {
    sgx_status_t err;
    const char *msg;
    const char *sug; /* Suggestion */
} sgx_errlist_t;

/* Error code returned by sgx_create_enclave */
static sgx_errlist_t sgx_errlist[] = {
    {
        SGX_ERROR_UNEXPECTED,
        "Unexpected error occurred.",
        NULL
    },
    {
        SGX_ERROR_INVALID_PARAMETER,
        "Invalid parameter.",
        NULL
    },
    {
        SGX_ERROR_OUT_OF_MEMORY,
        "Out of memory.",
        NULL
    },
    {
        SGX_ERROR_ENCLAVE_LOST,
        "Power transition occurred.",
        "Please refer to the sample \"PowerTransition\" for details."
    },
    {
        SGX_ERROR_INVALID_ENCLAVE,
        "Invalid enclave image.",
        NULL
    },
    {
        SGX_ERROR_INVALID_ENCLAVE_ID,
        "Invalid enclave identification.",
        NULL
    },
    {
        SGX_ERROR_INVALID_SIGNATURE,
        "Invalid enclave signature.",
        NULL
    },
    {
        SGX_ERROR_OUT_OF_EPC,
        "Out of EPC memory.",
        NULL
    },
    {
        SGX_ERROR_NO_DEVICE,
        "Invalid SGX device.",
        "Please make sure SGX module is enabled in the BIOS, and install SGX driver afterwards."
    },
    {
        SGX_ERROR_MEMORY_MAP_CONFLICT,
        "Memory map conflicted.",
        NULL
    },
    {
        SGX_ERROR_INVALID_METADATA,
        "Invalid enclave metadata.",
        NULL
    },
    {
        SGX_ERROR_DEVICE_BUSY,
        "SGX device was busy.",
        NULL
    },
    {
        SGX_ERROR_INVALID_VERSION,
        "Enclave version was invalid.",
        NULL
    },
    {
        SGX_ERROR_INVALID_ATTRIBUTE,
        "Enclave was not authorized.",
        NULL
    },
    {
        SGX_ERROR_ENCLAVE_FILE_ACCESS,
        "Can't open enclave file.",
        NULL
    },
};

#if defined(__cplusplus)
}
#endif


text:
package scifn.gen.impl.map

import scifn.gen.{FeatureGen, MacroCompanion, MacroFeatureGen}

import scala.language.experimental.macros
import scala.reflect.macros.blackbox

object MacroMapFeatureGen extends MacroCompanion[Map[String, Any]] {
  override protected[this] def instance[A <: Map[String, Any] : c.WeakTypeTag](c: blackbox.Context) =
    new MacroFeatureGen[A, c.type, c.universe.type](c)
      with FeatureGen[A, c.universe.type]
      with MapBasisCreator[A, c.universe.type]
}


text:
package com.kumuluz.ee.logs.messages;

/**
 * @author Rok Povse
 * @author Marko Skrjanec
 */
public interface ResourceInvokeLogMessage extends LogMessage {
}


text:
class OutPacket : public Packet {

public:

    virtual void write(TCPSocketClient *client) = 0;

};

#endif //OPENCVCLIENT_OUTPACKET_HPP


text:
package springfox.documentation.builders;

import springfox.documentation.service.CollectionFormat;
import springfox.documentation.service.ContentSpecification;
import springfox.documentation.service.ParameterSpecification;
import springfox.documentation.service.ParameterStyle;
import springfox.documentation.service.SimpleParameterSpecification;

public class CookieParameterSpecificationProvider implements ParameterSpecificationProvider {
  @Override
  public ParameterSpecification create(ParameterSpecificationContext context) {
    SimpleParameterSpecification simpleParameter = context.getSimpleParameter();
    SimpleParameterSpecification validSimpleParameter = null;
    ContentSpecification validContentEncoding = null;
    if (simpleParameter.getModel().getScalar().isPresent()) {
      validSimpleParameter = context.getSimpleParameterSpecificationBuilder()
          .copyOf(simpleParameter)
          .explode(simpleParameter.getExplode())
          .style(ParameterStyle.FORM)
          .build();
    } else if (simpleParameter.getModel().getCollection().isPresent()) {
      validSimpleParameter = context.getSimpleParameterSpecificationBuilder()
          .copyOf(simpleParameter)
          .explode(simpleParameter.getExplode())
          .style(ParameterStyle.FORM)
          .collectionFormat(simpleParameter.nullSafeIsExplode()
              ? CollectionFormat.MULTI
              : CollectionFormat.CSV)
          .build();
    }  else {
      validSimpleParameter = context.getSimpleParameterSpecificationBuilder()
          .copyOf(simpleParameter)
          .explode(simpleParameter.getExplode())
          .style(ParameterStyle.FORM)
          .collectionFormat(null)
          .build();
    }
    if (context.getContentParameter() != null) {
      validContentEncoding = context.getContentSpecificationBuilder()
          .copyOf(context.getContentParameter())
          .build();
    }
    return new ParameterSpecification(
        validSimpleParameter,
        validContentEncoding);
  }
}


text:
    Zulip supports both Git and Mercurial notifications from
    Bitbucket. This integration is for the new-style Bitbucket
    webhooks used by the Bitbucket SAAS service.

    First, create the stream you'd like to use for Bitbucket notifications,
    and subscribe all interested parties to this stream. The integration will
    use the default stream bitbucket if no stream is supplied in the
    hook; you still need to create the stream even if you are using this
    default.

The URL you create will be in the following format:

{{ external_api_uri_subdomain }}/v1/external/bitbucket2?api_key=abcdefgh&stream=bitbucket

    where api_key is the API key of your Zulip bot,
    and stream is the stream name you want the
    notifications sent to.

    Next, from your repository's web page, go to the Settings page and choose Webhooks on the left-hand side.
    Click Add webhook, set URL to the URL you created above. Remember to click the 'active' checkbox.
    Click Save.

    Congratulations! You're done!

    Example message:


text:
<!DOCTYPE html>

  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0"/>
  <title>Better Beer</title>

  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <link href="css/materialize.css" type="text/css" rel="stylesheet" media="screen,projection"/>
  <link href="css/style.css" type="text/css" rel="stylesheet" media="screen,projection"/>

Better Beer

Find

Help

Find

Help

      menu

Better Beer

The perfect beer for you

        Start Searching Now!

Our Mission

 The software will take multiple data values from different websites about the composition of different types of beers and calculate the average creating the 'Better' ratio for the desired beer type..

Connect

Submit Another

Start Searching

Get Help


text:
* Write Here

### TODO
* None


text:
import INext from "./../INext";
import IHttpRequest from "./IHttpRequest";
import IHttpResponse from "./IHttpResponse";

/**
 * A handler that is executed over a layer.
 */
type IHttpHandler = (req: IHttpRequest, res: IHttpResponse, next?: INext, error?: Error) => void;
export default IHttpHandler;


text:
import arez.annotations.ArezComponent;

@ArezComponent
public abstract class DefaultMethodsModel
  implements MyAnnotatedInterface
{
}


text:
'use strict';
var getWindow = require('./isWindow');

module.exports = function scrollTop(node, val) {
  var win = getWindow(node);

  if (val === undefined) return win ? 'pageXOffset' in win ? win.pageXOffset : win.document.documentElement.scrollLeft : node.scrollLeft;

  if (win) win.scrollTo(val, 'pageYOffset' in win ? win.pageYOffset : win.document.documentElement.scrollTop);else node.scrollLeft = val;
};


text:
<?hh // strict

require_once $_SERVER['DOCUMENT_ROOT'].'/core/controller/recipe/init.php';
require_once "demo.php";

class AssertRecipe extends Recipe implements RecipeWithDemo {

  protected function getName(): string {
    return 'Assert';
  }

  <<Override>>
  protected function getDescription(): ?string {
    return 'When you have values with unknown types, it is useful to make '.
      'some runtime assertions and have the type checker understand. This '.
      'recipe demonstrates one approach.';
  }

  protected function getFilenames(): Vector<string> {
    return Vector {
      'Assert.php',
    };
  }

  protected function getDocs(): Vector<(string, string)> {
    return Vector{
      tuple ('Mixed Types', 'hack.annotations.mixedtypes'),
      tuple ('Type Inference', 'hack.otherrulesandfeatures.typeinference'),
    };
  }

  public function getDemoFilename(): string {
    return 'demo.php';
  }

  public function getDemoResult(): string {
    return assert_main();
  }

  public function getDemoXHP(): ?:xhp {
    return null;
  }
}


text:
package info.arimateia.androidmvm.model;

import java.util.List;

/**
 * Created by felipets on 8/23/16.
 */

public class PeopleResults {
    private List<Person> results;

    public List<Person> getResults() {
        return results;
    }

    public void setResults(List<Person> results) {
        this.results = results;
    }
}


text:
Function Initialize-AzureAffinityGroup
{
    param(
        [parameter(Mandatory=$true)]
        [ValidateNotNullOrEmpty()]
        [string] $Name,

        [parameter(Mandatory=$true)]
        [ValidateNotNullOrEmpty()]
        [string] $Location
    )

    $affinityGroup = Find-AzureAffinityGroup -Name $Name

    if ($affinityGroup -ne $null)
    {
        return
    }

    Write-Host "Creating Azure Affinity Group '$Name'..."
    New-AzureAffinityGroup -Name $Name -Location $Location
    Write-Host "Successfully created Azure Affinity Group." -ForegroundColor Green
}


text:
module XYZ
  module ImportImplementationPackage
    # this should be precded by fn that adds the component to R8::Config[:repo][:base_directory] location
    def self.add(library_idh, impl_name)
      version = '0.0.1' #TODO: stub
      r8meta_type = :yaml #TODO: stub

      # put component meta info in hash
      components_hash = get_r8meta_hash(impl_name, r8meta_type: r8meta_type)
      library = library_idh.create_object().update_object!(:ref)

      # put implement info in hash
      hash_content = { 'library' => { library[:ref] => { 'component' => components_hash } } }
      Model.add_implementations!(hash_content, version, library[:ref], R8::Config[:repo][:base_directory], impl_name)

      # create in db
      Model.input_hash_content_into_model(library_idh.create_top(), hash_content)
    end

    def self.add_or_update_component(parent_idh, component_name, opts = {})
      component_hash = get_r8meta_hash(component_name, opts)
      add_implementation_id!(component_hash, parent_idh, component_name)
      Model.input_into_model(parent_idh, 'component' => { component_name => component_hash })
    end

    private

    def self.get_r8meta_hash(cmp_or_impl_name, opts = {})
      r8meta_type = opts[:r8meta_type]
      r8meta_file = find_r8meta_file(cmp_or_impl_name, r8meta_type)
      ret = nil
      case r8meta_type
       when :yaml
        require 'yaml'
        ret = YAML.load_file(r8meta_file)
       else
        fail Error.new("Type #{r8meta_type} not supported")
      end
      ret
    end

    def self.find_r8meta_file(cmp_or_impl_name, r8meta_type)
      file_ext = TypeMapping[r8meta_type]
      fail Error.new('illegal type extension') unless file_ext
      repo = cmp_or_impl_name.gsub(/__.+$/, '')
      files = Dir.glob("#{R8::Config[:repo][:base_directory]}/#{repo}/r8meta.*.#{file_ext}")
      if files.empty?
        fail Error.new('Cannot find valid r8meta file')
      elsif files.size > 1
        fail Error.new('Multiple r8meta files found')
      end
      files.first
    end
    TypeMapping = {
      yaml: 'yml'
    }

    def self.add_implementation_id!(component_hash, parent_idh, component_name)
      impl_display_name = component_name.gsub(/__.+$/, '')
      sp_hash = {
        cols: [:id],
        filter: [:and, [:eq, :display_name, impl_display_name],
                 [:eq, DB.parent_field(parent_idh[:model_name], :implementation), parent_idh.get_id()]]
      }
      rows = Model.get_objs(parent_idh.createMH(:implementation), sp_hash)
      fail Error.new("Error in finding implementation for component #{component_name}") unless rows.size = 1
      component_hash.merge!(implementation_id: rows.first[:id])
    end

    def self.update_implementation_ids(library_idh, impl_name, component_refs)
      # TODO: can more effiiently implement witrh update_from_select
      library_id = library_idh.get_id()
      cmp_mh = library_idh.createMH(:component)
      sp_hash = {
        cols: [:id],
        filter: [:and, [:oneof, :ref, component_refs],
                 [:eq, DB.parent_field(:library, :component), library_id]]
      }
      cmps = Model.get_objs(cmp_mh, sp_hash)

      sp_hash = {
        cols: [:id],
        filter: [:and, [:eq, :display_name, impl_name],
                 [:eq, DB.parent_field(:library, :implementation), library_id]]
      }
      impl_id = Model.get_objs(library_idh.createMH(:implementation), sp_hash).first[:id]

      update_rows = cmps.map do |cmp|
        {
          id: cmp[:id],
          implemtation_id: impl_id
        }
      end
      Model.update_from_rows(cmp_mh, update_rows)
    end
  end
end


text:
id: OUTLINE
title: Goals of the documentation
layout: docs
prev: 09.1-tutorial.html
---
- Flow of docs should mimic progression of questions a new user would ask
- High information density -- assume the reader is adept at JS
- Talk about best practices
- JSFiddles for all code samples
- Provide background for some of the design decisions
- Less words less words less words!

## Outline

Motivation / Why React?
- Declarative (simple)
- Components (separation of concerns)
- Give it 5 minutes

Displaying data
- Hello world example
- Reactive updates
- Components are just functions
- JSX syntax (link to separate doc?)
- JSX gotchas

Interactivity and dynamic UIs
- Click handler example
- Event handlers / synthetic events (link to w3c docs)
- Under the hood: autoBind and event delegation (IE8 notes)
- React is a state machine
- How state works
- What components should have state?
- What should go in state?
- What shouldn't go in state?

Scaling up: using multiple components
- Motivation: separate concerns
- Composition example
- Ownership (and owner vs. parent)
- Children
- Data flow (one-way data binding)
- A note on performance

Building effective reusable components
- You should build a reusable component library (CSS, testing etc)
- Prop validation
- Transferring props: a shortcut
- Mixins
- Testing

Forms

Working with the browser
- The mock DOM
- Refs / getDOMNode()
- More about refs
- Component lifecycle
- Browser support and polyfills

Working with your environment
- CDN-hosted React
- Using master
- In-browser JSX transform
- Productionizing: precompiled JSX
- Helpful open-source projects

Integrating with other UI libraries
- Using jQuery plugins
- Letting jQuery manage React components
- Using with Backbone.View
- CoffeeScript
- Moving from Handlebars to React: an example

Server / static rendering
- Motivation
- Simple example
- How does it work? (No DOM)
- Rendr + React

Big ideas
- Animation
- Bootstrap bindings (responsive grids)
- Reactive CSS
- Web workers
- Native views

Case studies
- Comment box tutorial from scratch
- From HTML mock to application: React one-hour email
- Jordan's LikeToggler example

Reference
- API
- DOM differences


text:
class Renderable
{
private:

	Mesh& _mesh;
	Matrix4f _transform;

public:

	Renderable(Mesh& mesh, Matrix4f transform = Matrix4f::Translation(0,0,0));

	Mesh& getMesh();
	Matrix4f& getTransform();

};


text:
package com.google.appengine.tools.cloudstorage;

import static com.google.appengine.tools.cloudstorage.RetryParams.DEFAULT_REQUEST_TIMEOUT_RETRY_FACTOR;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Strings.isNullOrEmpty;

import com.google.common.collect.ImmutableMap;

import java.io.Serializable;
import java.util.Map;
import java.util.Objects;

/**
 * A class to hold options for the GcsService.
 */
public class GcsServiceOptions implements Serializable {

  private static final long serialVersionUID = 6595783378343634936L;
  public static final GcsServiceOptions DEFAULT = new Builder().build();

  private final RetryParams retryParams;
  private final Integer defaultWriteBufferSize;
  private final String pathDelimiter;
  private final Map<String, String> headers;

  /**
   * GcsServiceOptions builder.
   */
  public static final class Builder {

    private RetryParams retryParams;
    private Integer defaultWriteBufferSize;
    private String pathDelimiter = "/";
    private Map<String, String> headers = ImmutableMap.of();

    public Builder setRetryParams(RetryParams retryParams) {
      this.retryParams = retryParams;
      return this;
    }

    /**
     * @param defaultWriteBufferSize the size of the default write buffer in bytes
     */
    public Builder setDefaultWriteBufferSize(Integer defaultWriteBufferSize) {
      this.defaultWriteBufferSize = defaultWriteBufferSize;
      return this;
    }

    public Builder setPathDelimiter(String pathDelimiter) {
      checkArgument(isNullOrEmpty(pathDelimiter), "pathDelimiter must not be null or empty");
      this.pathDelimiter = pathDelimiter;
      return this;
    }

    public Builder setHttpHeaders(Map<String, String> headers) {
      this.headers = ImmutableMap.copyOf(checkNotNull(headers));
      return this;
    }

    public GcsServiceOptions build() {
      return new GcsServiceOptions(this);
    }
  }

  private GcsServiceOptions(Builder builder) {
    retryParams = new RetryParams.Builder(
        firstNonNull(builder.retryParams, RetryParams.getDefaultInstance()))
        .requestTimeoutRetryFactor(DEFAULT_REQUEST_TIMEOUT_RETRY_FACTOR)
        .build();
    defaultWriteBufferSize = builder.defaultWriteBufferSize;
    pathDelimiter = builder.pathDelimiter;
    headers = builder.headers;
  }

  private static <T> T firstNonNull(T v1, T v2) {
    return v1 != null ? v1 : v2;
  }

  public RetryParams getRetryParams() {
    return retryParams;
  }

  public Integer getDefaultWriteBufferSize() {
    return defaultWriteBufferSize;
  }

  public String getPathDelimiter() {
    return pathDelimiter;
  }

  public Map<String, String> getHttpHeaders() {
    return headers;
  }

  @Override
  public int hashCode() {
    return Objects.hash(retryParams, defaultWriteBufferSize, pathDelimiter, headers);
  }

  @Override
  public boolean equals(Object obj) {
    if (this == obj) {
      return true;
    }
    if (obj == null) {
      return false;
    }
    if (getClass() != obj.getClass()) {
      return false;
    }
    GcsServiceOptions other = (GcsServiceOptions) obj;
    return Objects.equals(retryParams, other.retryParams)
        && Objects.equals(defaultWriteBufferSize, other.defaultWriteBufferSize)
        && Objects.equals(pathDelimiter, other.pathDelimiter)
        && Objects.equals(headers, other.headers);
  }

  @Override
  public String toString() {
    return "GcsServiceOptions [retryParams=" + retryParams + ", defaultWriteBufferSize="
        + defaultWriteBufferSize + ", pathDelimiter=" + pathDelimiter + ", headers="
        + headers + "]";
  }
}


text:
struct mouse_state {
	int axis[2];
	int button[3];
};

class cMouse {
  private:
	pthread_t thread;
	bool active;
	int mouse_fd;
	input_event *mouse_ev;
	mouse_state mouse_st;
	char name[256];

  protected:
  public:
	cMouse();
	~cMouse();
	static void* loop(void* obj);
	void readEv();
	mouse_state getMouseState();
};

#endif


text:
package com.nortal.spring.cw.core.web.component.modal;

import com.nortal.spring.cw.core.web.component.composite.ComponentType;

public class BaseModalComponent extends AbstractModalDialogComponent {
   private static final long serialVersionUID = 1L;

   private ModalType type;

   public BaseModalComponent(ModalType type, String componentName) {
      super(componentName);
      this.type = type;
   }

   @Override
   public ModalType getType() {
      return type;
   }

   @Override
   public ComponentType getComponentType() {
      return ComponentType.MODAL;
   }

}


text:
ssh-keygen -q -N "" -t rsa -f /root/.ssh/id_rsa
cat /root/.ssh/id_rsa.pub >> /root/.ssh/authorized_keys
echo "    StrictHostKeyChecking no                     " >> /etc/ssh/ssh_config
service ssh restart


text:
"""
    Name: ble_utils.py
    Author: Francis T
    Description:
        Source code for generic BLE functionality
"""
from bluepy.btle import Scanner, Peripheral, BTLEException
#from dryad.cache_node import NCLAS_UNKNOWN, NCLAS_BLUNO, NCLAS_PARROT
import logging
from time import sleep, time

UUID_BLUNO  = "0000dfb0-0000-1000-8000-00805f9b34fb"
UUID_PARROT = "39e1fa00-84a8-11e2-afba-0002a5d5c51b"

NCLAS_UNKNOWN   = "UNKNOWN"
NCLAS_UNUSED    = "UNUSED"
NCLAS_SENSOR    = "SENSOR"

NTYPE_UNKNOWN   = "UNKNOWN"
NTYPE_UNUSED    = "UNUSED"
NTYPE_BLUNO     = "BLUNO"
NTYPE_PARROT    = "PARROT"

MAX_CONN_RETRIES = 5
CONN_ATTEMPT_INTERVAL = 1.5
CONN_ATTEMPT_TIMEOUT    = 35.0

TBL_SVC_ID = [
    { 'uuid' : UUID_BLUNO, 'device_type' : NTYPE_BLUNO },
    { 'uuid' : UUID_PARROT, 'device_type' : NTYPE_PARROT },
]

module_logger = logging.getLogger("main.ble_utils")

# @desc     Scans for nearby BLE devices
# @return   A list of Bluepy ScanEntry objects
def scan_for_devices(num):
    scanner = Scanner()
    module_logger.info("Scanning for devices...")
    scanned_devices = scanner.scan(20.0)
    module_logger.info("Scan finished")
    return scanned_devices

# @desc     Performs checks to determine the type of Sensor Node this BLE device is
# @return   A String containing the device class
def check_device_type(address, name):
    device_type = NTYPE_UNKNOWN

    # Establish a connection to the peripheral
    ppap = connect(address)
    if ppap == None:
        module_logger.error("Could not connect to device")
        return device_type

    # Return the device type based on the BLE services on the device
    for ref_service in TBL_SVC_ID:
        try:
            service = ppap.getServiceByUUID(ref_service['uuid'])
        except BTLEException:
            module_logger.error("Service {} not found. ".format(ref_service['uuid']))
            continue

        if not service == None:
            ppap.disconnect()
            device_type = ref_service['device_type']

            module_logger.info("Service {} found. ".format(ref_service['uuid']))
            module_logger.info("Device type is {}. ".format(device_type))
            break

    # If the device did not satisfy any of the service-by-uuid checks, flag it as
   #   unusable
    if device_type == NTYPE_UNKNOWN:
        device_type = NTYPE_UNUSED

    return device_type

def discover_node_category(node_addr, node_id):
    node_class  = NCLAS_UNKNOWN
    node_type   = NTYPE_UNKNOWN

    # Check the device type
    node_type = check_device_type(node_addr, node_id)

    if ( not node_type == NTYPE_UNKNOWN ):
        # If the device type is either BLUNO or PARROT_FP, then
        #   classify it as a SENSOR device
        if ( node_type == NTYPE_BLUNO ) or ( node_type == NTYPE_PARROT ):
            node_class = NCLAS_SENSOR

        elif node_type == NTYPE_UNUSED:
            node_class = NCLAS_UNUSED

    return (node_type, node_class)

def connect(address):
    module_logger.info("[{}] Attempting to connect".format(address))

    peripheral = None
    retries = 0
    is_connected = False
    start_time = time()

    while (peripheral is None) and (retries < MAX_CONN_RETRIES):
        conn_success = True
        conn_attempt_time = time()

        try:
            peripheral = Peripheral(address, "public")
        except Exception as e:
            module_logger.error("[{}] Connecton failed: {}".format(address, e.message))
            conn_success = False

        elapsed_time = time() - conn_attempt_time

        # End the loop if connection is successful
        if conn_success:
            module_logger.debug("[{}] Overall connect time: {} secs, Total retries: {}".format(address, time() - start_time, retries))
            is_connected = True
            break

        # Put out a warning and cut down retries if our connect attempt exceeds thresholds
        if elapsed_time > CONN_ATTEMPT_TIMEOUT:
            module_logger.debug("[{}] Connect attempt took {} secs".format(address, elapsed_time))
            module_logger.warning("[{}] Connect attempt exceeds threshold. Is the device nearby?".format(address))
            break

        retries += 1

        sleep(CONN_ATTEMPT_INTERVAL)
        module_logger.debug("[{}] Attempting to connect ({})...".format(address, retries))

    # Check if a successful connection was established
    if (is_connected):
        module_logger.info("[{}] Connected.".format(address))

        return peripheral

    # Otherwise, indicate that a connection problem has occurred
    module_logger.error("[{}] Failed to connect to device".format(address))

    return None


text:
package org.springframework.data.neo4j.transactions.service;

import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.neo4j.transactions.domain.User;
import org.springframework.data.neo4j.transactions.repo.UserRepository;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author vince
 */
@Component
public class ServiceB {

    @Autowired
    private UserRepository userRepository;

    @Transactional(rollbackFor = Exception.class)
    public void update() throws Exception {
        getBilbo();
        throw new Exception();
    }

    public User getBilbo() {
        Collection<User> userList = userRepository.findUserByName("Bilbo Baggins");
        if (userList.iterator().hasNext()) {
            return userList.iterator().next();
        }
        return null;
    }
}


text:
name: Julie Johnson
tagline: Jules
layout: default
modal-id: johnson02
img: johnson02.png
institution: Blackburn College, Blackburn, Lancashire
institutionURL: http://www.blackburn.ac.uk
institutionLogo: blackburnCollegeLogo.jpg
website: https://juliej61.wordpress.com/
bio: I am a computing lecturer at Blackburn College where I have been teaching for over 15 years. My main subjects are PC Technician, troubleshooting and repair and maintenance. I have some knowledge of Networking and mobile communication. I am currently running a Girl Geek club within the college to encourage more females into computing and technology. We have created many projects including an interactive quilt, satellite in a coca cola can and used Makey Makey with the Childrens University. We are modding computer cases and looking at any ideas for future projects. I also belong to a new hackspace in Blackburn were we have currently 3 member including me. I have very basic knowledge of Arduino through using a lillypad arduino for e-textiles. I love creating and breaking things with some success at putting them back together. I want to do more.

social:
  - title: twitter
    url: https://twitter.com/juliejohnson61
  - title: linkedin
    url: https://www.linkedin.com/pub/julie-johnson/32/971/304

---


text: HADRIAN_NIX=YES hadrian/build.stack.sh


text:
module Aws::NetworkManager

  # When NetworkManager returns an error response, the Ruby SDK constructs and raises an error.
  # These errors all extend Aws::NetworkManager::Errors::ServiceError < {Aws::Errors::ServiceError}
  #
  # You can rescue all NetworkManager errors using ServiceError:
  #
  #     begin
  #       # do stuff
  #     rescue Aws::NetworkManager::Errors::ServiceError
  #       # rescues all NetworkManager API errors
  #     end
  #
  #
  # ## Request Context
  # ServiceError objects have a {Aws::Errors::ServiceError#context #context} method that returns
  # information about the request that generated the error.
  # See {Seahorse::Client::RequestContext} for more information.
  #
  # ## Error Classes
  # * {AccessDeniedException}
  # * {ConflictException}
  # * {CoreNetworkPolicyException}
  # * {InternalServerException}
  # * {ResourceNotFoundException}
  # * {ServiceQuotaExceededException}
  # * {ThrottlingException}
  # * {ValidationException}
  #
  # Additionally, error classes are dynamically generated for service errors based on the error code
  # if they are not defined above.
  module Errors

    extend Aws::Errors::DynamicErrors

    class AccessDeniedException < ServiceError

      # @param [Seahorse::Client::RequestContext] context
      # @param [String] message
      # @param [Aws::NetworkManager::Types::AccessDeniedException] data
      def initialize(context, message, data = Aws::EmptyStructure.new)
        super(context, message, data)
      end

      # @return [String]
      def message
        @message || @data[:message]
      end
    end

    class ConflictException < ServiceError

      # @param [Seahorse::Client::RequestContext] context
      # @param [String] message
      # @param [Aws::NetworkManager::Types::ConflictException] data
      def initialize(context, message, data = Aws::EmptyStructure.new)
        super(context, message, data)
      end

      # @return [String]
      def message
        @message || @data[:message]
      end

      # @return [String]
      def resource_id
        @data[:resource_id]
      end

      # @return [String]
      def resource_type
        @data[:resource_type]
      end
    end

    class CoreNetworkPolicyException < ServiceError

      # @param [Seahorse::Client::RequestContext] context
      # @param [String] message
      # @param [Aws::NetworkManager::Types::CoreNetworkPolicyException] data
      def initialize(context, message, data = Aws::EmptyStructure.new)
        super(context, message, data)
      end

      # @return [String]
      def message
        @message || @data[:message]
      end

      # @return [String]
      def errors
        @data[:errors]
      end
    end

    class InternalServerException < ServiceError

      # @param [Seahorse::Client::RequestContext] context
      # @param [String] message
      # @param [Aws::NetworkManager::Types::InternalServerException] data
      def initialize(context, message, data = Aws::EmptyStructure.new)
        super(context, message, data)
      end

      # @return [String]
      def message
        @message || @data[:message]
      end

      # @return [String]
      def retry_after_seconds
        @data[:retry_after_seconds]
      end
    end

    class ResourceNotFoundException < ServiceError

      # @param [Seahorse::Client::RequestContext] context
      # @param [String] message
      # @param [Aws::NetworkManager::Types::ResourceNotFoundException] data
      def initialize(context, message, data = Aws::EmptyStructure.new)
        super(context, message, data)
      end

      # @return [String]
      def message
        @message || @data[:message]
      end

      # @return [String]
      def resource_id
        @data[:resource_id]
      end

      # @return [String]
      def resource_type
        @data[:resource_type]
      end

      # @return [String]
      def context
        @data[:context]
      end
    end

    class ServiceQuotaExceededException < ServiceError

      # @param [Seahorse::Client::RequestContext] context
      # @param [String] message
      # @param [Aws::NetworkManager::Types::ServiceQuotaExceededException] data
      def initialize(context, message, data = Aws::EmptyStructure.new)
        super(context, message, data)
      end

      # @return [String]
      def message
        @message || @data[:message]
      end

      # @return [String]
      def resource_id
        @data[:resource_id]
      end

      # @return [String]
      def resource_type
        @data[:resource_type]
      end

      # @return [String]
      def limit_code
        @data[:limit_code]
      end

      # @return [String]
      def service_code
        @data[:service_code]
      end
    end

    class ThrottlingException < ServiceError

      # @param [Seahorse::Client::RequestContext] context
      # @param [String] message
      # @param [Aws::NetworkManager::Types::ThrottlingException] data
      def initialize(context, message, data = Aws::EmptyStructure.new)
        super(context, message, data)
      end

      # @return [String]
      def message
        @message || @data[:message]
      end

      # @return [String]
      def retry_after_seconds
        @data[:retry_after_seconds]
      end
    end

    class ValidationException < ServiceError

      # @param [Seahorse::Client::RequestContext] context
      # @param [String] message
      # @param [Aws::NetworkManager::Types::ValidationException] data
      def initialize(context, message, data = Aws::EmptyStructure.new)
        super(context, message, data)
      end

      # @return [String]
      def message
        @message || @data[:message]
      end

      # @return [String]
      def reason
        @data[:reason]
      end

      # @return [String]
      def fields
        @data[:fields]
      end
    end

  end
end


text:
import re
from collections import namedtuple

from . import mql
from . import schema as S
from .base import Document, partialmethod
from .util import reify

backref = namedtuple('backref', 'cname fname')

class FieldCollection(Document):

    def __init__(self, fields):
        super(FieldCollection, self).__init__(
            (f._name, f) for f in fields)

    def make_schema(self, metadata, **options):
        d_schema = {name: f._schema for name, f in self.items()}
        s_schema = S.compile_schema(metadata, d_schema, **options)
        return s_schema

    def bind_metadata(self, metadata):
        for fld in self.values():
            fld.bind_metadata(metadata)

    def __dir__(self):
        return self.keys()

class Field(object):

    def __init__(self, name, schema, **options):
        self._name = name
        self._orig_schema = schema
        self._options = options
        self.backref = options.pop('backref', None)
        self._metadata = None

    def bind_metadata(self, metadata):
        self._metadata = metadata

    @reify
    def _schema(self):
        if isinstance(self._orig_schema, type):
            if issubclass(self._orig_schema, S.Validator):
                return self._orig_schema(**self._options)
        return S.compile_schema(
            self._metadata, self._orig_schema, **self._options)

    def __repr__(self):
        return '<Field {}: {}>'.format(self._name, self._orig_schema)

    def __get__(self, inst, cls=None):
        if inst is None:
            return self
        return inst[self._name]

    def __set__(self, inst, value):
        inst[self._name] = self._schema.validate(value)

    def __getattr__(self, name):
        return self[name]

    def __getitem__(self, name):
        from barin import manager
        subname = '{}.{}'.format(self._name, name)
        try:
            subfield = self._schema[name]
        except KeyError:
            return Field(subname, S.Anything())
        if isinstance(subfield, Field):
            return Field(subname, subfield._schema)
        elif isinstance(subfield, S.Validator):
            return Field(subname, subfield)
        elif isinstance(subfield, manager.ClassManager):
            return Field(subname, subfield)
        else:
            raise KeyError(name)

    # Sort operators
    def __pos__(self):
        return (self._name, 1)

    def __neg__(self):
        return (self._name, -1)

    # Update operators
    def _uop(self, op, value):
        return mql.Clause({op: {self._name: value}})

    inc = partialmethod(_uop, '$inc')
    mul = partialmethod(_uop, '$mul')
    rename = partialmethod(_uop, '$rename')
    set_on_insert = partialmethod(_uop, '$setOnInsert')
    set = partialmethod(_uop, '$set')
    unset = partialmethod(_uop, '$unset')
    min = partialmethod(_uop, '$min')
    max = partialmethod(_uop, '$max')
    current_date = partialmethod(_uop, '$currentDate')
    add_to_set = partialmethod(_uop, '$addToSet')
    pop = partialmethod(_uop, '$pop')
    pull_all = partialmethod(_uop, '$pullAll')
    pull = partialmethod(_uop, '$pull')
    push_all = partialmethod(_uop, '$pushAll')
    push = partialmethod(_uop, '$push')
    bit = partialmethod(_uop, '$bit')

    # Query operators
    def _qop(self, op, value):
        return mql.Clause({self._name: {op: value}})

    def __eq__(self, value):
        return mql.Clause({self._name: value})

    __ne__ = partialmethod(_qop, '$ne')
    __gt__ = partialmethod(_qop, '$gt')
    __ge__ = partialmethod(_qop, '$gte')
    __lt__ = partialmethod(_qop, '$lt')
    __le__ = partialmethod(_qop, '$lte')
    in_ = partialmethod(_qop, '$in')
    nin = partialmethod(_qop, '$nin')
    exists = partialmethod(_qop, '$exists')
    type = partialmethod(_qop, '$type')
    where = partialmethod(_qop, '$where')
    geo_within = partialmethod(_qop, '$geoWithin')
    geo_intersects = partialmethod(_qop, '$geoIntersects')
    all = partialmethod(_qop, '$all')
    elem_match = partialmethod(_qop, '$elemMatch')
    size = partialmethod(_qop, '$size')
    bits_all_set = partialmethod(_qop, '$bitsAllSet')
    bits_any_set = partialmethod(_qop, '$bitsAnySet')
    bits_all_clear = partialmethod(_qop, '$bitsAllClear')
    bits_any_clear = partialmethod(_qop, '$bitsAnyClear')

    def mod(self, divisor, remainder):
        return mql.Clause(
            {self._name: {'$mod': [divisor, remainder]}})

    def startswith(self, prefix):
        regex = re.compile('^' + re.escape(prefix))
        return mql.Clause({self._name: regex})

    def regex(self, regex, options=None):
        spec = {'$regex': regex}
        if options is not None:
            spec['$options'] = options
        return mql.Clause({self._name: spec})

    def text(
            self, search,
            language=None, case_sensitive=False, diacritic_sensitive=False):
        spec = {'$search': search}
        if language:
            spec['$language'] = language
        if case_sensitive:
            spec['$caseSensitive'] = case_sensitive
        if diacritic_sensitive:
            spec['$diacriticSensitive'] = diacritic_sensitive
        return mql.Clause({self._name: spec})

    def near(self, value, min_distance=None, max_distance=None):
        spec = {'$near': value}
        if min_distance is not None:
            spec['$minDistance'] = min_distance
        if max_distance is not None:
            spec['$maxDistance'] = max_distance
        return mql.Clause({self._name: spec})

    def near_sphere(self, value, min_distance=None, max_distance=None):
        spec = {'$nearSphere': value}
        if min_distance is not None:
            spec['$minDistance'] = min_distance
        if max_distance is not None:
            spec['$maxDistance'] = max_distance
        return mql.Clause({self._name: spec})


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;

namespace ForSerial.Objects.TypeDefinitions
{
    public class JsonDictionaryDefinition : StructureDefinition
    {
        protected JsonDictionaryDefinition(Type dictionaryType)
            : base(dictionaryType)
        {
            KeyTypeDef = TypeCache.GetTypeDefinition(dictionaryType.GetGenericInterfaceType(typeof(IDictionary<,>), 0));
            ValueTypeDef = TypeCache.GetTypeDefinition(dictionaryType.GetGenericInterfaceType(typeof(IDictionary<,>), 1));
        }

        public TypeDefinition ValueTypeDef { get; set; }
        public TypeDefinition KeyTypeDef { get; set; }

        internal static JsonDictionaryDefinition CreateDictionaryDefinition(Type type)
        {
            Type keyType = type.GetGenericInterfaceType(typeof(IDictionary<,>));
            return IsJsonCompatibleKeyType(keyType)
                ? new JsonDictionaryDefinition(type)
                : null;
        }

        private static bool IsJsonCompatibleKeyType(Type keyType)
        {
            TypeCodeType typeCodeType = keyType.GetTypeCodeType();
            return typeCodeType == TypeCodeType.String
                || typeCodeType == TypeCodeType.Number;
        }

        public override void Read(object input, ObjectReader reader, Writer writer, PartialOptions optionsOverride)
        {
            IDictionary dictionary = input as IDictionary;
            if (dictionary == null) return;

            if (ReferenceStructure(input, reader, optionsOverride))
                return;

            if (ShouldWriteTypeIdentifier(reader.Options, optionsOverride))
                writer.BeginStructure(CurrentTypeResolver.GetTypeIdentifier(Type), reader.GetType());
            else
                writer.BeginStructure(Type);

            foreach (object key in dictionary.Keys)
            {
                // Convert.ToString is in case the keys are numbers, which are represented
                // as strings when used as keys, but can be indexed with numbers in JavaScript
                string name = Convert.ToString(key, CultureInfo.InvariantCulture);
                object value = dictionary[key];

                writer.AddProperty(name);
                ValueTypeDef.ReadObject(value, reader, writer, PartialOptions.Default);
            }

            writer.EndStructure();
        }

        public override ObjectContainer CreateStructure()
        {
            return new DictionaryStructure(this);
        }

        public override ObjectContainer CreateStructureForProperty(string name)
        {
            return ValueTypeDef.CreateStructure();
        }

        public override ObjectContainer CreateSequenceForProperty(string name)
        {
            return ValueTypeDef.CreateSequence();
        }

        public override ObjectOutput CreateValueForProperty(string name, object value)
        {
            return ValueTypeDef.CreateValue(value);
        }

        public object ConstructNew()
        {
            return ConstructDefault();
        }
    }
}


text:
title:  inQuire
date:  16/10/2020
---

#### inQuire

`Describe a hypothetical scenario of having the capability for development but not enough time.`

`Describe another scenario of having enough time but not the capability for development.`

`How has sin almost obliterated the image of God in humanity? Why is it "almost"?`

`Name aspects of the worldview presented by Satan in Genesis 3 also found in contemporary worldviews.`

`How do modern theories and values of education reflect God's values?`

`How do modern theories and values of education reflect Satan's values?`

`How are redemption and education linked?`


text:
package models

type Formatter interface {
	Format() error
}