text:
<?php

class MicroMvcEventsTest extends PHPUnit_Framework_TestCase
{

	public function testMicroBeforeHandlers()
	{

		$trace = array();

		$app = new Phalcon\Mvc\Micro();

		$app->before(function() use (&$trace) {
			$trace[] = 1;
			return false;
		});

		$app->before(function() use (&$trace) {
			$trace[] = 1;
			return false;
		});

		$app->map('/blog', function() use (&$trace) {
			$trace[] = 1;
		});

		$app->handle('/blog');

		$this->assertEquals(count($trace), 1);
	}

	public function testMicroAfterHandlers()
	{

		$trace = array();

		$app = new Phalcon\Mvc\Micro();

		$app->after(function() use (&$trace) {
			$trace[] = 1;
		});

		$app->after(function() use (&$trace) {
			$trace[] = 1;
		});

		$app->map('/blog', function() use (&$trace) {
			$trace[] = 1;
		});

		$app->handle('/blog');

		$this->assertEquals(count($trace), 3);
	}

	public function testMicroFinishHandlers()
	{

		$trace = array();

		$app = new Phalcon\Mvc\Micro();

		$app->finish(function() use (&$trace) {
			$trace[] = 1;
		});

		$app->finish(function() use (&$trace) {
			$trace[] = 1;
		});

		$app->map('/blog', function() use (&$trace) {
			$trace[] = 1;
		});

		$app->handle('/blog');

		$this->assertEquals(count($trace), 3);
	}

	public function testMicroEvents()
	{

		$trace = array();

		$eventsManager = new Phalcon\Events\Manager();

		$eventsManager->attach('micro', function($event) use (&$trace) {
			$trace[$event->getType()] = true;
		});

		$app = new Phalcon\Mvc\Micro();

		$app->setEventsManager($eventsManager);

		$app->map('/blog', function() {

		});

		$app->handle('/blog');

		$this->assertEquals($trace, array(
			'beforeHandleRoute' => true,
			'beforeExecuteRoute' => true,
			'afterExecuteRoute' => true,
			'afterHandleRoute' => true,
		));
	}

}


text:
package aggregate

import (
	"sync"

	"istio.io/istio/pilot/pkg/model"
	"istio.io/istio/pilot/pkg/serviceregistry"
	"istio.io/istio/pilot/pkg/serviceregistry/provider"
	"istio.io/istio/pkg/cluster"
	"istio.io/istio/pkg/config/host"
	"istio.io/istio/pkg/config/labels"
	"istio.io/istio/pkg/config/mesh"
	"istio.io/pkg/log"
)

// The aggregate controller does not implement serviceregistry.Instance since it may be comprised of various
// providers and clusters.
var (
	_ model.ServiceDiscovery    = &Controller{}
	_ model.AggregateController = &Controller{}
)

// Controller aggregates data across different registries and monitors for changes
type Controller struct {
	meshHolder mesh.Holder

	// The lock is used to protect the registries and controller's running status.
	storeLock  sync.RWMutex
	registries []*registryEntry
	// indicates whether the controller has run.
	// if true, all the registries added later should be run manually.
	running bool

	handlers          model.ControllerHandlers
	handlersByCluster map[cluster.ID]*model.ControllerHandlers
	model.NetworkGatewaysHandler
}

type registryEntry struct {
	serviceregistry.Instance
	// stop if not nil is the per-registry stop chan. If null, the server stop chan should be used to Run the registry.
	stop <-chan struct{}
}

type Options struct {
	MeshHolder mesh.Holder
}

// NewController creates a new Aggregate controller
func NewController(opt Options) *Controller {
	return &Controller{
		registries:        make([]*registryEntry, 0),
		meshHolder:        opt.MeshHolder,
		running:           false,
		handlersByCluster: map[cluster.ID]*model.ControllerHandlers{},
	}
}

func (c *Controller) addRegistry(registry serviceregistry.Instance, stop <-chan struct{}) {
	c.registries = append(c.registries, &registryEntry{Instance: registry, stop: stop})

	// Observe the registry for events.
	registry.AppendNetworkGatewayHandler(c.NotifyGatewayHandlers)
	registry.AppendServiceHandler(c.handlers.NotifyServiceHandlers)
	registry.AppendServiceHandler(func(service *model.Service, event model.Event) {
		for _, handlers := range c.getClusterHandlers() {
			handlers.NotifyServiceHandlers(service, event)
		}
	})
}

func (c *Controller) getClusterHandlers() []*model.ControllerHandlers {
	c.storeLock.Lock()
	defer c.storeLock.Unlock()
	out := make([]*model.ControllerHandlers, 0, len(c.handlersByCluster))
	for _, handlers := range c.handlersByCluster {
		out = append(out, handlers)
	}
	return out
}

// AddRegistry adds registries into the aggregated controller.
// If the aggregated controller is already Running, the given registry will never be started.
func (c *Controller) AddRegistry(registry serviceregistry.Instance) {
	c.storeLock.Lock()
	defer c.storeLock.Unlock()
	c.addRegistry(registry, nil)
}

// AddRegistryAndRun adds registries into the aggregated controller and makes sure it is Run.
// If the aggregated controller is running, the given registry is Run immediately.
// Otherwise, the given registry is Run when the aggregate controller is Run, using the given stop.
func (c *Controller) AddRegistryAndRun(registry serviceregistry.Instance, stop <-chan struct{}) {
	if stop == nil {
		log.Warnf("nil stop channel passed to AddRegistryAndRun for registry %s/%s", registry.Provider(), registry.Cluster())
	}
	c.storeLock.Lock()
	defer c.storeLock.Unlock()
	c.addRegistry(registry, stop)
	if c.running {
		go registry.Run(stop)
	}
}

// DeleteRegistry deletes specified registry from the aggregated controller
func (c *Controller) DeleteRegistry(clusterID cluster.ID, providerID provider.ID) {
	c.storeLock.Lock()
	defer c.storeLock.Unlock()

	if len(c.registries) == 0 {
		log.Warnf("Registry list is empty, nothing to delete")
		return
	}
	index, ok := c.getRegistryIndex(clusterID, providerID)
	if !ok {
		log.Warnf("Registry %s/%s is not found in the registries list, nothing to delete", providerID, clusterID)
		return
	}
	c.registries[index] = nil
	c.registries = append(c.registries[:index], c.registries[index+1:]...)
	log.Infof("%s registry for the cluster %s has been deleted.", providerID, clusterID)
}

// GetRegistries returns a copy of all registries
func (c *Controller) GetRegistries() []serviceregistry.Instance {
	c.storeLock.RLock()
	defer c.storeLock.RUnlock()

	// copy registries to prevent race, no need to deep copy here.
	out := make([]serviceregistry.Instance, len(c.registries))
	for i := range c.registries {
		out[i] = c.registries[i]
	}
	return out
}

func (c *Controller) getRegistryIndex(clusterID cluster.ID, provider provider.ID) (int, bool) {
	for i, r := range c.registries {
		if r.Cluster().Equals(clusterID) && r.Provider() == provider {
			return i, true
		}
	}
	return 0, false
}

// Services lists services from all platforms
func (c *Controller) Services() []*model.Service {
	// smap is a map of hostname (string) to service index, used to identify services that
	// are installed in multiple clusters.
	smap := make(map[host.Name]int)
	index := 0
	services := make([]*model.Service, 0)
	// Locking Registries list while walking it to prevent inconsistent results
	for _, r := range c.GetRegistries() {
		svcs := r.Services()
		if r.Provider() != provider.Kubernetes {
			index += len(svcs)
			services = append(services, svcs...)
		} else {
			for _, s := range svcs {
				previous, ok := smap[s.Hostname]
				if !ok {
					// First time we see a service. The result will have a single service per hostname
					// The first cluster will be listed first, so the services in the primary cluster
					// will be used for default settings. If a service appears in multiple clusters,
					// the order is less clear.
					smap[s.Hostname] = index
					index++
					services = append(services, s)
				} else {
					// We must deepcopy before merge, and after merging, the ClusterVips length will be >= 2.
					// This is an optimization to prevent deepcopy multi-times
					if len(services[previous].ClusterVIPs.GetAddresses()) < 2 {
						// Deep copy before merging, otherwise there is a case
						// a service in remote cluster can be deleted, but the ClusterIP left.
						services[previous] = services[previous].DeepCopy()
					}
					// If it is seen second time, that means it is from a different cluster, update cluster VIPs.
					mergeService(services[previous], s, r)
				}
			}
		}
	}
	return services
}

// GetService retrieves a service by hostname if exists
func (c *Controller) GetService(hostname host.Name) *model.Service {
	var out *model.Service
	for _, r := range c.GetRegistries() {
		service := r.GetService(hostname)
		if service == nil {
			continue
		}
		if r.Provider() != provider.Kubernetes {
			return service
		}
		if out == nil {
			out = service.DeepCopy()
		} else {
			// If we are seeing the service for the second time, it means it is available in multiple clusters.
			mergeService(out, service, r)
		}
	}
	return out
}

func mergeService(dst, src *model.Service, srcRegistry serviceregistry.Instance) {
	// Prefer the k8s HostVIPs where possible
	clusterID := srcRegistry.Cluster()
	if srcRegistry.Provider() == provider.Kubernetes || len(dst.ClusterVIPs.GetAddressesFor(clusterID)) == 0 {
		newAddresses := src.ClusterVIPs.GetAddressesFor(clusterID)
		dst.ClusterVIPs.SetAddressesFor(clusterID, newAddresses)
	}
}

// NetworkGateways merges the service-based cross-network gateways from each registry.
func (c *Controller) NetworkGateways() []model.NetworkGateway {
	var gws []model.NetworkGateway
	for _, r := range c.GetRegistries() {
		gws = append(gws, r.NetworkGateways()...)
	}
	return gws
}

func (c *Controller) MCSServices() []model.MCSServiceInfo {
	var out []model.MCSServiceInfo
	for _, r := range c.GetRegistries() {
		out = append(out, r.MCSServices()...)
	}
	return out
}

// InstancesByPort retrieves instances for a service on a given port that match
// any of the supplied labels. All instances match an empty label list.
func (c *Controller) InstancesByPort(svc *model.Service, port int, labels labels.Instance) []*model.ServiceInstance {
	var instances []*model.ServiceInstance
	for _, r := range c.GetRegistries() {
		instances = append(instances, r.InstancesByPort(svc, port, labels)...)
	}
	return instances
}

func nodeClusterID(node *model.Proxy) cluster.ID {
	if node.Metadata == nil || node.Metadata.ClusterID == "" {
		return ""
	}
	return node.Metadata.ClusterID
}

// Skip the service registry when there won't be a match
// because the proxy is in a different cluster.
func skipSearchingRegistryForProxy(nodeClusterID cluster.ID, r serviceregistry.Instance) bool {
	// Always search non-kube (usually serviceentry) registry.
	// Check every registry if cluster ID isn't specified.
	if r.Provider() != provider.Kubernetes || nodeClusterID == "" {
		return false
	}

	return !r.Cluster().Equals(nodeClusterID)
}

// GetProxyServiceInstances lists service instances co-located with a given proxy
func (c *Controller) GetProxyServiceInstances(node *model.Proxy) []*model.ServiceInstance {
	out := make([]*model.ServiceInstance, 0)
	nodeClusterID := nodeClusterID(node)
	for _, r := range c.GetRegistries() {
		if skipSearchingRegistryForProxy(nodeClusterID, r) {
			log.Debugf("GetProxyServiceInstances(): not searching registry %v: proxy %v CLUSTER_ID is %v",
				r.Cluster(), node.ID, nodeClusterID)
			continue
		}

		instances := r.GetProxyServiceInstances(node)
		if len(instances) > 0 {
			out = append(out, instances...)
		}
	}

	return out
}

func (c *Controller) GetProxyWorkloadLabels(proxy *model.Proxy) labels.Instance {
	clusterID := nodeClusterID(proxy)
	for _, r := range c.GetRegistries() {
		// If proxy clusterID unset, we may find incorrect workload label.
		// This can not happen in k8s env.
		if clusterID == "" {
			lbls := r.GetProxyWorkloadLabels(proxy)
			if lbls != nil {
				return lbls
			}
		} else if clusterID == r.Cluster() {
			// find proxy in the specified cluster
			lbls := r.GetProxyWorkloadLabels(proxy)
			if lbls != nil {
				return lbls
			}
		}
	}

	return nil
}

// Run starts all the controllers
func (c *Controller) Run(stop <-chan struct{}) {
	c.storeLock.Lock()
	for _, r := range c.registries {
		// prefer the per-registry stop channel
		registryStop := stop
		if s := r.stop; s != nil {
			registryStop = s
		}
		go r.Run(registryStop)
	}
	c.running = true
	c.storeLock.Unlock()

	<-stop
	log.Info("Registry Aggregator terminated")
}

// HasSynced returns true when all registries have synced
func (c *Controller) HasSynced() bool {
	for _, r := range c.GetRegistries() {
		if !r.HasSynced() {
			log.Debugf("registry %s is syncing", r.Cluster())
			return false
		}
	}
	return true
}

func (c *Controller) AppendServiceHandler(f func(*model.Service, model.Event)) {
	c.handlers.AppendServiceHandler(f)
}

func (c *Controller) AppendWorkloadHandler(f func(*model.WorkloadInstance, model.Event)) {
	// Currently, it is not used.
	// Note: take care when you want to enable it, it will register the handlers to all registries
	// c.handlers.AppendWorkloadHandler(f)
}

func (c *Controller) AppendServiceHandlerForCluster(id cluster.ID, f func(*model.Service, model.Event)) {
	c.storeLock.Lock()
	defer c.storeLock.Unlock()
	handler, ok := c.handlersByCluster[id]
	if !ok {
		c.handlersByCluster[id] = &model.ControllerHandlers{}
		handler = c.handlersByCluster[id]
	}
	handler.AppendServiceHandler(f)
}

func (c *Controller) AppendWorkloadHandlerForCluster(id cluster.ID, f func(*model.WorkloadInstance, model.Event)) {
	c.storeLock.Lock()
	defer c.storeLock.Unlock()
	handler, ok := c.handlersByCluster[id]
	if !ok {
		c.handlersByCluster[id] = &model.ControllerHandlers{}
		handler = c.handlersByCluster[id]
	}
	handler.AppendWorkloadHandler(f)
}

func (c *Controller) UnRegisterHandlersForCluster(id cluster.ID) {
	c.storeLock.Lock()
	defer c.storeLock.Unlock()
	delete(c.handlersByCluster, id)
}

redpajama_set_name: RedPajamaGithub


text:
#pragma warning(disable:4786)

#include <qmprotocoldriver.h>
#include <qmsession.h>

#include <qsassert.h>
#include <qsstl.h>
#include <qsstring.h>

#include <algorithm>
#include <vector>

using namespace qm;
using namespace qs;

namespace qm {
struct ProtocolFactoryImpl;
}

/****************************************************************************
 *
 * ProtocolDriver
 *
 */

qm::ProtocolDriver::~ProtocolDriver()
{
}

bool qm::ProtocolDriver::init()
{
	return true;
}

bool qm::ProtocolDriver::save(bool bForce)
{
	return true;
}

void qm::ProtocolDriver::setOffline(bool bOffline)
{
}

void qm::ProtocolDriver::setSubAccount(SubAccount* pSubAccount)
{
}

std::auto_ptr<NormalFolder> qm::ProtocolDriver::createFolder(const WCHAR* pwszName,
															 Folder* pParent)
{
	assert(false);
	return std::auto_ptr<NormalFolder>(0);
}

bool qm::ProtocolDriver::removeFolder(NormalFolder* pFolder)
{
	assert(false);
	return false;
}

bool qm::ProtocolDriver::renameFolder(NormalFolder* pFolder,
									  const WCHAR* pwszName)
{
	assert(false);
	return false;
}

bool qm::ProtocolDriver::moveFolder(NormalFolder* pFolder,
									NormalFolder* pParent,
									const WCHAR* pwszName)
{
	assert(false);
	return false;
}

bool qm::ProtocolDriver::createDefaultFolders(Account::FolderList* pList)
{
	return true;
}

bool qm::ProtocolDriver::getRemoteFolders(RemoteFolderList* pList)
{
	assert(false);
	return false;
}

std::pair<const WCHAR**, size_t> qm::ProtocolDriver::getFolderParamNames(Folder* pFolder)
{
	return std::pair<const WCHAR**, size_t>(0, 0);
}

void qm::ProtocolDriver::setDefaultFolderParams(NormalFolder* pFolder)
{
}

bool qm::ProtocolDriver::getMessage(MessageHolder* pmh,
									unsigned int nFlags,
									GetMessageCallback* pCallback)
{
	assert(false);
	return false;
}

bool qm::ProtocolDriver::setMessagesFlags(NormalFolder* pFolder,
										  const MessageHolderList& l,
										  unsigned int nFlags,
										  unsigned int nMask)
{
	assert(false);
	return false;
}

bool qm::ProtocolDriver::setMessagesLabel(NormalFolder* pFolder,
										  const MessageHolderList& l,
										  const WCHAR* pwszLabel)
{
	assert(false);
	return false;
}

bool qm::ProtocolDriver::appendMessage(NormalFolder* pFolder,
									   const CHAR* pszMessage,
									   size_t nLen,
									   unsigned int nFlags,
									   const WCHAR* pwszLabel)
{
	assert(false);
	return false;
}

bool qm::ProtocolDriver::removeMessages(NormalFolder* pFolder,
										const MessageHolderList& l)
{
	assert(false);
	return false;
}

bool qm::ProtocolDriver::copyMessages(const MessageHolderList& l,
									  NormalFolder* pFolderFrom,
									  NormalFolder* pFolderTo,
									  bool bMove)
{
	assert(false);
	return false;
}

bool qm::ProtocolDriver::prepareFolder(NormalFolder* pFolder)
{
	return true;
}

/****************************************************************************
 *
 * ProtocolDriver::GetMessageCallback
 *
 */

qm::ProtocolDriver::GetMessageCallback::~GetMessageCallback()
{
}

/****************************************************************************
 *
 * ProtocolFactoryImpl
 *
 */

struct qm::ProtocolFactoryImpl
{
	typedef std::vector<std::pair<const WCHAR*, ProtocolFactory*> > FactoryList;

	static FactoryList::iterator getIterator(const WCHAR* pwszName);

	static FactoryList listFactory__;
	static std::auto_ptr<PasswordCallback> pPasswordCallback_;
	static ErrorCallback* pErrorCallback_;
};

ProtocolFactoryImpl::FactoryList qm::ProtocolFactoryImpl::listFactory__;
std::auto_ptr<PasswordCallback> qm::ProtocolFactoryImpl::pPasswordCallback_;
ErrorCallback* qm::ProtocolFactoryImpl::pErrorCallback_;

ProtocolFactoryImpl::FactoryList::iterator qm::ProtocolFactoryImpl::getIterator(const WCHAR* pwszName)
{
	return std::find_if(listFactory__.begin(), listFactory__.end(),
		boost::bind(string_equal<WCHAR>(),
			boost::bind(&FactoryList::value_type::first, _1), pwszName));
}

/****************************************************************************
 *
 * ProtocolFactory
 *
 */

qm::ProtocolFactory::ProtocolFactory()
{
}

qm::ProtocolFactory::~ProtocolFactory()
{
}

std::auto_ptr<ProtocolDriver> qm::ProtocolFactory::getDriver(Account* pAccount,
															 const Security* pSecurity)
{
	const WCHAR* pwszName = pAccount->getType(Account::HOST_RECEIVE);
	ProtocolFactoryImpl::FactoryList::iterator it =
		ProtocolFactoryImpl::getIterator(pwszName);
	if (it == ProtocolFactoryImpl::listFactory__.end())
		return std::auto_ptr<ProtocolDriver>(0);

	return (*it).second->createDriver(pAccount, pSecurity,
		ProtocolFactoryImpl::pPasswordCallback_.get(),
		ProtocolFactoryImpl::pErrorCallback_);
}

void qm::ProtocolFactory::setPasswordCallback(std::auto_ptr<PasswordCallback> pPasswordCallback)
{
	ProtocolFactoryImpl::pPasswordCallback_ = pPasswordCallback;
}

void qm::ProtocolFactory::setErrorCallback(ErrorCallback* pErrorCallback)
{
	ProtocolFactoryImpl::pErrorCallback_ = pErrorCallback;
}

void qm::ProtocolFactory::registerFactory(const WCHAR* pwszName,
										  ProtocolFactory* pFactory)
{
	assert(pwszName);
	assert(pFactory);

	ProtocolFactoryImpl::listFactory__.push_back(std::make_pair(pwszName, pFactory));
}

void qm::ProtocolFactory::unregisterFactory(const WCHAR* pwszName)
{
	assert(pwszName);

	ProtocolFactoryImpl::FactoryList::iterator it =
		ProtocolFactoryImpl::getIterator(pwszName);
	if (it != ProtocolFactoryImpl::listFactory__.end())
		ProtocolFactoryImpl::listFactory__.erase(it);
}


text:
#include "avionics/firmware/drivers/q7_watchdog.h"

#include <stdbool.h>
#include <stdint.h>

#include "avionics/firmware/cpu/clock.h"
#include "avionics/firmware/cpu/n2het.h"
#include "avionics/firmware/cpu/registers.h"

// Specify the Q7 watchdog timeout. This timeout specifies the amount of time
// the TMS570 will wait for the Q7 to toggle the watchdog kick pin. After the
// Q7 toggles the watchdog kick pin, the TMS570 resets the timer. If the Q7
// fails to toggle the watchdog pin and the timeout elapses, the TMS570 will
// reset the Q7. Here, we assume that the TMS570 polls the watchdog kick pin
// at least twice as fast as the Q7 toggles the pin.
#define WATCHDOG_TIMEOUT_CYCLES CLOCK32_MSEC_TO_CYCLES(1000)

// Specify the amount of time to hold the Q7 in reset.
#define Q7_RESET_CYCLES CLOCK32_MSEC_TO_CYCLES(100)

#define FC_N2HET_KICK kN2het1Pin22
#define FC_N2HET_RESET kN2het1Pin18

#define RECORDER_SPI3_KICK (1U << 4)
#define RECORDER_SPI1_RESET (1U << 4)

static bool g_enabled = false;
static bool g_kick_state = false;
static bool g_in_reset = false;
static uint32_t g_timeout_cycles = 0U;

static void Q7WatchdogInit(void) {
  g_enabled = false;
  g_kick_state = false;
  g_in_reset = false;
  g_timeout_cycles = 0U;
}

static void Q7WatchdogPoll(bool (* const get_kick)(void),
                           void (* const assert_reset)(bool reset)) {
  if (get_kick() != g_kick_state) {
    g_enabled = true;
    g_kick_state = !g_kick_state;
    g_timeout_cycles = Clock32GetCycles() + WATCHDOG_TIMEOUT_CYCLES;
  } else if (g_enabled) {
    if (g_in_reset && CLOCK32_GE(Clock32GetCycles(), g_timeout_cycles)) {
      // Release Q7 reset button. Disable watchdog until Q7 reboots and begins
      // kicking the watchdog again.
      assert_reset(false);
      g_in_reset = false;
      g_enabled = false;
    } else if (CLOCK32_GE(Clock32GetCycles(), g_timeout_cycles)) {
      // Assert Q7 reset button.
      assert_reset(true);
      g_in_reset = true;
      g_timeout_cycles = Clock32GetCycles() + Q7_RESET_CYCLES;
    }
  }
}

static bool FcGetKickState(void) {
  return N2hetGetValue(FC_N2HET_KICK);
}

static void FcAssertReset(bool reset) {
  N2hetSetValue(FC_N2HET_RESET, !reset);  // Reset when low.
}

static void FcInit(void) {
  // Configure Q7_SIG0 as input.
  N2hetConfigureAsInputPullDown(FC_N2HET_KICK);
  // Configure Q7_nRSTBTN as open drain.
  N2hetConfigureAsOutputOpenDrain(FC_N2HET_RESET, true);  // High impedance.
  // Disable watchdog by default.
  g_kick_state = FcGetKickState();
}

static bool RecorderGetKickState(void) {
  return (SPI(3).PC2.SCSDIN & RECORDER_SPI3_KICK) != 0x0;
}

static void RecorderAssertReset(bool reset) {
  if (reset) {
    SPI(1).PC5.raw = RECORDER_SPI1_RESET;  // Low.
  } else {
    SPI(1).PC4.raw = RECORDER_SPI1_RESET;  // High impedance.
  }
}

static void RecorderInit(void) {
  // Configure Q7_SIG0 as input.
  SPI(3).GCR0.NRESET = 1;
  SPI(3).PC8.SCSPSEL &= ~RECORDER_SPI3_KICK;  // Configure as pull-down.
  SPI(3).PC7.SCSPDIS &= ~RECORDER_SPI3_KICK;  // Enable internal pull.
  SPI(3).PC1.SCSDIR &= ~RECORDER_SPI3_KICK;   // Configure as input.
  SPI(3).PC0.SCSFUN &= ~RECORDER_SPI3_KICK;   // Configure as GPIO.

  // Configure Q7_nRSTBTN as open drain.
  SPI(1).GCR0.NRESET = 1;
  RecorderAssertReset(false);
  SPI(1).PC6.SCSPDR |= RECORDER_SPI1_RESET;   // Configure as open drain.
  SPI(1).PC1.SCSDIR |= RECORDER_SPI1_RESET;   // Configure as output.
  SPI(1).PC0.SCSFUN &= ~RECORDER_SPI1_RESET;  // Configure as GPIO.

  // Disable watchdog by default.
  g_kick_state = RecorderGetKickState();
}

void Q7WatchdogFcInit(void) {
  Q7WatchdogInit();
  FcInit();
}

void Q7WatchdogFcPoll(void) {
  Q7WatchdogPoll(FcGetKickState, FcAssertReset);
}

void Q7WatchdogRecorderInit(void) {
  Q7WatchdogInit();
  RecorderInit();
}

void Q7WatchdogRecorderPoll(void) {
  Q7WatchdogPoll(RecorderGetKickState, RecorderAssertReset);
}


text:
package craftdevs.chibill.deobfcraft.patcher;

public class ClassPatcher {

}


text:
package org.apache.jackrabbit.oak.security.authorization.permission;

import org.apache.jackrabbit.oak.api.PropertyState;
import org.apache.jackrabbit.oak.spi.security.authorization.permission.Permissions;
import org.apache.jackrabbit.oak.spi.security.authorization.permission.RepositoryPermission;
import org.apache.jackrabbit.oak.spi.security.authorization.permission.TreePermission;
import org.apache.jackrabbit.oak.spi.state.NodeState;
import org.jetbrains.annotations.NotNull;

/**
 * {@code TreePermission} implementation for the access control policy coverying
 * repository level permissions. In this implementation these permissions are
 * managed in the policy tree defined at /rep:repoPolicy, which is considered
 * protected access control content.
 *
 * This implementation relies on the precondition that the subtree defined by the
 * /rep:repoPolicy node only consists of trees of type access control. Consequently,
 * read access to trees and properties is granted if and only if {@link Permissions#READ_ACCESS_CONTROL}
 * is granted at the repo-level.
 *
 * For the same reason any other permissions are evaluated by checking the
 * {@link org.apache.jackrabbit.oak.spi.security.authorization.permission.RepositoryPermission},
 * which apply for all items defined by this special subtree.
 */
final class RepoPolicyTreePermission implements TreePermission {

    private RepositoryPermission repoPermission;
    private ReadStatus readStatus;

    RepoPolicyTreePermission(RepositoryPermission repoPermission) {
        this.repoPermission = repoPermission;
    }

    TreePermission getChildPermission() {
        return this;
    }

    //-----------------------------------------------------< TreePermission >---
    @NotNull
    @Override
    public TreePermission getChildPermission(@NotNull String childName, @NotNull NodeState childState) {
        return getChildPermission();
    }

    @Override
    public boolean canRead() {
        return getReadStatus().allowsThis();
    }

    @Override
    public boolean canRead(@NotNull PropertyState property) {
        return getReadStatus().allowsThis();
    }

    @Override
    public boolean canReadAll() {
        return getReadStatus().allowsAll();
    }

    @Override
    public boolean canReadProperties() {
        return getReadStatus().allowsProperties();
    }

    @Override
    public boolean isGranted(long permissions) {
        return repoPermission.isGranted(permissions);
    }

    @Override
    public boolean isGranted(long permissions, @NotNull PropertyState property) {
        return repoPermission.isGranted(permissions);
    }

    private ReadStatus getReadStatus() {
        if (readStatus == null) {
            boolean canRead = repoPermission.isGranted(Permissions.READ_ACCESS_CONTROL);
            readStatus = (canRead) ? ReadStatus.ALLOW_ALL : ReadStatus.DENY_ALL;
        }
        return readStatus;
    }
}


text:
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using EPiServer.Core;
using EPiServer.Globalization;
using EPiServer.ServiceLocation;
using EPiServer.Web.Routing;
using EPiServer;

namespace EPiServerSite1.Helpers
{
    public static class UrlHelpers
    {
        /// <summary>
        /// Returns the target URL for a PageReference. Respects the page's shortcut setting
        /// so if the page is set as a shortcut to another page or an external URL that URL
        /// will be returned.
        /// </summary>
        public static IHtmlString PageLinkUrl(this UrlHelper urlHelper, PageReference pageLink)
        {
            if(ContentReference.IsNullOrEmpty(pageLink))
            {
                return MvcHtmlString.Empty;
            }

            var contentLoader = ServiceLocator.Current.GetInstance<IContentLoader>();
            var page = contentLoader.Get<PageData>(pageLink);

            return PageLinkUrl(urlHelper, page);
        }

        /// <summary>
        /// Returns the target URL for a page. Respects the page's shortcut setting
        /// so if the page is set as a shortcut to another page or an external URL that URL
        /// will be returned.
        /// </summary>
        public static IHtmlString PageLinkUrl(this UrlHelper urlHelper, PageData page)
        {
            var urlResolver = ServiceLocator.Current.GetInstance<UrlResolver>();
            switch (page.LinkType)
            {
                case PageShortcutType.Normal:
                case PageShortcutType.FetchData:
                    return new MvcHtmlString(urlResolver.GetUrl(page.PageLink));

                case PageShortcutType.Shortcut:
                    var shortcutProperty = page.Property["PageShortcutLink"] as PropertyPageReference;
                    if (shortcutProperty != null && !ContentReference.IsNullOrEmpty(shortcutProperty.PageLink))
                    {
                        return urlHelper.PageLinkUrl(shortcutProperty.PageLink);
                    }
                    break;

                case PageShortcutType.External:
                    return new MvcHtmlString(page.LinkURL);
            }
            return MvcHtmlString.Empty;
        }

        public static RouteValueDictionary GetPageRoute(this RequestContext requestContext, PageReference pageLink)
        {
            var values = new RouteValueDictionary();
            values[RoutingConstants.NodeKey] = pageLink;
            values[RoutingConstants.LanguageKey] = ContentLanguage.PreferredCulture.Name;
            return values;
        }
    }
}


text:
import re
import os,sys
selfpath = os.path.split(os.path.realpath(__file__))[0]
PATH = os.path.abspath(os.path.join(selfpath, '..'))
sys.path.append(PATH)
from crawler import settings  # your project settings file
from django.core.management import setup_environ  # environment setup function
setup_environ(settings)
from spider.models import Car
from lxml.html.clean import Cleaner
import logging
import logging.config
from base import BaseCraw
logging.config.fileConfig('crawler/seraph_spider/logging.conf')
logger = logging.getLogger(__name__)

class Caranddrive(BaseCraw):

    def __init__(self,url):
        BaseCraw.__init__(self,url)

    def get_list(self):
        # print self._url
        page = self.fetch_page(self._url)
        html = self.fromstring(page)
        nodes_list = self.locate(html,'ol')
        final_html = self.parse_list(nodes_list,html)
        return final_html

    def parse_list(self,nodes_list,html):
        next_node = self.locate(html,'.future')[-1]
        if next_node.text == u'Older Posts »':
            next_url = next_node.get('href') if next_node.get('href').startswith('http') else self._url + next_node.get('href')
            next_page = self.fetch_page(next_url)
            next_html = self.fromstring(next_page)
            next_nodes_list = self.locate(next_html,'ol')
            nodes_list += next_nodes_list
            self.parse_list(next_html)
        else:
            return nodes_list

    def get_list_item(self):
        nodes_list = self.get_list()
        for nodes in nodes_list:
            for node in self.locate(nodes,'li'):
                car_title = self.locate(node,'h1 a')[0].text_content().encode('utf-8')
                print 'car_title',car_title
                car_des = self.locate(node,'div.post')[0].text_content().encode('utf-8')
                print 'car_des',car_des
                car_icon = self.locate(node,'div.post p img')[0].get('data-lazy-src')
                car_link = self.locate(node,'h1.postTitle a')[0].get('href')
                print 'car_link',car_link
                try:
                    car_body = self.get_item_details(car_link)
                except:
                    car_body = ''
                car_source = 'caranddrive'
                car_cate = 'car'
                # car_publish_time =
                ca = Car(car_title=car_title,
                     car_des=car_des,
                     car_link=car_link,
                     car_body=car_body,
                     car_icon=car_icon,
                     car_source=car_source,
                     car_cate=car_cate)

                ca.save()
                logger.info('done one')

    def get_item_details(self,link):
        page = self.fetch_page(link)
        html = self.fromstring(page)
        car_body = self.locate(html,'div.postWrapper')[0]
        car_body = self.tostring(car_body)
        car_body = self.clean(car_body,flag='lazy')
        # r=re.compile(r'
.*?
')
        # car_body = r.sub(car_body,'')

        return car_body

    def run(self):
        self.get_list_item()

if __name__ == '__main__':
    car = Caranddrive('http://blog.caranddriver.com')
    car.run()


text:
package water;

import java.util.Arrays;
import water.init.JarHash;

/**
 * Struct holding H2ONode health info.
 * @author
 */
public class HeartBeat extends Iced<HeartBeat> {
  char _hb_version;             // Incrementing counter for sorting timelines better.
  int _cloud_hash;              // Cloud-membership hash
  int _cloud_name_hash;         // Hash of this cloud's name
  boolean _common_knowledge;    // Cloud shares common knowledge
  char _cloud_size;             // Cloud-size this guy is reporting
  long _jvm_boot_msec;          // Boot time of JVM
  public long jvmBootTimeMsec(){return _jvm_boot_msec;}
  byte[] _jar_md5;              // JAR file digest

  public boolean _client;       // This is a client node: no keys homed here
  public boolean _watchdog_client = false; // Special client mode - kill cluster when client disappears

  public int _pid;              // Process ID

  // Static cpus & threads
  public short _num_cpus;        // Number of CPUs on this Node
  public short _cpus_allowed;    // Number of CPUs allowed by process
  public short _nthreads;        // Number of threads allowed by cmd line

  // Dynamic resource usage: ticks, files
  public float _system_load_average;
  public long _system_idle_ticks;
  public long _system_total_ticks;
  public long _process_total_ticks;
  public int _process_num_open_fds;

  // Memory & Disk scaled by K or by M setters & getters.

  // Sum of KV + POJO + FREE == MEM_MAX (heap set at JVM launch)
  private int _kv_mem;          // Memory used by K/V as of last FullGC
  private int _pojo_mem;        // POJO used as of last FullGC
  private int _free_mem;        // Free memory as of last FullGC
  private int _swap_mem;        // Swapped K/V as of last FullGC
  void   set_kv_mem (long n) { _kv_mem =        (int)(n>>10); }
  void set_pojo_mem (long n) { _pojo_mem =      (int)(n>>10); }
  void set_free_mem (long n) { _free_mem =      (int)(n>>10); }
  void set_swap_mem (long n) { _swap_mem =      (int)(n>>10); }
  public long get_kv_mem  () { return ((long) _kv_mem )<<10 ; }
  public long get_pojo_mem() { return ((long)_pojo_mem)<<10 ; }
  public long get_free_mem() { return ((long)_free_mem)<<10 ; }
  public long get_swap_mem() { return ((long)_swap_mem)<<10 ; }

  public int _keys;       // Number of LOCAL keys in this node, cached or homed

  int _free_disk;        // Free disk (internally stored in megabyte precision)
  void set_free_disk(long n) { _free_disk = (int)(n>>20); }
  public long get_free_disk()  { return ((long)_free_disk)<<20 ; }
  int _max_disk;         // Disk size (internally stored in megabyte precision)
  void set_max_disk (long n) {  _max_disk = (int)(n>>20); }
  public long get_max_disk ()  { return  ((long)_max_disk)<<20 ; }

  boolean check_jar_md5() {
    return H2O.ARGS.md5skip || Arrays.equals(JarHash.JARHASH, _jar_md5);
  }

  // Internal profiling
  public float _gflops = Float.NaN;         // Number of GFlops for this node
  public float _membw;          // Memory bandwidth in GB/s

  // Number of elements & threads in high FJ work queues
  public char _rpcs;            // Outstanding RemoteProcedureCalls
  public short _fjthrds[];      // Number of threads (not all are runnable)
  public short _fjqueue[];      // Number of elements in FJ work queue
  public char _tcps_active;     // Threads trying do a TCP send
}


text:
grade = float(input())

if grade >= 5.50:
    print("Excellent!")

else:
    print("Not excellent.")


text:
var filesToValidate = [
    'src/**/*.js',
    'tests/unit/**/*.js',
    '!src/zip/src/**/*.js'
];

module.exports = function (grunt) {
    grunt.initConfig({
        webpack: {
            app: require('./webpack.config.js')
        },
        eslint: {
            app: filesToValidate
        },
        jscs: {
            src: filesToValidate
        }
    });

    grunt.loadNpmTasks('grunt-webpack');
    grunt.loadNpmTasks('grunt-jscs');
    grunt.loadNpmTasks('grunt-blobify');
    grunt.loadNpmTasks('grunt-remove');
    grunt.loadNpmTasks('grunt-eslint');
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-contrib-copy');

    /**
     * include tasks
     */
    require('grunt-config-dir')(grunt, {
        configDir: require('path').resolve(__dirname + '/grunt_tasks_config'),
        fileExtensions: ['js']
    }, function (err) {
        grunt.log.error(err);
    });

    grunt.registerTask('build', [
        'remove',
        'jscs',
        'eslint',
        'copy',
        'webpack',
        'uglify'
    ]);
};


text:
The following is a list of parameters you will often deal with.

Parameter		|	Type	|	Function
----------------|-----------|------------
`editable`		|	Bool	|	When `FALSE`, field value displays as text instead of input. When `TRUE` it is displayed as a field.
`render`		|	Bool	|	If set to `FALSE`, Formo will not render or validate the field
`ignore`		|	Bool	|	If set to `TRUE`, Formo will ignore the field's validate rules
`attr`			|	Array	|	Carried over into forms/fields rendered as HTML. These are `key => value` pairs of HTML attribute tags
`css`			|	Array	|	Carried over into forms/fields rendered as HTML. These are `key => value` pairs of the `style` attribute tag
`label`			|	String	|	Becomes a field's label. If not specified, the alias is its label
`driver`		|	String	|	The driver that handles the field/form type
`options`		|	Array	|	Become available options for selects, radio groups and checkbox groups
`order`			|	Mixed	|	Specifies where the field is placed relative to other fields

## Setting specific parameters

### Value

To set/retrive a field's **value**, use `val()`:

	// Sets the value to "my_username"
	$form->username->val('my_username');

	// Returns "my_username"
	$form->username->val();

### Alias

	// Sets the alias to "special_form"
	$form->alias('special_form');

	// Returns "special_form"
	$form->alias();


text:
i_want_pets = ["I", "want", 3, "pets", "but", "only", "have", 2]
my_family_pets_ages = {"Evi" => 6, "Ditto" => 3, "Hoobie" => 3, "George" => 12, "Bogart" => 4, "Poly" => 4, "Annabelle" => 0}

# Person 1's solution
def my_array_finding_method(source, thing_to_find)
  source # This line is here to make sure all tests initially fail. Delete it when you begin coding.
end

def my_hash_finding_method(source, thing_to_find)
  source # This line is here to make sure all tests initially fail. Delete it when you begin coding.
end

# Identify and describe the Ruby method(s) you implemented.
#
#
#

# Person 2
def my_array_modification_method!(source, thing_to_modify)
  source.dup # This line is here to make sure all tests initially fail. Delete it when you begin coding.
end

def my_hash_modification_method!(source, thing_to_modify)
  source.dup # This line is here to make sure all tests initially fail. Delete it when you begin coding.
end

# Identify and describe the Ruby method(s) you implemented.
#
#
#

# Person 3
def my_array_sorting_method(source)
  source.sort {|x,y| x.to_s <=> y.to_s }
end

def my_hash_sorting_method(source)
  source.to_a.sort { |x,y| x[1] <=> y[1] }
end

# Identify and describe the Ruby method(s) you implemented.
=begin
- I implemented the array and hash sorting methods using an Enumerable method called
  sort. This allows you to sort an Enumerable using your own comparison given in the
  form of a code block. For the array, I sorted based on the string values. For the
  hash, I sorted based on the hash values.
- You can use this method by calling sort on an Enumerable and then passing in the
  block of code for the comparison method.
- One trick I use for deciphering the Ruby document is to figure out exactly what I
  want the command I'm looking for to do. This makes it easier for me to search for the appropriate command in the documentation.
=end

# Person 4
def my_array_deletion_method!(source, thing_to_delete)
  source.dup # This line is here to make sure all tests initially fail. Delete it when you begin coding.
end

def my_hash_deletion_method!(source, thing_to_delete)
  source.dup # This line is here to make sure all tests initially fail. Delete it when you begin coding.
end

# Identify and describe the Ruby method(s) you implemented.
#
#
#

# Person 5
def my_array_splitting_method(source)
  source # This line is here to make sure all tests initially fail. Delete it when you begin coding.
end

def my_hash_splitting_method(source, age)
  source # This line is here to make sure all tests initially fail. Delete it when you begin coding.
end

# Identify and describe the Ruby method(s) you implemented.
#
#
#

# Release 1: Identify and describe the Ruby method you implemented. Teach your
# accountability group how to use the methods.
#
#
#

# Release 3: Reflect!
# What did you learn about researching and explaining your research to others?
#
#
#
#


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
CvStatModel
</TITLE>

<META NAME="date" CONTENT="2013-12-28">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Tree
      Index
      Help

OpenCV 2.4.8

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.opencv.ml

Class CvStatModel

java.lang.Object
  org.opencv.ml.CvStatModel

Direct Known Subclasses:
CvANN_MLP, CvBoost, CvDTree, CvGBTrees, CvKNearest, CvNormalBayesClassifier, CvRTrees, CvSVM

public class CvStatModel
extends java.lang.Object

Base class for statistical models in ML.

class CvStatModel

// C++ code:

public:

/ * CvStatModel(); * /

/ * CvStatModel(const Mat& train_data...); * /

virtual ~CvStatModel();

virtual void clear()=0;

/ * virtual bool train(const Mat& train_data, [int tflag,]..., const

Mat& responses,...,

[const Mat& var_idx,]..., [const Mat& sample_idx,]...

[const Mat& var_type,]..., [const Mat& missing_mask,]

<misc_training_alg_params>...)=0;

 /

/ * virtual float predict(const Mat& sample...) const=0; * /

virtual void save(const char* filename, const char* name=0)=0;

virtual void load(const char* filename, const char* name=0)=0;

virtual void write(CvFileStorage* storage, const char* name)=0;

virtual void read(CvFileStorage* storage, CvFileNode* node)=0;

};

In this declaration, some methods are commented off. These are methods for
 which there is no unified API (with the exception of the default
 constructor). However, there are many similarities in the syntax and
 semantics that are briefly described below in this section, as if they are
 part of the base class.

See Also:
org.opencv.ml.CvStatModel

Method Summary

 void
load(java.lang.String filename)

          Loads the model from a file.

 void
load(java.lang.String filename,
     java.lang.String name)

          Loads the model from a file.

 void
save(java.lang.String filename)

          Saves the model to a file.

 void
save(java.lang.String filename,
     java.lang.String name)

          Saves the model to a file.

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Method Detail

load

public void load(java.lang.String filename)

Loads the model from a file.

The method load loads the complete model state with the
 specified name (or default model-dependent name) from the specified XML or
 YAML file. The previous model state is cleared by "CvStatModel.clear".

Parameters:
filename - a filename
See Also:
org.opencv.ml.CvStatModel.load

load

public void load(java.lang.String filename,
                 java.lang.String name)

Loads the model from a file.

The method load loads the complete model state with the
 specified name (or default model-dependent name) from the specified XML or
 YAML file. The previous model state is cleared by "CvStatModel.clear".

Parameters:
filename - a filename
name - a name
See Also:
org.opencv.ml.CvStatModel.load

save

public void save(java.lang.String filename)

Saves the model to a file.

The method save saves the complete model state to the specified
 XML or YAML file with the specified name or default name (which depends on a
 particular class). *Data persistence* functionality from CxCore
 is used.

Parameters:
filename - a filename
See Also:
org.opencv.ml.CvStatModel.save

save

public void save(java.lang.String filename,
                 java.lang.String name)

Saves the model to a file.

The method save saves the complete model state to the specified
 XML or YAML file with the specified name or default name (which depends on a
 particular class). *Data persistence* functionality from CxCore
 is used.

Parameters:
filename - a filename
name - a name
See Also:
org.opencv.ml.CvStatModel.save

      Overview
      Package
    Class
      Tree
      Index
      Help

OpenCV 2.4.8 Documentation

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
import React from 'react';
import Vehicle from "./Vehicle";

function Vehicles(props) {
  return (
    <div className="vehicles"> {
      props.vehicles.map((vehicle) => {
        return <Vehicle
          key={vehicle.id}
          mark={vehicle.mark}
          model={vehicle.model}
          year={vehicle.year}
          gearbox={vehicle.gearboxType}
          image={vehicle.image}
          pricePerDay={vehicle.pricePerDay}
          status={vehicle.status}
          id={vehicle.id}
        />
      })}
    </div>
  );
}

export default Vehicles;


text: export { default } from 'ilios-common/models/session-objective';


text:
/* $Id$  */

package org.apache.lenya.cms.rc;

/**
 * A RCML entry
 */
public class RCMLEntryImpl implements RCMLEntry {

    private String identity = null;
    private long time = 0;
    private short type = 0;
    private String sessionId;

    /**
     * Creates a new RCMLEntry object.
     * @param sessionId The session ID.
     * @param _identity The identity of the person for this RCML
     * @param _time The time of the checkin / checkout
     */
    public RCMLEntryImpl(String sessionId, String _identity, long _time) {
        this.identity = _identity;
        this.time = _time;
        this.sessionId = sessionId;
    }

    /**
     * Get the identity of the creator (i.e. the user name)
     * FIXME: this should be changed to an o.a.l.ac.Identity object
     * @return the identity
     */
    public String getIdentity() {
        return this.identity;
    }

    /**
     * Get the creation time.
     * @return the time
     */
    public long getTime() {
        return this.time;
    }

    /**
     * Get the type (checkin or checkout).
     * @see org.apache.lenya.cms.rc.RCML.ci
     * @see org.apache.lenya.cms.rc.RCML.co
     * @return the type
     */
    public short getType() {
        return this.type;
    }

    /**
     * Set the type (checkin or checkout).
     * @see org.apache.lenya.cms.rc.RCML.ci
     * @see org.apache.lenya.cms.rc.RCML.co
     * @param s the type
     */
    protected void setType(short s) {
        this.type = s;
    }

    public String getSessionId() {
        return this.sessionId;
    }

}


text:
import electron from 'electron';
import fs from 'fs';
import mkdirp from 'mkdirp';
import path from 'path';
import writeFileAtomic from 'write-file-atomic';
import _get from 'lodash.get';
import _has from 'lodash.has';
import _set from 'lodash.set';
import _unset from 'lodash.unset';

/**
 * At the basic level, a key path is the string equivalent
 * of dot notation in JavaScript. Take the following object,
 * for example:
 *
 *     const obj = {
 *       color: {
 *         name: 'cerulean',
 *         code: {
 *           rgb: [0, 179, 230],
 *           hex: '#003BE6'
 *         }
 *       }
 *     }
 *
 * You can access the value of the key `name` in plain
 * JavaScript by traversing the tree using object dot
 * notation, like so:
 *
 *     console.log(obj.color.name);
 *     // => "cerulean"
 *
 * Similarly in Electron Settings, you are reading and
 * writing to a JSON object in a file, and a key path is
 * just a string that points to a specific key within that
 * object -- essentially using object dot notation in
 * string form.
 *
 *     settings.get('color.name');
 *     // => "cerulean"
 *
 * Key paths need not be just strings. In fact, there are
 * perfectly valid use-cases where you might need to access
 * a key, but the name of the key is stored in some
 * variable. In this case, you can specify an array of
 * strings which can be flattened into a regular key path.
 *
 *     const h = 'hue';
 *     settings.get(['color', h]);
 *     // => undefined
 *
 * Additionally, since Electron Settings uses Lodash's
 * {@link https://lodash.com/docs/4.17.15#get|get()}
 * function under the hood, you can even use array syntax:
 *
 *     settings.get('color.code.rgb[1]');
 *     // => 179
 *
 * Using key paths, you are not limited to setting only
 * top-level keys like you would be with LocalStorage. With
 * Electron Settings, you can deeply nest properties like
 * you would with any other object in JavaScript, and it
 * just feels natural.
 */
type KeyPath = string | Array<string | number>;

/**
 * `SettingsValue` types are the datatypes supported by
 * Electron Settings. Since Electron Settings reads and
 * writes to a JSON file, any value you set must be a valid
 * JSON value. This does however mean that `Date` types are
 * _not_ supported.
 *
 * Either simply store a numeric unix timestamp using
 * `Date.now()`, or convert dates back into `Date` types
 * using `new Date()`:
 *
 *     await settings.set('user.lastLogin', new Date());
 *
 *     const lastLogin = await settings.get('user.lastLogin');
 *     const lastLoginDate = new Date(lastLogin);
 */
type SettingsValue = null | boolean | string | number | SettingsObject | SettingsValue[];

/**
 * A `SettingsObject` is an object whose property values
 * are of the type `SettingsValue`.
 */
type SettingsObject = {
  [key: string]: SettingsValue;
};

/**
 * `Config` types contain all the configuration options for
 * Electron Settings that can be set using
 * [[configure|configure()]].
 */
type Config = {

  /**
   * Whether or not to save the settings file atomically.
   */
  atomicSave: boolean;

  /**
   * The path to the settings directory. Defaults to your
   * app's user data direcory.
   */
  dir?: string;

  /**
   * A custom Electron instance to use. Great for testing!
   */
  electron?: typeof Electron;

  /**
   * The name of the settings file that will be saved to
   * the disk.
   */
  fileName: string;

  /**
   * The number of spaces to use when stringifying the data
   * before saving to disk if `prettify` is set to `true`.
   */
  numSpaces: number;

  /**
   * Whether or not to prettify the data when it's saved to
   * disk.
   */
  prettify: boolean;
};

/** @internal */
const defaultConfig: Config = {
  atomicSave: true,
  fileName: 'settings.json',
  numSpaces: 2,
  prettify: false,
};

/** @internal */
let config: Config = {
  ...defaultConfig,
};

/**
 * Returns the Electron instance. The developer may define
 * a custom Electron instance by using `configure()`.
 *
 * @returns The Electron instance.
 * @internal
 */
function getElectron(): typeof Electron {
  return config.electron ?? electron;
}

/**
 * Returns the Electron app. The app may need be accessed
 * via `Remote` depending on whether this code is running
 * in the main or renderer process.
 *
 * @returns The Electron app.
 * @internal
 */
function getElectronApp(): Electron.App {
  const e = getElectron();
  const app = e.app ?? e.remote.app;

  return app;
}

/**
 * Returns the path to the settings directory. The path
 * may be customized by the developer by using
 * `configure()`.
 *
 * @returns The path to the settings directory.
 * @internal
 */
function getSettingsDirPath(): string {
  return config.dir ?? getElectronApp().getPath('userData');
}

/**
 * Returns the path to the settings file. The file name
 * may be customized by the developer using `configure()`.
 *
 * @returns The path to the settings file.
 * @internal
 */
function getSettingsFilePath(): string {
  const dir = getSettingsDirPath();

  return path.join(dir, config.fileName);
}

/**
 * Ensures that the settings file exists. If it does not
 * exist, then it is created.
 *
 * @returns A promise which resolves when the settings file exists.
 * @internal
 */
function ensureSettingsFile(): Promise<void> {
  const filePath = getSettingsFilePath();

  return new Promise((resolve, reject) => {
    fs.stat(filePath, (err) => {
      if (err) {
        if (err.code === 'ENOENT') {
          saveSettings({}).then(resolve, reject);
        } else {
          reject(err);
        }
      } else {
        resolve();
      }
    });
  });
}

/**
 * Ensures that the settings file exists. If it does not
 * exist, then it is created.
 *
 * @internal
 */
function ensureSettingsFileSync(): void {
  const filePath = getSettingsFilePath();

  try {
    fs.statSync(filePath);
  } catch (err) {
    if (err) {
      if (err.code === 'ENOENT') {
        saveSettingsSync({});
      } else {
        throw err;
      }
    }
  }
}

/**
 * Ensures that the settings directory exists. If it does
 * not exist, then it is created.
 *
 * @returns A promise which resolves when the settings dir exists.
 * @internal
 */
function ensureSettingsDir(): Promise<void> {
  const dirPath = getSettingsDirPath();

  return new Promise((resolve, reject) => {
    fs.stat(dirPath, (err) => {
      if (err) {
        if (err.code === 'ENOENT') {
          mkdirp(dirPath).then(() => resolve(), reject);
        } else {
          reject(err);
        }
      } else {
        resolve();
      }
    });
  });
}

/**
 * Ensures that the settings directory exists. If it does
 * not exist, then it is created.
 *
 * @internal
 */
function ensureSettingsDirSync(): void {
  const dirPath = getSettingsDirPath();

  try {
    fs.statSync(dirPath);
  } catch (err) {
    if (err.code === 'ENOENT') {
      mkdirp.sync(dirPath);
    } else {
      throw err;
    }
  }
}

/**
 * First ensures that the settings file exists then loads
 * the settings from the disk.
 *
 * @returns A promise which resolves with the settings object.
 * @internal
 */
function loadSettings(): Promise<SettingsObject> {
  return ensureSettingsFile().then(() => {
    const filePath = getSettingsFilePath();

    return new Promise((resolve, reject) => {
      fs.readFile(filePath, 'utf-8', (err, data) => {
        if (err) {
          reject(err);
        } else {
          try {
            resolve(JSON.parse(data));
          } catch (err) {
            reject(err);
          }
        }
      });
    });
  });
}

/**
 * First ensures that the settings file exists then loads
 * the settings from the disk.
 *
 * @returns The settings object.
 * @internal
 */
function loadSettingsSync(): SettingsObject {
  const filePath = getSettingsFilePath();

  ensureSettingsFileSync();

  const data = fs.readFileSync(filePath, 'utf-8');

  return JSON.parse(data);
}

/**
 * Saves the settings to the disk.
 *
 * @param obj The settings object to save.
 * @returns A promise which resolves when the settings have been saved.
 * @internal
 */
function saveSettings(obj: SettingsObject): Promise<void> {
  return ensureSettingsDir().then(() => {
    const filePath = getSettingsFilePath();
    const numSpaces = config.prettify ? config.numSpaces : 0;
    const data = JSON.stringify(obj, null, numSpaces);

    return new Promise((resolve, reject) => {
      if (config.atomicSave) {
        writeFileAtomic(filePath, data, (err) => {
          return err
            ? reject(err)
            : resolve();
        });
      } else {
        fs.writeFile(filePath, data, (err) => {
          return err
            ? reject(err)
            : resolve();
        });
      }
    });
  });
}

/**
 * Saves the settings to the disk.
 *
 * @param obj The settings object to save.
 * @internal
 */
function saveSettingsSync(obj: SettingsObject): void {
  const filePath = getSettingsFilePath();
  const numSpaces = config.prettify ? config.numSpaces : 0;
  const data = JSON.stringify(obj, null, numSpaces);

  ensureSettingsDirSync();

  if (config.atomicSave) {
    writeFileAtomic.sync(filePath, data);
  } else {
    fs.writeFileSync(filePath, data);
  }
}

/**
 * Returns the path to the settings file.
 *
 * In general, the settings file is stored in your app's
 * user data directory in a file called `settings.json`.
 * The default user data directory varies by system.
 *
 * - **macOS** - `~/Library/Application\ Support/<Your App>`
 * - **Windows** - `%APPDATA%/<Your App>`
 * - **Linux** - Either `$XDG_CONFIG_HOME/<Your App>` or
 * `~/.config/<Your App>`
 *
 * Although it is not recommended, you may change the name
 * or location of the settings file using
 * [[configure|configure()]].
 *
 * @returns The path to the settings file.
 * @example
 *
 * Get the path to the settings file.
 *
 *     settings.file();
 *     // => /home/nathan/.config/MyApp/settings.json
 */
function file(): string {
  return getSettingsFilePath();
}

/**
 * Sets the configuration for Electron Settings. To reset
 * to defaults, use [[reset|reset()]].
 *
 * Defaults:
 *
 *     {
 *       atomicSave: true,
 *       fileName: 'settings.json',
 *       numSpaces: 2,
 *       prettify: false
 *     }
 *
 * @param customConfig The custom configuration to use.
 * @example
 *
 * Update the filename to `cool-settings.json` and prettify
 * the output.
 *
 *     settings.configure({
 *       fileName: 'cool-settings.json',
 *       prettify: true
 *     });
 */
function configure(customConfig: Partial<Config>): void {
  config = { ...config, ...customConfig };
}

/**
 * Resets the Electron Settings configuration to defaults.
 *
 * @example
 *
 * Reset configuration to defaults.
 *
 *     settings.reset();
 */
function reset(): void {
  config = { ...defaultConfig };
}

/**
 * Checks if the given key path exists. For sync,
 * use [[hasSync|hasSync()]].
 *
 * @category Core
 * @param keyPath The key path to check.
 * @returns A promise which resolves to `true` if the
 * `keyPath` exists, else `false`.
 * @example
 *
 * Check if the value at `color.name` exists.
 *
 *     // Given:
 *     //
 *     // {
 *     //   "color": {
 *     //     "name": "cerulean",
 *     //     "code": {
 *     //       "rgb": [0, 179, 230],
 *     //       "hex": "#003BE6"
 *     //     }
 *     //   }
 *     // }
 *
 *     const exists = await settings.has('color.name');
 *     // => true
 *
 * @example
 *
 * Check if the value at `color.hue` exists.
 *
 *     const h = 'hue';
 *     const exists = await settings.has(['color', h]);
 *     // => false
 *
 *  @example
 *
 * Check if the value at `color.code.rgb[1]` exists.
 *
 *     const exists = await settings.has(color.code.rgb[1]);
 *     // => true
 */
async function has(keyPath: KeyPath): Promise<boolean> {
  const obj = await loadSettings();

  return _has(obj, keyPath);
}

/**
 * Checks if the given key path exists. For async,
 * use [[hasSync|hasSync()]].
 *
 * @category Core
 * @param keyPath The key path to check.
 * @returns `true` if the `keyPath` exists, else `false`.
 * @example
 *
 * Check if the value at `color.name` exists.
 *
 *     // Given:
 *     //
 *     // {
 *     //   "color": {
 *     //     "name": "cerulean",
 *     //     "code": {
 *     //       "rgb": [0, 179, 230],
 *     //       "hex": "#003BE6"
 *     //     }
 *     //   }
 *     // }
 *
 *     const exists = settings.hasSync('color.name');
 *     // => true
 *
 * @example
 *
 * Check if the value at `color.hue` exists.
 *
 *     const h = 'hue';
 *     const exists = settings.hasSync(['color', h]);
 *     // => false
 *
 * @example
 *
 * Check if the value at `color.code.rgb[1]` exists.
 *
 *     const exists = settings.hasSync(color.code.rgb[1]);
 *     // => true
 */
function hasSync(keyPath: KeyPath): boolean {
  const obj = loadSettingsSync();

  return _has(obj, keyPath);
}

/**
 * Gets all settings. For sync, use
 * [[getSync|getSync()]].
 *
 * @category Core
 * @returns A promise which resolves with all settings.
 * @example
 *
 * Gets all settings.
 *
 *     const obj = await get();
 */
async function get(): Promise<SettingsObject>;

/**
 * Gets the value at the given key path. For sync,
 * use [[getSync|getSync()]].
 *
 * @category Core
 * @param keyPath The key path of the property.
 * @returns A promise which resolves with the value at the
 * given key path.
 * @example
 *
 * Get the value at `color.name`.
 *
 *     // Given:
 *     //
 *     // {
 *     //   "color": {
 *     //     "name": "cerulean",
 *     //     "code": {
 *     //       "rgb": [0, 179, 230],
 *     //       "hex": "#003BE6"
 *     //     }
 *     //   }
 *     // }
 *
 *     const value = await settings.get('color.name');
 *     // => "cerulean"
 *
 * @example
 *
 * Get the value at `color.hue`.
 *
 *     const h = 'hue';
 *     const value = await settings.get(['color', h]);
 *     // => undefined
 *
 * @example
 *
 * Get the value at `color.code.rgb[1]`.
 *
 *     const h = 'hue';
 *     const value = await settings.get('color.code.rgb[1]');
 *     // => 179
 */
async function get(keyPath: KeyPath): Promise<SettingsValue>;

async function get(keyPath?: KeyPath): Promise<SettingsObject | SettingsValue> {
  const obj = await loadSettings();

  if (keyPath) {
    return _get(obj, keyPath);
  } else {
    return obj;
  }
}

/**
 * Gets all settings. For async, use [[get|get()]].
 *
 * @category Core
 * @returns All settings.
 * @example
 *
 * Gets all settings.
 *
 *     const obj = getSync();
 */
function getSync(): SettingsObject;

/**
 * Gets the value at the given key path. For async,
 * use [[get|get()]].
 *
 * @category Core
 * @param keyPath The key path of the property.
 * @returns The value at the given key path.
 * @example
 *
 * Get the value at `color.name`.
 *
 *     // Given:
 *     //
 *     // {
 *     //   "color": {
 *     //     "name": "cerulean",
 *     //     "code": {
 *     //       "rgb": [0, 179, 230],
 *     //       "hex": "#003BE6"
 *     //     }
 *     //   }
 *     // }
 *
 *     const value = settings.getSync('color.name');
 *     // => "cerulean"
 *
 * @example
 *
 * Get the value at `color.hue`.
 *
 *     const h = 'hue';
 *     const value = settings.getSync(['color', h]);
 *     // => undefined
 *
 * @example
 *
 * Get the value at `color.code.rgb[1]`.
 *
 *     const h = 'hue';
 *     const value = settings.getSync('color.code.rgb[1]');
 *     // => 179
 */
function getSync(keyPath: KeyPath): SettingsValue;

function getSync(keyPath?: KeyPath): SettingsValue {
  const obj = loadSettingsSync();

  if (keyPath) {
    return _get(obj, keyPath);
  } else {
    return obj;
  }
}

/**
 * Sets all settings. For sync, use [[setSync|setSync()]].
 *
 * @category Core
 * @param obj The new settings.
 * @returns A promise which resolves when the settings have
 * been set.
 * @example
 *
 * Set all settings.
 *
 *     await settings.set({ aqpw: 'nice' });
 */
async function set(obj: SettingsObject): Promise<void>;

/**
 * Sets the value at the given key path. For sync,
 * use [[setSync|setSync()]].
 *
 * @category Core
 * @param keyPath The key path of the property.
 * @param value The value to set.
 * @returns A promise which resolves when the setting has
 * been set.
 * @example
 *
 * Change the value at `color.name` to `sapphire`.
 *
 *     // Given:
 *     //
 *     // {
 *     //   "color": {
 *     //     "name": "cerulean",
 *     //     "code": {
 *     //       "rgb": [0, 179, 230],
 *     //       "hex": "#003BE6"
 *     //     }
 *     //   }
 *     // }
 *
 *     await settings.set('color.name', 'sapphire');
 *
 * @example
 *
 * Set the value of `color.hue` to `blue-ish`.
 *
 *     const h = 'hue';
 *     await settings.set(['color', h], 'blue-ish);
 *
 * @example
 *
 * Change the value of `color.code`.
 *
 *     await settings.set('color.code', {
 *       rgb: [16, 31, 134],
 *       hex: '#101F86'
 *     });
 */
async function set(keyPath: KeyPath, obj: SettingsValue): Promise<void>;

async function set(...args: [SettingsObject] | [KeyPath, SettingsValue]): Promise<void> {
  if (args.length === 1) {
    const [value] = args;

    return saveSettings(value);
  } else {
    const [keyPath, value] = args;
    const obj = await loadSettings();

    _set(obj, keyPath, value);

    return saveSettings(obj);
  }
}

/**
 * Sets all settings. For async, use [[set|set()]].
 *
 * @category Core
 * @param obj The new settings.
 * @example
 *
 * Set all settings.
 *
 *     settings.setSync({ aqpw: 'nice' });
 */
function setSync(obj: SettingsObject): void;

/**
 * Sets the value at the given key path. For async,
 * use [[set|set()]].
 *
 * @category Core
 * @param keyPath The key path of the property.
 * @param value The value to set.
 * @example
 *
 * Change the value at `color.name` to `sapphire`.
 *
 *     // Given:
 *     //
 *     // {
 *     //   "color": {
 *     //     "name": "cerulean",
 *     //     "code": {
 *     //       "rgb": [0, 179, 230],
 *     //       "hex": "#003BE6"
 *     //     }
 *     //   }
 *     // }
 *
 *     settings.setSync('color.name', 'sapphire');
 *
 * @example
 *
 * Set the value of `color.hue` to `blue-ish`.
 *
 *     const h = 'hue';
 *     settings.setSync(['color', h], 'blue-ish);
 *
 * @example
 *
 * Change the value of `color.code`.
 *
 *     settings.setSync('color.code', {
 *       rgb: [16, 31, 134],
 *       hex: '#101F86'
 *     });
 */
function setSync(keyPath: KeyPath, value: SettingsValue): void;

function setSync(...args: [SettingsObject] | [KeyPath, SettingsValue]): void {
  if (args.length === 1) {
    const [value] = args;

    saveSettingsSync(value);
  } else {
    const [keyPath, value] = args;
    const obj = loadSettingsSync();

    _set(obj, keyPath, value);

    saveSettingsSync(obj);
  }
}

/**
 * Unsets all settings. For sync, use [[unsetSync|unsetSync()]].
 *
 * @category Core
 * @returns A promise which resolves when the settings have
 * been unset.
 * @example
 *
 * Unsets all settings.
 *
 *     await settings.unset();
 */
async function unset(): Promise<void>;

/**
 * Unsets the property at the given key path. For sync,
 * use [[unsetSync|unsetSync()]].
 *
 * @category Core
 * @param keyPath The key path of the property.
 * @returns A promise which resolves when the setting has
 * been unset.
 * @example
 *
 * Unset the property `color.name`.
 *
 *     // Given:
 *     //
 *     // {
 *     //   "color": {
 *     //     "name": "cerulean",
 *     //     "code": {
 *     //       "rgb": [0, 179, 230],
 *     //       "hex": "#003BE6"
 *     //     }
 *     //   }
 *     // }
 *
 *     await settings.unset('color.name');
 *
 *     await settings.get('color.name');
 *     // => undefined
 *
 * @example
 *
 * Unset the property `color.code.rgba[1]`.
 *
 *     await settings.unset('color.code.rgba[1]');
 *
 *     await settings.get('color.code.rgb');
 *     // => [0, null, 230]
 */
async function unset(keyPath: KeyPath): Promise<void>;

async function unset(keyPath?: KeyPath): Promise<void> {
  if (keyPath) {
    const obj = await loadSettings();

    _unset(obj, keyPath);

    return saveSettings(obj);
  } else {
    // Unset all settings by saving empty object.
    return saveSettings({});
  }
}

/**
 * Unsets all settings. For async, use [[unset|unset()]].
 *
 * @category Core
 * @example
 *
 * Unsets all settings.
 *
 *     settings.unsetSync();
 */
function unsetSync(): void;

/**
 * Unsets the property at the given key path. For async,
 * use [[unset|unset()]].
 *
 * @category Core
 * @param keyPath The key path of the property.
 * @example
 *
 * Unset the property `color.name`.
 *
 *     // Given:
 *     //
 *     // {
 *     //   "color": {
 *     //     "name": "cerulean",
 *     //     "code": {
 *     //       "rgb": [0, 179, 230],
 *     //       "hex": "#003BE6"
 *     //     }
 *     //   }
 *     // }
 *
 *     settings.unsetSync('color.name');
 *
 *     settings.getSync('color.name');
 *     // => undefined
 *
 * @example
 *
 * Unset the property `color.code.rgba[1]`.
 *
 *     settings.unsetSync('color.code.rgba[1]');
 *
 *     settings.getSync('color.code.rgb');
 *     // => [0, null, 230]
 */
function unsetSync(keyPath: KeyPath): void;

function unsetSync(keyPath?: KeyPath): void {
  if (keyPath) {
    const obj = loadSettingsSync();

    _unset(obj, keyPath);

    saveSettingsSync(obj);
  } else {
    // Unset all settings by saving empty object.
    saveSettingsSync({});
  }
}

export = {
  file,
  configure,
  reset,
  has,
  hasSync,
  get,
  getSync,
  set,
  setSync,
  unset,
  unsetSync,
};


text:
The `sqlserver` plugin provides metrics for your SQL Server instance. It
currently works with SQL Server 2008 SP3 and newer. Recorded metrics are
lightweight and use Dynamic Management Views supplied by SQL Server.

### Additional Setup:

You have to create a login on every instance you want to monitor, with following script:
```sql
USE master;
GO
CREATE LOGIN [telegraf] WITH PASSWORD = N'mystrongpassword';
GO
GRANT VIEW SERVER STATE TO [telegraf];
GO
GRANT VIEW ANY DEFINITION TO [telegraf];
GO
```

For Azure SQL Database, you require the View Database State permission and can create a user with a password directly in the database.
```sql
CREATE USER [telegraf] WITH PASSWORD = N'mystrongpassword';
GO
GRANT VIEW DATABASE STATE TO [telegraf];
GO
```

### Configuration:

```toml
[agent]
  ## Default data collection interval for all inputs, can be changed as per collection interval needs
  interval = "10s"

# Read metrics from Microsoft SQL Server
[[inputs.sqlserver]]
  ## Specify instances to monitor with a list of connection strings.
  ## All connection parameters are optional.
  ## By default, the host is localhost, listening on default port, TCP 1433.
  ##   for Windows, the user is the currently running AD user (SSO).
  ##   See https://github.com/denisenkom/go-mssqldb for detailed connection
  ##   parameters, in particular, tls connections can be created like so:
  ##   "encrypt=true;certificate=<cert>;hostNameInCertificate=<SqlServer host fqdn>"
  # servers = [
  #  "Server=192.168.1.10;Port=1433;User Id=<user>;Password=<pw>;app name=telegraf;log=1;",
  # ]

  ## Optional parameter, setting this to 2 will use a new version
  ## of the collection queries that break compatibility with the original
  ## dashboards. All new functionality is under V2
  query_version = 2

  ## If you are using AzureDB, setting this to true will gather resource utilization metrics
  # azuredb = true

  ## If you would like to exclude some of the metrics queries, list them here
  ## Possible choices:
  ## - PerformanceCounters
  ## - WaitStatsCategorized
  ## - DatabaseIO
  ## - DatabaseProperties
  ## - CPUHistory
  ## - DatabaseSize
  ## - DatabaseStats
  ## - MemoryClerk
  ## - VolumeSpace
  ## - Schedulers
  ## - AzureDBResourceStats
  ## - AzureDBResourceGovernance
  ## - SqlRequests
  ## - ServerProperties
  exclude_query = [ 'Schedulers' , 'SqlRequests']
```

### Metrics:
To provide backwards compatibility, this plugin support two versions of metrics queries.

**Note**: Version 2 queries are not backwards compatible with the old queries. Any dashboards or queries based on the old query format will not work with the new format. The version 2 queries are written in such a way as to only gather SQL specific metrics (no disk space or overall CPU related metrics) and they only report raw metrics, no math has been done to calculate deltas. To graph this data you must calculate deltas in your dashboarding software.

#### Version 1 (deprecated in 1.6):
The original metrics queries provide:
- *Performance counters*: 1000+ metrics from `sys.dm_os_performance_counters`
- *Performance metrics*: special performance and ratio metrics
- *Wait stats*: wait tasks categorized from `sys.dm_os_wait_stats`
- *Memory clerk*: memory breakdown from `sys.dm_os_memory_clerks`
- *Database size*: databases size trend from `sys.dm_io_virtual_file_stats`
- *Database IO*: databases I/O from `sys.dm_io_virtual_file_stats`
- *Database latency*: databases latency from `sys.dm_io_virtual_file_stats`
- *Database properties*: databases properties, state and recovery model, from `sys.databases`
- *OS Volume*: available, used and total space from `sys.dm_os_volume_stats`
- *CPU*: cpu usage from `sys.dm_os_ring_buffers`

If you are using the original queries all stats have the following tags:
- `servername`:  hostname:instance
- `type`: type of stats to easily filter measurements

#### Version 2:
The new (version 2) metrics provide:
- *Database IO*: IO stats from `sys.dm_io_virtual_file_stats`
- *Memory Clerk*: Memory clerk breakdown from `sys.dm_os_memory_clerks`, most clerks have been given a friendly name.
- *Performance Counters*: A select list of performance counters from `sys.dm_os_performance_counters`. Some of the important metrics included:
  - *Activity*: Transactions/sec/database, Batch requests/sec, blocked processes, + more
  - *Availability Groups*: Bytes sent to replica, Bytes received from replica, Log bytes received, Log send queue, transaction delay, + more
  - *Log activity*: Log bytes flushed/sec, Log flushes/sec, Log Flush Wait Time
  - *Memory*: PLE, Page reads/sec, Page writes/sec, + more
  - *TempDB*: Free space, Version store usage, Active temp tables, temp table creation rate, + more
  - *Resource Governor*: CPU Usage, Requests/sec, Queued Requests, and Blocked tasks per workload group + more
- *Server properties*: Number of databases in all possible states (online, offline, suspect, etc.), cpu count, physical memory, SQL Server service uptime, and SQL Server version. In the case of Azure SQL relevent properties such as Tier, #Vcores, Memory etc.
- *Wait stats*: Wait time in ms, number of waiting tasks, resource wait time, signal wait time, max wait time in ms, wait type, and wait category. The waits are categorized using the same categories used in Query Store.
- *Schedulers* - This captures sys.dm_os_schedulers.
- *SqlRequests* - This captures a snapshot of dm_exec_requests and dm_exec_sessions that gives you running requests as well as wait types and blocking sessions
- *Azure Managed Instances*
  - Stats from `sys.server_resource_stats`:
    - cpu_count
    - server_memory
    - sku
    - engine_edition
    - hardware_type
    - total_storage_mb
    - available_storage_mb
    - uptime
  - Resource governance stats from sys.dm_instance_resource_governance
- *Azure SQL Database*
  - Stats from sys.dm_db_wait_stats
  - Resource governance stats from sys.dm_user_db_resource_governance
  - Stats from sys.dm_db_resource_stats

The following metrics can be used directly, with no delta calculations:
 - SQLServer:Buffer Manager\Buffer cache hit ratio
 - SQLServer:Buffer Manager\Page life expectancy
 - SQLServer:Buffer Node\Page life expectancy
 - SQLServer:Database Replica\Log Apply Pending Queue
 - SQLServer:Database Replica\Log Apply Ready Queue
 - SQLServer:Database Replica\Log Send Queue
 - SQLServer:Database Replica\Recovery Queue
 - SQLServer:Databases\Data File(s) Size (KB)
 - SQLServer:Databases\Log File(s) Size (KB)
 - SQLServer:Databases\Log File(s) Used Size (KB)
 - SQLServer:Databases\XTP Memory Used (KB)
 - SQLServer:General Statistics\Active Temp Tables
 - SQLServer:General Statistics\Processes blocked
 - SQLServer:General Statistics\Temp Tables For Destruction
 - SQLServer:General Statistics\User Connections
 - SQLServer:Memory Broker Clerks\Memory broker clerk size
 - SQLServer:Memory Manager\Memory Grants Pending
 - SQLServer:Memory Manager\Target Server Memory (KB)
 - SQLServer:Memory Manager\Total Server Memory (KB)
 - SQLServer:Resource Pool Stats\Active memory grant amount (KB)
 - SQLServer:Resource Pool Stats\Disk Read Bytes/sec
 - SQLServer:Resource Pool Stats\Disk Read IO Throttled/sec
 - SQLServer:Resource Pool Stats\Disk Read IO/sec
 - SQLServer:Resource Pool Stats\Disk Write Bytes/sec
 - SQLServer:Resource Pool Stats\Disk Write IO Throttled/sec
 - SQLServer:Resource Pool Stats\Disk Write IO/sec
 - SQLServer:Resource Pool Stats\Used memory (KB)
 - SQLServer:Transactions\Free Space in tempdb (KB)
 - SQLServer:Transactions\Version Store Size (KB)
 - SQLServer:User Settable\Query
 - SQLServer:Workload Group Stats\Blocked tasks
 - SQLServer:Workload Group Stats\CPU usage %
 - SQLServer:Workload Group Stats\Queued requests
 - SQLServer:Workload Group Stats\Requests completed/sec

Version 2 queries have the following tags:
- `sql_instance`: Physical host and instance name (hostname:instance)
- database_name:  For Azure SQLDB, database_name denotes the name of the Azure SQL Database as server name is a logical construct.


text:
import collections
class MyCalendarThree:

    def __init__(self):
        self.table = collections.Counter()

    def book(self, start: int, end: int) -> int:
        self.table[start] += 1
        self.table[end] -= 1
        curr = maxCount = 0
        for k in sorted(self.table):
            curr += self.table[k]
            maxCount = max(maxCount, curr)
        return maxCount

# Your MyCalendarThree object will be instantiated and called as such:
# obj = MyCalendarThree()
# param_1 = obj.book(start,end)


text:
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';

import * as actions from './actions';

import {destinationTypes} from './constants';

const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);

let mockSpark;

describe('widget-space redux actions', () => {
  beforeEach(() => {
    mockSpark = {
      request: jest.fn(() => Promise.resolve({body: 'mocked response body'}))
    };
  });

  it('has exported actions', () => {
    expect(actions).toMatchSnapshot();
  });

  describe('basic actions', () => {
    describe('#reloadWidget', () => {
      it('should reload the widget', () => {
        const store = mockStore({});

        store.dispatch(actions.reloadWidget());
        expect(store.getActions()).toMatchSnapshot();
      });
    });

    describe('#storeActivityTypes', () => {
      it('should store the activity types', () => {
        const store = mockStore({});

        store.dispatch(actions.storeActivityTypes({activityTypes: []}));
        expect(store.getActions()).toMatchSnapshot();
      });
    });

    describe('#storeDestination', () => {
      it('should store the destination type and id', () => {
        const store = mockStore({});

        store.dispatch(actions.storeDestination({id: 'you@u.net', type: 'email'}));
        expect(store.getActions()).toMatchSnapshot();
      });
    });

    describe('#toggleActivityMenuVisible', () => {
      it('should toggle the activity menu visible', () => {
        const store = mockStore({});

        store.dispatch(actions.toggleActivityMenuVisible());
        expect(store.getActions()).toMatchSnapshot();
      });
    });

    describe('#updateActivityType', () => {
      it('should update an activity type', () => {
        const store = mockStore({});

        store.dispatch(actions.updateActivityType({type: 'my-activity'}));
        expect(store.getActions()).toMatchSnapshot();
      });
    });

    describe('#updateSecondaryActivityType', () => {
      it('should update a secondary activity type', () => {
        const store = mockStore({});

        store.dispatch(actions.updateSecondaryActivityType({type: 'my-activity'}));
        expect(store.getActions()).toMatchSnapshot();
      });
    });

    describe('#updateWidgetStatus', () => {
      it('should store the activity types', () => {
        const store = mockStore({});

        store.dispatch(actions.updateWidgetStatus({status: {mocked: true}}));
        expect(store.getActions()).toMatchSnapshot();
      });
    });
  });

  describe('thunked actions', () => {
    const mockIntl = {formatMessage: () => 'mockIntl'};

    describe('#getSpaceDetails', () => {
      it('should fetch and store details about a space', () => {
        const destinationId = 'f17f413a-8530-4d08-ac9a-ca416d46988b';
        const store = mockStore({});

        return store.dispatch(actions.getSpaceDetails({
          sparkInstance: mockSpark,
          destinationId,
          destinationType: destinationTypes.SPACEID,
          intl: mockIntl
        }))
          .then(() => {
            expect(store.getActions()).toMatchSnapshot();
          });
      });

      it('should not fetch details about direct email spaces', () => {
        const destinationId = 'email@net.net';
        const store = mockStore({});

        store.dispatch(actions.getSpaceDetails({
          sparkInstance: mockSpark,
          destinationId,
          destinationType: destinationTypes.EMAIL,
          intl: mockIntl
        }));
        expect(store.getActions()).toMatchSnapshot();
      });
    });
  });
});


text:
package com.haulmont.cuba.web.sys.linkhandling;

import com.haulmont.cuba.core.app.DataService;
import com.haulmont.cuba.core.entity.Entity;
import com.haulmont.cuba.core.global.*;
import com.haulmont.cuba.gui.NoSuchScreenException;
import com.haulmont.cuba.gui.config.WindowConfig;
import com.haulmont.cuba.gui.config.WindowInfo;
import com.haulmont.cuba.gui.exception.AccessDeniedHandler;
import com.haulmont.cuba.gui.exception.EntityAccessExceptionHandler;
import com.haulmont.cuba.gui.exception.NoSuchScreenHandler;
import com.haulmont.cuba.web.App;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import javax.inject.Inject;
import java.util.HashMap;
import java.util.Map;

import static com.haulmont.cuba.gui.WindowManager.OpenType;

@Component(ScreensLinkHandlerProcessor.NAME)
public class ScreensLinkHandlerProcessor implements LinkHandlerProcessor, Ordered {
    public static final String NAME = "cuba_ScreensLinkHandlerProcessor";

    @Inject
    private Logger log;

    @Inject
    protected Metadata metadata;

    @Inject
    protected DataService dataService;

    @Inject
    protected WindowConfig windowConfig;

    @Inject
    protected EntityAccessExceptionHandler entityAccessExceptionHandler;
    @Inject
    protected AccessDeniedHandler accessDeniedHandler;
    @Inject
    protected NoSuchScreenHandler noSuchScreenHandler;

    @Override
    public boolean canHandle(ExternalLinkContext linkContext) {
        return linkContext.getRequestParams().containsKey("screen");
    }

    @Override
    public void handle(ExternalLinkContext linkContext) {
        String screenName = linkContext.getRequestParams().get("screen");
        App app = linkContext.getApp();

        final WindowInfo windowInfo = windowConfig.getWindowInfo(screenName);
        if (windowInfo == null) {
            log.warn("WindowInfo not found for screen: {}", screenName);
            return;
        }

        try {
            openWindow(windowInfo, linkContext);
        } catch (EntityAccessException e) {
            entityAccessExceptionHandler.handle(e, app.getWindowManager());
        } catch (AccessDeniedException e) {
            accessDeniedHandler.handle(e, app.getWindowManager());
        } catch (NoSuchScreenException e) {
            noSuchScreenHandler.handle(e, app.getWindowManager());
        }
    }

    protected void openWindow(WindowInfo windowInfo, ExternalLinkContext linkContext) {
        Map<String, String> requestParams = linkContext.getRequestParams();
        App app = linkContext.getApp();

        String itemStr = requestParams.get("item");
        String openTypeParam = requestParams.get("openType");
        OpenType openType = OpenType.NEW_TAB;

        if (StringUtils.isNotEmpty(openTypeParam)) {
            try {
                openType = OpenType.valueOf(openTypeParam);
            } catch (IllegalArgumentException e) {
                log.warn("Unknown open type ({}) in request parameters", openTypeParam);
            }
        }

        if (itemStr == null) {
            app.getWindowManager().openWindow(windowInfo, openType, getParamsMap(requestParams));
        } else {
            EntityLoadInfo info = EntityLoadInfo.parse(itemStr);
            if (info == null) {
                log.warn("Invalid item definition: {}", itemStr);
            } else {
                Entity entity = loadEntityInstance(info);
                if (entity != null)
                    app.getWindowManager().openEditor(windowInfo, entity, openType, getParamsMap(requestParams));
                else
                    throw new EntityAccessException();
            }
        }
    }

    protected Map<String, Object> getParamsMap(Map<String, String> requestParams) {
        Map<String, Object> params = new HashMap<>();
        String paramsStr = requestParams.get("params");
        if (paramsStr == null)
            return params;

        String[] entries = paramsStr.split(",");
        for (String entry : entries) {
            String[] parts = entry.split(":");
            if (parts.length != 2) {
                log.warn("Invalid parameter: {}", entry);
                return params;
            }
            String name = parts[0];
            String value = parts[1];
            EntityLoadInfo info = EntityLoadInfo.parse(value);
            if (info != null) {
                Entity entity = loadEntityInstance(info);
                if (entity != null)
                    params.put(name, entity);
            } else if (Boolean.TRUE.toString().equals(value) || Boolean.FALSE.toString().equals(value)) {
                params.put(name, BooleanUtils.toBoolean(value));
            } else {
                params.put(name, value);
            }
        }
        return params;
    }

    protected Entity loadEntityInstance(EntityLoadInfo info) {
        if (info.isNewEntity()) {
            return metadata.create(info.getMetaClass());
        }

        @SuppressWarnings("unchecked")
        LoadContext<Entity> ctx = new LoadContext(info.getMetaClass()).setId(info.getId());
        if (info.getViewName() != null)
            ctx.setView(info.getViewName());
        Entity entity;
        try {
            entity = dataService.load(ctx);
        } catch (Exception e) {
            log.warn("Unable to load item: {}", info, e);
            return null;
        }
        return entity;
    }

    @Override
    public int getOrder() {
        return HIGHEST_PLATFORM_PRECEDENCE + 30;
    }
}


text:
# rs-motion Sample

> In order to run this example, a device supporting IMU (D435i) is required.

## Overview
This sample demonstrates how to use data from gyroscope and accelerometer to compute the rotation ([Euler Angles](https://en.wikipedia.org/wiki/Euler_angles)) of the camera, denoted by `theta`.

> The example is based on [code](https://github.com/GruffyPuffy/imutest) by @GruffyPuffy.

In this example, we use complemetary filter to aggregate data from gyroscope and accelerometer. For more information, you can look at this [tutorial](http://www.pieter-jan.com/node/11) by Pieter-Jan or this [presentation](https://github.com/jcarrus/MakeMITSelfBalancingRobot/blob/master/segspecs/filter.pdf) by Shane Colton, among other resources available online.

## Expected Output
![expected output](https://raw.githubusercontent.com/wiki/IntelRealSense/librealsense/res/imu.gif)

The application should open a window with a 3D model of the camera, approximating the physical orientation. In addition, you should be able to interact with the camera using your mouse, for rotating, zooming, and panning.

## Code Overview

First, we include the Intel® RealSense™ Cross-Platform API.
All but advanced functionality is provided through a single header:
```cpp
#include <librealsense2/rs.hpp> // Include RealSense Cross Platform API
```

In this example we will also use the auxiliary library of `example.hpp`:
```cpp
#include "../example.hpp"
```

We define 3 auxilary functions: `draw_axes` and `draw_floor`, which draw axes and floor grid respectively; and `render_scene` which prepares the general set-up of the scence, handles user manipulation etc.

Rendering the 3D model of the camera is encapsulated inside `camera_renderer` class. It holds vertexes of the camera model and applies rotation according to `theta`.

Calculation of the rotation angle, based on gyroscope and accelerometer data, is handled by the class `rotation_estimator`.
The class holds `theta` itself, which is updated on each IMU frame. We will process IMU frames asynchronously and therefore a mutex `theta_mtx` is needed ([learn more](https://github.com/IntelRealSense/librealsense/tree/master/examples/callback)).

`rotation_estimator` also holds the parameter `alpha`, which is used to combine gyroscope and accelerometer data in the calculation of `theta`.
The first iteration needs separate handling and therfore `first` is defined.
`last_ts_gyro` is needed to calculate the time elapsed between arrival of subsequent frames from gyroscope stream.
```cpp
// theta is the angle of camera rotation in x, y and z components
float3 theta;
std::mutex theta_mtx;
/* alpha indicates the part that gyro and accelerometer take in computation of theta; higher alpha gives more
weight to gyro, but too high values cause drift; lower alpha gives more weight to accelerometer, which is more
sensitive to disturbances */
float alpha = 0.98;
bool first = true;
// Keeps the arrival time of previous gyro frame
double last_ts_gyro = 0;
```

The function `process_gyro` computes the change in rotation angle, based on gyroscope measurements. It accepts `gyro_data`, an `rs2_vector` containing measurements retrieved from gyroscope, and `ts`, the timestamp of the current frame from gyroscope stream.

In order to compute the change in the direction of motion, we multiply gyroscope measurements by the length of the time period they correspond to (which equals the time passed since we processed the previous gyro frame). Then, we add or subtract from the current `theta` the retrieved angle difference. The sign is determined by the defined positive direction of the axis.

Note that gyroscope data is ignored until accelerometer data arrives, since the initial position is retrieved from the accelerometer (and afterwards, gyroscope allows us to calculate the direction of motion ).

```cpp
void process_gyro(rs2_vector gyro_data, double ts)
{
    if (first) // On the first iteration, use only data from accelerometer to set the camera's initial position
    {
        last_ts_gyro = ts;
        return;
    }
    // Holds the change in angle, as calculated from gyro
    float3 gyro_angle;

     // Initialize gyro_angle with data from gyro
    gyro_angle.x = gyro_data.x; // Pitch
    gyro_angle.y = gyro_data.y; // Yaw
    gyro_angle.z = gyro_data.z; // Roll

    // Compute the difference between arrival times of previous and current gyro frames
    double dt_gyro = (ts - last_ts_gyro) / 1000.0;
    last_ts_gyro = ts;

    // Change in angle equals gyro measurements * time passed since last measurement
    gyro_angle = gyro_angle * dt_gyro;

    // Apply the calculated change of angle to the current angle (theta)
    std::lock_guard<std::mutex> lock(theta_mtx);
	theta.add(-gyro_angle.z, -gyro_angle.y, gyro_angle.x);
}
```

The function `process_accel` computes the rotation angle from accelerometer data and updates the current `theta`. `accel_data` is an `rs2_vector` that holds the measurements retrieved from the accelerometer stream.

The angles in the z and x axis are computed from acclerometer data, using trigonometric calculations. Note that motion around Y axis cannot be estimated using accelerometer.
```cpp
void process_accel(rs2_vector accel_data)
{
    // Holds the angle as calculated from accelerometer data
    float3 accel_angle;
    // Calculate rotation angle from accelerometer data
    accel_angle.z = atan2(accel_data.y, accel_data.z);
    accel_angle.x = atan2(accel_data.x, sqrt(accel_data.y * accel_data.y + accel_data.z * accel_data.z));
```

If it is the first time we handle accelerometer data, we intiailize `theta` with the angles computed above. `theta` in Y direction is set to `PI` (180 degrees), facing the user.
```cpp
    // If it is the first iteration, set initial pose of camera according to accelerometer data
    // (note the different handling for Y axis)
    std::lock_guard<std::mutex> lock(theta_mtx);
    if (first)
    {
        first = false;
        theta = accel_angle;
        // Since we can't infer the angle around Y axis using accelerometer data, we'll use PI as a convetion
        // for the initial pose
        theta.y = PI;
    }
```

Otherwise, we use an approximate version of Complementary Filter to balance gyroscope and accelerometer results. Gyroscope gives generally accurate motion data, but it tends to drift, not returning to zero when the system goes back to its original position. Accelerometer, on the other hand, doesn't have this problem, but its signals are not as smooth and are easily affected by noises and disturbances. We use `alpha` to aggregate the data. New `theta` is the combination of the previous angle adjusted by difference computed from gyroscope data, and the angle calculated from accelerometer data. Note that this calculation does not apply to the Y component of `theta`, since it is measured by gyroscope only.
```cpp
        else
        {
            /*
            Apply Complementary Filter:
                - "high-pass filter" = theta * alpha:  allows short-duration signals to pass through while
                  filtering out signals that are steady over time, is used to cancel out drift.
                - "low-pass filter" = accel * (1- alpha): lets through long term changes, filtering out short
                  term fluctuations
            */
            theta.x = theta.x * alpha + accel_angle.x * (1 - alpha);
            theta.z = theta.z * alpha + accel_angle.z * (1 - alpha);
        }
    }
```

The main function handels frames arriving from IMU streams.

First, we check that a device that supports IMU is connected by calling the function `check_imu_is_supported`. This function queries all sensors from all devices and checks if their profiles support IMU streams. If a device that supports the streams `RS2_STREAM_GYRO` and `RS2_STREAM_ACCEL` is not found, we return an error code.

If the check passed successfully, we start the example. We declare the pipeline and configure it with `RS2_STREAM_ACCEL` and `RS2_STREAM_GYRO`.
```cpp
// Declare RealSense pipeline, encapsulating the actual device and sensors
rs2::pipeline pipe;
// Create a configuration for configuring the pipeline with a non default profile
rs2::config cfg;

// Add streams of gyro and accelerometer to configuration
cfg.enable_stream(RS2_STREAM_ACCEL, RS2_FORMAT_MOTION_XYZ32F);
cfg.enable_stream(RS2_STREAM_GYRO,  RS2_FORMAT_MOTION_XYZ32F);
```

Next, we declare objects of the helper classes we defined above.
```cpp
// Declare object for rendering camera motion
camera_renderer camera;
// Declare object that handles camera pose calculations
rotation_estimator algo;
```

To process frames from gyroscope and accelerometer streams asynchronously, we'll use pipeline's callback. This will ensure minimal latency. When a frame arrives, we cast it to `rs2::motion_frame`. If it's a gyro frame, we also find its timestamp using `motion.get_timestamp()`. Then, we can get the IMU data and call the corresponding function to calculate rotation angle.
```cpp
auto profile = pipe.start(cfg, [&](rs2::frame frame)
{
    // Cast the frame that arrived to motion frame
    auto motion = frame.as<rs2::motion_frame>();
    // If casting succeeded and the arrived frame is from gyro stream
    if (motion && motion.get_profile().stream_type() == RS2_STREAM_GYRO &&
    	motion.get_profile().format() == RS2_FORMAT_MOTION_XYZ32F)
    {
        // Get the timestamp of the current frame
        double ts = motion.get_timestamp();
        // Get gyro measurements
        rs2_vector gyro_data = motion.get_motion_data();
        // Call function that computes the angle of motion based on the retrieved data
        algo.process_gyro(gyro_data, ts);
    }
    // If casting succeeded and the arrived frame is from accelerometer stream
    if (motion && motion.get_profile().stream_type() == RS2_STREAM_ACCEL &&
    	motion.get_profile().format() == RS2_FORMAT_MOTION_XYZ32F)
    {
        // Get accelerometer measurements
        rs2_vector accel_data = motion.get_motion_data();
        // Call function that computes the angle of motion based on the retrieved data
        algo.process_accel(accel_data);
    }
});
```

The main loop renders the camera model, retrieving the current `theta` from the `algo` object in each iteration.
```cpp
while (app)
{
    // Configure scene, draw floor, handle manipultation by the user etc.
    render_scene(app_state);
    // Draw the camera according to the computed theta
    camera.render_camera(algo.get_theta());
}
```


text:
package com.cedarsoftware.util;

import org.junit.Assert;
import org.junit.Test;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.HashSet;
import java.util.Set;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

/**
 * Created by kpartlow on 5/5/2014.
 */
public class TestProxyFactory
{
    @Test
    public void testClassCompliance() throws Exception {
        Class c = ProxyFactory.class;
        Assert.assertEquals(Modifier.FINAL, c.getModifiers() & Modifier.FINAL);

        Constructor<ProxyFactory> con = c.getDeclaredConstructor();
        Assert.assertEquals(Modifier.PRIVATE, con.getModifiers() & Modifier.PRIVATE);

        con.setAccessible(true);
        Assert.assertNotNull(con.newInstance());
    }

    @Test
    public void testProxyFactory() {
        final Set<String> set = new HashSet<String>();

        AInt i = ProxyFactory.create(AInt.class, new InvocationHandler(){

            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
            {
                set.add(method.getName());
                return null;
            }
        });

        assertTrue(set.isEmpty());
        i.foo();
        assertTrue(set.contains("foo"));
        assertFalse(set.contains("bar"));
        assertFalse(set.contains("baz"));
        i.bar();
        assertTrue(set.contains("foo"));
        assertTrue(set.contains("bar"));
        assertFalse(set.contains("baz"));
        i.baz();
        assertTrue(set.contains("foo"));
        assertTrue(set.contains("bar"));
        assertTrue(set.contains("baz"));
    }

    private interface AInt
    {
        public void foo();
        public void bar();
        public void baz();
    }

}