text:
import benchmarkFunctions
import numpy
import random

MAX_ITERATIONS = 1000
NUM_DIMENSIONS = 20
POPULATION_SIZE = 50
NUM_TRIALS = 25

X_MAX = 32.0
X_MIN = -32.0

USE_CROSS_OVER = True

LINEAR_INERTIA_DECREASE = True

FASE_DURANTION = 125
NUMBER_OF_FASES = MAX_ITERATIONS/FASE_DURANTION

EPS = 1e-5

D_MAX = 0.005
N_MAX = 0.01
OMEGA_N = 0.9
OMEGA_F = 0.9
V_f = 0.02
C_t = 0.5

# Global iteration value
curr_iteration = 0

# Global fitness values
Xworst = (list(), 0.0, list(), 0.0)
Xbest = (list(), 1e10, list(), 1e10)
best_change_iterations = 0

############################################
# Begin helpers
############################################

# Implemented according to PEP 485
def isclose(a, b, rel_tol=1e-09, abs_tol=0.0):
    return abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)

def initialize_function(benchmark_params, dims):
    global fitness
    global X_MIN
    global X_MAX
    global EPS
    global NUM_DIMENSIONS

    fitness = benchmark_params[0]
    if dims==None:
        NUM_DIMENSIONS = benchmark_params[1]
    else:
        NUM_DIMENSIONS = dims
    EPS = benchmark_params[2]
    X_MIN = benchmark_params[3]
    X_MAX = benchmark_params[4]

    if fitness == benchmarkFunctions.branin:
        global Y_MIN
        global Y_MAX
        global generate_population
        Y_MIN = benchmark_params[5]
        Y_MAX = benchmark_params[6]
        generate_population = generate_population_branin

#-------------------------------------------
# End helpers
#-------------------------------------------

############################################
# Begin local alpha calculation functions
############################################

def xij_hat(Xi, Xj):
    distance = numpy.subtract(Xj[0], Xi[0])
    return numpy.divide(distance, numpy.linalg.norm(distance) + EPS)

def kij_hat(Xi, Xj):
    return float(Xi[1] - Xj[1]) / (Xworst[1] - Xbest[1])

def sensing_distance(Xi, population):
    constant = 1.0 / (5.0 * POPULATION_SIZE)
    distance = 0.0
    for Xj in population:
        distance += numpy.linalg.norm(numpy.subtract(Xi[0], Xj[0]))
    return distance * constant

def detect_neighbours(Xi, d, population):
    neighbours = list()
    for Xj in population:
        euc_dist = numpy.linalg.norm(numpy.subtract(Xi[0], Xj[0]))
        if euc_dist < d and not isclose(euc_dist, 0.0):
            neighbours.append(Xj)
    return neighbours

# Each alpha is a P-sized list where each element is an N-dimensional array
def local_alpha(population):
    alphas = list()
    for Xi in population:
        alphai = [0.0 for i in range(NUM_DIMENSIONS)]
        distance = sensing_distance(Xi, population)
        neighbours = detect_neighbours(Xi, distance, population)
        for Xj in neighbours:
            curr = [kij_hat(Xi, Xj) * x for x in xij_hat(Xi, Xj)]
            alphai = numpy.add(alphai, curr)
        alphas.append(alphai)
    return alphas

#-------------------------------------------
# End local alpha calculation functions
#-------------------------------------------

############################################
# Begin target alpha calculation functions #
############################################

# Each alpha is a P-sized list where each element is an N-dimensional array
def target_alpha(population):
    Cbest = 2.0 * (random.uniform(0.0, 1.0) + (float(curr_iteration) / MAX_ITERATIONS))
    alphas = list()
    for Xi in population:
        alphai = [Cbest * kij_hat(Xi, Xbest) * x for x in xij_hat(Xi, Xbest)]
        alphas.append(alphai)
    return alphas

#-------------------------------------------
# End target alpha calculation functions
#-------------------------------------------

############################################
# Begin foraging motion functions
############################################

def find_food(population):
    enum = [0.0 for i in range(NUM_DIMENSIONS)]
    denom = 0.0
    for Xi in population:
        cur_fitness = Xi[1]
        if cur_fitness == 0:
            cur_fitness = 1e-100
        enum = numpy.add(enum, [(1.0 / cur_fitness) * x for x in Xi[0]])
        denom += 1.0 / cur_fitness
    position = numpy.divide(enum, denom)
    return (position, fitness(position))

# Each beta is a P-sized list where each element is an N-dimensional array
def beta_food(population):
    Xfood = find_food(population)
    Cfood = 2.0 * (1.0 - (float(curr_iteration) / MAX_ITERATIONS))
    betas = list()
    for Xi in population:
        betai = [Cfood * kij_hat(Xi, Xfood) * x for x in xij_hat(Xi, Xfood)]
        betas.append(betai)
    return betas

# Each beta is a P-sized list where each element is an N-dimensional array
def beta_best(population):
    betas = list()
    for Xi in population:
        betai = [kij_hat(Xi, Xi[2:]) * x for x in xij_hat(Xi, Xi[2:])]
        betas.append(betai)
    return betas

#-------------------------------------------
# End foraging motion functions
#-------------------------------------------

############################################
# Begin physical diffusion functions
############################################

def Di():
    direction = [random.uniform(-1.0, 1.0) for i in range(NUM_DIMENSIONS)]
    constant = D_MAX * (1.0 - (float(curr_iteration) / MAX_ITERATIONS))
    return [constant * x for x in direction]

#-------------------------------------------
# End physical diffusion functions
#-------------------------------------------

############################################
# Begin motion process functions
############################################

# Each Ni is n P-sized list where each element is an N-dimensional array
def Ni(population, Ni_old):
    N = list()
    alphas = numpy.add(local_alpha(population), target_alpha(population))
    for i in range(len(population)):
        Ni_ = numpy.add([N_MAX * x for x in alphas[i]],
                        [OMEGA_N * x for x in Ni_old[i]])
        N.append(Ni_)
    return N

# Each Fi is n P-sized list where each element is an N-dimensional array
def Fi(population, Fi_old):
    F = list()
    betas = numpy.add(beta_food(population), beta_best(population))
    #betas = beta_food(population)
    for i in range(len(population)):
        Fi_ = numpy.add([V_f * x for x in betas[i]],
                        [OMEGA_F * x for x in Fi_old[i]])
        F.append(Fi_)
    return F

def dt(population):
    upper_bounds = list()
    lower_bounds = list()
    for i in range(NUM_DIMENSIONS):
        upper = -1e10
        lower = 1e10
        for Xi in population:
            if Xi[0][i] > upper:
                upper = min (Xi[0][i],X_MAX)
            if Xi[0][i] < lower:
                lower = max(Xi[0][i],X_MIN)
        upper_bounds.append(upper)
        lower_bounds.append(lower)
    return C_t * min(sum(numpy.subtract(upper_bounds, lower_bounds)), NUM_DIMENSIONS * (X_MAX - X_MIN))

def dt2(population):
    upper_bounds = list()
    lower_bounds = list()
    for i in range(NUM_DIMENSIONS):
        upper_bounds.append(X_MAX)
        lower_bounds.append(X_MIN)
    return C_t * sum(numpy.subtract(upper_bounds, lower_bounds))

def move():
    global curr_iteration
    global OMEGA_F
    global OMEGA_N
    global Xworst
    global Xbest
    global best_change_iterations
    global D_MAX

    Xworst = (list(), 0.0, list(), 0.0)
    Xbest = (list(), 1e10, list(), 1e10)

    curr_iteration = 0.0

    population = generate_population()
    zero = [0.0 for i in range(NUM_DIMENSIONS)]
    Ni_old = [list(zero) for i in range(POPULATION_SIZE)]
    Fi_old = [list(zero) for i in range(POPULATION_SIZE)]

    for it in range(MAX_ITERATIONS):
        #print "#" + str(it) + " Best: " + str(Xbest[1]) + " Worst: " + str(Xworst[1])

        # Fitness evaluation
        set_fitness_bounds(population)
        set_history_fitness_bounds(population)
        flag = False

        if  best_change_iterations > 50:
            D_MAX *= 10
            flag = True
            best_change_iterations = 0

        # Calculate motion
        Ni_curr = list(Ni(population, Ni_old))
        Fi_curr = list(Fi(population, Ni_old))
        dX_dt = numpy.add(Ni_curr, Fi_curr)
        dX_dt = numpy.add(dX_dt, [Di() for n in range(POPULATION_SIZE)])
        Ni_old = list(Ni_curr)
        Fi_old = list(Fi_curr)

        if flag:
            D_MAX = 0.005

        # Update positions
        new_population = list()
        isExploration = int(it/FASE_DURANTION)%2 == 0
        # if isExploration:
        #     dt_ = dt2(population) * (1 - float(it/FASE_DURANTION)/NUMBER_OF_FASES)
        # else:
        dt_ = dt(population)

        for i in range(POPULATION_SIZE):
            step = [dt_ * x for x in dX_dt[i]]
            Xi_new = list(population[i])
            Xi_new[0] = numpy.add(Xi_new[0], step)
            Xi_new[1] = fitness(Xi_new[0])
            new_population.append(tuple(Xi_new))

        if USE_CROSS_OVER:
            cross_over_operador(new_population)

        population = list(new_population)
        # Linearly decrease inertia
        if LINEAR_INERTIA_DECREASE:
            OMEGA_F = 0.9 - ((curr_iteration * 0.8) / MAX_ITERATIONS)
            OMEGA_N = 0.9 - ((curr_iteration * 0.8) / MAX_ITERATIONS)

        # Go to next iteration
        curr_iteration += 1
    return (population, Xbest)

#-------------------------------------------
# End motion process functions
#-------------------------------------------

############################################
# Begin evolutionary functions
############################################

# Change the benchmark function here in order to modify the fitness evaluation
fitness = benchmarkFunctions.ackley

# Each genome follows this pattern:
# (<n-dimensional position>, <fitness>, <best position in history>, <best fitness in history>)
def generate_population():
    population = list()
    for i in range(POPULATION_SIZE):
        genome = list()
        for s in range(NUM_DIMENSIONS):
            coord = random.uniform(X_MIN, X_MAX);
            genome.append(coord)
        population.append((genome, fitness(genome), genome, fitness(genome)))
    set_fitness_bounds(population)
    set_history_fitness_bounds(population)
    return population

def generate_population_branin():
    population = list()
    for i in range(POPULATION_SIZE):
        genome = list()
        coord1 = random.uniform(X_MIN, X_MAX)
        coord2 = random.uniform(Y_MIN, Y_MAX);
        genome.extend([coord1,coord2])
        population.append((genome, fitness(genome), genome, fitness(genome)))
    set_fitness_bounds(population)
    set_history_fitness_bounds(population)
    return population

def set_fitness_bounds(population):
    global Xworst
    global Xbest
    global best_change_iterations
    iteration_worst = population[0]
    index_iter_worst = 0
    best_has_changed = False
    for idx, Xi in enumerate(population):
        if Xi[1] < Xbest[1]:
            Xbest = Xi
            best_has_changed = True
            best_change_iterations = 0
        else:
            best_change_iterations += 1

        if Xi[1] > Xworst[1]:
            Xworst = Xi

        if Xi[1] > iteration_worst[1]:
            iteration_worst = Xi
            index_iter_worst = idx

    if not best_has_changed:
        population.pop(index_iter_worst)
        population.append(Xbest)

def set_history_fitness_bounds(population):
    for Xi in population:
        Xi_ = list(Xi)
        # If current fitness is better than the best in history, swap
        if Xi[1] < Xi[3]:
            Xi_[3] = Xi[1]
            Xi_[2] = list(Xi[0])
        Xi = tuple(Xi_)

def cross_over_operador(population):
    pop_len = len(population)
    for Xi in population:
        Cr = 0.2 * kij_hat(Xi, Xbest)
        for d in range(NUM_DIMENSIONS):
            if random.uniform(0,1) < Cr:
                j = random.randint(0,pop_len - 1)
                Xj = population[j]
                Xi[0][d] = Xj[0][d]

#-------------------------------------------
# End evolutionary functions
#-------------------------------------------

def main(function_params, dims = None):
    initialize_function(function_params, dims)
    best = 1e10
    avg = 0.0
    std = 0.0
    for i in range(NUM_TRIALS):
        print "Running trial #" + str(i+1)
        (p, b) = move()
        best = min(b[1], best)
        avg += numpy.mean([x[1] for x in p])
        std += numpy.std([x[1] for x in p])
        print best
    avg = avg / NUM_TRIALS
    std = std / NUM_TRIALS
    print "Best out of " + str(NUM_TRIALS) + " runs: " + str(best)
    print "Std. dev out of " + str(NUM_TRIALS) + " runs: " + str(std)
    print "Average out of " + str(NUM_TRIALS) + " runs: " + str(avg)

def test_case_2(benchmark_params):
    global LINEAR_INERTIA_DECREASE
    dimensions = [2,4,6,8]

    for dim in dimensions:
        LINEAR_INERTIA_DECREASE = True
        print 'DIMENSIONS: ' + str(dim) +' linear decrease TRUE'
        main(benchmark_params, dim)

print "RASTRIGIN"
test_case_2(benchmarkFunctions.RASTRIGIN())


text:
package features

import (
	apiextensionsfeatures "k8s.io/apiextensions-apiserver/pkg/features"
	genericfeatures "k8s.io/apiserver/pkg/features"
	utilfeature "k8s.io/apiserver/pkg/util/feature"
)

const (
	// Every feature gate should add method here following this template:
	//
	// // owner: @username
	// // alpha: v1.X
	// MyFeature utilfeature.Feature = "MyFeature"

	// owner: @tallclair
	// beta: v1.4
	AppArmor utilfeature.Feature = "AppArmor"

	// owner: @mtaufen
	// alpha: v1.4
	// beta: v1.11
	DynamicKubeletConfig utilfeature.Feature = "DynamicKubeletConfig"

	// owner: @pweil-
	// alpha: v1.5
	//
	// Default userns=host for containers that are using other host namespaces, host mounts, the pod
	// contains a privileged container, or specific non-namespaced capabilities (MKNOD, SYS_MODULE,
	// SYS_TIME). This should only be enabled if user namespace remapping is enabled in the docker daemon.
	ExperimentalHostUserNamespaceDefaultingGate utilfeature.Feature = "ExperimentalHostUserNamespaceDefaulting"

	// owner: @vishh
	// alpha: v1.5
	//
	// DEPRECATED - This feature is deprecated by Pod Priority and Preemption as of Kubernetes 1.13.
	// Ensures guaranteed scheduling of pods marked with a special pod annotation `scheduler.alpha.kubernetes.io/critical-pod`
	// and also prevents them from being evicted from a node.
	// Note: This feature is not supported for `BestEffort` pods.
	ExperimentalCriticalPodAnnotation utilfeature.Feature = "ExperimentalCriticalPodAnnotation"

	// owner: @jiayingz
	// beta: v1.10
	//
	// Enables support for Device Plugins
	DevicePlugins utilfeature.Feature = "DevicePlugins"

	// owner: @Huang-Wei
	// beta: v1.13
	//
	// Changes the logic behind evicting Pods from not ready Nodes
	// to take advantage of NoExecute Taints and Tolerations.
	TaintBasedEvictions utilfeature.Feature = "TaintBasedEvictions"

	// owner: @mikedanese
	// alpha: v1.7
	// beta: v1.12
	//
	// Gets a server certificate for the kubelet from the Certificate Signing
	// Request API instead of generating one self signed and auto rotates the
	// certificate as expiration approaches.
	RotateKubeletServerCertificate utilfeature.Feature = "RotateKubeletServerCertificate"

	// owner: @mikedanese
	// beta: v1.8
	//
	// Automatically renews the client certificate used for communicating with
	// the API server as the certificate approaches expiration.
	RotateKubeletClientCertificate utilfeature.Feature = "RotateKubeletClientCertificate"

	// owner: @msau42
	// alpha: v1.7
	//
	// A new volume type that supports local disks on a node.
	PersistentLocalVolumes utilfeature.Feature = "PersistentLocalVolumes"

	// owner: @jinxu
	// beta: v1.10
	//
	// New local storage types to support local storage capacity isolation
	LocalStorageCapacityIsolation utilfeature.Feature = "LocalStorageCapacityIsolation"

	// owner: @gnufied
	// beta: v1.11
	// Ability to Expand persistent volumes
	ExpandPersistentVolumes utilfeature.Feature = "ExpandPersistentVolumes"

	// owner: @mlmhl
	// alpha: v1.11
	// Ability to expand persistent volumes' file system without unmounting volumes.
	ExpandInUsePersistentVolumes utilfeature.Feature = "ExpandInUsePersistentVolumes"

	// owner: @verb
	// alpha: v1.10
	//
	// Allows running a "debug container" in a pod namespaces to troubleshoot a running pod.
	DebugContainers utilfeature.Feature = "DebugContainers"

	// owner: @verb
	// beta: v1.12
	//
	// Allows all containers in a pod to share a process namespace.
	PodShareProcessNamespace utilfeature.Feature = "PodShareProcessNamespace"

	// owner: @bsalamat
	// alpha: v1.8
	//
	// Add priority to pods. Priority affects scheduling and preemption of pods.
	PodPriority utilfeature.Feature = "PodPriority"

	// owner: @resouer
	// alpha: v1.8
	//
	// Enable equivalence class cache for scheduler.
	EnableEquivalenceClassCache utilfeature.Feature = "EnableEquivalenceClassCache"

	// owner: @k82cn
	// beta: v1.12
	//
	// Taint nodes based on their condition status for 'NetworkUnavailable',
	// 'MemoryPressure', 'OutOfDisk' and 'DiskPressure'.
	TaintNodesByCondition utilfeature.Feature = "TaintNodesByCondition"

	// owner: @jsafrane
	// GA: v1.12
	//
	// Note: This feature gate is unconditionally enabled in v1.13 and will be removed in v1.14.
	// Enable mount propagation of volumes.
	MountPropagation utilfeature.Feature = "MountPropagation"

	// owner: @sjenning
	// alpha: v1.11
	//
	// Allows resource reservations at the QoS level preventing pods at lower QoS levels from
	// bursting into resources requested at higher QoS levels (memory only for now)
	QOSReserved utilfeature.Feature = "QOSReserved"

	// owner: @ConnorDoyle
	// alpha: v1.8
	//
	// Alternative container-level CPU affinity policies.
	CPUManager utilfeature.Feature = "CPUManager"

	// owner: @szuecs
	// alpha: v1.12
	//
	// Enable nodes to change CPUCFSQuotaPeriod
	CPUCFSQuotaPeriod utilfeature.Feature = "CustomCPUCFSQuotaPeriod"

	// owner: @derekwaynecarr
	// beta: v1.10
	//
	// Enable pods to consume pre-allocated huge pages of varying page sizes
	HugePages utilfeature.Feature = "HugePages"

	// owner: @sjenning
	// beta: v1.11
	//
	// Enable pods to set sysctls on a pod
	Sysctls utilfeature.Feature = "Sysctls"

	// owner @brendandburns
	// alpha: v1.9
	//
	// Enable nodes to exclude themselves from service load balancers
	ServiceNodeExclusion utilfeature.Feature = "ServiceNodeExclusion"

	// owner: @jsafrane
	// alpha: v1.9
	//
	// Enable running mount utilities in containers.
	MountContainers utilfeature.Feature = "MountContainers"

	// owner: @msau42
	// GA: v1.13
	//
	// Extend the default scheduler to be aware of PV topology and handle PV binding
	VolumeScheduling utilfeature.Feature = "VolumeScheduling"

	// owner: @vladimirvivien
	// GA: v1.13
	//
	// Enable mount/attachment of Container Storage Interface (CSI) backed PVs
	CSIPersistentVolume utilfeature.Feature = "CSIPersistentVolume"

	// owner: @saad-ali
	// alpha: v1.12
	// Enable all logic related to the CSIDriver API object in csi.storage.k8s.io
	CSIDriverRegistry utilfeature.Feature = "CSIDriverRegistry"

	// owner: @verult
	// alpha: v1.12
	// Enable all logic related to the CSINodeInfo API object in csi.storage.k8s.io
	CSINodeInfo utilfeature.Feature = "CSINodeInfo"

	// owner @MrHohn
	// beta: v1.10
	//
	// Support configurable pod DNS parameters.
	CustomPodDNS utilfeature.Feature = "CustomPodDNS"

	// owner: @screeley44
	// alpha: v1.9
	// beta: v1.13
	//
	// Enable Block volume support in containers.
	BlockVolume utilfeature.Feature = "BlockVolume"

	// owner: @pospispa
	// GA: v1.11
	//
	// Postpone deletion of a PV or a PVC when they are being used
	StorageObjectInUseProtection utilfeature.Feature = "StorageObjectInUseProtection"

	// owner: @aveshagarwal
	// alpha: v1.9
	//
	// Enable resource limits priority function
	ResourceLimitsPriorityFunction utilfeature.Feature = "ResourceLimitsPriorityFunction"

	// owner: @m1093782566
	// GA: v1.11
	//
	// Implement IPVS-based in-cluster service load balancing
	SupportIPVSProxyMode utilfeature.Feature = "SupportIPVSProxyMode"

	// owner: @dims
	// alpha: v1.10
	//
	// Implement support for limiting pids in pods
	SupportPodPidsLimit utilfeature.Feature = "SupportPodPidsLimit"

	// owner: @feiskyer
	// alpha: v1.10
	//
	// Enable Hyper-V containers on Windows
	HyperVContainer utilfeature.Feature = "HyperVContainer"

	// owner: @k82cn
	// beta: v1.12
	//
	// Schedule DaemonSet Pods by default scheduler instead of DaemonSet controller
	ScheduleDaemonSetPods utilfeature.Feature = "ScheduleDaemonSetPods"

	// owner: @mikedanese
	// beta: v1.12
	//
	// Implement TokenRequest endpoint on service account resources.
	TokenRequest utilfeature.Feature = "TokenRequest"

	// owner: @mikedanese
	// beta: v1.12
	//
	// Enable ServiceAccountTokenVolumeProjection support in ProjectedVolumes.
	TokenRequestProjection utilfeature.Feature = "TokenRequestProjection"

	// owner: @mikedanese
	// alpha: v1.13
	//
	// Migrate ServiceAccount volumes to use a projected volume consisting of a
	// ServiceAccountTokenVolumeProjection. This feature adds new required flags
	// to the API server.
	BoundServiceAccountTokenVolume utilfeature.Feature = "BoundServiceAccountTokenVolume"

	// owner: @Random-Liu
	// beta: v1.11
	//
	// Enable container log rotation for cri container runtime
	CRIContainerLogRotation utilfeature.Feature = "CRIContainerLogRotation"

	// owner: @verult
	// GA: v1.13
	//
	// Enables the regional PD feature on GCE.
	GCERegionalPersistentDisk utilfeature.Feature = "GCERegionalPersistentDisk"

	// owner: @krmayankk
	// alpha: v1.10
	//
	// Enables control over the primary group ID of containers' init processes.
	RunAsGroup utilfeature.Feature = "RunAsGroup"

	// owner: @saad-ali
	// ga
	//
	// Allow mounting a subpath of a volume in a container
	// Do not remove this feature gate even though it's GA
	VolumeSubpath utilfeature.Feature = "VolumeSubpath"

	// owner: @gnufied
	// beta : v1.12
	//
	// Add support for volume plugins to report node specific
	// volume limits
	AttachVolumeLimit utilfeature.Feature = "AttachVolumeLimit"

	// owner: @ravig
	// alpha: v1.11
	//
	// Include volume count on node to be considered for balanced resource allocation while scheduling.
	// A node which has closer cpu,memory utilization and volume count is favoured by scheduler
	// while making decisions.
	BalanceAttachedNodeVolumes utilfeature.Feature = "BalanceAttachedNodeVolumes"

	// owner @freehan
	// beta: v1.11
	//
	// Support Pod Ready++
	PodReadinessGates utilfeature.Feature = "PodReadinessGates"

	// owner: @kevtaylor
	// alpha: v1.11
	//
	// Allow subpath environment variable substitution
	// Only applicable if the VolumeSubpath feature is also enabled
	VolumeSubpathEnvExpansion utilfeature.Feature = "VolumeSubpathEnvExpansion"

	// owner: @vikaschoudhary16
	// GA: v1.13
	//
	//
	// Enable probe based plugin watcher utility for discovering Kubelet plugins
	KubeletPluginsWatcher utilfeature.Feature = "KubeletPluginsWatcher"

	// owner: @vikaschoudhary16
	// beta: v1.12
	//
	//
	// Enable resource quota scope selectors
	ResourceQuotaScopeSelectors utilfeature.Feature = "ResourceQuotaScopeSelectors"

	// owner: @vladimirvivien
	// alpha: v1.11
	//
	// Enables CSI to use raw block storage volumes
	CSIBlockVolume utilfeature.Feature = "CSIBlockVolume"

	// owner: @tallclair
	// alpha: v1.12
	//
	// Enables RuntimeClass, for selecting between multiple runtimes to run a pod.
	RuntimeClass utilfeature.Feature = "RuntimeClass"

	// owner: @mtaufen
	// alpha: v1.12
	//
	// Kubelet uses the new Lease API to report node heartbeats,
	// (Kube) Node Lifecycle Controller uses these heartbeats as a node health signal.
	NodeLease utilfeature.Feature = "NodeLease"

	// owner: @janosi
	// alpha: v1.12
	//
	// Enables SCTP as new protocol for Service ports, NetworkPolicy, and ContainerPort in Pod/Containers definition
	SCTPSupport utilfeature.Feature = "SCTPSupport"

	// owner: @xing-yang
	// alpha: v1.12
	//
	// Enable volume snapshot data source support.
	VolumeSnapshotDataSource utilfeature.Feature = "VolumeSnapshotDataSource"

	// owner: @jessfraz
	// alpha: v1.12
	//
	// Enables control over ProcMountType for containers.
	ProcMountType utilfeature.Feature = "ProcMountType"

	// owner: @janetkuo
	// alpha: v1.12
	//
	// Allow TTL controller to clean up Pods and Jobs after they finish.
	TTLAfterFinished utilfeature.Feature = "TTLAfterFinished"

	// owner: @dashpole
	// alpha: v1.13
	//
	// Enables the kubelet's pod resources grpc endpoint
	KubeletPodResources utilfeature.Feature = "KubeletPodResources"
)

func init() {
	utilfeature.DefaultFeatureGate.Add(defaultKubernetesFeatureGates)
}

// defaultKubernetesFeatureGates consists of all known Kubernetes-specific feature keys.
// To add a new feature, define a key for it above and add it here. The features will be
// available throughout Kubernetes binaries.
var defaultKubernetesFeatureGates = map[utilfeature.Feature]utilfeature.FeatureSpec{
	AppArmor:             {Default: true, PreRelease: utilfeature.Beta},
	DynamicKubeletConfig: {Default: true, PreRelease: utilfeature.Beta},
	ExperimentalHostUserNamespaceDefaultingGate: {Default: false, PreRelease: utilfeature.Beta},
	ExperimentalCriticalPodAnnotation:           {Default: false, PreRelease: utilfeature.Alpha},
	DevicePlugins:                               {Default: true, PreRelease: utilfeature.Beta},
	TaintBasedEvictions:                         {Default: true, PreRelease: utilfeature.Beta},
	RotateKubeletServerCertificate:              {Default: true, PreRelease: utilfeature.Beta},
	RotateKubeletClientCertificate:              {Default: true, PreRelease: utilfeature.Beta},
	PersistentLocalVolumes:                      {Default: true, PreRelease: utilfeature.Beta},
	LocalStorageCapacityIsolation:               {Default: true, PreRelease: utilfeature.Beta},
	HugePages:                                   {Default: true, PreRelease: utilfeature.Beta},
	Sysctls:                                     {Default: true, PreRelease: utilfeature.Beta},
	DebugContainers:                             {Default: false, PreRelease: utilfeature.Alpha},
	PodShareProcessNamespace:                    {Default: true, PreRelease: utilfeature.Beta},
	PodPriority:                                 {Default: true, PreRelease: utilfeature.Beta},
	EnableEquivalenceClassCache:                 {Default: false, PreRelease: utilfeature.Alpha},
	TaintNodesByCondition:                       {Default: true, PreRelease: utilfeature.Beta},
	MountPropagation:                            {Default: true, PreRelease: utilfeature.GA},
	QOSReserved:                                 {Default: false, PreRelease: utilfeature.Alpha},
	ExpandPersistentVolumes:                     {Default: true, PreRelease: utilfeature.Beta},
	ExpandInUsePersistentVolumes:                {Default: false, PreRelease: utilfeature.Alpha},
	AttachVolumeLimit:                           {Default: true, PreRelease: utilfeature.Beta},
	CPUManager:                                  {Default: true, PreRelease: utilfeature.Beta},
	CPUCFSQuotaPeriod:                           {Default: false, PreRelease: utilfeature.Alpha},
	ServiceNodeExclusion:                        {Default: false, PreRelease: utilfeature.Alpha},
	MountContainers:                             {Default: false, PreRelease: utilfeature.Alpha},
	VolumeScheduling:                            {Default: true, PreRelease: utilfeature.GA},
	CSIPersistentVolume:                         {Default: true, PreRelease: utilfeature.GA},
	CSIDriverRegistry:                           {Default: false, PreRelease: utilfeature.Alpha},
	CSINodeInfo:                                 {Default: false, PreRelease: utilfeature.Alpha},
	CustomPodDNS:                                {Default: true, PreRelease: utilfeature.Beta},
	BlockVolume:                                 {Default: true, PreRelease: utilfeature.Beta},
	StorageObjectInUseProtection:                {Default: true, PreRelease: utilfeature.GA},
	ResourceLimitsPriorityFunction:              {Default: false, PreRelease: utilfeature.Alpha},
	SupportIPVSProxyMode:                        {Default: true, PreRelease: utilfeature.GA},
	SupportPodPidsLimit:                         {Default: false, PreRelease: utilfeature.Alpha},
	HyperVContainer:                             {Default: false, PreRelease: utilfeature.Alpha},
	ScheduleDaemonSetPods:                       {Default: true, PreRelease: utilfeature.Beta},
	TokenRequest:                                {Default: true, PreRelease: utilfeature.Beta},
	TokenRequestProjection:                      {Default: true, PreRelease: utilfeature.Beta},
	BoundServiceAccountTokenVolume:              {Default: false, PreRelease: utilfeature.Alpha},
	CRIContainerLogRotation:                     {Default: true, PreRelease: utilfeature.Beta},
	GCERegionalPersistentDisk:                   {Default: true, PreRelease: utilfeature.GA},
	RunAsGroup:                                  {Default: false, PreRelease: utilfeature.Alpha},
	VolumeSubpath:                               {Default: true, PreRelease: utilfeature.GA},
	BalanceAttachedNodeVolumes:                  {Default: false, PreRelease: utilfeature.Alpha},
	PodReadinessGates:                           {Default: true, PreRelease: utilfeature.Beta},
	VolumeSubpathEnvExpansion:                   {Default: false, PreRelease: utilfeature.Alpha},
	KubeletPluginsWatcher:                       {Default: true, PreRelease: utilfeature.GA},
	ResourceQuotaScopeSelectors:                 {Default: true, PreRelease: utilfeature.Beta},
	CSIBlockVolume:                              {Default: false, PreRelease: utilfeature.Alpha},
	RuntimeClass:                                {Default: false, PreRelease: utilfeature.Alpha},
	NodeLease:                                   {Default: false, PreRelease: utilfeature.Alpha},
	SCTPSupport:                                 {Default: false, PreRelease: utilfeature.Alpha},
	VolumeSnapshotDataSource:                    {Default: false, PreRelease: utilfeature.Alpha},
	ProcMountType:                               {Default: false, PreRelease: utilfeature.Alpha},
	TTLAfterFinished:                            {Default: false, PreRelease: utilfeature.Alpha},
	KubeletPodResources:                         {Default: false, PreRelease: utilfeature.Alpha},

	// inherited features from generic apiserver, relisted here to get a conflict if it is changed
	// unintentionally on either side:
	genericfeatures.StreamingProxyRedirects: {Default: true, PreRelease: utilfeature.Beta},
	genericfeatures.AdvancedAuditing:        {Default: true, PreRelease: utilfeature.GA},
	genericfeatures.DynamicAuditing:         {Default: false, PreRelease: utilfeature.Alpha},
	genericfeatures.APIResponseCompression:  {Default: false, PreRelease: utilfeature.Alpha},
	genericfeatures.Initializers:            {Default: false, PreRelease: utilfeature.Alpha},
	genericfeatures.APIListChunking:         {Default: true, PreRelease: utilfeature.Beta},
	genericfeatures.DryRun:                  {Default: true, PreRelease: utilfeature.Beta},

	// inherited features from apiextensions-apiserver, relisted here to get a conflict if it is changed
	// unintentionally on either side:
	apiextensionsfeatures.CustomResourceValidation:        {Default: true, PreRelease: utilfeature.Beta},
	apiextensionsfeatures.CustomResourceSubresources:      {Default: true, PreRelease: utilfeature.Beta},
	apiextensionsfeatures.CustomResourceWebhookConversion: {Default: false, PreRelease: utilfeature.Alpha},

	// features that enable backwards compatibility but are scheduled to be removed
	// ...
}

redpajama_set_name: RedPajamaGithub


text:
import React from 'react'
import PropTypes from 'prop-types'
import { MarkerCanvasProvider } from './MarkerCanvasContext'
import TimelineMarkersRenderer from './TimelineMarkersRenderer'
import { TimelineStateConsumer } from '../timeline/TimelineStateContext'

// expand to fill entire parent container (ScrollElement)
const staticStyles = {
  position: 'absolute',
  left: 0,
  right: 0,
  top: 0,
  bottom: 0
}

/**
 * Renders registered markers and exposes a mouse over listener for
 * CursorMarkers to subscribe to
 */
class MarkerCanvas extends React.Component {
  static propTypes = {
    getDateFromLeftOffsetPosition: PropTypes.func.isRequired,
    children: PropTypes.node
  }

  handleMouseMove = evt => {
    if (this.subscription != null) {
      const { pageX } = evt
      // FIXME: dont use getBoundingClientRect. Use passed in scroll amount
      const { left: containerLeft } = this.containerEl.getBoundingClientRect()

      // number of pixels from left we are on canvas
      // we do this calculation as pageX is based on x from viewport whereas
      // our canvas can be scrolled left and right and is generally outside
      // of the viewport.  This calculation is to get how many pixels the cursor
      // is from left of this element
      const canvasX = pageX - containerLeft
      const date = this.props.getDateFromLeftOffsetPosition(canvasX)
      this.subscription({
        leftOffset: canvasX,
        date,
        isCursorOverCanvas: true
      })
    }
  }

  handleMouseLeave = () => {
    if (this.subscription != null) {
      // tell subscriber that we're not on canvas
      this.subscription({ leftOffset: 0, date: 0, isCursorOverCanvas: false })
    }
  }

  handleMouseMoveSubscribe = sub => {
    this.subscription = sub
    return () => {
      this.subscription = null
    }
  }

  state = {
    subscribeToMouseOver: this.handleMouseMoveSubscribe
  }

  render() {
    return (
      <MarkerCanvasProvider value={this.state}>
        <div
          style={staticStyles}
          onMouseMove={this.handleMouseMove}
          onMouseLeave={this.handleMouseLeave}
          ref={el => (this.containerEl = el)}
        >
          <TimelineMarkersRenderer />
          {this.props.children}
        </div>
      </MarkerCanvasProvider>
    )
  }
}

const MarkerCanvasWrapper = props => (
  <TimelineStateConsumer>
    {({ getDateFromLeftOffsetPosition }) => (
      <MarkerCanvas
        getDateFromLeftOffsetPosition={getDateFromLeftOffsetPosition}
        {...props}
      />
    )}
  </TimelineStateConsumer>
)

export default MarkerCanvasWrapper


text:
START=`date +%s`

CWD=`pwd`

BUILD_DIR=${CWD}/../gadsu_release_build
ARTIFACTS_DIR=${BUILD_DIR}/release_artifacts
# unfortunately the fatJar plugin uses the folder name as the jar filename :-/
CHECKOUT_DIR=${BUILD_DIR}/Gadsu
GIT_URL=https://github.com/christophpickl/gadsu.git
VERSION_PROPERTIES_FILE=version.properties
VERSION_PROPERTIES_PATH="$CWD/$VERSION_PROPERTIES_FILE"
VERSION_LATEST_FILE=version_latest.txt

myEcho() {
    echo "[RELEASE] $1"
}

checkLastCommand() {
    if [ $? -ne 0 ] ; then
        myEcho "Last command did not end successful!"
        exit 1
    fi
}

changeVersion() {
    echo
    myEcho "Changing version in [${VERSION_PROPERTIES_FILE}] to: $1"
    echo "version=$1" > ${VERSION_PROPERTIES_FILE}
    checkLastCommand
}
changeLatestVersion() {
    echo
    myEcho "Changing latest version in [${VERSION_LATEST_FILE}] to: $1"
    echo "$1" > ${VERSION_LATEST_FILE}
    checkLastCommand
}

# loads the 'version' property from a properties file
version="N/A"
source ${VERSION_PROPERTIES_PATH}
#echo "Loaded version '$version' from: $VERSION_PROPERTIES_PATH"

echo
myEcho "Preparing new GADSU release"
myEcho "===================================="
myEcho "Current version is: $version"

DEFAULT_RELEASE_VERSION=$(echo ${version}| cut -d "-" -f 1)

CURRENT_MINOR_VERSION=$(echo ${DEFAULT_RELEASE_VERSION}| cut -d "." -f 2)
NEXT_MINOR_VERSION=$(($CURRENT_MINOR_VERSION + 1))
DEFAULT_DEVELOPMENT_VERSION="1.$NEXT_MINOR_VERSION.0-SNAPSHOT"

echo
read -p "Enter RELEASE Version [$DEFAULT_RELEASE_VERSION]: " ENTERED_VERSION_RELEASE
read -p "Enter next DEVELOPMENT Version [$DEFAULT_DEVELOPMENT_VERSION]: " ENTERED_VERSION_DEVELOPMENT
# maybe also prompt for git credentials?!?

if [ ! -z "$ENTERED_VERSION_RELEASE" ]; then
    VERSION_RELEASE=${ENTERED_VERSION_RELEASE}
else
    VERSION_RELEASE=${DEFAULT_RELEASE_VERSION}
fi
if [ ! -z "$ENTERED_VERSION_DEVELOPMENT" ]; then
    VERSION_DEVELOPMENT=${ENTERED_VERSION_DEVELOPMENT}
else
    VERSION_DEVELOPMENT=${DEFAULT_DEVELOPMENT_VERSION}
fi

echo
myEcho "Release Summary:"
myEcho "------------------------------------"
myEcho "  Release Version: $VERSION_RELEASE"
myEcho "  Development Version: $VERSION_DEVELOPMENT"
myEcho "  Build Directory: $BUILD_DIR"
myEcho ""
./gradlew -version
git --version

echo

while true; do
    read -p "[RELEASE] Do you confirm this release? [y/n] >> " yn
    case ${yn} in
        [Yy]* ) break;;
        [Nn]* ) echo "Aborted"; exit;;
        * ) myEcho "Please answer y(es) or n(o)";;
    esac
done
echo

if [ -d "$BUILD_DIR" ]; then
    echo
    myEcho "Removing old build directory at: $BUILD_DIR"
    rm -rf ${BUILD_DIR}
fi
mkdir ${BUILD_DIR}
mkdir ${ARTIFACTS_DIR}

cd ${BUILD_DIR}

echo
myEcho "Checking out source to: $CHECKOUT_DIR"
myEcho "------------------------------------"
git clone ${GIT_URL} ${CHECKOUT_DIR}
cd ${CHECKOUT_DIR}

echo
myEcho "Change release version"
myEcho "------------------------------------"
changeVersion ${VERSION_RELEASE}
changeLatestVersion ${VERSION_RELEASE}

echo
myEcho "Verifying release build (TODOs, test)"
myEcho "------------------------------------"
#./gradlew check checkTodo test testUi
./gradlew check test testUi
checkLastCommand

echo
myEcho "Creating assemblies"
myEcho "------------------------------------"
./gradlew createDmg fatJar buildExe -Dgadsu.enableMacBundle=true
checkLastCommand

cp build/distributions/*.dmg ${ARTIFACTS_DIR}
cp build/libs/*.jar ${ARTIFACTS_DIR}
cp build/*.exe ${ARTIFACTS_DIR}

echo
myEcho "Copied artifacts to: $ARTIFACTS_DIR"

echo
myEcho "GIT committing and tagging result"
myEcho "------------------------------------"
git add .
git commit -m "[Auto-Release] current release version: $VERSION_RELEASE"
checkLastCommand

# https://git-scm.com/book/en/v2/Git-Basics-Tagging
# or a heavy weight annotated tag? $ git tag -a 1.1.0 -m "[Auto-Release] current release version: 1.1.0"
git tag ${VERSION_RELEASE}
checkLastCommand

echo
myEcho "Change next version"
myEcho "------------------------------------"
changeVersion ${VERSION_DEVELOPMENT}

git add .
git commit -m "[Auto-Release] next development version: $VERSION_DEVELOPMENT"
checkLastCommand

echo
myEcho "GIT push"
myEcho "------------------------------------"
# first do a usual push, then with tags, otherwise it wont work, i dont get it...
git push
checkLastCommand
git push origin --tags
checkLastCommand

END=`date +%s`
ELAPSED=$(( $END - $START ))

echo
echo
myEcho "Release $VERSION_RELEASE SUCCESSFULL"
myEcho "===================================="
echo
myEcho "Time needed: $ELAPSED seconds"
myEcho "Contents of: $ARTIFACTS_DIR"
ls -l ${ARTIFACTS_DIR}
myEcho
myEcho "Now start the Post Release Kotlin script (release_generator.kt)."
myEcho
echo

exit 0


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Vaccine.Data.Models
{
    using System.Data.Entity;

    public class VaccineDataContextInitializer : DropCreateDatabaseAlways<VaccineDataContext>
    {
        protected override void Seed(VaccineDataContext context)
        {
            Person person = new Person() { FirstName = "First person"};
            context.Persons.Add(person);
            context.SaveChanges();
        }
    }
}


text:
<?php defined("SYSPATH") or die("No direct script access.");

class advanced_search_Controller extends Controller {

  /**
  * Create of the index page
  */

  public function index(){
     $items_okay = array();
      $view = new Theme_View("page.html", "collection", "advanced_search");
      $view->content = new View ("advanced_search.html");
      $view->content->offset = 0;
      $view->content->total = 0;
      $view->content->limit = module::get_var("advanced_search","limit_per_page");
      $view->content->items = $items_okay;
      $view->content->enable_exif_gps = module::is_active("exif_gps");
      $view->content->enable_tags = module::is_active("tag");
      $view->content->groups = ORM::factory("group")
            ->join("groups_users", "groups_users.group_id", "groups.id", "left")
            ->where("groups_users.group_id", "IS NOT", null)
            ->group_by("id")->find_all();
      print $view;
  }

  /**
  * Beginning of search functions
  */
   public function search() {

      /**
      * Check the Module Tag or Exif is Actived
      */
      $enable_exif_gps = module::is_active("exif_gps");
      $enable_tags = module::is_active("tag");

      /**
      * Get variable limit per page to use pagination in the Gallery Configuration Page
      */
      $limit = module::get_var("advanced_search","limit_per_page");

      /**
      * Get values of Page
      */
      $title = Input::instance()->post("title");
      $description = Input::instance()->post("description");
      $tags = Input::instance()->post("tags");
      $login = Input::instance()->post("login");
      $fullname = Input::instance()->post("fullname");
      $without = Input::instance()->post("without");
      $groups = Input::instance()->post("groups");
      $orderby = Input::instance()->post("orderby");
      $itemtype = Input::instance()->post("itemtype");
      $offset = Input::instance()->post("offset");
      $dateby = Input::instance()->post("dateby");
      $datefrom = Input::instance()->post("datefrom");
      $dateto = Input::instance()->post("dateto");

      /**
      * Set the date and time format to capture the values of the data field
      */
      $timestampfrom = strtotime(str_replace('/', '-', $datefrom));
      $timestampto = strtotime(str_replace('/', '-', $dateto));

      /**
      * Insert values of Page in array for use in the queries conditions and printing again the Page
      */
      $form = array("tags" => $tags, "title" => $title, "login" => $login, "fullname" => $fullname,
       "description" => $description, "groups" => $groups, "orderby" => $orderby, "itemtype" => $itemtype,
        "withouttag" => in_array("withouttag", $without), "withoutgps" => in_array("withoutgps", $without),
        "dateby" => $dateby, "datefrom" => $datefrom, "dateto" => $dateto);

      /*
      *  The post send information to the group in the following format:
      *  groups
      *  {
      *    select_index: the index of the group within the select
      *    group_id: is the id of the group corresponding to the index of the select
      *  }
      */
      $values_groups = explode(":", $groups);
      $group_id = $values_groups[1];

      if($group_id > 0){
        $groups_users = db::build()->select()->from("groups_users")->where("group_id", "=", $group_id)->execute();

        $group_users_id = array();

        foreach ($groups_users as $key => $group_users) {
          $group_users_id[$key] = $group_users->user_id;
        }

      }

      /**
      * Instance Objects (User and Item) for to use in query conditions
      */
      $users = ORM::factory("user");
      $items = ORM::factory("item");
      $items2 = ORM::factory("item");

      /**
      * Conditions queries responsible for fetching user using login and owner fields
      */
      if($login){
          $users->where("name", "like","%".trim($login)."%");
      }
      if($fullname){
          $users->where("full_name", "like","%".trim($fullname)."%");
      }

      $users = $users->find_all();

      /**
      * "If" used to capture the id of users
      */
      if($users->as_array()){
        $users_id = array();
        foreach ($users as $key => $user) {
            $users_id[$key] = $user->id;
            $user_array[$user->id] = $user;
        }
      }

      /**
      * "Array_intersec" used to caputurar users who are in the selected group
      */
      $user_result = array_intersect($group_users_id, $users_id);

      /**
      * Conditions queries responsible for fetching user using title and description fields
      * Obs.: To make appointments and counts items for use in pagination was necessary to create duplicate queries.
      */
      if($title){
        $items->where("title", "like","%".trim($title)."%");
        $items2->where("title", "like","%".trim($title)."%");
      }
      if($description){
        $items->where("description", "like","%".trim($description)."%");
        $items2->where("description", "like","%".trim($description)."%");
      }

      /**
      * The first thing is to test if the module is active tag;
      * After validating tag module is necessary to blow up the tags that were entered in the fields on the page to perform the search of items containing respectvas tags.
      * The variable $ message_tags will be used to validate the tag inserted into the tag field.
      */
      if($enable_tags){

        $tags_data = array();

        foreach (explode(",", $tags) as $tag_name) {

          if ($tag_name) {

                $tag = ORM::factory("tag")->where("name", "=", trim($tag_name))->find();

                if(!$tag->loaded()){
                  $message_tags = true;
                  break;
                }

                /**
                * If the entered tag there is no $ tags_data array is reset
                */
                $tags_data[] = $tag->id;
                 if(is_null($tag->id)){
                  $tags_data = array();
                  break;
                }
            }
          }

        /*
        * If typed tags, runs the query below to search items with one or more combinations of tags.
        */

        if($tags_data){
          $total_tags = count($tags_data);
          $items->join("items_tags","items.id","items_tags.item_id", "left")
            ->where("items_tags.tag_id","IN",$tags_data)
            ->group_by("items_tags.item_id")
            ->having('count("*")', '>=', $total_tags);

          $items2->join("items_tags","items.id","items_tags.item_id", "left")
            ->where("items_tags.tag_id","IN",$tags_data)
            ->group_by("items_tags.item_id")
            ->having('count("*")', '>=', $total_tags);
        }

        /*
        * Querry to search all items that do not contain tags
        */
        if(in_array("withouttag", $without)){
          $items->join("items_tags", "items.id", "items_tags.item_id", "left")
            ->where("items_tags.item_id", "IS", null);
          $items2->join("items_tags", "items.id", "items_tags.item_id", "left")
            ->where("items_tags.item_id", "IS", null);
        }
      }

      /*
      * The "if" checks whether the module is active exif_gps
      * Querry to search all items that do not contain tags
      */
      if($enable_exif_gps){
        if(in_array("withoutgps", $without)){
          $items->join("exif_coordinates", "items.id", "exif_coordinates.item_id", "left")
            ->where("exif_coordinates.item_id", "IS", null);
          $items2->join("exif_coordinates", "items.id", "exif_coordinates.item_id", "left")
            ->where("exif_coordinates.item_id", "IS", null);
        }
      }

      /**
      * Select items by item type
      */
      switch ($itemtype) {
        case "0":
          $items->where("type", "=", "photo");
          $items2->where("type", "=", "photo");
          break;
        case "1":
          $items->where("type", "=", "movie");
          $items2->where("type", "=", "movie");
          break;
        case "2":
          $items->where("type", "=", "album");
          $items2->where("type", "=", "album");
          break;
        case "3":
          break;
      }

      /**
      * Select items using the period between two dates and type of data;
      * When the option is case "0" is displayed photos of all time
      */
      switch ($dateby) {
        case "0":
          break;
        case "1":
          $items->where("captured", 'BETWEEN', array($timestampfrom, $timestampto));
          $items2->where("captured", 'BETWEEN', array($timestampfrom, $timestampto));
          break;
        case "2":
          $items->where("created", 'BETWEEN', array($timestampfrom, $timestampto));
          $items2->where("created", 'BETWEEN', array($timestampfrom, $timestampto));
          break;
        case "3":
          $items->where("updated", 'BETWEEN', array($timestampfrom, $timestampto));
          $items2->where("updated", 'BETWEEN', array($timestampfrom, $timestampto));
          break;
      }

      /**
      * Switch case utilizado para ordenar os itens na tela
      */
      switch ($orderby) {
        case "0":
          $items->order_by("owner_id","asc");
          break;
        case "1":
          $items->order_by("title","asc");
          break;
        case "2":
          $items->order_by("captured","asc");
          break;
        case "3":
          $items->order_by("created","asc");
          break;
        case "4":
          $items->order_by("updated","asc");
          break;
      }

      /**
      * This query gets the intersect between the table groups and users using $user_result
      */
      $items->where("owner_id","IN",$user_result);
      $items2->where("owner_id","IN",$user_result);

      /**
      * Create combobox only with groups containing user
      */
      $groups_okay = ORM::factory("group");
      $groups_okay->join("groups_users", "groups_users.group_id", "groups.id", "left")
            ->where("groups_users.group_id", "IS NOT", null)
            ->group_by("id");
      $groups_okay = $groups_okay->find_all();

      /**
      * Creating page sending the activation status exif_gps, tags and all groups with users to combobox
      */
      $view = new Theme_View("page.html", "collection", "advanced_search");
      $view->content = new View ("advanced_search.html");
      $view->content->enable_exif_gps = $enable_exif_gps;
      $view->content->enable_tags = $enable_tags;
      $view->content->groups = $groups_okay;
      /**
      * Variable for field validation
      */
      $valid_fields = true;

      /**
      * Checking if login and fullname found in database or group selected.
      */
      if(($login && !$user_result) || ($fullname && !$user_result)){
           message::warning(t(" Owner or Login not found"));
           $valid_fields = false;
      }

      /**
      * Function to validate the date
      */
      function validDate($date){

        $dt=explode("/",$date);
        $d=$dt[0];
        $m=$dt[1];
        $y=$dt[2];

        if (!checkdate($m,$d,$y))
          return false;

        return true;
      }

      /**
      *  If the combobox date is greater than zero is called the following next that
      *  invokes the validation date and if it is true is shown the error message
      */
      if($dateby > 0) {
        if((!validDate($datefrom)) || (!validDate($dateto))){
             message::warning(t("Invalid Date"));
             $valid_fields = false;
        }
      }

      /**
      * if($message_tags || (!$message_tags && $tags == ',')){
      */
      if($message_tags){
          message::warning(t("Invalid Tag"));
          $valid_fields = false;
      }

      /**
      * If one or all fields were typed search is performed and the result printed on the screen as below items
      *
      */
      if(($title || $description || $without ||
        ($login && $user_result)|| ($fullname && $user_result) ||
        ($tags && !$message_tags)) && $valid_fields){
        //
        if($users->as_array()){
          // Using find_all to search and paging
          $items = $items->find_all($limit,$offset);
          //Using find_all to count
          $total = $items2->find_all()->count();
          $items_okay = $items->as_array();
          // If the total is equal to zero, shows message " Items not found"
          if(!$total){
             message::warning(t("Items not found"));
          }
          // Show item only when user has permission to view the item
          foreach ($items_okay as $key => $item) {
            if(!access::can("view",$item)){
               unset($items_okay[$key]);
            }
          }
          // Sending variables to the page
          $view->content->items = $items_okay;
          $view->content->users = $user_array;
          $view->content->form = $form;
          $view->content->offset = $offset;
          $view->content->limit = $limit;
          $view->content->total = $total;
        }
      }else{
        // If $valid_fields is true, show message "Blakn fields"
        if($valid_fields){
          message::warning(t("Blank Fields"));
        }
        // If "if" is false, the values below are sent to page because of else.
        $view->content->form = $form;
        $view->content->offset = 0;
        $view->content->total = 0;
        $view->content->limit = module::get_var("advanced_search","limit_per_page");
        $items_okay = array();
      }
      print $view;
 }

  /**
  * Function to check the type of the item before loading the editing screen
  */
 public function form_edit($id) {
    $item = model_cache::get("item", $id);
    access::required("view", $item);
    access::required("edit", $item);

    switch ($item->type) {
    case "album":
      $form = $this->album_edit_form($item);
      break;

    case "photo":
      $form = $this->photo_edit_form($item);
      break;

    case "movie":
      $form = $this->movie_edit_form($item);
      break;
    }

    print $form;
  }

  /**
  * Forge to edit album
  */

  static function album_edit_form($parent) {
    $form = new Forge(
      "advanced_search/album_update/{$parent->id}", "", "post", array("id" => "g-edit-album-form"));
    $form->hidden("from_id")->value($parent->id);
    $group = $form->group("edit_item")->label(t("Edit Album"));

    $group->input("title")->label(t("Title"))->value($parent->title)
        ->error_messages("required", t("You must provide a title"))
      ->error_messages("length", t("Your title is too long"));
    $group->textarea("description")->label(t("Description"))->value($parent->description);
    if ($parent->id != 1) {
      $group->input("name")->label(t("Directory Name"))->value($parent->name)
        ->error_messages("conflict", t("There is already a movie, photo or album with this name"))
        ->error_messages("no_slashes", t("The directory name can't contain a \"/\""))
        ->error_messages("no_trailing_period", t("The directory name can't end in \".\""))
        ->error_messages("required", t("You must provide a directory name"))
        ->error_messages("length", t("Your directory name is too long"));
      $group->input("slug")->label(t("Internet Address"))->value($parent->slug)
        ->error_messages(
          "conflict", t("There is already a movie, photo or album with this internet address"))
        ->error_messages(
          "reserved", t("This address is reserved and can't be used."))
        ->error_messages(
          "not_url_safe",
          t("The internet address should contain only letters, numbers, hyphens and underscores"))
        ->error_messages("required", t("You must provide an internet address"))
        ->error_messages("length", t("Your internet address is too long"));
    } else {
      $group->hidden("name")->value($parent->name);
      $group->hidden("slug")->value($parent->slug);
    }

    $sort_order = $group->group("sort_order", array("id" => "g-album-sort-order"))
      ->label(t("Sort Order"));

    $sort_order->dropdown("column", array("id" => "g-album-sort-column"))
      ->label(t("Sort by"))
      ->options(album::get_sort_order_options())
      ->selected($parent->sort_column);
    $sort_order->dropdown("direction", array("id" => "g-album-sort-direction"))
      ->label(t("Order"))
      ->options(array("ASC" => t("Ascending"),
                      "DESC" => t("Descending")))
      ->selected($parent->sort_order);

    // Get csrf to send in the post editor
    $csrf = access::csrf_token();

    // JavaScript that will overwrite the post of forge submit and modify their behavior
    $group->script('edit_submit')->text('
           var edit_submit = function() {
        $("input[name=edit]").click(function(){
            $.post("'. url::site("advanced_search/album_update/{$parent->id}?csrf={$csrf}").'", function(data){
            $("#g-dialog").dialog("close");
            $("#btn-search").click();
          });
        });
      }
      $(document).ready(edit_submit);
    ');

    module::event("item_edit_form", $parent, $form);

    $group = $form->group("buttons")->label("");
    $group->hidden("type")->value("album");
    $group->submit("edit")->value(t("Modify"));
    return $form;
  }

  /**
  * Function of update album
  */

  public function album_update($album_id) {
    access::verify_csrf();
    $album = ORM::factory("item", $album_id);
    access::required("view", $album);
    access::required("edit", $album);

    $form = $this->album_edit_form($album);

    try {
      $valid = $form->validate();
      $album->title = $form->edit_item->title->value;
      $album->description = $form->edit_item->description->value;
      $album->sort_column = $form->edit_item->sort_order->column->value;
      $album->sort_order = $form->edit_item->sort_order->direction->value;
      if (array_key_exists("name", $form->edit_item->inputs)) {
        $album->name = $form->edit_item->inputs["name"]->value;
      }
      $album->slug = $form->edit_item->slug->value;
      $album->validate();
    } catch (ORM_Validation_Exception $e) {
      // Translate ORM validation errors into form error messages
      foreach ($e->validation->errors() as $key => $error) {
        $form->edit_item->inputs[$key]->add_error($error, 1);
      }
      $valid = false;
    }

    if ($valid) {
      $album->save();
      module::event("item_edit_form_completed", $album, $form);

      log::success("content", "Updated album", "id\">view");
      message::success(t("Saved album %album_title",
                         array("album_title" => html::purify($album->title))));

      // Stay on the same page
      json::reply(array("result" => "success"));
      }
    else {
      json::reply(array("result" => "error", "html" => (string)$form));
    }
  }

  /**
  * Forge to edit photo
  */
  static function photo_edit_form($photo) {
    $form = new Forge("advanced_search/photo_update/{$photo->id}?csrf={$csrf}", "", "post", array("id" => "g-edit-photo-form"));
    $form->hidden("from_id")->value($photo->id);
    $group = $form->group("edit_item")->label(t("Edit Photo"));
    $group->input("title")->label(t("Title"))->value($photo->title)
      ->error_messages("required", t("You must provide a title"))
      ->error_messages("length", t("Your title is too long"));
    $group->textarea("description")->label(t("Description"))->value($photo->description);
    $group->input("name")->label(t("Filename"))->value($photo->name)
      ->error_messages("conflict", t("There is already a movie, photo or album with this name"))
      ->error_messages("no_slashes", t("The photo name can't contain a \"/\""))
      ->error_messages("no_trailing_period", t("The photo name can't end in \".\""))
      ->error_messages("illegal_data_file_extension", t("You cannot change the photo file extension"))
      ->error_messages("required", t("You must provide a photo file name"))
      ->error_messages("length", t("Your photo file name is too long"));
    $group->input("slug")->label(t("Internet Address"))->value($photo->slug)
      ->error_messages(
        "conflict", t("There is already a movie, photo or album with this internet address"))
      ->error_messages(
        "not_url_safe",
        t("The internet address should contain only letters, numbers, hyphens and underscores"))
      ->error_messages("required", t("You must provide an internet address"))
      ->error_messages("length", t("Your internet address is too long"));

    // Get csrf to send in the post editor
    $csrf = access::csrf_token();

    // JavaScript that will overwrite the post of forge submit and modify their behavior
    $group->script('edit_submit')->text('
           var edit_submit = function() {
        $("input[name=edit]").click(function(){
          $.post("'. url::site("advanced_search/photo_update/{$photo->id}?csrf={$csrf}").'", function(data){
            $("#g-dialog").dialog("close");
            $("#btn-search").click();
          });
        });
      }
      $(document).ready(edit_submit);
    ');

    module::event("item_edit_form", $photo, $form);

    $group = $form->group("buttons")->label("");
    $group->submit("edit")->value(t("Modify"));
    return $form;
  }

  /**
  * Function of update photo
  */
  public function photo_update($photo_id) {

    access::verify_csrf();
    $photo = ORM::factory("item", $photo_id);
    access::required("view", $photo);
    access::required("edit", $photo);

    $form = photo::get_edit_form($photo);
    try {
      $valid = $form->validate();
      $photo->title = $form->edit_item->title->value;
      $photo->description = $form->edit_item->description->value;
      $photo->slug = $form->edit_item->slug->value;
      $photo->name = $form->edit_item->inputs["name"]->value;
      $photo->validate();
    } catch (ORM_Validation_Exception $e) {
      // Translate ORM validation errors into form error messages
      foreach ($e->validation->errors() as $key => $error) {
        $form->edit_item->inputs[$key]->add_error($error, 1);
      }
      $valid = false;
    }

    if ($valid) {
      $photo->save();
      module::event("item_edit_form_completed", $photo, $form);

      log::success("content", "Updated photo", "url()}\">view");
      message::success(
        t("Saved photo %photo_title", array("photo_title" => html::purify($photo->title))));

      // Stay on the same page
      json::reply(array("result" => "success"));
      }
    else {
      json::reply(array("result" => "error", "html" => (string)$form));
    }
  }

  /**
  * Forge to edit movie
  */
  static function movie_edit_form($movie) {
    $form = new Forge("advanced_search/movie_update/$movie->id", "", "post", array("id" => "g-edit-movie-form"));
    $form->hidden("from_id")->value($movie->id);
    $group = $form->group("edit_item")->label(t("Edit Movie"));
    $group->input("title")->label(t("Title"))->value($movie->title)
      ->error_messages("required", t("You must provide a title batatinha quando nasce...."))
      ->error_messages("length", t("Your title is too long"));
    $group->textarea("description")->label(t("Description"))->value($movie->description);
    $group->input("name")->label(t("Filename"))->value($movie->name)
      ->error_messages(
        "conflict", t("There is already a movie, photo or album with this name"))
      ->error_messages("no_slashes", t("The movie name can't contain a \"/\""))
      ->error_messages("no_trailing_period", t("The movie name can't end in \".\""))
      ->error_messages("illegal_data_file_extension", t("You cannot change the movie file extension"))
      ->error_messages("required", t("You must provide a movie file name"))
      ->error_messages("length", t("Your movie file name is too long"));
    $group->input("slug")->label(t("Internet Address"))->value($movie->slug)
      ->error_messages(
        "conflict", t("There is already a movie, photo or album with this internet address"))
      ->error_messages(
        "not_url_safe",
        t("The internet address should contain only letters, numbers, hyphens and underscores"))
      ->error_messages("required", t("You must provide an internet address"))
      ->error_messages("length", t("Your internet address is too long"));

    // Get csrf to send in the post editor
    $csrf = access::csrf_token();

    // JavaScript that will overwrite the post of forge submit and modify their behavior
    $group->script('edit_submit')->text('
           var edit_submit = function() {
        $("input[name=edit]").click(function(){
          $.post("'. url::site("advanced_search/movie_update/{$movie->id}?csrf={$csrf}").'", function(data){
            $("#g-dialog").dialog("close");
            $("#btn-search").click();
          });
        });
      }
      $(document).ready(edit_submit);
    ');

    module::event("item_edit_form", $movie, $form);

    $group = $form->group("buttons")->label("");
    $group->submit("edit")->value(t("Modify"));

    return $form;
  }

  /**
  *
  */
  public function movie_update($movie_id) {
    access::verify_csrf();
    $movie = ORM::factory("item", $movie_id);
    access::required("view", $movie);
    access::required("edit", $movie);

    $form = $this->movie_edit_form($movie);
    try {
      $valid = $form->validate();
      $movie->title = $form->edit_item->title->value;
      $movie->description = $form->edit_item->description->value;
      $movie->slug = $form->edit_item->slug->value;
      $movie->name = $form->edit_item->inputs["name"]->value;
      $movie->validate();
    } catch (ORM_Validation_Exception $e) {
      // Translate ORM validation errors into form error messages
      foreach ($e->validation->errors() as $key => $error) {
        $form->edit_item->inputs[$key]->add_error($error, 1);
      }
      $valid = false;
    }

    if ($valid) {
      $movie->save();
      module::event("item_edit_form_completed", $movie, $form);

      log::success("content", "Updated movie", "url()}\">view");
      message::success(
        t("Saved movie %movie_title", array("movie_title" => html::purify($movie->title))));

      // Stay on the same page
      json::reply(array("result" => "success"));
      }
    else {
      json::reply(array("result" => "error", "html" => (string) $form));
    }
  }

  /**
  * Screen to confirm the deletion
  */

  public function form_delete($id) {
    $item = model_cache::get("item", $id);
    access::required("view", $item);
    access::required("edit", $item);

    $form = new Forge("#", "","post", array("id" => "g-confirm-delete"));
    $group = $form->group("confirm_delete")->label(t("Confirm Deletion"));

    // Get csrf to send in the post delete.
    $csrf = access::csrf_token();

    // JavaScript that will overwrite the post of forge submit and modify their behavior
    $group->script('delete_submit')->text('

      var delete_submit = function() {
        $("input[name=delete]").click(function(){
          $.post("'. url::site("advanced_search/delete/{$item->id}?csrf={$csrf}").'", function(data){
            $("#g-dialog").dialog("close");
            $("#btn-search").click();
          });
          return false;
        });
      }
      $(document).ready(delete_submit);
    ');

    $group->submit("delete")->value(t("Delete"));
    $form->script("")->url(url::abs_file("modules/gallery/js/item_form_delete.js"));

    $v = new View("quick_delete_confirm.html");
    $v->item = $item;
    $v->form = $form;
    print $v;
  }

  /**
  * Delete function
  */
  public function delete($id) {
    access::verify_csrf();

    $item = model_cache::get("item", $id);
    access::required("view", $item);
    access::required("edit", $item);

    if ($item->is_album()) {
      $msg = t("Deleted album %title", array("title" => html::purify($item->title)));
    } else {
      $msg = t("Deleted photo %title", array("title" => html::purify($item->title)));
    }

    $parent = $item->parent();

    // The batch is for recursive delete of items
    if ($item->is_album()) {
      batch::start();
      $item->delete();
      batch::stop();
    } else {
      $item->delete();
    }

    message::success($msg);

    json::reply(array("result" => "success", "reload"));
  }

}


text:
#include <stdio.h>

#include <cmml.h>
#include <string.h>

/**
 * \file
 * cmml-uri-file-open:
 *
 * A simple example program to show how to open a CMML file given
 * through a file: uri and print out the desc tags of the clip
 * tag. Error handling is ignored.
 */

/** the reading buffer's size */
#define BUFSIZE 100000

/** a struct for holding basic URI parts */
typedef struct {
  char *scheme;    /**< the URI scheme to work with, here file: */
  char *authority; /**< the scheme's namespace authority, here not used */
  char *path;      /**< the path parts including filename */
  char *querystr;  /**< the query string, here not used XXX */
  char *fragstr;   /**< the fragment offset */
} URI;

/**
 * parse_file_uri: a rough function to parse a uri string into its
 * components
 *
 * \param uri_string the given uri
 *
 * \returns a URI structure containing the different parsed components
 */
static URI *
parse_file_uri (const char *uri_string)
{
  const char *location;
  const char *locbegin;
  int length;
  URI *result;
  locbegin = uri_string;
  result = (URI*) calloc(sizeof(URI), sizeof(char));

  /* ignore file:// and authority parts to get path */
  location = strstr (locbegin, "://");
  locbegin = location+3;
  length = strlen(locbegin);
  location = strchr(locbegin, '#'); /* XXX: ignore queries for the moment */
  if (location != NULL) length = location - locbegin;
  result->path = (char*) calloc (length+1, sizeof(char));
  result->path = strncpy(result->path, locbegin, length);
  result->path[length] = '\0';

  if (location != NULL) {
    /* fragment given */
    length = strlen(location);
    result->fragstr = NULL;
    result->fragstr = (char*) calloc (length, sizeof(char));
    result->fragstr = strncpy(result->fragstr, location+1, length);
  } else {
    result->fragstr = NULL;
  }
  return result;
}

/**
 * read_clip: the callback for a clip element
 *
 * \param cmml the CMML* handle in use
 * \param clip the clip element's content represented in a
 *        CMML_Clip*
 * \param user_data user defined data
 *
 * \returns 0 on success, 1 on error
 */
static int
read_clip (CMML * cmml, const CMML_Clip * clip, void * user_data) {
  puts(clip->desc_text);
  return 0;
}

/**
 * main function of cmml-uri-file-open, which opens the CMML file
 * given through a file uri, checks any offsets, registers the
 * callbacks, and then steps through the file in chunks of BUFSIZE
 * size, during which the callbacks get activated as the relevant
 * elements get parsed.
 *
 * Fragments may be given to the uri in one of two forms:
 * - #name - name is the value of an clip's id tag
 * - #clock:YYYYMMDDThhmmss.ffZ - this is a utc time; npt or smpte also possible
 */
int main(int argc, char *argv[])
{
  char *uri_string = NULL;
  URI * uri;
  CMML * doc;
  long n = 0;

  if (argc < 2) {
    fprintf (stderr, "Usage: %s <file://filename#fragment>\n", argv[0]);
    exit (1);
  }
  uri_string = argv[1];

  uri = parse_file_uri(uri_string);

  doc = cmml_open(uri->path);

  /* if fragment given, forward to that */
  if (uri->fragstr != NULL) cmml_skip_to_offset(doc, uri->fragstr);

  cmml_set_read_callbacks (doc, NULL, NULL, read_clip, NULL);

  while (((n = cmml_read (doc, BUFSIZE)) > 0));

  cmml_close(doc);

  exit(0);
}


text:
package org.apache.cassandra.hints;

import java.io.IOException;
import java.nio.ByteBuffer;

import org.apache.cassandra.io.FSReadError;
import org.apache.cassandra.io.compress.ICompressor;
import org.apache.cassandra.io.util.ChannelProxy;
import org.apache.cassandra.utils.memory.BufferPool;

public final class CompressedChecksummedDataInput extends ChecksummedDataInput
{
    private final ICompressor compressor;
    private volatile long filePosition = 0;
    private volatile ByteBuffer compressedBuffer = null;
    private final ByteBuffer metadataBuffer = ByteBuffer.allocate(CompressedHintsWriter.METADATA_SIZE);

    public CompressedChecksummedDataInput(Builder builder)
    {
        super(builder);
        assert regions == null;  //mmapped regions are not supported

        compressor = builder.compressor;
        filePosition = builder.position;
    }

    /**
     * Since an entire block of compressed data is read off of disk, not just a hint at a time,
     * we don't report EOF until the decompressed data has also been read completely
     */
    public boolean isEOF()
    {
        return filePosition == channel.size() && buffer.remaining() == 0;
    }

    protected void reBufferStandard()
    {
        metadataBuffer.clear();
        channel.read(metadataBuffer, filePosition);
        filePosition += CompressedHintsWriter.METADATA_SIZE;
        metadataBuffer.rewind();

        int uncompressedSize = metadataBuffer.getInt();
        int compressedSize = metadataBuffer.getInt();

        if (compressedBuffer == null || compressedSize > compressedBuffer.capacity())
        {
            int bufferSize = compressedSize + (compressedSize / 20);  // allocate +5% to cover variability in compressed size
            if (compressedBuffer != null)
            {
                BufferPool.put(compressedBuffer);
            }
            compressedBuffer = allocateBuffer(bufferSize, compressor.preferredBufferType());
        }

        compressedBuffer.clear();
        compressedBuffer.limit(compressedSize);
        channel.read(compressedBuffer, filePosition);
        compressedBuffer.rewind();
        filePosition += compressedSize;

        bufferOffset += buffer.position();
        if (buffer.capacity() < uncompressedSize)
        {
            int bufferSize = uncompressedSize + (uncompressedSize / 20);
            BufferPool.put(buffer);
            buffer = allocateBuffer(bufferSize, compressor.preferredBufferType());
        }

        buffer.clear();
        buffer.limit(uncompressedSize);
        try
        {
            compressor.uncompress(compressedBuffer, buffer);
            buffer.flip();
        }
        catch (IOException e)
        {
            throw new FSReadError(e, getPath());
        }
    }

    protected void releaseBuffer()
    {
        super.releaseBuffer();
        if (compressedBuffer != null)
        {
            BufferPool.put(compressedBuffer);
            compressedBuffer = null;
        }
    }

    protected void reBufferMmap()
    {
        throw new UnsupportedOperationException();
    }

    public static final class Builder extends ChecksummedDataInput.Builder
    {
        private long position;
        private ICompressor compressor;

        public Builder(ChannelProxy channel)
        {
            super(channel);
            bufferType = null;
        }

        public CompressedChecksummedDataInput build()
        {
            assert position >= 0;
            assert compressor != null;
            return new CompressedChecksummedDataInput(this);
        }

        public Builder withCompressor(ICompressor compressor)
        {
            this.compressor = compressor;
            bufferType = compressor.preferredBufferType();
            return this;
        }

        public Builder withPosition(long position)
        {
            this.position = position;
            return this;
        }
    }

    public static final CompressedChecksummedDataInput upgradeInput(ChecksummedDataInput input, ICompressor compressor)
    {
        long position = input.getPosition();
        input.close();

        Builder builder = new Builder(new ChannelProxy(input.getPath()));
        builder.withPosition(position);
        builder.withCompressor(compressor);
        return builder.build();
    }
}


text:
dc.ui.DEAnnotationListing = dc.ui.BaseAnnotationListing.extend({
  showEdit: true, //Show edit UI in DV

  render : function() {
    dc.ui.BaseAnnotationListing.prototype.render.apply(this, arguments);

    if( this.model.get('location') ){
        this.$('.clone_item').hide();
        this.$('.row_status').removeClass('incomplete');
        this.$('.row_status').addClass('complete');
    }

    return this;
  }
});


text:
/* Geodesy by Mike Gavaghan
 *
 * http://www.gavaghan.org/blog/free-source-code/geodesy-library-vincentys-formula/
 *
 * This code may be freely used and modified on any personal or professional
 * project.  It comes with no warranty.
 */
package org.gavaghan.geodesy;

import java.io.Serializable;

/**
 *

 * Encapsulation of latitude and longitude coordinates on a globe. Negative
 * latitude is southern hemisphere. Negative longitude is western hemisphere.
 *

 *

 * Any angle may be specified for longtiude and latitude, but all angles will be
 * canonicalized such that:
 *

 *
 *

 * -90 <= latitude <= +90 - 180 < longitude <= +180
 *

 *
 * @author Mike Gavaghan
 */
public class GlobalCoordinates implements Comparable<GlobalCoordinates>, Serializable
{
   /** Latitude in degrees. Negative latitude is southern hemisphere. */
   private double mLatitude;

   /** Longitude in degrees. Negative longitude is western hemisphere. */
   private double mLongitude;

   /**
    * Canonicalize the current latitude and longitude values such that:
    *
    *

    * -90 <= latitude <= +90 - 180 < longitude <= +180
    *

    */
   private void canonicalize()
   {
      mLatitude = (mLatitude + 180) % 360;
      if (mLatitude < 0) mLatitude += 360;
      mLatitude -= 180;

      if (mLatitude > 90)
      {
         mLatitude = 180 - mLatitude;
         mLongitude += 180;
      }
      else if (mLatitude < -90)
      {
         mLatitude = -180 - mLatitude;
         mLongitude += 180;
      }

      mLongitude = ((mLongitude + 180) % 360);
      if (mLongitude <= 0) mLongitude += 360;
      mLongitude -= 180;
   }

   /**
    * Construct a new GlobalCoordinates. Angles will be canonicalized.
    *
    * @param latitude latitude in degrees
    * @param longitude longitude in degrees
    */
   public GlobalCoordinates(double latitude, double longitude)
   {
      mLatitude = latitude;
      mLongitude = longitude;
      canonicalize();
   }

   /**
    * Get latitude.
    *
    * @return latitude in degrees
    */
   public double getLatitude()
   {
      return mLatitude;
   }

   /**
    * Set latitude. The latitude value will be canonicalized (which might result
    * in a change to the longitude). Negative latitude is southern hemisphere.
    *
    * @param latitude in degrees
    */
   public void setLatitude(double latitude)
   {
      mLatitude = latitude;
      canonicalize();
   }

   /**
    * Get longitude.
    *
    * @return longitude in degrees
    */
   public double getLongitude()
   {
      return mLongitude;
   }

   /**
    * Set longitude. The longitude value will be canonicalized. Negative
    * longitude is western hemisphere.
    *
    * @param longitude in degrees
    */
   public void setLongitude(double longitude)
   {
      mLongitude = longitude;
      canonicalize();
   }

   /**
    * Compare these coordinates to another set of coordiates. Western longitudes
    * are less than eastern logitudes. If longitudes are equal, then southern
    * latitudes are less than northern latitudes.
    *
    * @param other instance to compare to
    * @return -1, 0, or +1 as per Comparable contract
    */
   public int compareTo(GlobalCoordinates other)
   {
      int retval;

      if (mLongitude < other.mLongitude) retval = -1;
      else if (mLongitude > other.mLongitude) retval = +1;
      else if (mLatitude < other.mLatitude) retval = -1;
      else if (mLatitude > other.mLatitude) retval = +1;
      else retval = 0;

      return retval;
   }

   /**
    * Get a hash code for these coordinates.
    *
    * @return
    */
   @Override
   public int hashCode()
   {
      return ((int) (mLongitude * mLatitude * 1000000 + 1021)) * 1000033;
   }

   /**
    * Compare these coordinates to another object for equality.
    *
    * @param other
    * @return
    */
   @Override
   public boolean equals(Object obj)
   {
      if (!(obj instanceof GlobalCoordinates)) return false;

      GlobalCoordinates other = (GlobalCoordinates) obj;

      return (mLongitude == other.mLongitude) && (mLatitude == other.mLatitude);
   }

   /**
    * Get coordinates as a string.
    */
   @Override
   public String toString()
   {
      StringBuffer buffer = new StringBuffer();

      buffer.append(Math.abs(mLatitude));
      buffer.append((mLatitude >= 0) ? 'N' : 'S');
      buffer.append(';');
      buffer.append(Math.abs(mLongitude));
      buffer.append((mLongitude >= 0) ? 'E' : 'W');
      buffer.append(';');

      return buffer.toString();
   }
}


text:
battle-net.js [![Build Status](https://travis-ci.org/webmakersteve/battle-net.js.svg?branch=master)](https://travis-ci.org/webmakersteve/battle-net.js)
=============

This package allows you to integrate Blizzard's Battle.net API's into your website. It is pretty easy to use, and still a work in progress.

Feel free to help by tracking issues or forking the repository.

Install with:

    npm install --save battlenet.js

Once you install it you can require it on any of your pages.

    var BlizzardClient = require('battlenet.js');

## Notice

I have redone the API wrapper from the old version, which reminded me of Java. The new version is a bit easier to use, but there have been loads of breaking changes. Stay on 1.0 if you don't want them.

## Tests

This package contains unit tests. I haven't written all of them, but the core should be stable enough in v2. A lot of the unit testing is boilerplate stuff to simulate real responses, so I have some level of confidence in it, though I haven't tested all of the endpoints myself.

Run `grunt test` to run the tests. There are no prerequesites as long as you have installed `devDependencies`.

## Usage

```js
    var BnetClient = require("battlenet.js"),
    var client = new BnetClient('validAPIKey', {
      region: 'us',
      locale: 'en_US'
    });
```

You must put your API key in when you instantiate the client. Otherwise, it's going to throw an exception. Don't say I didn't warn you.

From there, there are abstracted methods to allow you to access Battle.net data without having to deal with knowing the API endpoints and so on.

The client defaults to the US region in the `en_US` locale. If you need something else just pass configuration changes.

## Promises

__The API no longer uses promises. If you want a promise based API, use a library with lift support__

# API

## Warcraft

```js
    var BnetClient = require("battlenet.js"),
    var client = new BnetClient('validAPIKey', {
      region: 'us',
      locale: 'en_US'
    });

    // var warcraft = client.warcraft;
```

Here's the part everyone came to see. Just how do we get that data from the API? The API is organized by game. Currently, only World of Warcraft is supported. `client` will refer to an instantiated object of the main API class.

### client.warcraft.getAchievement(id, cb)

Fetches achievement data for a given achievement ID.

### client.warcraft.getAuctionStatus(realm, cb)

Fetches the auctions for a given realm

### client.warcraft.getBoss(id, cb)

Gets a boss by ID

### client.warcraft.getBosses(cb)

Gets a list of bosses

### client.warcraft.getRealmLeaderboard(realm, cb)

Returns challenge mode leaderboards for a given realm.

### client.warcraft.getRegionLeaderboard(cb)

Gets challenge mode leaderboards for the currently configured region.

### client.warcraft.getCharacter(realm, name, fields, cb)

Returns a character specified. The fields object is an array of data keys for the data you are requesting. If you want to get responses faster, only request the data you're going to use.

For example:

```js
  var fields = ['feed', 'guild'];
  client.warcraft.getCharacter('Maelstrom', 'Chaosity', fields, function(err, response) {
    if (err) {
      throw err;
    }
  });
```

Here's a list of all the available fields

```js
/**
 * All possible character fields for documentation purposes
 * @type {Array}
 */
var characterFields = [
  'achievements',
  'appearance',
  'feed',
  'guild',
  'hunterPets',
  'items',
  'mounts',
  'pets',
  'petSlots',
  'professions',
  'progression',
  'pvp',
  'quests',
  'reputation',
  'statistics',
  'stats',
  'talents',
  'titles',
  'audit'
];
```

### client.warcraft.getGuild(realm, name, fields, cb)

Get a guild on a given realm with a given name. Names will be normalized, so feel free to use spaces and all of that. Fields works the same way on guild as it does on character. Request the data you want by putting it in array (e.g. `['feed']`).

```js
/**
 * All possible guild fields for documentation purposes
 * @type {Array}
 */
var guildFields = [
  'achievements',
  'challenge',
  'news'
];
```

### client.warcraft.getItem(id, cb)

Gets an item by its ID.

### client.warcraft.getItemSet(id, cb)

Gets a set of items by its set ID. Judgment anyone?

### client.warcraft.getMounts(cb)

Gets a list of existing mounts.

### client.warcraft.getPets(cb)

Gets a list of existing pets

### client.warcraft.getPetAbility(id, cb)

Gets a pet ability by its ID

### client.warcraft.getPetSpecies(id, cb)

Gets a pet species by its ID

### client.warcraft.getPetStats(speciesID, cb)

Gets pet stats based on their species ID

### client.warcraft.getPvpLeaderboard(bracket, cb)

Gets leaderboards by bracket. E.g.

```js
client.warcraft.getPvpLeaderboard('3v3', function(err, response) {

});
```

### client.warcraft.getQuest(id, cb)

Gets quest information by ID

### client.warcraft.getRealmStatus(cb)

Gets a list of realms and their realm status.

### client.warcraft.getRecipe(id, cb)

Gets a recipe by its ID

### client.warcraft.getSpell(id, cb)

Gets a spell by its ID

### client.warcraft.getZones(cb)

Gets a list of zones.

### client.warcraft.getZone(id, cb)

Gets a zone by its ID

### client.warcraft.getBattlegroups(cb)

Gets a list of battlegroups.

### client.warcraft.getCharacterRaces(cb)

Gets a list of character races.

### client.warcraft.getCharacterClasses(cb)

Gets a list of character classes.

### client.warcraft.getCharacterAchievements(cb)

Gets a list of character achievements.

### client.warcraft.getGuildRewards(cb)

Gets a list of guild rewards.

### client.warcraft.getGuildPerks(cb)

Gets a list of guild perks.

### client.warcraft.getGuildAchievements(cb)

Gets a list of guild achievements.

### client.warcraft.getItemClasses(cb)

Gets a list of item classes.

### client.warcraft.getTalents(cb)

Gets a list of talents.

### client.warcraft.getPetTypes(cb)

Gets a list of pet types.

### client.warcraft.getUserCharacters(token, cb)

Gets a list of all characters of the user associated with the specified access token.

# Other Stuff

If you like my code, star it! If you use it, tell me about it! I'd love to hear how you can make use of this code in your application.

## How to Contribute
- open a pull request and then wait for feedback (if
  [webmakersteve](http://github.com/webmakersteve) doesn't get back to you, Reav is right and he is a baddy.

## Contributors
No one yet, but always welcoming people to help!

## LICENSE - "MIT License"

Copyright (c) 2010 Matthew Ranney, http://ranney.com/

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

![spacer](http://ranney.com/1px.gif)


text:
For a comprehensive list of **gRPC community resources**, visit our [Community][] page on
[grpc.io][].

This repository holds documents and resources shared across the [gRPC
organization][] — in particular, the organization's [governance][] rules
and [contribution][] guidelines.

[Community]: https://grpc.io/community/
[contribution]: CONTRIBUTING.md
[governance]: governance.md
[gRPC organization]: https://github.com/grpc
[grpc.io]: https://grpc.io/


text:
package com.dong.design.command;

import java.util.ArrayList;
import java.util.List;

public class MacroCommand implements Command {

	private List<Command> list;

	public MacroCommand() {
		list = new ArrayList<>();
	}

	public void addCommand(Command command) {
		list.add(command);
	}

	public void removeCommand(Command command) {
		list.remove(command);
	}

	public Command getCommand(int i) {
		return list.get(i);
	}

	@Override
	public void execute() {
		for (Command command : list) {
			command.execute();
		}
	}

}


text:
<?php

namespace NavigationBundle\Location;

use NavigationBundle\Location\PostableLocation;

/**
 * Description of BulletinLocation
 *
 * @author Draeius
 */
class BulletinLocation extends PostableLocation {

    public function getVariables() {
        $params = parent::getVariables();

        return array_merge($params, array(
            'bulletins' => $this->getLocation()->getBulletins()
        ));
    }

}


text:
``locale_name``
===============

The ``locale_name`` filter returns the locale name given its two-letter
code:

.. code-block:: twig

    {# German #}
    {{ 'de'|locale_name }}

By default, the filter uses the current locale. You can pass it explicitly:

.. code-block:: twig

    {# allemand #}
    {{ 'de'|locale_name('fr') }}

    {# français (Canada) #}
    {{ 'fr_CA'|locale_name('fr_FR') }}

.. note::

    The ``locale_name`` filter is part of the ``IntlExtension`` which is not
    installed by default. Install it first:

    .. code-block:: bash

        $ composer req twig/intl-extra

    Then, use the ``twig/extra-bundle`` on Symfony projects or add the extension
    explicitly on the Twig environment::

        use Twig\Extra\Intl\IntlExtension;

        $twig = new \Twig\Environment(...);
        $twig->addExtension(new IntlExtension());

Arguments
---------

* ``locale``: The locale


text:
define([
    'dojo/_base/declare',
    'dojo/dom-construct',
    'dojox/widget/Standby',
    'sqleditor/widgets/_TabPageMixin',
    'sqleditor/widgets/Grid',
    'sqleditor/widgets/VirtualGrid',
    'sqleditor/models/GridModel',
    'sqleditor/prettyPrint',
    'sqleditor/models/SettingsModel',
    'dojo/dom-class',
    'dojo/query',
    'dojo/keys',
    'sqleditor/widgets/SqlCodeMirror'
], function (declare, domConstruct, Standby, _TabPageMixin, Grid,
             VirtualGrid, GridModel, prettyPrint, SettingsModel, domClass, query, keys) {

    var gridModel = new GridModel(),
        settings = new SettingsModel();

    function isGridTypeChanged() {
        if (!this.grid) {
            return false;
        }

        return settings.getPaginationType() === 'virtual' ?
                !this.grid.pagingMethod :
                !!this.grid.pagingMethod;
    }

    function destroyGrid() {
        if (this.grid) {
            this.grid.destroy();
            this.grid = null;
        }

        domConstruct.empty(this.queryResultNode);
    }

    function renderGrid(data) {
        var GridCls;
        if (this.grid && !isGridTypeChanged.call(this)) {
            this.grid.set('columns', data.columns);
            this.grid.set('store', data.store);
            return;
        }

        destroyGrid.call(this);

        GridCls = settings.getPaginationType() === 'virtual' ? VirtualGrid : Grid;

        this.grid = new GridCls({
            store: data.store,
            columns: data.columns
        });

        domConstruct.place(this.grid.domNode, this.queryResultNode);
    }

    function renderText(text) {
        destroyGrid.call(this);
        domConstruct.create('pre', {
            innerHTML: text
        }, this.queryResultNode);
    }

    function render(results) {
        var format = settings.getDataFormat(),
            data = {data: results.store.data,
                    columns: results.columns},
            delimiter = { tabDelimited: '\t',
                          commaDelimited: ',',
                          pipeDelimited: '|' };

        switch (format) {
        case 'grid':
            renderGrid.call(this, results);
            break;
        case 'text':
            renderText.call(this, prettyPrint.padDelimit(data, 200, ' '));
            break;
        case 'tabDelimited':
        case 'commaDelimited':
        case 'pipeDelimited':
            renderText.call(this, prettyPrint.charDelimit(data, delimiter[format]));
            break;
        case 'vertical':
            renderText.call(this, prettyPrint.vertical(data));
            break;
        }
    }

    function runQuery(sql, system, limit) {
        var that = this;

        return gridModel.getModel(sql, system, limit).then(function (data) {
            if (data.isLoginRequired) {
                return data;
            }

            render.call(that, data);
            that.contentPaneBottom.set('content', data.message);
            return data;
        }, function (error) {
            that.contentPaneBottom.set('content', error.response.data.message);
            return error;
        });
    }

    function initStandby() {
        if (this.standby) {
            return;
        }

        this.standby = new Standby({
            id: this.file,
            target : this.contentPaneResult.domNode
        });

        this.contentPaneResult.addChild(this.standby);
    }

    return declare('sqleditor.widgets.TabPage', _TabPageMixin, {

        standby: null,

        onClose: function () {
            if (this.standby) {
                this.standby.destroy();
            }

            return true;
        },

        execute: function (system, limit) {
            var sql = this.editor.get('value'),
                that = this;

            initStandby.call(this);
            this.standby.show();

            return runQuery.call(this, sql, system, limit).then(function (data) {
                that.standby.hide();
                return data;
            });
        },

        refresh: function () {
            if (!this.grid) {
                return;
            }

            if (this.grid._started){
                this.grid.resize();
                return;
            }

            this.grid.startup();
        },

        isFullScreenResults: function () {
            if (!this.queryResultNode) {
                return false;
            }

            return domClass.contains(this.queryResultNode, "fullscreen");
        },

        toggleFullScreenResults: function () {
            var isFullScreen = this.isFullScreenResults();

            if (!this.queryResultNode) {
                return;
            }

            if (!isFullScreen) {
                domClass.add(this.queryResultNode, 'fullscreen');
            }

            //// dgrid manages it's own scrollbars so only add scroll to text results.
            if (!isFullScreen && !this.grid) {
                query(".fullscreen").style("overflow", "scroll");
            }

            if (isFullScreen) {
                query(".fullscreen").style("overflow", "initial");
                domClass.remove(this.queryResultNode, 'fullscreen');
            }

            if (this.grid) {
                this.grid.resize();
            }

            //// Hide the container as z-index property does not apply.
            query('#layoutBorderContainer').style({
                height: isFullScreen ? '' : 0
            });
        }
    });
});


text:
package python.error;

public class UndefinedException extends ParseException
{
	public UndefinedException(int lineNumber, int columnNumber, String variableName, String scopeName) {
		super(lineNumber, columnNumber, variableName + " was not defined in " + scopeName);
	}

}


text:
layout: page
title: Emerald Solutions Seminar
date: 2016-05-24
author: Hannah Church
tags: weekly links, java
status: published
summary: In sagittis sollicitudin metus at.
banner: images/banner/leisure-03.jpg
booking:
  startDate: 02/26/2018
  endDate: 03/03/2018
  ctyhocn: CRNGAHX
  groupCode: ESS
published: true
---
Fusce egestas sapien lorem, sed gravida lacus laoreet eu. Vivamus nec magna a velit auctor porta. Integer feugiat, lectus ac pharetra consectetur, nisi tellus bibendum nunc, nec rhoncus ex turpis id ligula. Aenean blandit eu orci vitae rhoncus. Integer tempus mi ante, non mollis ex luctus a. Sed lobortis consequat diam, id varius sapien convallis molestie. Vestibulum luctus velit quis erat auctor tincidunt. Donec hendrerit, dui posuere scelerisque molestie, nunc nisl porta ipsum, ac sagittis magna metus non eros.

* Cras vel ante pharetra, scelerisque sem efficitur, dictum nibh
* Integer pulvinar sem semper velit accumsan, id dignissim massa bibendum
* Cras quis eros blandit, sollicitudin dolor vel, consequat risus
* Donec dignissim tortor non porttitor tempus
* Sed et nulla et nulla aliquet finibus.

Quisque aliquet nibh eu consectetur laoreet. Integer eget aliquet massa. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nunc egestas ex quis metus auctor, at varius dolor lobortis. Phasellus vel leo turpis. Mauris venenatis velit nibh, nec luctus justo bibendum sed. Fusce nec ullamcorper lorem. Pellentesque malesuada, risus vel viverra ornare, nisl urna maximus augue, ut maximus eros justo eget sem.
Vestibulum quis commodo sapien. Integer vestibulum lectus ex. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Fusce at facilisis elit, sit amet placerat ligula. Pellentesque bibendum eleifend enim, sit amet lobortis felis. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum egestas metus quis congue euismod. Cras non scelerisque dolor. Maecenas luctus ex justo. Mauris ut libero tincidunt, ornare erat sed, varius metus. Fusce facilisis lorem lacus, at finibus diam varius ac. Proin ac sodales lectus.


text:
/*
 * Copyright 2015 DuraSpace, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.fcrepo.kernel.modeshape.utils.iterators;

import com.google.common.util.concurrent.ListenableFuture;
import org.fcrepo.kernel.api.exception.MalformedRdfException;

/**
 * Implemented by something that can consume an {@link java.util.Iterator}. The
 * assumption is that a reference to the appropriate iterator is managed as part
 * of the state of any implementation.
 *
 * @author ajs6f
 * @since Oct 24, 2013
 * @param <E> E
 * @param <T> T
 */
public interface IteratorConsumer<E, T> {

    /**
     * Synchronous consumption.
     * @throws MalformedRdfException if malformed rdf exception occurred
     */
    void consume() throws MalformedRdfException;

    /**
     * Asynchronous consumption.
     *
     * @return ListenableFuture
     */
    ListenableFuture<T> consumeAsync();

}