text:
<?php

// Ensure that the class autoloader is the first include.
require_once 'google/appengine/runtime/autoloader.php';

function _gae_syslog($priority, $format_string, $message) {
  // TODO(bquinlan): Use the logs service to persist this message.
}

$unsetEnv = function($var_name) {
  putenv($var_name);
  unset($_ENV[$var_name]);
  unset($_SERVER[$var_name]);
};

$setup = function() {
  $setupGaeExtension = function() {
    $allowed_buckets = '';
    $ini_file = getenv('APPLICATION_ROOT') . DIRECTORY_SEPARATOR . 'php.ini';
    $config_values = @parse_ini_file($ini_file);
    if ($config_values &&
        array_key_exists('google_app_engine.allow_include_gs_buckets',
                         $config_values)) {
      $allowed_buckets =
          $config_values['google_app_engine.allow_include_gs_buckets'];
    }
    define('GAE_INCLUDE_REQUIRE_GS_STREAMS',
           // All values are considered true except the empty string.
           $allowed_buckets ? 1 : 0);
    define('GAE_INCLUDE_GS_BUCKETS', $allowed_buckets);
  };

  $configureDefaults = function() {
    if (!ini_get('date.timezone')) {
      date_default_timezone_set('UTC');
    }
  };

  $updateScriptFilename = function() {
    $unixPath = function($path) {
      return str_replace(DIRECTORY_SEPARATOR, "/", $path);
    };

    global $unsetEnv;
    $_SERVER['DOCUMENT_ROOT'] = $unixPath($_SERVER['APPLICATION_ROOT']);
    $unsetEnv('APPLICATION_ROOT');

    putenv('SCRIPT_FILENAME=' . getenv('REAL_SCRIPT_FILENAME'));
    $_ENV['SCRIPT_FILENAME'] = getenv('REAL_SCRIPT_FILENAME');

    $relativePath = dirname(getenv('REAL_SCRIPT_FILENAME'));
    // $actualPath = full path to file, discovered using
    // stream_resolve_include_path checking include paths against
    // $relativePath to see if directory exists.
    $actualPath = stream_resolve_include_path($relativePath);
    chdir($actualPath);

    $_SERVER['SCRIPT_FILENAME'] = $unixPath(getenv('REAL_SCRIPT_FILENAME'));
    $unsetEnv('REAL_SCRIPT_FILENAME');

    // Replicate the SCRIPT_NAME and PHP_SELF setup used in production.
    // Set SCRIPT_NAME to SCRIPT_FILENAME made relative to DOCUMENT_ROOT and
    // PHP_SELF to SCRIPT_NAME except when the script is included in PATH_INFO (
    // REQUEST_URI without the query string) which matches Apache behavior.
    $_SERVER['SCRIPT_NAME'] = substr(
      $_SERVER['SCRIPT_FILENAME'], strlen($_SERVER['DOCUMENT_ROOT']));
    if (strpos($_SERVER['PATH_INFO'], $_SERVER['SCRIPT_NAME']) === 0) {
      $_SERVER['PHP_SELF'] = $_SERVER['PATH_INFO'];
    } else {
      $_SERVER['PHP_SELF'] = $_SERVER['SCRIPT_NAME'];
    }
  };

  $setupApiProxy = function() {
    global $unsetEnv;
    if (!function_exists('make_call')) {
      require_once 'google/appengine/runtime/ApiProxy.php';
      require_once 'google/appengine/runtime/RemoteApiProxy.php';
      \google\appengine\runtime\ApiProxy::setApiProxy(
        new \google\appengine\runtime\RemoteApiProxy(
          getenv('REMOTE_API_HOST'), getenv('REMOTE_API_PORT'),
          getenv('REMOTE_REQUEST_ID')));
      $unsetEnv('REMOTE_API_HOST');
      $unsetEnv('REMOTE_API_PORT');
      $unsetEnv('REMOTE_REQUEST_ID');
    }
  };

  $setupBuiltins = function() {
    require_once 'google/appengine/runtime/Setup.php';
  };

  $setupAPC = function() {
    /**
     * On the development AppServer users may not have APC available, especially
     * if they built the php-cgi binary themselves. Provide stub functions here
     * so we don't need to complicate the logic later by checking if the
     * functions are avaialble.
     */
    if (!function_exists('apc_fetch')) {
      function apc_fetch($key, &$success) {
        $success = false;
        return false;
      }

      function apc_store($name, $value, $ttl) {
        return false;
      }
    }
  };

  if (!extension_loaded('GAE Runtime Module')) {
    $setupGaeExtension();
  }
  $configureDefaults();
  $updateScriptFilename();
  $setupApiProxy();
  $setupBuiltins();
  $setupAPC();
};
$setup();
unset($setup);

if (isset($_ENV['HTTP_X_APPENGINE_DEV_REQUEST_TYPE']) &&
    $_ENV['HTTP_X_APPENGINE_DEV_REQUEST_TYPE'] == 'interactive') {
  $unsetEnv('HTTP_X_APPENGINE_DEV_REQUEST_TYPE');
  unset($unsetEnv);
  eval(file_get_contents("php://input"));
} else {
  unset($unsetEnv);
  require($_ENV['SCRIPT_FILENAME']);
}


text:
#pragma once

#include <string>

#include "envoy/config/route/v3/route.pb.h"
#include "envoy/event/dispatcher.h"
#include "envoy/extensions/filters/network/http_connection_manager/v3/http_connection_manager.pb.h"
#include "envoy/json/json_object.h"
#include "envoy/local_info/local_info.h"
#include "envoy/router/rds.h"
#include "envoy/runtime/runtime.h"
#include "envoy/server/filter_config.h"
#include "envoy/thread_local/thread_local.h"
#include "envoy/upstream/cluster_manager.h"

namespace Envoy {
namespace Router {

/**
 * The RouteConfigProviderManager exposes the ability to get a RouteConfigProvider. This interface
 * is exposed to the Server's FactoryContext in order to allow HttpConnectionManagers to get
 * RouteConfigProviders.
 */
class RouteConfigProviderManager {
public:
  virtual ~RouteConfigProviderManager() = default;

  /**
   * Get a RouteConfigProviderPtr for a route from RDS. Ownership of the RouteConfigProvider is the
   * HttpConnectionManagers who calls this function. The RouteConfigProviderManager holds raw
   * pointers to the RouteConfigProviders. Clean up of the pointers happen from the destructor of
   * the RouteConfigProvider. This method creates a RouteConfigProvider which may share the
   * underlying RDS subscription with the same (route_config_name, cluster).
   * @param rds supplies the proto configuration of an RDS-configured RouteConfigProvider.
   * @param factory_context is the context to use for the route config provider.
   * @param stat_prefix supplies the stat_prefix to use for the provider stats.
   * @param init_manager the Init::Manager used to coordinate initialization of a the underlying RDS
   * subscription.
   */
  virtual RouteConfigProviderSharedPtr createRdsRouteConfigProvider(
      const envoy::extensions::filters::network::http_connection_manager::v3::Rds& rds,
      Server::Configuration::FactoryContext& factory_context, const std::string& stat_prefix,
      Init::Manager& init_manager) PURE;

  /**
   * Get a RouteConfigSharedPtr for a statically defined route. Ownership is as described for
   * getRdsRouteConfigProvider above. This method always create a new RouteConfigProvider.
   * @param route_config supplies the RouteConfiguration for this route
   * @param runtime supplies the runtime loader.
   * @param cm supplies the ClusterManager.
   */
  virtual RouteConfigProviderPtr
  createStaticRouteConfigProvider(const envoy::config::route::v3::RouteConfiguration& route_config,
                                  Server::Configuration::FactoryContext& factory_context) PURE;
};

} // namespace Router
} // namespace Envoy

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<component xmlns="http://www.osgi.org/xmlns/scr/v1.1.0">

	<implementation class="gov.nasa.arc.mct.component.management.console.ManagementConsoleComponentProvider" />

	<property name="service.description" value="NASA MCT Component - Management Console" />
	<property name="service.vendor" value="NASA MCT" />

	<service>
		<provide interface="gov.nasa.arc.mct.services.component.ComponentProvider" />
	</service>

</component>


text:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from ray.tune.error import TuneError
from ray.tune.tune import run_experiments, run
from ray.tune.experiment import Experiment
from ray.tune.analysis import ExperimentAnalysis, Analysis
from ray.tune.registry import register_env, register_trainable
from ray.tune.trainable import Trainable
from ray.tune.suggest import grid_search
from ray.tune.sample import (function, sample_from, uniform, choice, randint,
                             randn, loguniform)

__all__ = [
    "Trainable", "TuneError", "grid_search", "register_env",
    "register_trainable", "run", "run_experiments", "Experiment", "function",
    "sample_from", "track", "uniform", "choice", "randint", "randn",
    "loguniform", "ExperimentAnalysis", "Analysis"
]


text:
package eviction

import (
	"fmt"
	"sort"
	"sync"
	"time"

	"github.com/golang/glog"

	"k8s.io/apimachinery/pkg/api/resource"
	"k8s.io/apimachinery/pkg/util/clock"
	"k8s.io/apimachinery/pkg/util/wait"
	utilfeature "k8s.io/apiserver/pkg/util/feature"
	clientv1 "k8s.io/client-go/pkg/api/v1"
	"k8s.io/client-go/tools/record"
	"k8s.io/kubernetes/pkg/api/v1"
	v1qos "k8s.io/kubernetes/pkg/api/v1/helper/qos"
	"k8s.io/kubernetes/pkg/features"
	statsapi "k8s.io/kubernetes/pkg/kubelet/apis/stats/v1alpha1"
	"k8s.io/kubernetes/pkg/kubelet/cm"
	evictionapi "k8s.io/kubernetes/pkg/kubelet/eviction/api"
	"k8s.io/kubernetes/pkg/kubelet/lifecycle"
	"k8s.io/kubernetes/pkg/kubelet/metrics"
	kubepod "k8s.io/kubernetes/pkg/kubelet/pod"
	"k8s.io/kubernetes/pkg/kubelet/server/stats"
	kubelettypes "k8s.io/kubernetes/pkg/kubelet/types"
	"k8s.io/kubernetes/pkg/kubelet/util/format"
)

const (
	podCleanupTimeout  = 30 * time.Second
	podCleanupPollFreq = time.Second
)

// managerImpl implements Manager
type managerImpl struct {
	//  used to track time
	clock clock.Clock
	// config is how the manager is configured
	config Config
	// the function to invoke to kill a pod
	killPodFunc KillPodFunc
	// the interface that knows how to do image gc
	imageGC ImageGC
	// the interface that knows how to do image gc
	containerGC ContainerGC
	// protects access to internal state
	sync.RWMutex
	// node conditions are the set of conditions present
	nodeConditions []v1.NodeConditionType
	// captures when a node condition was last observed based on a threshold being met
	nodeConditionsLastObservedAt nodeConditionsObservedAt
	// nodeRef is a reference to the node
	nodeRef *clientv1.ObjectReference
	// used to record events about the node
	recorder record.EventRecorder
	// used to measure usage stats on system
	summaryProvider stats.SummaryProvider
	// records when a threshold was first observed
	thresholdsFirstObservedAt thresholdsObservedAt
	// records the set of thresholds that have been met (including graceperiod) but not yet resolved
	thresholdsMet []evictionapi.Threshold
	// resourceToRankFunc maps a resource to ranking function for that resource.
	resourceToRankFunc map[v1.ResourceName]rankFunc
	// resourceToNodeReclaimFuncs maps a resource to an ordered list of functions that know how to reclaim that resource.
	resourceToNodeReclaimFuncs map[v1.ResourceName]nodeReclaimFuncs
	// last observations from synchronize
	lastObservations signalObservations
	// notifiersInitialized indicates if the threshold notifiers have been initialized (i.e. synchronize() has been called once)
	notifiersInitialized bool
	// dedicatedImageFs indicates if imagefs is on a separate device from the rootfs
	dedicatedImageFs *bool
}

// ensure it implements the required interface
var _ Manager = &managerImpl{}

// NewManager returns a configured Manager and an associated admission handler to enforce eviction configuration.
func NewManager(
	summaryProvider stats.SummaryProvider,
	config Config,
	killPodFunc KillPodFunc,
	imageGC ImageGC,
	containerGC ContainerGC,
	recorder record.EventRecorder,
	nodeRef *clientv1.ObjectReference,
	clock clock.Clock) (Manager, lifecycle.PodAdmitHandler) {
	manager := &managerImpl{
		clock:           clock,
		killPodFunc:     killPodFunc,
		imageGC:         imageGC,
		containerGC:     containerGC,
		config:          config,
		recorder:        recorder,
		summaryProvider: summaryProvider,
		nodeRef:         nodeRef,
		nodeConditionsLastObservedAt: nodeConditionsObservedAt{},
		thresholdsFirstObservedAt:    thresholdsObservedAt{},
		dedicatedImageFs:             nil,
	}
	return manager, manager
}

// Admit rejects a pod if its not safe to admit for node stability.
func (m *managerImpl) Admit(attrs *lifecycle.PodAdmitAttributes) lifecycle.PodAdmitResult {
	m.RLock()
	defer m.RUnlock()
	if len(m.nodeConditions) == 0 {
		return lifecycle.PodAdmitResult{Admit: true}
	}
	// Admit Critical pods even under resource pressure since they are required for system stability.
	// https://github.com/kubernetes/kubernetes/issues/40573 has more details.
	if utilfeature.DefaultFeatureGate.Enabled(features.ExperimentalCriticalPodAnnotation) && kubelettypes.IsCriticalPod(attrs.Pod) {
		return lifecycle.PodAdmitResult{Admit: true}
	}
	// the node has memory pressure, admit if not best-effort
	if hasNodeCondition(m.nodeConditions, v1.NodeMemoryPressure) {
		notBestEffort := v1.PodQOSBestEffort != v1qos.GetPodQOS(attrs.Pod)
		if notBestEffort {
			return lifecycle.PodAdmitResult{Admit: true}
		}
	}

	// reject pods when under memory pressure (if pod is best effort), or if under disk pressure.
	glog.Warningf("Failed to admit pod %s - node has conditions: %v", format.Pod(attrs.Pod), m.nodeConditions)
	return lifecycle.PodAdmitResult{
		Admit:   false,
		Reason:  reason,
		Message: fmt.Sprintf(message, m.nodeConditions),
	}
}

// Start starts the control loop to observe and response to low compute resources.
func (m *managerImpl) Start(diskInfoProvider DiskInfoProvider, podFunc ActivePodsFunc, podCleanedUpFunc PodCleanedUpFunc, nodeProvider NodeProvider, monitoringInterval time.Duration) {
	// start the eviction manager monitoring
	go func() {
		for {
			if evictedPods := m.synchronize(diskInfoProvider, podFunc, nodeProvider); evictedPods != nil {
				glog.Infof("eviction manager: pods %s evicted, waiting for pod to be cleaned up", format.Pods(evictedPods))
				m.waitForPodsCleanup(podCleanedUpFunc, evictedPods)
			} else {
				time.Sleep(monitoringInterval)
			}
		}
	}()
}

// IsUnderMemoryPressure returns true if the node is under memory pressure.
func (m *managerImpl) IsUnderMemoryPressure() bool {
	m.RLock()
	defer m.RUnlock()
	return hasNodeCondition(m.nodeConditions, v1.NodeMemoryPressure)
}

// IsUnderDiskPressure returns true if the node is under disk pressure.
func (m *managerImpl) IsUnderDiskPressure() bool {
	m.RLock()
	defer m.RUnlock()
	return hasNodeCondition(m.nodeConditions, v1.NodeDiskPressure)
}

func startMemoryThresholdNotifier(thresholds []evictionapi.Threshold, observations signalObservations, hard bool, handler thresholdNotifierHandlerFunc) error {
	for _, threshold := range thresholds {
		if threshold.Signal != evictionapi.SignalMemoryAvailable || hard != isHardEvictionThreshold(threshold) {
			continue
		}
		observed, found := observations[evictionapi.SignalMemoryAvailable]
		if !found {
			continue
		}
		cgroups, err := cm.GetCgroupSubsystems()
		if err != nil {
			return err
		}
		// TODO add support for eviction from --cgroup-root
		cgpath, found := cgroups.MountPoints["memory"]
		if !found || len(cgpath) == 0 {
			return fmt.Errorf("memory cgroup mount point not found")
		}
		attribute := "memory.usage_in_bytes"
		quantity := evictionapi.GetThresholdQuantity(threshold.Value, observed.capacity)
		usageThreshold := resource.NewQuantity(observed.capacity.Value(), resource.DecimalSI)
		usageThreshold.Sub(*quantity)
		description := fmt.Sprintf("<%s available", formatThresholdValue(threshold.Value))
		memcgThresholdNotifier, err := NewMemCGThresholdNotifier(cgpath, attribute, usageThreshold.String(), description, handler)
		if err != nil {
			return err
		}
		go memcgThresholdNotifier.Start(wait.NeverStop)
		return nil
	}
	return nil
}

// synchronize is the main control loop that enforces eviction thresholds.
// Returns the pod that was killed, or nil if no pod was killed.
func (m *managerImpl) synchronize(diskInfoProvider DiskInfoProvider, podFunc ActivePodsFunc, nodeProvider NodeProvider) []*v1.Pod {
	// if we have nothing to do, just return
	thresholds := m.config.Thresholds
	if len(thresholds) == 0 {
		return nil
	}

	glog.V(3).Infof("eviction manager: synchronize housekeeping")
	// build the ranking functions (if not yet known)
	// TODO: have a function in cadvisor that lets us know if global housekeeping has completed
	if m.dedicatedImageFs == nil {
		hasImageFs, ok := diskInfoProvider.HasDedicatedImageFs()
		if ok != nil {
			return nil
		}
		m.dedicatedImageFs = &hasImageFs
		m.resourceToRankFunc = buildResourceToRankFunc(hasImageFs)
		m.resourceToNodeReclaimFuncs = buildResourceToNodeReclaimFuncs(m.imageGC, m.containerGC, hasImageFs)
	}

	activePods := podFunc()
	// make observations and get a function to derive pod usage stats relative to those observations.
	observations, statsFunc, err := makeSignalObservations(m.summaryProvider, nodeProvider, activePods, *m.dedicatedImageFs)
	if err != nil {
		glog.Errorf("eviction manager: unexpected err: %v", err)
		return nil
	}
	debugLogObservations("observations", observations)

	// attempt to create a threshold notifier to improve eviction response time
	if m.config.KernelMemcgNotification && !m.notifiersInitialized {
		glog.Infof("eviction manager attempting to integrate with kernel memcg notification api")
		m.notifiersInitialized = true
		// start soft memory notification
		err = startMemoryThresholdNotifier(m.config.Thresholds, observations, false, func(desc string) {
			glog.Infof("soft memory eviction threshold crossed at %s", desc)
			// TODO wait grace period for soft memory limit
			m.synchronize(diskInfoProvider, podFunc, nodeProvider)
		})
		if err != nil {
			glog.Warningf("eviction manager: failed to create hard memory threshold notifier: %v", err)
		}
		// start hard memory notification
		err = startMemoryThresholdNotifier(m.config.Thresholds, observations, true, func(desc string) {
			glog.Infof("hard memory eviction threshold crossed at %s", desc)
			m.synchronize(diskInfoProvider, podFunc, nodeProvider)
		})
		if err != nil {
			glog.Warningf("eviction manager: failed to create soft memory threshold notifier: %v", err)
		}
	}

	// determine the set of thresholds met independent of grace period
	thresholds = thresholdsMet(thresholds, observations, false)
	debugLogThresholdsWithObservation("thresholds - ignoring grace period", thresholds, observations)

	// determine the set of thresholds previously met that have not yet satisfied the associated min-reclaim
	if len(m.thresholdsMet) > 0 {
		thresholdsNotYetResolved := thresholdsMet(m.thresholdsMet, observations, true)
		thresholds = mergeThresholds(thresholds, thresholdsNotYetResolved)
	}
	debugLogThresholdsWithObservation("thresholds - reclaim not satisfied", thresholds, observations)

	// determine the set of thresholds whose stats have been updated since the last sync
	thresholds = thresholdsUpdatedStats(thresholds, observations, m.lastObservations)
	debugLogThresholdsWithObservation("thresholds - updated stats", thresholds, observations)

	// track when a threshold was first observed
	now := m.clock.Now()
	thresholdsFirstObservedAt := thresholdsFirstObservedAt(thresholds, m.thresholdsFirstObservedAt, now)

	// the set of node conditions that are triggered by currently observed thresholds
	nodeConditions := nodeConditions(thresholds)
	if len(nodeConditions) > 0 {
		glog.V(3).Infof("eviction manager: node conditions - observed: %v", nodeConditions)
	}

	// track when a node condition was last observed
	nodeConditionsLastObservedAt := nodeConditionsLastObservedAt(nodeConditions, m.nodeConditionsLastObservedAt, now)

	// node conditions report true if it has been observed within the transition period window
	nodeConditions = nodeConditionsObservedSince(nodeConditionsLastObservedAt, m.config.PressureTransitionPeriod, now)
	if len(nodeConditions) > 0 {
		glog.V(3).Infof("eviction manager: node conditions - transition period not met: %v", nodeConditions)
	}

	// determine the set of thresholds we need to drive eviction behavior (i.e. all grace periods are met)
	thresholds = thresholdsMetGracePeriod(thresholdsFirstObservedAt, now)
	debugLogThresholdsWithObservation("thresholds - grace periods satisified", thresholds, observations)

	// update internal state
	m.Lock()
	m.nodeConditions = nodeConditions
	m.thresholdsFirstObservedAt = thresholdsFirstObservedAt
	m.nodeConditionsLastObservedAt = nodeConditionsLastObservedAt
	m.thresholdsMet = thresholds
	m.lastObservations = observations
	m.Unlock()

	// evict pods if there is a resource uage violation from local volume temporary storage
	// If eviction happenes in localVolumeEviction function, skip the rest of eviction action
	if utilfeature.DefaultFeatureGate.Enabled(features.LocalStorageCapacityIsolation) {
		if evictedPods := m.localStorageEviction(activePods); len(evictedPods) > 0 {
			return evictedPods
		}
	}

	// determine the set of resources under starvation
	starvedResources := getStarvedResources(thresholds)
	if len(starvedResources) == 0 {
		glog.V(3).Infof("eviction manager: no resources are starved")
		return nil
	}

	// rank the resources to reclaim by eviction priority
	sort.Sort(byEvictionPriority(starvedResources))
	resourceToReclaim := starvedResources[0]
	glog.Warningf("eviction manager: attempting to reclaim %v", resourceToReclaim)

	// determine if this is a soft or hard eviction associated with the resource
	softEviction := isSoftEvictionThresholds(thresholds, resourceToReclaim)

	// record an event about the resources we are now attempting to reclaim via eviction
	m.recorder.Eventf(m.nodeRef, v1.EventTypeWarning, "EvictionThresholdMet", "Attempting to reclaim %s", resourceToReclaim)

	// check if there are node-level resources we can reclaim to reduce pressure before evicting end-user pods.
	if m.reclaimNodeLevelResources(resourceToReclaim, observations) {
		glog.Infof("eviction manager: able to reduce %v pressure without evicting pods.", resourceToReclaim)
		return nil
	}

	glog.Infof("eviction manager: must evict pod(s) to reclaim %v", resourceToReclaim)

	// rank the pods for eviction
	rank, ok := m.resourceToRankFunc[resourceToReclaim]
	if !ok {
		glog.Errorf("eviction manager: no ranking function for resource %s", resourceToReclaim)
		return nil
	}

	// the only candidates viable for eviction are those pods that had anything running.
	if len(activePods) == 0 {
		glog.Errorf("eviction manager: eviction thresholds have been met, but no pods are active to evict")
		return nil
	}

	// rank the running pods for eviction for the specified resource
	rank(activePods, statsFunc)

	glog.Infof("eviction manager: pods ranked for eviction: %s", format.Pods(activePods))

	//record age of metrics for met thresholds that we are using for evictions.
	for _, t := range thresholds {
		timeObserved := observations[t.Signal].time
		if !timeObserved.IsZero() {
			metrics.EvictionStatsAge.WithLabelValues(string(t.Signal)).Observe(metrics.SinceInMicroseconds(timeObserved.Time))
		}
	}

	// we kill at most a single pod during each eviction interval
	for i := range activePods {
		pod := activePods[i]
		// If the pod is marked as critical and static, and support for critical pod annotations is enabled,
		// do not evict such pods. Static pods are not re-admitted after evictions.
		// https://github.com/kubernetes/kubernetes/issues/40573 has more details.
		if utilfeature.DefaultFeatureGate.Enabled(features.ExperimentalCriticalPodAnnotation) &&
			kubelettypes.IsCriticalPod(pod) && kubepod.IsStaticPod(pod) {
			continue
		}
		status := v1.PodStatus{
			Phase:   v1.PodFailed,
			Message: fmt.Sprintf(message, resourceToReclaim),
			Reason:  reason,
		}
		// record that we are evicting the pod
		m.recorder.Eventf(pod, v1.EventTypeWarning, reason, fmt.Sprintf(message, resourceToReclaim))
		gracePeriodOverride := int64(0)
		if softEviction {
			gracePeriodOverride = m.config.MaxPodGracePeriodSeconds
		}
		// this is a blocking call and should only return when the pod and its containers are killed.
		err := m.killPodFunc(pod, status, &gracePeriodOverride)
		if err != nil {
			glog.Warningf("eviction manager: error while evicting pod %s: %v", format.Pod(pod), err)
		}
		return []*v1.Pod{pod}
	}
	glog.Infof("eviction manager: unable to evict any pods from the node")
	return nil
}

func (m *managerImpl) waitForPodsCleanup(podCleanedUpFunc PodCleanedUpFunc, pods []*v1.Pod) {
	timeout := m.clock.NewTimer(podCleanupTimeout)
	tick := m.clock.Tick(podCleanupPollFreq)
	for {
		select {
		case <-timeout.C():
			glog.Warningf("eviction manager: timed out waiting for pods %s to be cleaned up", format.Pods(pods))
			return
		case <-tick:
			for i, pod := range pods {
				if !podCleanedUpFunc(pod) {
					break
				}
				if i == len(pods)-1 {
					glog.Infof("eviction manager: pods %s successfully cleaned up", format.Pods(pods))
					return
				}
			}
		}
	}
}

// reclaimNodeLevelResources attempts to reclaim node level resources.  returns true if thresholds were satisfied and no pod eviction is required.
func (m *managerImpl) reclaimNodeLevelResources(resourceToReclaim v1.ResourceName, observations signalObservations) bool {
	nodeReclaimFuncs := m.resourceToNodeReclaimFuncs[resourceToReclaim]
	for _, nodeReclaimFunc := range nodeReclaimFuncs {
		// attempt to reclaim the pressured resource.
		reclaimed, err := nodeReclaimFunc()
		if err != nil {
			glog.Warningf("eviction manager: unexpected error when attempting to reduce %v pressure: %v", resourceToReclaim, err)
		}
		// update our local observations based on the amount reported to have been reclaimed.
		// note: this is optimistic, other things could have been still consuming the pressured resource in the interim.
		signal := resourceToSignal[resourceToReclaim]
		value, ok := observations[signal]
		if !ok {
			glog.Errorf("eviction manager: unable to find value associated with signal %v", signal)
			continue
		}
		value.available.Add(*reclaimed)

		// evaluate all current thresholds to see if with adjusted observations, we think we have met min reclaim goals
		if len(thresholdsMet(m.thresholdsMet, observations, true)) == 0 {
			return true
		}
	}
	return false
}

// localStorageEviction checks the EmptyDir volume usage for each pod and determine whether it exceeds the specified limit and needs
// to be evicted. It also checks every container in the pod, if the container overlay usage exceeds the limit, the pod will be evicted too.
func (m *managerImpl) localStorageEviction(pods []*v1.Pod) []*v1.Pod {
	summary, err := m.summaryProvider.Get()
	if err != nil {
		glog.Errorf("Could not get summary provider")
		return nil
	}

	statsFunc := cachedStatsFunc(summary.Pods)
	evicted := []*v1.Pod{}
	for _, pod := range pods {
		podStats, ok := statsFunc(pod)
		if !ok {
			continue
		}

		if m.emptyDirLimitEviction(podStats, pod) {
			evicted = append(evicted, pod)
			continue
		}

		if m.containerOverlayLimitEviction(podStats, pod) {
			evicted = append(evicted, pod)
		}
	}

	return evicted
}

func (m *managerImpl) emptyDirLimitEviction(podStats statsapi.PodStats, pod *v1.Pod) bool {
	podVolumeUsed := make(map[string]*resource.Quantity)
	for _, volume := range podStats.VolumeStats {
		podVolumeUsed[volume.Name] = resource.NewQuantity(int64(*volume.UsedBytes), resource.BinarySI)
	}
	for i := range pod.Spec.Volumes {
		source := &pod.Spec.Volumes[i].VolumeSource
		if source.EmptyDir != nil {
			size := source.EmptyDir.SizeLimit
			used := podVolumeUsed[pod.Spec.Volumes[i].Name]
			if used != nil && size.Sign() == 1 && used.Cmp(size) > 0 {
				// the emptyDir usage exceeds the size limit, evict the pod
				return m.evictPod(pod, v1.ResourceName("EmptyDir"), fmt.Sprintf("emptyDir usage exceeds the limit %q", size.String()))
			}
		}
	}
	return false
}

func (m *managerImpl) containerOverlayLimitEviction(podStats statsapi.PodStats, pod *v1.Pod) bool {
	thresholdsMap := make(map[string]*resource.Quantity)
	for _, container := range pod.Spec.Containers {
		overlayLimit := container.Resources.Limits.StorageOverlay()
		if overlayLimit != nil && overlayLimit.Value() != 0 {
			thresholdsMap[container.Name] = overlayLimit
		}
	}

	for _, containerStat := range podStats.Containers {
		rootfs := diskUsage(containerStat.Rootfs)
		if overlayThreshold, ok := thresholdsMap[containerStat.Name]; ok {
			if overlayThreshold.Cmp(*rootfs) < 0 {
				return m.evictPod(pod, v1.ResourceName("containerOverlay"), fmt.Sprintf("container's overlay usage exceeds the limit %q", overlayThreshold.String()))

			}
		}
	}
	return false
}

func (m *managerImpl) evictPod(pod *v1.Pod, resourceName v1.ResourceName, evictMsg string) bool {
	if utilfeature.DefaultFeatureGate.Enabled(features.ExperimentalCriticalPodAnnotation) &&
		kubelettypes.IsCriticalPod(pod) && kubepod.IsStaticPod(pod) {
		glog.Errorf("eviction manager: cannot evict a critical pod %s", format.Pod(pod))
		return false
	}
	status := v1.PodStatus{
		Phase:   v1.PodFailed,
		Message: fmt.Sprintf(message, resourceName),
		Reason:  reason,
	}
	// record that we are evicting the pod
	m.recorder.Eventf(pod, v1.EventTypeWarning, reason, evictMsg)
	gracePeriod := int64(0)
	err := m.killPodFunc(pod, status, &gracePeriod)
	if err != nil {
		glog.Errorf("eviction manager: pod %s failed to evict %v", format.Pod(pod), err)
	} else {
		glog.Infof("eviction manager: pod %s is evicted successfully", format.Pod(pod))
	}
	return true
}


text:
<?php
namespace nochso\Omni\PhpCsFixer;

use Symfony\CS\Config\Config;
use Symfony\CS\FixerInterface;

/**
 * PrettyPSR lies inbetween FixerInterface's PSR2 and Symfony level.
 *
 * Create a new file `.php_cs` in your project root:
 *
 * ```
 * <?php
 * require_once 'vendor/autoload.php';
 * use nochso\Omni\PhpCsFixer\PrettyPSR;
 * return PrettyPSR::createIn(['src', 'test']);
 * ```
 *
 * Running `php-cs-fixer` will fix all files in folders `src` and `test`.
 *
 * Note that `php-cs-fixer` is not included by default. You have to require it first:
 * ```
 * composer require --dev fabpot/php-cs-fixer
 * ```
 */
class PrettyPSR extends Config {
	/**
	 * @param string|array $dirs
	 *
	 * @return static
	 */
	public static function createIn($dirs) {
		$config = new static();
		$config->finder(DefaultFinder::createIn($dirs));
		return $config;
	}

	/**
	 * @param string $name
	 * @param string $description
	 */
	public function __construct($name = self::class, $description = '') {
		parent::__construct($name, $description);
		$this->level = FixerInterface::PSR2_LEVEL;
		$this->fixers = $this->getDefaultFixers();
		$this->setUsingCache(true);
	}

	/**
	 * @return string[]
	 */
	public function getDefaultFixers() {
		return [
			'-psr0',
			'-return',
			'-concat_without_spaces',
			'-empty_return',
			'extra_empty_lines',
			'concat_with_spaces',
			'array_element_no_space_before_comma',
			'array_element_white_space_after_comma',
			'double_arrow_multiline_whitespaces',
			'duplicate_semicolon',
			'function_typehint_space',
			'include',
			'list_commas',
			'multiline_array_trailing_comma',
			'namespace_no_leading_whitespace',
			'newline_after_open_tag',
			'new_with_braces',
			'no_blank_lines_after_class_opening',
			'no_blank_lines_before_namespace',
			'no_empty_lines_after_phpdocs',
			'object_operator',
			'operators_spaces',
			'spaces_cast',
			'ordered_use',
			'phpdoc_indent',
			'phpdoc_inline_tag',
			'phpdoc_no_access',
			'phpdoc_no_package',
			'phpdoc_order',
			'phpdoc_params',
			'phpdoc_scalar',
			'phpdoc_separation',
			'phpdoc_short_description',
			'phpdoc_to_comment',
			'phpdoc_trim',
			'phpdoc_types',
			'phpdoc_type_to_var',
			'print_to_echo',
			'remove_lines_between_uses',
			'self_accessor',
			'short_array_syntax',
			'single_array_no_trailing_comma',
			'single_quote',
			'spaces_before_semicolon',
			'ternary_spaces',
			'trim_array_spaces',
			'unalign_double_arrow',
			'unalign_equals',
			'unary_operators_spaces',
			'unneeded_control_parentheses',
			'unused_use',
			'whitespacy_lines',
		];
	}
}


text:
package com.palantir.nexus.db.pool;

import com.google.common.base.Stopwatch;
import com.palantir.logsafe.Preconditions;
import com.palantir.logsafe.SafeArg;
import com.palantir.logsafe.UnsafeArg;
import com.palantir.logsafe.exceptions.SafeRuntimeException;
import com.palantir.nexus.db.DBType;
import com.palantir.nexus.db.pool.config.ConnectionConfig;
import com.palantir.nexus.db.sql.ExceptionCheck;
import com.zaxxer.hikari.HikariDataSource;
import com.zaxxer.hikari.HikariPoolMXBean;
import com.zaxxer.hikari.pool.HikariPool.PoolInitializationException;
import java.lang.management.ManagementFactory;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.TimeZone;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import javax.management.JMX;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * HikariCP Connection Manager.
 *
 * @author dstipp
 */
@SuppressWarnings("checkstyle:AbbreviationAsWordInName")
public class HikariCPConnectionManager extends BaseConnectionManager {
    private static final Logger log = LoggerFactory.getLogger(HikariCPConnectionManager.class);

    private ConnectionConfig connConfig;

    private enum StateType {
        // Base state at construction.  Nothing is set.
        ZERO,

        // "Normal" state.  dataSourcePool and poolProxy are set.
        NORMAL,

        // Closed state.  closeTrace is set.
        CLOSED;
    }

    private static class State {
        final StateType type;
        final HikariDataSource dataSourcePool;
        final HikariPoolMXBean poolProxy;
        final Throwable closeTrace;

        State(StateType type, HikariDataSource dataSourcePool, HikariPoolMXBean poolProxy, Throwable closeTrace) {
            this.type = type;
            this.dataSourcePool = dataSourcePool;
            this.poolProxy = poolProxy;
            this.closeTrace = closeTrace;
        }
    }

    private volatile State state = new State(StateType.ZERO, null, null, null);

    public HikariCPConnectionManager(ConnectionConfig connConfig) {
        this.connConfig = Preconditions.checkNotNull(connConfig, "ConnectionConfig must not be null");
    }

    @Override
    public Connection getConnection() throws SQLException {
        ConnectionAcquisitionProfiler profiler = new ConnectionAcquisitionProfiler();
        try {
            return acquirePooledConnection(profiler);
        } finally {
            profiler.logQueryDuration();
        }
    }

    /**
     * Attempts to acquire a valid database connection from the pool.
     * @param profiler Connection acquisition profiler for this attempt to acquire a connection
     * @return valid pooled connection
     * @throws SQLException if a connection cannot be acquired within the {@link ConnectionConfig#getCheckoutTimeout()}
     */
    private Connection acquirePooledConnection(ConnectionAcquisitionProfiler profiler) throws SQLException {
        while (true) {
            HikariDataSource dataSourcePool = checkAndGetDataSourcePool();
            Connection conn = dataSourcePool.getConnection();
            profiler.logAcquisitionAndRestart();

            try {
                testConnection(conn);
                profiler.logConnectionTest();
                return conn;
            } catch (SQLException e) {
                log.error(
                        "[{}] Dropping connection which failed validation",
                        SafeArg.of("connectionPoolName", connConfig.getConnectionPoolName()),
                        e);
                dataSourcePool.evictConnection(conn);

                if (profiler.globalStopwatch.elapsed(TimeUnit.MILLISECONDS) > connConfig.getCheckoutTimeout()) {
                    // It's been long enough that had hikari been
                    // validating internally it would have given up rather
                    // than retry
                    throw e;
                }
            }
        }
    }

    private void logPoolStats() {
        if (log.isWarnEnabled()) {
            State stateLocal = state;
            HikariPoolMXBean poolProxy = stateLocal.poolProxy;
            if (poolProxy != null) {
                try {
                    log.warn(
                            "[{}] HikariCP: "
                                    + "numBusyConnections = {}, "
                                    + "numIdleConnections = {}, "
                                    + "numConnections = {}, "
                                    + "numThreadsAwaitingCheckout = {}",
                            SafeArg.of("connectionPoolName", connConfig.getConnectionPoolName()),
                            SafeArg.of("activeConnections", poolProxy.getActiveConnections()),
                            SafeArg.of("idleConnections", poolProxy.getIdleConnections()),
                            SafeArg.of("totalConnections", poolProxy.getTotalConnections()),
                            SafeArg.of("threadsAwaitingConnection", poolProxy.getThreadsAwaitingConnection()));
                } catch (Exception e) {
                    log.error(
                            "[{}] Unable to log pool statistics.",
                            SafeArg.of("connectionPoolName", connConfig.getConnectionPoolName()),
                            e);
                }
            }
        }
    }

    private HikariDataSource checkAndGetDataSourcePool() throws SQLException {
        while (true) {
            // Volatile read state to see if we can get through here without locking.
            State stateLocal = state;

            switch (stateLocal.type) {
                case ZERO:
                    // Not yet initialized, no such luck.
                    synchronized (this) {
                        if (state == stateLocal) {
                            // The state hasn't changed on us, we can perform
                            // the initialization and start over again.
                            state = normalState();
                        } else {
                            // Someone else changed the state on us, just start over.
                        }
                    }
                    break;

                case NORMAL:
                    // Normal state, good to go
                    return stateLocal.dataSourcePool;

                case CLOSED:
                    throw new SQLException("Hikari connection pool already closed!", stateLocal.closeTrace);
            }

            // fall throughs are spins
        }
    }

    private void logConnectionFailure() {
        log.error(
                "Failed to get connection from the datasource "
                        + "{}. Please check the jdbc url ({}), the password, "
                        + "and that the secure server key is correct for the hashed password.",
                SafeArg.of("connectionPoolName", connConfig.getConnectionPoolName()),
                UnsafeArg.of("url", connConfig.getUrl()));
    }

    /**
     * Test an initialized dataSourcePool by running a simple query.
     * @param dataSourcePool data source to validate
     * @throws SQLException if data source is invalid and cannot be used.
     */
    private void testDataSource(HikariDataSource dataSourcePool) throws SQLException {
        try {
            try (Connection conn = dataSourcePool.getConnection()) {
                testConnection(conn);
            }
        } catch (SQLException e) {
            logConnectionFailure();
            throw e;
        }
    }

    /**
     * Test a database connection to determine if it is valid for use.
     * @param connection connection to validate
     * @throws SQLException if connection is invalid and cannot be used.
     */
    private void testConnection(Connection connection) throws SQLException {
        try (Statement stmt = connection.createStatement();
                ResultSet rs = stmt.executeQuery(connConfig.getTestQuery())) {
            if (!rs.next()) {
                throw new SQLException(String.format(
                        "Connection %s could not be validated as it did not return any results for test query %s",
                        connection, connConfig.getTestQuery()));
            }
        }
    }

    @Override
    public synchronized void close() {
        try {
            switch (state.type) {
                case ZERO:
                    break;

                case NORMAL:
                    if (log.isDebugEnabled()) {
                        log.debug(
                                "Closing connection pool",
                                UnsafeArg.of("connConfig", connConfig),
                                new SafeRuntimeException("Closing connection pool"));
                    }

                    state.dataSourcePool.close();
                    break;

                case CLOSED:
                    break;
            }
        } finally {
            state = new State(StateType.CLOSED, null, null, new Throwable("Hikari pool closed here"));
        }
    }

    /**
     * Initializes a connection to the provided database.
     */
    @Override
    public synchronized void init() throws SQLException {
        if (state.type == StateType.ZERO) {
            state = normalState();
        }
    }

    private State normalState() throws SQLException {
        HikariDataSource dataSourcePool = getDataSourcePool();
        boolean keep = false;

        try {
            // Setup monitoring
            HikariPoolMXBean poolProxy = initPoolMbeans();
            testDataSource(dataSourcePool);
            keep = true;
            return new State(StateType.NORMAL, dataSourcePool, poolProxy, null);
        } finally {
            if (!keep) {
                IOUtils.closeQuietly(dataSourcePool);
            }
        }
    }

    private HikariDataSource getDataSourcePool() {
        // Print a stack trace whenever we initialize a pool
        if (log.isDebugEnabled()) {
            log.debug(
                    "Initializing connection pool",
                    UnsafeArg.of("connConfig", connConfig),
                    new SafeRuntimeException("Initializing connection pool"));
        }

        HikariDataSource dataSourcePool;

        try {
            try {
                dataSourcePool = new HikariDataSource(connConfig.getHikariConfig());
            } catch (IllegalArgumentException e) {
                // allow multiple pools on same JVM (they need unique names / endpoints)
                if (e.getMessage().contains("A metric named")) {
                    String poolName = connConfig.getConnectionPoolName();

                    connConfig
                            .getHikariConfig()
                            .setPoolName(
                                    poolName + "-" + ThreadLocalRandom.current().nextInt());
                    dataSourcePool = new HikariDataSource(connConfig.getHikariConfig());
                } else {
                    throw e;
                }
            }
        } catch (PoolInitializationException e) {
            log.error(
                    "Failed to initialize hikari data source",
                    SafeArg.of("connectionPoolName", connConfig.getConnectionPoolName()),
                    UnsafeArg.of("url", connConfig.getUrl()),
                    e);

            if (ExceptionCheck.isTimezoneInvalid(e)) {
                String tzname = TimeZone.getDefault().getID();

                final String errorPreamble = "Invalid system timezone " + tzname + " detected.";
                final String errorAfterward = "This can be corrected at the system level or overridden in the JVM "
                        + "startup flags by appending -Duser.timezone=UTC. Contact support for more information.";

                if (tzname.equals("Etc/Universal")) {
                    // Really common failure case. UTC is both a name AND an abbreviation.
                    log.error("{} The timezone *name* should be UTC. {}", errorPreamble, errorAfterward);
                } else {
                    log.error(
                            "{} This is caused by using non-standard or unsupported timezone names. {}",
                            errorPreamble,
                            errorAfterward);
                }
            }

            // This exception gets thrown by HikariCP and is useless outside of ConnectionManagers.
            RuntimeException e2 = new RuntimeException(ExceptionUtils.getMessage(e), e.getCause());
            e2.setStackTrace(e.getStackTrace());
            throw e2;
        }
        return dataSourcePool;
    }

    /**
     * Setup JMX client.  This is only used for trace logging.
     */
    private HikariPoolMXBean initPoolMbeans() {
        MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer();

        ObjectName poolName = null;
        try {
            poolName = new ObjectName("com.zaxxer.hikari:type=Pool (" + connConfig.getConnectionPoolName() + ")");
        } catch (MalformedObjectNameException e) {
            log.error(
                    "Unable to setup mBean monitoring for pool {}.",
                    SafeArg.of("connectionPoolName", connConfig.getConnectionPoolName()),
                    e);
        }
        return JMX.newMBeanProxy(mbeanServer, poolName, HikariPoolMXBean.class);
    }

    @Override
    public DBType getDbType() {
        return connConfig.getDbType();
    }

    private final class ConnectionAcquisitionProfiler {
        private final Stopwatch globalStopwatch;
        private final Stopwatch trialStopwatch;

        private long acquisitionMillis;
        private long connectionTestMillis;

        private ConnectionAcquisitionProfiler() {
            this(Stopwatch.createStarted(), Stopwatch.createStarted());
        }

        private ConnectionAcquisitionProfiler(Stopwatch globalStopwatch, Stopwatch trialStopwatch) {
            this.globalStopwatch = globalStopwatch;
            this.trialStopwatch = trialStopwatch;
        }

        private void logAcquisitionAndRestart() {
            trialStopwatch.stop();
            acquisitionMillis = trialStopwatch.elapsed(TimeUnit.MILLISECONDS);
            trialStopwatch.reset().start();
        }

        private void logConnectionTest() {
            trialStopwatch.stop();
            connectionTestMillis = trialStopwatch.elapsed(TimeUnit.MILLISECONDS);
        }

        private void logQueryDuration() {
            long elapsedMillis = globalStopwatch.elapsed(TimeUnit.MILLISECONDS);
            if (elapsedMillis > 1000) {
                log.warn(
                        "[{}] Waited {}ms for connection (acquisition: {}, connectionTest: {})",
                        SafeArg.of("connectionPoolName", connConfig.getConnectionPoolName()),
                        SafeArg.of("elapsedMillis", elapsedMillis),
                        SafeArg.of("acquisitionMillis", acquisitionMillis),
                        SafeArg.of("connectionTestMillis", connectionTestMillis));
                logPoolStats();
            } else {
                if (log.isDebugEnabled()) {
                    log.debug(
                            "[{}] Waited {}ms for connection (acquisition: {}, connectionTest: {})",
                            SafeArg.of("connectionPoolName", connConfig.getConnectionPoolName()),
                            SafeArg.of("elapsedMillis", elapsedMillis),
                            SafeArg.of("acquisitionMillis", acquisitionMillis),
                            SafeArg.of("connectionTestMillis", connectionTestMillis));
                }
            }
        }
    }
}


text:
using System;
using System.Linq;
using Domain;
using ProtoBuf.Meta;
using TypeAlias;
using UnityEngine;

public class SelfHostEntityNetworkManager : EntityNetworkManager
{
    public bool UseAi;

    private static TypeAliasTable _typeAliasTable;
    private static TypeModel _typeModel;

    public override TypeAliasTable GetTypeAliasTable()
    {
        return _typeAliasTable ?? (_typeAliasTable = new TypeAliasTable());
    }

    public override TypeModel GetTypeModel()
    {
        return _typeModel ?? (_typeModel = new DomainProtobufSerializer());
    }

    protected override void OnClientAdd(int clientId)
    {
        Zone.RunAction(zone =>
        {
            var controller = zone.GetEntity<ServerZoneController>();
            if (controller == null)
                controller = (ServerZoneController)zone.Spawn(typeof(IZoneController), 0);

            if (controller.Data.State == ZoneState.None)
            {
                if (UseAi)
                {
                    controller.Start(clientId, clientId, false, true);
                }
                else
                {
                    var clientIds = zone.GetClientIds().ToList();
                    if (clientIds.Count == 2)
                        controller.Start(clientIds[0], clientIds[1], false, false);
                }
            }
        });
    }

    private void OnGUI()
    {
        if (isNetworkActive == false)
            UseAi = GUI.Toggle(new Rect(230, 40, 200, 30), UseAi, "Use AI");
    }
}


text:
import * as errors from '../../config/errors';
import { UserService } from '../services';

export async function execute(socket: any, data: any) {
    const userId = data;
    const result = await new UserService().getUser(userId);
    socket.write(result ? JSON.stringify(result) : '');
}


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ScrollView
        android:id="@+id/content"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:lineSpacingMultiplier="1.2"
            android:text="@string/loading_content"
            android:padding="16dp"/>

    </ScrollView>

    <ProgressBar
        android:id="@+id/loading_spinner"
        style="?android:progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"/>

</FrameLayout>


text:
<?php
/**
 * BusinessLogicServicePermissionGroup
 *
 * PHP version 5
 *
 * @category Class
 * @package  Alfaview
 * @author   Swagger Codegen team
 * @link     https://github.com/swagger-api/swagger-codegen
 */

/**
 * businessLogicService/businessLogicService.proto
 *
 * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
 *
 * OpenAPI spec version: version not set
 *
 * Generated by: https://github.com/swagger-api/swagger-codegen.git
 * Swagger Codegen version: 2.4.27
 */

/**
 * NOTE: This class is auto generated by the swagger code generator program.
 * https://github.com/swagger-api/swagger-codegen
 * Do not edit the class manually.
 */

namespace Alfaview\Model;

use \ArrayAccess;
use \Alfaview\ObjectSerializer;

/**
 * BusinessLogicServicePermissionGroup Class Doc Comment
 *
 * @category Class
 * @package  Alfaview
 * @author   Swagger Codegen team
 * @link     https://github.com/swagger-api/swagger-codegen
 */
class BusinessLogicServicePermissionGroup implements ModelInterface, ArrayAccess
{
    const DISCRIMINATOR = null;

    /**
      * The original name of the model.
      *
      * @var string
      */
    protected static $swaggerModelName = 'businessLogicServicePermissionGroup';

    /**
      * Array of property to type mappings. Used for (de)serialization
      *
      * @var string[]
      */
    protected static $swaggerTypes = [
        'name' => 'string',
        'order' => 'int',
        'permissions' => '\Alfaview\Model\CommonPermissions'
    ];

    /**
      * Array of property to format mappings. Used for (de)serialization
      *
      * @var string[]
      */
    protected static $swaggerFormats = [
        'name' => null,
        'order' => 'int64',
        'permissions' => null
    ];

    /**
     * Array of property to type mappings. Used for (de)serialization
     *
     * @return array
     */
    public static function swaggerTypes()
    {
        return self::$swaggerTypes;
    }

    /**
     * Array of property to format mappings. Used for (de)serialization
     *
     * @return array
     */
    public static function swaggerFormats()
    {
        return self::$swaggerFormats;
    }

    /**
     * Array of attributes where the key is the local name,
     * and the value is the original name
     *
     * @var string[]
     */
    protected static $attributeMap = [
        'name' => 'name',
        'order' => 'order',
        'permissions' => 'permissions'
    ];

    /**
     * Array of attributes to setter functions (for deserialization of responses)
     *
     * @var string[]
     */
    protected static $setters = [
        'name' => 'setName',
        'order' => 'setOrder',
        'permissions' => 'setPermissions'
    ];

    /**
     * Array of attributes to getter functions (for serialization of requests)
     *
     * @var string[]
     */
    protected static $getters = [
        'name' => 'getName',
        'order' => 'getOrder',
        'permissions' => 'getPermissions'
    ];

    /**
     * Array of attributes where the key is the local name,
     * and the value is the original name
     *
     * @return array
     */
    public static function attributeMap()
    {
        return self::$attributeMap;
    }

    /**
     * Array of attributes to setter functions (for deserialization of responses)
     *
     * @return array
     */
    public static function setters()
    {
        return self::$setters;
    }

    /**
     * Array of attributes to getter functions (for serialization of requests)
     *
     * @return array
     */
    public static function getters()
    {
        return self::$getters;
    }

    /**
     * The original name of the model.
     *
     * @return string
     */
    public function getModelName()
    {
        return self::$swaggerModelName;
    }

    /**
     * Associative array for storing property values
     *
     * @var mixed[]
     */
    protected $container = [];

    /**
     * Constructor
     *
     * @param mixed[] $data Associated array of property values
     *                      initializing the model
     */
    public function __construct(array $data = null)
    {
        $this->container['name'] = isset($data['name']) ? $data['name'] : null;
        $this->container['order'] = isset($data['order']) ? $data['order'] : null;
        $this->container['permissions'] = isset($data['permissions']) ? $data['permissions'] : null;
    }

    /**
     * Show all the invalid properties with reasons.
     *
     * @return array invalid properties with reasons
     */
    public function listInvalidProperties()
    {
        $invalidProperties = [];

        return $invalidProperties;
    }

    /**
     * Validate all the properties in the model
     * return true if all passed
     *
     * @return bool True if all properties are valid
     */
    public function valid()
    {
        return count($this->listInvalidProperties()) === 0;
    }

    /**
     * Gets name
     *
     * @return string
     */
    public function getName()
    {
        return $this->container['name'];
    }

    /**
     * Sets name
     *
     * @param string $name name
     *
     * @return $this
     */
    public function setName($name)
    {
        $this->container['name'] = $name;

        return $this;
    }

    /**
     * Gets order
     *
     * @return int
     */
    public function getOrder()
    {
        return $this->container['order'];
    }

    /**
     * Sets order
     *
     * @param int $order order
     *
     * @return $this
     */
    public function setOrder($order)
    {
        $this->container['order'] = $order;

        return $this;
    }

    /**
     * Gets permissions
     *
     * @return \Alfaview\Model\CommonPermissions
     */
    public function getPermissions()
    {
        return $this->container['permissions'];
    }

    /**
     * Sets permissions
     *
     * @param \Alfaview\Model\CommonPermissions $permissions permissions
     *
     * @return $this
     */
    public function setPermissions($permissions)
    {
        $this->container['permissions'] = $permissions;

        return $this;
    }
    /**
     * Returns true if offset exists. False otherwise.
     *
     * @param integer $offset Offset
     *
     * @return boolean
     */
    public function offsetExists($offset)
    {
        return isset($this->container[$offset]);
    }

    /**
     * Gets offset.
     *
     * @param integer $offset Offset
     *
     * @return mixed
     */
    public function offsetGet($offset)
    {
        return isset($this->container[$offset]) ? $this->container[$offset] : null;
    }

    /**
     * Sets value based on offset.
     *
     * @param integer $offset Offset
     * @param mixed   $value  Value to be set
     *
     * @return void
     */
    public function offsetSet($offset, $value)
    {
        if (is_null($offset)) {
            $this->container[] = $value;
        } else {
            $this->container[$offset] = $value;
        }
    }

    /**
     * Unsets offset.
     *
     * @param integer $offset Offset
     *
     * @return void
     */
    public function offsetUnset($offset)
    {
        unset($this->container[$offset]);
    }

    /**
     * Gets the string presentation of the object
     *
     * @return string
     */
    public function __toString()
    {
        if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print
            return json_encode(
                ObjectSerializer::sanitizeForSerialization($this),
                JSON_PRETTY_PRINT
            );
        }

        return json_encode(ObjectSerializer::sanitizeForSerialization($this));
    }
}


text:
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type

import codecs
import re

from ansible.errors import AnsibleParserError
from ansible.module_utils._text import to_text
from ansible.parsing.quoting import unquote

# Decode escapes adapted from rspeer's answer here:
# http://stackoverflow.com/questions/4020539/process-escape-sequences-in-a-string-in-python
_HEXCHAR = '[a-fA-F0-9]'
_ESCAPE_SEQUENCE_RE = re.compile(r'''
    ( \\U{0}           # 8-digit hex escapes
    | \\u{1}           # 4-digit hex escapes
    | \\x{2}           # 2-digit hex escapes
    | \\N\{{[^}}]+\}}  # Unicode characters by name
    | \\[\\'"abfnrtv]  # Single-character escapes
    )'''.format(_HEXCHAR * 8, _HEXCHAR * 4, _HEXCHAR * 2), re.UNICODE | re.VERBOSE)

def _decode_escapes(s):
    def decode_match(match):
        return codecs.decode(match.group(0), 'unicode-escape')

    return _ESCAPE_SEQUENCE_RE.sub(decode_match, s)

def parse_kv(args, check_raw=False):
    '''
    Convert a string of key/value items to a dict. If any free-form params
    are found and the check_raw option is set to True, they will be added
    to a new parameter called '_raw_params'. If check_raw is not enabled,
    they will simply be ignored.
    '''

    args = to_text(args, nonstring='passthru')

    options = {}
    if args is not None:
        try:
            vargs = split_args(args)
        except ValueError as ve:
            if 'no closing quotation' in str(ve).lower():
                raise AnsibleParserError("error parsing argument string, try quoting the entire line.", orig_exc=ve)
            else:
                raise

        raw_params = []
        for orig_x in vargs:
            x = _decode_escapes(orig_x)
            if "=" in x:
                pos = 0
                try:
                    while True:
                        pos = x.index('=', pos + 1)
                        if pos > 0 and x[pos - 1] != '\\':
                            break
                except ValueError:
                    # ran out of string, but we must have some escaped equals,
                    # so replace those and append this to the list of raw params
                    raw_params.append(x.replace('\\=', '='))
                    continue

                k = x[:pos]
                v = x[pos + 1:]

                # FIXME: make the retrieval of this list of shell/command
                #        options a function, so the list is centralized
                if check_raw and k not in ('creates', 'removes', 'chdir', 'executable', 'warn'):
                    raw_params.append(orig_x)
                else:
                    options[k.strip()] = unquote(v.strip())
            else:
                raw_params.append(orig_x)

        # recombine the free-form params, if any were found, and assign
        # them to a special option for use later by the shell/command module
        if len(raw_params) > 0:
            options[u'_raw_params'] = ' '.join(raw_params)

    return options

def _get_quote_state(token, quote_char):
    '''
    the goal of this block is to determine if the quoted string
    is unterminated in which case it needs to be put back together
    '''
    # the char before the current one, used to see if
    # the current character is escaped
    prev_char = None
    for idx, cur_char in enumerate(token):
        if idx > 0:
            prev_char = token[idx - 1]
        if cur_char in '"\'' and prev_char != '\\':
            if quote_char:
                if cur_char == quote_char:
                    quote_char = None
            else:
                quote_char = cur_char
    return quote_char

def _count_jinja2_blocks(token, cur_depth, open_token, close_token):
    '''
    this function counts the number of opening/closing blocks for a
    given opening/closing type and adjusts the current depth for that
    block based on the difference
    '''
    num_open = token.count(open_token)
    num_close = token.count(close_token)
    if num_open != num_close:
        cur_depth += (num_open - num_close)
        if cur_depth < 0:
            cur_depth = 0
    return cur_depth

def split_args(args):
    '''
    Splits args on whitespace, but intelligently reassembles
    those that may have been split over a jinja2 block or quotes.

    When used in a remote module, we won't ever have to be concerned about
    jinja2 blocks, however this function is/will be used in the
    core portions as well before the args are templated.

    example input: a=b c="foo bar"
    example output: ['a=b', 'c="foo bar"']

    Basically this is a variation shlex that has some more intelligence for
    how Ansible needs to use it.
    '''

    # the list of params parsed out of the arg string
    # this is going to be the result value when we are done
    params = []

    # Initial split on white space
    args = args.strip()
    items = args.strip().split('\n')

    # iterate over the tokens, and reassemble any that may have been
    # split on a space inside a jinja2 block.
    # ex if tokens are "{{", "foo", "}}" these go together

    # These variables are used
    # to keep track of the state of the parsing, since blocks and quotes
    # may be nested within each other.

    quote_char = None
    inside_quotes = False
    print_depth = 0  # used to count nested jinja2 {{ }} blocks
    block_depth = 0  # used to count nested jinja2 {% %} blocks
    comment_depth = 0  # used to count nested jinja2 {# #} blocks

    # now we loop over each split chunk, coalescing tokens if the white space
    # split occurred within quotes or a jinja2 block of some kind
    for (itemidx, item) in enumerate(items):

        # we split on spaces and newlines separately, so that we
        # can tell which character we split on for reassembly
        # inside quotation characters
        tokens = item.strip().split(' ')

        line_continuation = False
        for (idx, token) in enumerate(tokens):

            # if we hit a line continuation character, but
            # we're not inside quotes, ignore it and continue
            # on to the next token while setting a flag
            if token == '\\' and not inside_quotes:
                line_continuation = True
                continue

            # store the previous quoting state for checking later
            was_inside_quotes = inside_quotes
            quote_char = _get_quote_state(token, quote_char)
            inside_quotes = quote_char is not None

            # multiple conditions may append a token to the list of params,
            # so we keep track with this flag to make sure it only happens once
            # append means add to the end of the list, don't append means concatenate
            # it to the end of the last token
            appended = False

            # if we're inside quotes now, but weren't before, append the token
            # to the end of the list, since we'll tack on more to it later
            # otherwise, if we're inside any jinja2 block, inside quotes, or we were
            # inside quotes (but aren't now) concat this token to the last param
            if inside_quotes and not was_inside_quotes and not(print_depth or block_depth or comment_depth):
                params.append(token)
                appended = True
            elif print_depth or block_depth or comment_depth or inside_quotes or was_inside_quotes:
                if idx == 0 and was_inside_quotes:
                    params[-1] = "%s%s" % (params[-1], token)
                elif len(tokens) > 1:
                    spacer = ''
                    if idx > 0:
                        spacer = ' '
                    params[-1] = "%s%s%s" % (params[-1], spacer, token)
                else:
                    params[-1] = "%s\n%s" % (params[-1], token)
                appended = True

            # if the number of paired block tags is not the same, the depth has changed, so we calculate that here
            # and may append the current token to the params (if we haven't previously done so)
            prev_print_depth = print_depth
            print_depth = _count_jinja2_blocks(token, print_depth, "{{", "}}")
            if print_depth != prev_print_depth and not appended:
                params.append(token)
                appended = True

            prev_block_depth = block_depth
            block_depth = _count_jinja2_blocks(token, block_depth, "{%", "%}")
            if block_depth != prev_block_depth and not appended:
                params.append(token)
                appended = True

            prev_comment_depth = comment_depth
            comment_depth = _count_jinja2_blocks(token, comment_depth, "{#", "#}")
            if comment_depth != prev_comment_depth and not appended:
                params.append(token)
                appended = True

            # finally, if we're at zero depth for all blocks and not inside quotes, and have not
            # yet appended anything to the list of params, we do so now
            if not (print_depth or block_depth or comment_depth) and not inside_quotes and not appended and token != '':
                params.append(token)

        # if this was the last token in the list, and we have more than
        # one item (meaning we split on newlines), add a newline back here
        # to preserve the original structure
        if len(items) > 1 and itemidx != len(items) - 1 and not line_continuation:
            params[-1] += '\n'

        # always clear the line continuation flag
        line_continuation = False

    # If we're done and things are not at zero depth or we're still inside quotes,
    # raise an error to indicate that the args were unbalanced
    if print_depth or block_depth or comment_depth or inside_quotes:
        raise AnsibleParserError("failed at splitting arguments, either an unbalanced jinja2 block or quotes: {}".format(args))

    return params


text:
package test.obvious.data;

import static org.junit.Assert.*;

import java.util.HashMap;
import java.util.Map;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import obvious.data.Edge;
import obvious.data.Forest;
import obvious.data.Node;
import obvious.data.Schema;
import obvious.data.Graph.EdgeType;
import obvious.impl.EdgeImpl;
import obvious.impl.NodeImpl;
import obvious.impl.SchemaImpl;

/**
 * Class ForestTest.
 * Override test methods that have specific needs in your implementation.
 * @author Hemery
 * @version $Revision$
 */
public abstract class ForestTest {

  /**
   * Forest instance used for tests.
   */
  protected Forest<Node, Edge> forest;

  /**
   * Gets the Forest test instance.
   * @return the Forest test instance
   */
  public Forest<Node, Edge> getForest() {
    return this.forest;
  }

  /**
   * Creates a suitable instance of network.
   * @param nSchema schema for the nodes the network
   * @param eSchema schema for the edges of the network
   * @return suitable network implementation instance
   */
  public abstract Forest<Node, Edge> newInstance(Schema nSchema,
      Schema eSchema);

  /**
   * @see junit.framework.TestCase#setUp()
   */
  @Before
  public void setUp() {
    // Creating the starting schema for node and edges
    Schema nodeSchema = new SchemaImpl();
    nodeSchema.addColumn("nodeName", String.class, "node_default");
    nodeSchema.addColumn("nodeId", int.class, -1);
    Schema edgeSchema = new SchemaImpl();
    edgeSchema.addColumn("edgeName", String.class, "edge_default");
    edgeSchema.addColumn("source", int.class, -1);
    edgeSchema.addColumn("target", int.class, -1);
    // Requesting a forest instance corresponding to these schemas.
    forest = newInstance(nodeSchema, edgeSchema);
    Map<String, Node> nodeMap = new HashMap<String, Node>();
    // Adding nodes
    for (int i = 0; i < 10; i++) {
      Node node = new NodeImpl(nodeSchema, new Object[] {"A" + i, i});
      nodeMap.put("A" + i, node);
      forest.addNode(node);
    }
    // Adding edges
    forest.addEdge(new EdgeImpl(edgeSchema, new Object[] {"A0-A1", 0, 1}),
        nodeMap.get("A0"), nodeMap.get("A1"), EdgeType.DIRECTED);
    forest.addEdge(new EdgeImpl(edgeSchema, new Object[] {"A0-A2", 0, 2}),
        nodeMap.get("A0"), nodeMap.get("A2"), EdgeType.DIRECTED);
    forest.addEdge(new EdgeImpl(edgeSchema, new Object[] {"A1-A3", 1, 3}),
        nodeMap.get("A1"), nodeMap.get("A3"), EdgeType.DIRECTED);
    forest.addEdge(new EdgeImpl(edgeSchema, new Object[] {"A2-A4", 2, 4}),
        nodeMap.get("A2"), nodeMap.get("A4"), EdgeType.DIRECTED);
    forest.addEdge(new EdgeImpl(edgeSchema, new Object[] {"A2-A5", 2, 5}),
        nodeMap.get("A2"), nodeMap.get("A5"), EdgeType.DIRECTED);
    forest.addEdge(new EdgeImpl(edgeSchema, new Object[] {"A6-A7", 6, 7}),
        nodeMap.get("A6"), nodeMap.get("A7"), EdgeType.DIRECTED);
    forest.addEdge(new EdgeImpl(edgeSchema, new Object[] {"A6-A8", 6, 8}),
        nodeMap.get("A6"), nodeMap.get("A8"), EdgeType.DIRECTED);
    forest.addEdge(new EdgeImpl(edgeSchema, new Object[] {"A8-A9", 8, 9}),
        nodeMap.get("A8"), nodeMap.get("A9"), EdgeType.DIRECTED);
  }

  /**
   * @see junit.framework.TestCase#tearDown()
   */
  @After
  public void tearDown() {
    this.forest = null;
  }

  /**
   * Test method for obvious.data.Forest.getTrees() method.
   */
  @Test
  public void testGetTrees() {
    assertEquals(2, forest.getTrees().size());
    assertEquals(6, forest.getTrees().iterator().next().getNodes().size());
    assertEquals(5, forest.getTrees().iterator().next().getEdges().size());
  }

}


text:
package com.haulmont.cuba.gui.meta;

import java.lang.annotation.*;

/**
 * Indicates that the annotated interface should be available in Studio Screen Designer as a part of UI Component,
 * e.g. column, action, field, etc. Provides metadata for Component Inspector of Screen Designer.
 *
 * When used on the getter or setter method, indicates that the annotated method should be shown in
 * Studio Screen Designer as a nested element of UI component, e.g. validator, formatter.
 * Method return type or parameter type will be used to determine element type.
 */
@Target({ElementType.METHOD, ElementType.TYPE})
@Inherited
public @interface StudioElement {
    /**
     * @return caption of the element in Studio Screen Designer
     */
    String caption() default "";

    /**
     * @return description of the element in Studio Screen Designer
     */
    String description() default "";

    /**
     * Specifies path to the component icon, SVG or PNG. Relative to the component module root.
     * The icon used in the Component Hierarchy.
     * @return relative path to the SVG or PNG icon file.
     */
    String icon() default "";

    /**
     * @return XML tag of the element
     */
    String xmlElement() default "";

    /**
     * Specifies xml namespace required for the element.
     *
     * @return xml namespace
     */
    String xmlns() default "";

    /**
     * Specifies xml namespace alias required for the element.
     *
     * @return xml namespace alias
     */
    String xmlnsAlias() default "";

    /**
     * @return name of the default property, it will be automatically selected in Properties panel
     */
    String defaultProperty() default "";

    /**
     * @return names of unsupported properties that should be hidden from Properties panel
     */
    String[] unsupportedProperties() default {};

    /**
     * Specifies URL pointing to the documentation page for the annotated element.
     * Used in CUBA Documentation action in the Studio Screen Designer.

     * If the documentation is version dependent, use %VERSION% as a placeholder.
     * It will be replaced with the minor version (e.g. 1.2) of the artifact containing UI component.
     *
     * @return URL of the documentation page
     */
    String documentationURL() default "";
}


text:
package org.openeos.erp.acct;

import org.openeos.erp.acct.model.FinancialMgmtAccountingCombination;
import org.openeos.erp.acct.model.FinancialMgmtAcctSchema;
import org.openeos.erp.acct.model.FinancialMgmtElement;
import org.openeos.erp.acct.model.FinancialMgmtGLCategory;
import org.openeos.erp.acct.model.FinancialMgmtGLJournal;
import org.openeos.services.ui.window.AbstractDictionaryBasedWindowDefinition;

public class AcctWindows {

	public static class AccountTreeWindow extends AbstractDictionaryBasedWindowDefinition {

		public static final String ID = AccountTreeWindow.class.getName();

		public AccountTreeWindow() {
			super(ID, FinancialMgmtElement.class);
			setName("Account Tree");
			addVisibleField(FinancialMgmtElement.PROPERTY_ORGANIZATION);
			addVisibleField(FinancialMgmtElement.PROPERTY_NAME);
			addVisibleField(FinancialMgmtElement.PROPERTY_ELEMENT_TYPE);
			addVisibleField(FinancialMgmtElement.PROPERTY_DESCRIPTION);
			addOrderAsc(FinancialMgmtElement.PROPERTY_NAME);
		}

	}

	public static class GeneralLedgerConfigurationWindow extends AbstractDictionaryBasedWindowDefinition {

		public static final String ID = GeneralLedgerConfigurationWindow.class.getName();

		public GeneralLedgerConfigurationWindow() {
			super(ID, FinancialMgmtAcctSchema.class);
			setName("General Ledger Configuration");
			addVisibleField(FinancialMgmtAcctSchema.PROPERTY_ORGANIZATION);
			addVisibleField(FinancialMgmtAcctSchema.PROPERTY_NAME);
			addVisibleField(FinancialMgmtAcctSchema.PROPERTY_DESCRIPTION);
			addOrderAsc(FinancialMgmtAcctSchema.PROPERTY_NAME);
		}

	}

	public static class AccountCombinationWindow extends AbstractDictionaryBasedWindowDefinition {

		public static final String ID = AccountCombinationWindow.class.getName();

		public AccountCombinationWindow() {
			super(ID, FinancialMgmtAccountingCombination.class);
			setName("Valid Account Combinations");
			addVisibleField(FinancialMgmtAccountingCombination.PROPERTY_ORGANIZATION);
			addVisibleField(FinancialMgmtAccountingCombination.PROPERTY_ALIAS);
			addVisibleField(FinancialMgmtAccountingCombination.PROPERTY_DESCRIPTION);
			addVisibleField(FinancialMgmtAccountingCombination.PROPERTY_FINANCIAL_MGMT_ACCT_SCHEMA);
			addVisibleField(FinancialMgmtAccountingCombination.PROPERTY_FINANCIAL_MGMT_ELEMENT_VALUE);
			addOrderAsc(FinancialMgmtAccountingCombination.PROPERTY_ORGANIZATION);
			addOrderAsc(FinancialMgmtAccountingCombination.PROPERTY_ALIAS);
		}

	}

	public static class GeneralLedgerCategoryWindow extends AbstractDictionaryBasedWindowDefinition {

		public static final String ID = GeneralLedgerCategoryWindow.class.getName();

		public GeneralLedgerCategoryWindow() {
			super(ID, FinancialMgmtGLCategory.class);
			setName("G/L Category");
			addVisibleField(FinancialMgmtGLCategory.PROPERTY_ORGANIZATION);
			addVisibleField(FinancialMgmtGLCategory.PROPERTY_NAME);
			addVisibleField(FinancialMgmtGLCategory.PROPERTY_CATEGORY_TYPE);
			addVisibleField(FinancialMgmtGLCategory.PROPERTY_DESCRIPTION);
			addOrderAsc(FinancialMgmtGLCategory.PROPERTY_NAME);
		}

	}

	public static class GeneralLedgerJournalWindow extends AbstractDictionaryBasedWindowDefinition {

		public static final String ID = GeneralLedgerJournalWindow.class.getName();

		public GeneralLedgerJournalWindow() {
			super(ID, FinancialMgmtGLJournal.class);
			setName("G/L Journal Entries");
			addVisibleField(FinancialMgmtGLJournal.PROPERTY_ORGANIZATION);
			addVisibleField(FinancialMgmtGLJournal.PROPERTY_DOCUMENT_TYPE);
			addVisibleField(FinancialMgmtGLJournal.PROPERTY_DOCUMENT_NO);
			addVisibleField(FinancialMgmtGLJournal.PROPERTY_DESCRIPTION);
			addVisibleField(FinancialMgmtGLJournal.PROPERTY_FINANCIAL_MGMT_G_L_CATEGORY);
			addVisibleField(FinancialMgmtGLJournal.PROPERTY_TRANSACTION_DATE);
			addVisibleField(FinancialMgmtGLJournal.PROPERTY_ACCT_DATE);
			addVisibleField(FinancialMgmtGLJournal.PROPERTY_TOTAL_D_R);
			addVisibleField(FinancialMgmtGLJournal.PROPERTY_TOTAL_C_R);
			addOrderAsc(FinancialMgmtGLJournal.PROPERTY_DOCUMENT_NO);
			addOrderDesc(FinancialMgmtGLJournal.PROPERTY_TRANSACTION_DATE);
		}

	}

}


text:
from __future__ import absolute_import

from django.core.urlresolvers import reverse

from sentry import tsdb
from sentry.testutils import APITestCase

class ProjectStatsTest(APITestCase):
    def test_simple(self):
        self.login_as(user=self.user)

        project1 = self.create_project(name='foo')
        project2 = self.create_project(name='bar')

        tsdb.incr(tsdb.models.project_total_received, project1.id, count=3)
        tsdb.incr(tsdb.models.project_total_received, project2.id, count=5)

        url = reverse('sentry-api-0-project-stats', kwargs={
            'organization_slug': project1.organization.slug,
            'project_slug': project1.slug,
        })
        response = self.client.get(url, format='json')

        assert response.status_code == 200, response.content
        assert response.data[-1][1] == 3, response.data
        for point in response.data[:-1]:
            assert point[1] == 0
        assert len(response.data) == 24


text:
title: OnClientDragStart
page_title: OnClientDragStart | RadWindow for ASP.NET AJAX Documentation
description: OnClientDragStart
slug: window/client-side-programming/events/onclientdragstart
tags: onclientdragstart
published: True
position: 9
---

# OnClientDragStart

The **OnClientDragStart** event of the **RadWindow** fires when the user starts dragging the popup. This action is also initiated by a click or a tap on the title bar.

The event handler receives the following arguments:

1. The [RadWindow]({%slug window/client-side-programming/radwindow-object%}) object that fired the event.

1. An event arguments object that does not expose any methods and properties.

You can use this event to get the starting position of the dialog by calling the `getWindowBounds()` method from the [RadWindow client-side API]({%slug window/client-side-programming/radwindow-object%}).

## See Also

 * [Overview]({%slug window/client-side-programming/events/overview%})

 * [RadWindow Object]({%slug window/client-side-programming/radwindow-object%})


text:
package org.adaptlab.chpir.android.participanttracker;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.text.InputType;
import android.text.TextUtils;
import android.text.method.PasswordTransformationMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import org.adaptlab.chpir.android.activerecordcloudsync.ActiveRecordCloudSync;
import org.adaptlab.chpir.android.participanttracker.models.AdminSettings;
import org.adaptlab.chpir.android.participanttracker.tasks.ApkUpdateTask;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import static org.adaptlab.chpir.android.participanttracker.AppUtil.WRITE_EXTERNAL_STORAGE_CODE;

public class AdminFragment extends Fragment {
    private EditText mDeviceIdentifierEditText;
    private EditText mDeviceLabelEditText;
    private EditText mApiEndPointEditText;
    private EditText mProjectIdEditText;
    private EditText mApiVersionEditText;
    private EditText mApiKeyEditText;
    private ArrayList<EditText> mTransformableFields;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setHasOptionsMenu(true);
        getActivity().setTitle(R.string.admin_settings);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_admin_settings, parent, false);
        mDeviceIdentifierEditText = (EditText) view.findViewById(R.id.device_identifier_edit_text);
        mDeviceIdentifierEditText.setText(getAdminSettingsInstanceDeviceId());

        mDeviceLabelEditText = (EditText) view.findViewById(R.id.device_label_edit_text);
        mDeviceLabelEditText.setText(AdminSettings.getInstance().getDeviceLabel());

        mApiEndPointEditText = (EditText) view.findViewById(R.id.api_endpoint_edit_text);
        mApiEndPointEditText.setText(getAdminSettingsInstanceApiDomainName());
        if (!TextUtils.isEmpty(getAdminSettingsInstanceApiDomainName())) setOnClickListener(mApiEndPointEditText);

        mApiVersionEditText = (EditText) view.findViewById(R.id.api_version_text);
        mApiVersionEditText.setText(getAdminSettingsInstanceApiVersion());
        if (!TextUtils.isEmpty(getAdminSettingsInstanceApiVersion())) setOnClickListener(mApiVersionEditText);

        mApiKeyEditText = (EditText) view.findViewById(R.id.api_key_text);
        mApiKeyEditText.setText(getAdminSettingsInstanceApiKey());
        if (!TextUtils.isEmpty(getAdminSettingsInstanceApiKey())) setOnClickListener(mApiKeyEditText);

        mProjectIdEditText = (EditText) view.findViewById(R.id.project_id_text);
        mProjectIdEditText.setText(getAdminSettingsInstanceProjectId());
        if (!TextUtils.isEmpty(getAdminSettingsInstanceProjectId())) setOnClickListener(mProjectIdEditText);

        mTransformableFields = new ArrayList<>(Arrays.asList(mApiEndPointEditText, mApiVersionEditText, mProjectIdEditText, mApiKeyEditText));

        final TextView lastUpdateTextView = (TextView) view.findViewById(R.id.last_update_label);
        lastUpdateTextView.setText(String.format(Locale.getDefault(), "%s%s%s", getString(R.string.last_update), " ", getLastSyncTime()));

        Button resetLastSyncTime = (Button) view.findViewById(R.id.reset_last_sync_time_button);
        resetLastSyncTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AdminSettings.getInstance().setLastSyncTime(null);
                lastUpdateTextView.setText(String.format(Locale.getDefault(), "%s%s%s",
                        getString(R.string.last_update), " ", getLastSyncTime()));
            }
        });

        TextView versionCodeTextView = (TextView) view.findViewById(R.id.version_code_label);
        versionCodeTextView.setText(String.format(Locale.getDefault(), "%s%s%d",
                getString(R.string.version_code), " ", AppUtil.getVersionCode(getActivity())));

        TextView versionNameTextView = (TextView) view.findViewById(R.id.version_name_label);
        versionNameTextView.setText(String.format(Locale.getDefault(), "%s%s%s",
                getString(R.string.version_name), " ", AppUtil.getVersionName(getActivity())));

        Button updatesCheckButton = (Button) view.findViewById(R.id.updates_check_button);
        updatesCheckButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (AppUtil.isPermissionNeeded(getActivity())) {
                    ActivityCompat.requestPermissions(getActivity(),  new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, WRITE_EXTERNAL_STORAGE_CODE);
                } else {
                    new ApkUpdateTask(getActivity()).execute();
                }
            }
        });

       // TODO: 9/15/17  Change
        Button saveSettingsButton = (Button) view.findViewById(R.id.save_admin_settings_button);
        saveSettingsButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                saveAdminSettings();
            }
        });

        return view;
    }

//    @Override
//    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
//        super.onCreateOptionsMenu(menu, inflater);
//        inflater.inflate(R.menu.admin_setting_menu, menu);
//    }

//    @Override
//    public void onPrepareOptionsMenu(Menu menu) {
//        super.onPrepareOptionsMenu(menu);
//    }

//    @Override
//    public boolean onOptionsItemSelected(MenuItem item) {
//        switch (item.getItemId()) {
//            case R.id.save_admin_settings_button:
//                saveAdminSettings();
//                return true;
//            default:
//                return super.onOptionsItemSelected(item);
//        }
//    }

    private void saveAdminSettings() {
        if (!requiredFieldIsEmpty()) {
            AdminSettings.getInstance().setDeviceIdentifier(mDeviceIdentifierEditText.getText().toString());
            AdminSettings.getInstance().setApiUrl(setApiUrl(mApiEndPointEditText.getText().toString()));
            AdminSettings.getInstance().setApiVersion(mApiVersionEditText.getText().toString());
            if (!TextUtils.isEmpty(mProjectIdEditText.getText().toString())) {
                AdminSettings.getInstance().setProjectId(Long.parseLong(mProjectIdEditText.getText().toString()));
            }
            AdminSettings.getInstance().setApiKey(mApiKeyEditText.getText().toString());
            AdminSettings.getInstance().setDeviceLabel(mDeviceLabelEditText.getText().toString());
            ActiveRecordCloudSync.setAccessToken(getAdminSettingsInstanceApiKey());
            ActiveRecordCloudSync.setEndPoint(getAdminSettingsInstanceApiUrl());
            getActivity().finish();
        }
    }

    private boolean requiredFieldIsEmpty() {
        for (EditText editText : mTransformableFields) {
            if (TextUtils.isEmpty(editText.getText())) {
                editText.setError(getString(R.string.required_field));
                return true;
            }
        }
        return false;
    }

    private String setApiUrl(String string) {
        char lastChar = string.charAt(string.length() - 1);
        if (lastChar != '/') string = string + "/";
        return string;
    }

    private Date getLastSyncTime() {
        Calendar calendar = Calendar.getInstance();
        if (AdminSettings.getInstance().getLastSyncTime().equals("")) {
            calendar.setTimeInMillis(0);
        } else {
            calendar.setTimeInMillis(Long.parseLong(AdminSettings.getInstance().getLastSyncTime()));
        }
        return calendar.getTime();
    }

    public String getAdminSettingsInstanceDeviceId() {
        return AdminSettings.getInstance().getDeviceIdentifier();
    }

    public String getAdminSettingsInstanceApiDomainName() {
        return AdminSettings.getInstance().getApiUrl();
    }

    public String getAdminSettingsInstanceApiVersion() {
        return AdminSettings.getInstance().getApiVersion();
    }

    public String getAdminSettingsInstanceApiKey() {
        return AdminSettings.getInstance().getApiKey();
    }

    public String getAdminSettingsInstanceProjectId() {
        if (AdminSettings.getInstance().getProjectId() == null) return "";
        return Long.toString(AdminSettings.getInstance().getProjectId());
    }

    private String getAdminSettingsInstanceApiUrl() {
        String domainName = AdminSettings.getInstance().getApiUrl();
        return domainName + "api/" + AdminSettings.getInstance().getApiVersion() + "/" +
                "projects/" + AdminSettings.getInstance().getProjectId() + "/";
    }

    private void setOnClickListener(final EditText editText) {
        editText.setTransformationMethod(new PasswordTransformationMethod());
        editText.setFocusable(false);
        editText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                displayPasswordPrompt();
            }
        });
    }

    private void displayPasswordPrompt() {
        final EditText input = new EditText(getActivity());
        input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        new AlertDialog.Builder(getActivity())
                .setTitle(R.string.password_title)
                .setMessage(R.string.password_message)
                .setView(input)
                .setPositiveButton(R.string.okay, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int button) {
                        if (AppUtil.checkAdminPassword(input.getText().toString())) {
                            for (EditText editText : mTransformableFields) {
                                editText.setTransformationMethod(null);
                                editText.setFocusableInTouchMode(true);
                                editText.setClickable(false);
                            }
                        } else {
                            Toast.makeText(getActivity(), R.string.incorrect_password, Toast.LENGTH_LONG).show();
                        }
                    }
                }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int button) {
            }
        }).show();
    }

    /*
    Called from the parent activity
     */
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case WRITE_EXTERNAL_STORAGE_CODE: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    new ApkUpdateTask(getActivity()).execute();
                }
            }
        }
    }

}


text:
#include "mem/ruby/structures/TimerTable.hh"

#include "mem/ruby/system/RubySystem.hh"

namespace gem5
{

namespace ruby
{

TimerTable::TimerTable()
    : m_next_time(0)
{
    m_consumer_ptr  = NULL;
    m_next_valid = false;
    m_next_address = 0;
}

bool
TimerTable::isReady(Tick curTime) const
{
    if (m_map.empty())
        return false;

    if (!m_next_valid) {
        updateNext();
    }
    assert(m_next_valid);
    return (curTime >= m_next_time);
}

Addr
TimerTable::nextAddress() const
{
    if (!m_next_valid) {
        updateNext();
    }
    assert(m_next_valid);
    return m_next_address;
}

void
TimerTable::set(Addr address, Tick ready_time)
{
    assert(address == makeLineAddress(address));
    assert(!m_map.count(address));

    m_map[address] = ready_time;
    assert(m_consumer_ptr != NULL);
    m_consumer_ptr->scheduleEventAbsolute(ready_time);
    m_next_valid = false;

    // Don't always recalculate the next ready address
    if (ready_time <= m_next_time) {
        m_next_valid = false;
    }
}

void
TimerTable::unset(Addr address)
{
    assert(address == makeLineAddress(address));
    assert(m_map.count(address));
    m_map.erase(address);

    // Don't always recalculate the next ready address
    if (address == m_next_address) {
        m_next_valid = false;
    }
}

void
TimerTable::print(std::ostream& out) const
{
}

void
TimerTable::updateNext() const
{
    if (m_map.empty()) {
        assert(!m_next_valid);
        return;
    }

    AddressMap::const_iterator i = m_map.begin();
    AddressMap::const_iterator end = m_map.end();

    m_next_address = i->first;
    m_next_time = i->second;
    ++i;

    for (; i != end; ++i) {
        if (i->second < m_next_time) {
            m_next_address = i->first;
            m_next_time = i->second;
        }
    }

    m_next_valid = true;
}

} // namespace ruby
} // namespace gem5


text:
package org.apereo.cas.interrupt;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpResponse;
import org.apereo.cas.CasProtocolConstants;
import org.apereo.cas.authentication.Authentication;
import org.apereo.cas.authentication.principal.Service;
import org.apereo.cas.configuration.model.support.interrupt.InterruptProperties;
import org.apereo.cas.services.RegisteredService;
import org.apereo.cas.util.HttpUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * This is {@link RestEndpointInterruptInquirer}.
 *
 * @author Misagh Moayyed
 * @since 5.2.0
 */
public class RestEndpointInterruptInquirer extends BaseInterruptInquirer {
    private static final Logger LOGGER = LoggerFactory.getLogger(RestEndpointInterruptInquirer.class);
    private static final ObjectMapper MAPPER = new ObjectMapper()
            .findAndRegisterModules()
            .configure(DeserializationFeature.READ_ENUMS_USING_TO_STRING, false)
            .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    private final InterruptProperties.Rest restProperties;

    public RestEndpointInterruptInquirer(final InterruptProperties.Rest restProperties) {
        this.restProperties = restProperties;
    }

    @Override
    public InterruptResponse inquire(final Authentication authentication, final RegisteredService registeredService, final Service service) {
        try {
            final Map<String, String> parameters = new HashMap<>();
            parameters.put("username", authentication.getPrincipal().getId());

            if (service != null) {
                parameters.put(CasProtocolConstants.PARAMETER_SERVICE, service.getId());
            }
            if (registeredService != null) {
                parameters.put("registeredService", registeredService.getServiceId());
            }
            final HttpResponse response = HttpUtils.execute(restProperties.getUrl(), restProperties.getMethod(),
                    restProperties.getBasicAuthUsername(), restProperties.getBasicAuthPassword(),
                    parameters);
            return MAPPER.readValue(response.getEntity().getContent(), InterruptResponse.class);
        } catch (final Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
        return new InterruptResponse(false);
    }
}