text:
package cluster

import (
	"context"
	"fmt"

	"github.com/go-logr/logr"
	admissionregistrationv1 "k8s.io/api/admissionregistration/v1"
	corev1 "k8s.io/api/core/v1"
	rbacv1 "k8s.io/api/rbac/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	apiregistrationv1 "k8s.io/kube-aggregator/pkg/apis/apiregistration/v1"
	"sigs.k8s.io/controller-runtime/pkg/client"

	cdicorev1alpha1 "kubevirt.io/containerized-data-importer-api/pkg/apis/core/v1alpha1"
	cdicorev1 "kubevirt.io/containerized-data-importer-api/pkg/apis/core/v1beta1"
	cdiuploadv1 "kubevirt.io/containerized-data-importer-api/pkg/apis/upload/v1beta1"
	"kubevirt.io/containerized-data-importer/pkg/operator/resources/utils"
)

const (
	apiServerResourceName = "cdi-apiserver"
	apiServerServiceName  = "cdi-api"
)

func createStaticAPIServerResources(args *FactoryArgs) []client.Object {
	return []client.Object{
		createAPIServerClusterRole(),
		createAPIServerClusterRoleBinding(args.Namespace),
	}
}

func createDynamicAPIServerResources(args *FactoryArgs) []client.Object {
	return []client.Object{
		createAPIService("v1beta1", args.Namespace, args.Client, args.Logger),
		createAPIService("v1alpha1", args.Namespace, args.Client, args.Logger),
		createDataVolumeValidatingWebhook(args.Namespace, args.Client, args.Logger),
		createDataVolumeMutatingWebhook(args.Namespace, args.Client, args.Logger),
		createCDIValidatingWebhook(args.Namespace, args.Client, args.Logger),
		createObjectTransferValidatingWebhook(args.Namespace, args.Client, args.Logger),
		createDataImportCronValidatingWebhook(args.Namespace, args.Client, args.Logger),
	}
}

func getAPIServerClusterPolicyRules() []rbacv1.PolicyRule {
	return []rbacv1.PolicyRule{
		{
			APIGroups: []string{
				"authorization.k8s.io",
			},
			Resources: []string{
				"subjectaccessreviews",
			},
			Verbs: []string{
				"create",
			},
		},
		{
			APIGroups: []string{
				"",
			},
			Resources: []string{
				"configmaps",
			},
			Verbs: []string{
				"get",
				"list",
				"watch",
			},
		},
		{
			APIGroups: []string{
				"",
			},
			Resources: []string{
				"persistentvolumeclaims",
			},
			Verbs: []string{
				"get",
			},
		},
		{
			APIGroups: []string{
				"",
			},
			Resources: []string{
				"namespaces",
			},
			Verbs: []string{
				"get",
			},
		},
		{
			APIGroups: []string{
				"cdi.kubevirt.io",
			},
			Resources: []string{
				"datavolumes",
			},
			Verbs: []string{
				"list",
				"get",
			},
		},
		{
			APIGroups: []string{
				"cdi.kubevirt.io",
			},
			Resources: []string{
				"datasources",
			},
			Verbs: []string{
				"list",
				"get",
			},
		},
		{
			APIGroups: []string{
				"cdi.kubevirt.io",
			},
			Resources: []string{
				"cdis",
			},
			Verbs: []string{
				"get",
			},
		},
		{
			APIGroups: []string{
				"cdi.kubevirt.io",
			},
			Resources: []string{
				"cdis/finalizers",
			},
			Verbs: []string{
				"*",
			},
		},
	}
}

func createAPIService(version, namespace string, c client.Client, l logr.Logger) *apiregistrationv1.APIService {
	apiService := &apiregistrationv1.APIService{
		TypeMeta: metav1.TypeMeta{
			APIVersion: "apiregistration.k8s.io/v1",
			Kind:       "APIService",
		},
		ObjectMeta: metav1.ObjectMeta{
			Name: fmt.Sprintf("%s.%s", version, cdiuploadv1.SchemeGroupVersion.Group),
			Labels: map[string]string{
				utils.CDILabel: apiServerServiceName,
			},
		},
		Spec: apiregistrationv1.APIServiceSpec{
			Service: &apiregistrationv1.ServiceReference{
				Namespace: namespace,
				Name:      apiServerServiceName,
			},
			Group:                cdiuploadv1.SchemeGroupVersion.Group,
			Version:              version,
			GroupPriorityMinimum: 1000,
			VersionPriority:      15,
		},
	}

	if c == nil {
		return apiService
	}

	bundle := getAPIServerCABundle(namespace, c, l)
	if bundle != nil {
		apiService.Spec.CABundle = bundle
	}

	return apiService
}
func createDataImportCronValidatingWebhook(namespace string, c client.Client, l logr.Logger) *admissionregistrationv1.ValidatingWebhookConfiguration {
	path := "/dataimportcron-validate"
	defaultServicePort := int32(443)
	allScopes := admissionregistrationv1.AllScopes
	exactPolicy := admissionregistrationv1.Exact
	failurePolicy := admissionregistrationv1.Fail
	defaultTimeoutSeconds := int32(30)
	sideEffect := admissionregistrationv1.SideEffectClassNone
	whc := &admissionregistrationv1.ValidatingWebhookConfiguration{
		TypeMeta: metav1.TypeMeta{
			APIVersion: "admissionregistration.k8s.io/v1",
			Kind:       "ValidatingWebhookConfiguration",
		},
		ObjectMeta: metav1.ObjectMeta{
			Name: "cdi-api-dataimportcron-validate",
			Labels: map[string]string{
				utils.CDILabel: apiServerServiceName,
			},
		},
		Webhooks: []admissionregistrationv1.ValidatingWebhook{
			{
				Name: "dataimportcron-validate.cdi.kubevirt.io",
				Rules: []admissionregistrationv1.RuleWithOperations{{
					Operations: []admissionregistrationv1.OperationType{
						admissionregistrationv1.Create,
						admissionregistrationv1.Update, //FIXME: Update and Delete needed?
					},
					Rule: admissionregistrationv1.Rule{
						APIGroups: []string{cdicorev1.SchemeGroupVersion.Group},
						APIVersions: []string{
							cdicorev1.SchemeGroupVersion.Version,
							cdicorev1alpha1.SchemeGroupVersion.Version,
						},
						Resources: []string{"dataimportcrons"},
						Scope:     &allScopes,
					},
				}},
				ClientConfig: admissionregistrationv1.WebhookClientConfig{
					Service: &admissionregistrationv1.ServiceReference{
						Namespace: namespace,
						Name:      apiServerServiceName,
						Path:      &path,
						Port:      &defaultServicePort,
					},
				},
				FailurePolicy:     &failurePolicy,
				SideEffects:       &sideEffect,
				MatchPolicy:       &exactPolicy,
				NamespaceSelector: &metav1.LabelSelector{},
				TimeoutSeconds:    &defaultTimeoutSeconds,
				AdmissionReviewVersions: []string{
					"v1", "v1beta1",
				},
				ObjectSelector: &metav1.LabelSelector{},
			},
		},
	}

	if c == nil {
		return whc
	}

	bundle := getAPIServerCABundle(namespace, c, l)
	if bundle != nil {
		whc.Webhooks[0].ClientConfig.CABundle = bundle
	}

	return whc
}

func createDataVolumeValidatingWebhook(namespace string, c client.Client, l logr.Logger) *admissionregistrationv1.ValidatingWebhookConfiguration {
	path := "/datavolume-validate"
	defaultServicePort := int32(443)
	allScopes := admissionregistrationv1.AllScopes
	exactPolicy := admissionregistrationv1.Exact
	failurePolicy := admissionregistrationv1.Fail
	defaultTimeoutSeconds := int32(30)
	sideEffect := admissionregistrationv1.SideEffectClassNone
	whc := &admissionregistrationv1.ValidatingWebhookConfiguration{
		TypeMeta: metav1.TypeMeta{
			APIVersion: "admissionregistration.k8s.io/v1",
			Kind:       "ValidatingWebhookConfiguration",
		},
		ObjectMeta: metav1.ObjectMeta{
			Name: "cdi-api-datavolume-validate",
			Labels: map[string]string{
				utils.CDILabel: apiServerServiceName,
			},
		},
		Webhooks: []admissionregistrationv1.ValidatingWebhook{
			{
				Name: "datavolume-validate.cdi.kubevirt.io",
				Rules: []admissionregistrationv1.RuleWithOperations{{
					Operations: []admissionregistrationv1.OperationType{
						admissionregistrationv1.Create,
						admissionregistrationv1.Update,
					},
					Rule: admissionregistrationv1.Rule{
						APIGroups: []string{cdicorev1.SchemeGroupVersion.Group},
						APIVersions: []string{
							cdicorev1.SchemeGroupVersion.Version,
							cdicorev1alpha1.SchemeGroupVersion.Version,
						},
						Resources: []string{"datavolumes"},
						Scope:     &allScopes,
					},
				}},
				ClientConfig: admissionregistrationv1.WebhookClientConfig{
					Service: &admissionregistrationv1.ServiceReference{
						Namespace: namespace,
						Name:      apiServerServiceName,
						Path:      &path,
						Port:      &defaultServicePort,
					},
				},
				FailurePolicy:     &failurePolicy,
				SideEffects:       &sideEffect,
				MatchPolicy:       &exactPolicy,
				NamespaceSelector: &metav1.LabelSelector{},
				TimeoutSeconds:    &defaultTimeoutSeconds,
				AdmissionReviewVersions: []string{
					"v1", "v1beta1",
				},
				ObjectSelector: &metav1.LabelSelector{},
			},
		},
	}

	if c == nil {
		return whc
	}

	bundle := getAPIServerCABundle(namespace, c, l)
	if bundle != nil {
		whc.Webhooks[0].ClientConfig.CABundle = bundle
	}

	return whc
}

func createCDIValidatingWebhook(namespace string, c client.Client, l logr.Logger) *admissionregistrationv1.ValidatingWebhookConfiguration {
	path := "/cdi-validate"
	sideEffect := admissionregistrationv1.SideEffectClassNone
	defaultServicePort := int32(443)
	allScopes := admissionregistrationv1.AllScopes
	exactPolicy := admissionregistrationv1.Exact
	failurePolicy := admissionregistrationv1.Fail
	defaultTimeoutSeconds := int32(30)
	whc := &admissionregistrationv1.ValidatingWebhookConfiguration{
		TypeMeta: metav1.TypeMeta{
			APIVersion: "admissionregistration.k8s.io/v1",
			Kind:       "ValidatingWebhookConfiguration",
		},
		ObjectMeta: metav1.ObjectMeta{
			Name: "cdi-api-validate",
			Labels: map[string]string{
				utils.CDILabel: apiServerServiceName,
			},
		},
		Webhooks: []admissionregistrationv1.ValidatingWebhook{
			{
				Name: "cdi-validate.cdi.kubevirt.io",
				Rules: []admissionregistrationv1.RuleWithOperations{{
					Operations: []admissionregistrationv1.OperationType{
						admissionregistrationv1.Delete,
					},
					Rule: admissionregistrationv1.Rule{
						APIGroups: []string{cdicorev1.SchemeGroupVersion.Group},
						APIVersions: []string{
							cdicorev1.SchemeGroupVersion.Version,
							cdicorev1alpha1.SchemeGroupVersion.Version,
						},
						Resources: []string{"cdis"},
						Scope:     &allScopes,
					},
				}},
				ClientConfig: admissionregistrationv1.WebhookClientConfig{
					Service: &admissionregistrationv1.ServiceReference{
						Namespace: namespace,
						Name:      apiServerServiceName,
						Path:      &path,
						Port:      &defaultServicePort,
					},
				},
				SideEffects:       &sideEffect,
				FailurePolicy:     &failurePolicy,
				MatchPolicy:       &exactPolicy,
				NamespaceSelector: &metav1.LabelSelector{},
				TimeoutSeconds:    &defaultTimeoutSeconds,
				AdmissionReviewVersions: []string{
					"v1", "v1beta1",
				},
				ObjectSelector: &metav1.LabelSelector{},
			},
		},
	}

	if c == nil {
		return whc
	}

	bundle := getAPIServerCABundle(namespace, c, l)
	if bundle != nil {
		for i := range whc.Webhooks {
			whc.Webhooks[i].ClientConfig.CABundle = bundle
			whc.Webhooks[i].FailurePolicy = &failurePolicy
		}
	}

	return whc
}

func createObjectTransferValidatingWebhook(namespace string, c client.Client, l logr.Logger) *admissionregistrationv1.ValidatingWebhookConfiguration {
	path := "/objecttransfer-validate"
	sideEffect := admissionregistrationv1.SideEffectClassNone
	defaultServicePort := int32(443)
	allScopes := admissionregistrationv1.AllScopes
	exactPolicy := admissionregistrationv1.Exact
	failurePolicy := admissionregistrationv1.Fail
	defaultTimeoutSeconds := int32(30)
	whc := &admissionregistrationv1.ValidatingWebhookConfiguration{
		TypeMeta: metav1.TypeMeta{
			APIVersion: "admissionregistration.k8s.io/v1",
			Kind:       "ValidatingWebhookConfiguration",
		},
		ObjectMeta: metav1.ObjectMeta{
			Name: "objecttransfer-api-validate",
			Labels: map[string]string{
				utils.CDILabel: apiServerServiceName,
			},
		},
		Webhooks: []admissionregistrationv1.ValidatingWebhook{
			{
				Name: "objecttransfer-validate.cdi.kubevirt.io",
				Rules: []admissionregistrationv1.RuleWithOperations{{
					Operations: []admissionregistrationv1.OperationType{
						admissionregistrationv1.Create,
						admissionregistrationv1.Update,
					},
					Rule: admissionregistrationv1.Rule{
						APIGroups: []string{cdicorev1.SchemeGroupVersion.Group},
						APIVersions: []string{
							cdicorev1.SchemeGroupVersion.Version,
						},
						Resources: []string{"objecttransfers"},
						Scope:     &allScopes,
					},
				}},
				ClientConfig: admissionregistrationv1.WebhookClientConfig{
					Service: &admissionregistrationv1.ServiceReference{
						Namespace: namespace,
						Name:      apiServerServiceName,
						Path:      &path,
						Port:      &defaultServicePort,
					},
				},
				SideEffects:       &sideEffect,
				FailurePolicy:     &failurePolicy,
				MatchPolicy:       &exactPolicy,
				NamespaceSelector: &metav1.LabelSelector{},
				TimeoutSeconds:    &defaultTimeoutSeconds,
				AdmissionReviewVersions: []string{
					"v1", "v1beta1",
				},
				ObjectSelector: &metav1.LabelSelector{},
			},
		},
	}

	if c == nil {
		return whc
	}

	bundle := getAPIServerCABundle(namespace, c, l)
	if bundle != nil {
		for i := range whc.Webhooks {
			whc.Webhooks[i].ClientConfig.CABundle = bundle
			whc.Webhooks[i].FailurePolicy = &failurePolicy
		}
	}

	return whc
}

func createDataVolumeMutatingWebhook(namespace string, c client.Client, l logr.Logger) *admissionregistrationv1.MutatingWebhookConfiguration {
	path := "/datavolume-mutate"
	defaultServicePort := int32(443)
	allScopes := admissionregistrationv1.AllScopes
	exactPolicy := admissionregistrationv1.Exact
	failurePolicy := admissionregistrationv1.Fail
	defaultTimeoutSeconds := int32(30)
	reinvocationNever := admissionregistrationv1.NeverReinvocationPolicy
	sideEffect := admissionregistrationv1.SideEffectClassNone
	whc := &admissionregistrationv1.MutatingWebhookConfiguration{
		TypeMeta: metav1.TypeMeta{
			APIVersion: "admissionregistration.k8s.io/v1",
			Kind:       "MutatingWebhookConfiguration",
		},
		ObjectMeta: metav1.ObjectMeta{
			Name: "cdi-api-datavolume-mutate",
			Labels: map[string]string{
				utils.CDILabel: apiServerServiceName,
			},
		},
		Webhooks: []admissionregistrationv1.MutatingWebhook{
			{
				Name: "datavolume-mutate.cdi.kubevirt.io",
				Rules: []admissionregistrationv1.RuleWithOperations{{
					Operations: []admissionregistrationv1.OperationType{
						admissionregistrationv1.Create,
						admissionregistrationv1.Update,
					},
					Rule: admissionregistrationv1.Rule{
						APIGroups: []string{cdicorev1.SchemeGroupVersion.Group},
						APIVersions: []string{
							cdicorev1.SchemeGroupVersion.Version,
							cdicorev1alpha1.SchemeGroupVersion.Version,
						},
						Resources: []string{"datavolumes"},
						Scope:     &allScopes,
					},
				}},
				ClientConfig: admissionregistrationv1.WebhookClientConfig{
					Service: &admissionregistrationv1.ServiceReference{
						Namespace: namespace,
						Name:      apiServerServiceName,
						Path:      &path,
						Port:      &defaultServicePort,
					},
				},
				FailurePolicy:     &failurePolicy,
				SideEffects:       &sideEffect,
				MatchPolicy:       &exactPolicy,
				NamespaceSelector: &metav1.LabelSelector{},
				TimeoutSeconds:    &defaultTimeoutSeconds,
				AdmissionReviewVersions: []string{
					"v1", "v1beta1",
				},
				ObjectSelector:     &metav1.LabelSelector{},
				ReinvocationPolicy: &reinvocationNever,
			},
		},
	}

	if c == nil {
		return whc
	}

	bundle := getAPIServerCABundle(namespace, c, l)
	if bundle != nil {
		whc.Webhooks[0].ClientConfig.CABundle = bundle
	}

	return whc
}

func getAPIServerCABundle(namespace string, c client.Client, l logr.Logger) []byte {
	cm := &corev1.ConfigMap{}
	key := client.ObjectKey{Namespace: namespace, Name: "cdi-apiserver-signer-bundle"}
	if err := c.Get(context.TODO(), key, cm); err != nil {
		l.Error(err, "error getting apiserver ca bundle")
		return nil
	}
	if cert, ok := cm.Data["ca-bundle.crt"]; ok {
		return []byte(cert)
	}
	l.V(2).Info("apiserver ca bundle missing from configmap")
	return nil
}

func createAPIServerClusterRoleBinding(namespace string) *rbacv1.ClusterRoleBinding {
	return utils.ResourceBuilder.CreateClusterRoleBinding(apiServerResourceName, apiServerResourceName, apiServerResourceName, namespace)
}

func createAPIServerClusterRole() *rbacv1.ClusterRole {
	return utils.ResourceBuilder.CreateClusterRole(apiServerResourceName, getAPIServerClusterPolicyRules())
}


text:
#include "xvmaininc.h"
#include "defines.h"
#include "declares.h"
#include "externs.h"

/* Deletes the virtual address space associated with an array file */

int free_mapped_sect(arraystate)
struct arraystate *arraystate;
{
   char *inadr[2];

   inadr[0] = arraystate->start;	/* starting address of array file */
   inadr[1] = inadr[0] + arraystate->size - 1;		/* ending address */

   return sys$deltva(inadr, 0, 0);

}

redpajama_set_name: RedPajamaGithub


text:
title: TestRDFDocArrayAccessSet::main — Eregansu Core Library Tests
package: lib-tests
packageTitle: Eregansu Core Library Tests
layout: default
className: TestRDFDocArrayAccessSet
type: method
---

# TestRDFDocArrayAccessSet::main

## Synopsis

public function TestRDFDocArrayAccessSet::main()


text:
author: slowe
comments: true
date: 2013-11-11 09:00:00+00:00
layout: post
slug: making-json-output-more-readable-with-bbedit
title: Making JSON Output More Readable with BBEdit
wordpress_id: 3328
categories: Tutorial
tags:
- JSON
- Linux
- Macintosh
- Productivity
- Web
---

In this post I'm going to show you how to make JSON (JavaScript Object Notation) output more readable using a BBEdit Text Filter. This post comes out of some recent work I've done in learning how to interact with various REST APIs. My initial REST API explorations have focused on the NVP/NSX API, but I plan to soon expand my explorations to include other APIs, like OpenStack.

<aside>You might be wondering _why_ I'm exploring REST APIs and stuff like JSON. I believe that having a better understanding of the APIs these products use will help drive a deeper and more complete understanding of the underlying products. I could be wrongtime will tell.</aside>

BBEdit Text Filters, as you may already know, simply take the current text (or selected text) in BBEdit, do something to it, and then output the result. The "do something to it" is, of course, the magic. You can, for example---and this something that I do---use the MultiMarkdown command-line executable to transform a (Multi)Markdown document in BBEdit to HTML. All that is required is to place the script (or a link to the script) in the `~/Library/Application Support/BBEdit/Text Filters` directory. The script just needs to accept input on STDIN, transform it in whatever way you want, and spit out the results on STDOUT. BBEdit does the rest.

In this case, you're going to use an extremely simple Bash shell script containing a single Python command to transform JSON-serialized output into a more human-readable format.

First, let's take a look at some JSON-serialized output. Here's [a GitHub gist][gist-1] that shows the output from an API call to NVP/NSX to list the logical switches.

As you can see, it _is_ human-readable, but just barely. How can we make this a bit easier for humans to read and parse? Well, it turns out that OS X (and probably most recent flavors of Linux) come with a version of Python pre-installed, and the pre-installed version of Python comes with the ability to "prettify" (make more human readable) JSON text. (In the case of OS X 10.8 "Mountain Lion", the pre-installed version of Python is version 2.7.2.) With grateful thanks to the folks on Twitter who introduced me to this trick, the command you would use in this instance is as follows:

    python -m json.tool

Very simple, right? To turn this into a BBEdit Text Filter, we need only wrap this into a very simple shell script, such as this:

``` bash
#!/bin/sh

python -m json.tool
```

Place this script (or a link to this script) in the `~/Library/Application Support/BBEdit/Text Filters` directory, restart BBEdit, and you should be good to go. Now you can copy and paste the output from an API call like the output above, run it through this text filter, and get output that looks like this:

``` json
{
    "result_count": 3,
    "results": [
        {
            "_href": "/ws.v1/lswitch/3ca2d5ef-6a0f-4392-9ec1-a6645234bc55",
            "_schema": "/ws.v1/schema/LogicalSwitchConfig",
            "type": "LogicalSwitchConfig"
        },
        {
            "_href": "/ws.v1/lswitch/81f51868-2142-48a8-93ff-ef612249e025",
            "_schema": "/ws.v1/schema/LogicalSwitchConfig",
            "type": "LogicalSwitchConfig"
        },
        {
            "_href": "/ws.v1/lswitch/9fed3467-dd74-421b-ab30-7bc9bfae6248",
            "_schema": "/ws.v1/schema/LogicalSwitchConfig",
            "type": "LogicalSwitchConfig"
        }
    ]
}
```

(Want this as [a GitHub gist][gist-3]?)

Given that I'm new to a lot of this stuff, I'm sure that I have probably overlooked something along the way. There might be better and/or more efficient ways of handling this, or better tools to use. If you have any suggestions on how to improve any of this---or just suggestions on how I might do better in my API explorations---feel free to speak out in the comments below.

[gist-1]: https://gist.github.com/lowescott/7370184
[gist-2]: https://gist.github.com/lowescott/7364842
[gist-3]: https://gist.github.com/lowescott/7370142


text:
<!DOCTYPE html>

<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>Hyperion</title>

<link rel="stylesheet" href="css/base.css" id="camera-css" />
<link rel="stylesheet" href="css/framework.css" />
<link rel="stylesheet" href="css/style.css" />
<link rel="stylesheet" href="css/noscript.css" media="screen,all" id="noscript" />

<link rel="shortcut icon" href="img/favicon.ico" />

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

home

- home layout 2

- home layout 3

- home layout 4

about

services

portfolio

- portfolio 2 column

- portfolio 3 column

- portfolio 4 column

blog

contact

pages

- column page

- table page

- button & list page

- typhography page

- testimonials page

- pricing page

- faq page

- single page

- fullwidth page

- 404 page

Our Blog

Home

Blog

Reprehenderit voluptate essequam molestiae

30

Aug 2012

Andrew Garfield

Timeline

8 Comments

Reprehenderit voluptate essequam molestiae

Nam libero tempore soluta nobis est eligendi optio cumque nihil impedit minus idquod maxime placeat facere possimus omnis voluptas assumenda est omnis dolor repellendus temporibus autem quibusdam officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint.

Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt labore dolore magnam.

At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga.

Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.

2 responses to "Reprehenderit voluptate essequam molestiae"

John Doe

                        April 28, 2010 01:23 am Reply

Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequ  vel illum qui dolorem eum fugiat quo voluptas nulla pariatur sunt in culpa qui officia deserunt mollit anim id est laborum adipisci velit.

Matt Somat

                                April 28, 2010 01:23 am Reply

Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequ  vel illum qui dolorem eum fugiat quo voluptas nulla pariatur sunt in culpa qui officia deserunt mollit anim.

John Doe

                        April 28, 2010 01:23 am Reply

Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequ  vel illum qui dolorem eum fugiat quo voluptas nulla pariatur sunt in culpa qui officia deserunt mollit anim id est laborum adipisci velit.

Leave a comment

                <form action="#" id="comment-form" />
                    <fieldset>
                    Name *
                    <input type="text" name="name" class="textfield" id="name" value="" />
                    E-mail *
                    <input type="text" name="email" class="textfield" id="email" value="" />
                    Subject
                    <input type="text" name="subject" class="textfield" id="subject" value="" />
                    <textarea name="message" id="message" class="textarea" cols="2" rows="4"></textarea>

                    <input type="submit" name="submit" class="buttoncontact" id="buttonsend" value="Submit" />
                    Please wait..

                    </fieldset>
                </form>

            	<form id="search" action="#" method="get" />
                    <fieldset class="search-fieldset">
                        <input type="text" id="search-form" value="Search here..." onblur="if (this.value == ''){this.value = 'Search here...'; }" onfocus="if (this.value == 'Search here...') {this.value = ''; }" />
                        <button type="submit" value="Submit">Submit</button>
                    </fieldset>
                </form>

Categories

National News

World of Sport

Travel & Accomodation

Technology News

Entertainment

Popular Post

Architecto beatae vitare dictasunt explicabo

12 Comments

By : Richard Burton

Reprehenderit voluptate essequam molestiae

8 Comments

By : Andrew Garfield

Exercitationem ullam corporisipi laboriosam

4 Comments

By : Dennis Rodman

Tabs

Archives

Comments

Text only

May 2012

8 post

June 2012

12 post

July 2012

4 post

August 2012

10 post

15 minutes ago by Jenglot on

Architecto beatae vitare dictasunt explicabo

20 minutes ago by Markus on

Exercitationem ullam corporisipi laboriosam

40 minutes ago by Andrew on

Reprehenderit voluptate essequam molestiae

Lorem ipsum dolor amet, consectetur adipite scinelit vestibulum vel quam sitare amet odio ultricies dapbus acer vitae augue duis nulla nunc dignissim

Tag Cloud

                    jquery
                    camera slide
                    minimalist
                    indonesia
                    web design
                    responsive
                    html 5
                    themeforest
                    site template

© Copyright © 2013.Company name All rights reserved.网页模板 -  More Templates 模板之家

Address

Armistice Building
Jakarta, JKT 1220
PO BOX 1234

Phone : +621 55566671

Email : info@crown.com

Company

About Hyperion

Careers

Press & Media

Environmental Impact

Affiliate Program

Privacy Policy

Flickr

Can't load Flickr feed, please activate your javascript first...


text:
yii2-tag-cloud
==============

[![Latest Stable Version](https://poser.pugx.org/alexander-suter/yii2-tag-cloud/v/stable)](https://packagist.org/packages/alexander-suter/yii2-tag-cloud)
[![Total Downloads](https://poser.pugx.org/alexander-suter/yii2-tag-cloud/downloads)](https://packagist.org/packages/alexander-suter/yii2-tag-cloud)

Yii2 extension. Tag Cloud.

## Installation

The preferred way to install this extension is through [composer](http://getcomposer.org/download/).

To install, either run

```
$ php composer.phar require alexander-suter/yii2-tag-cloud "*"
```

or add

```
"alexander-suter/yii2-tag-cloud": "*"
```

to the ```require``` section of your `composer.json` file.

## Usage

~~~
echo TagCloud::widget([
        'beginColor' => '00089A',
        'endColor' => 'A3AEFF',
        'minFontSize' => 8,
        'maxFontSize' => 15,
        'displayWeight' => false,
        'arrTags' => [
                        "MVC"     => ['weight'=> 2],
                        "PHP"     => ['weight'=> 9, 'url' => 'http://php.net'],
                        "MySQL"   => ['weight'=> 8, 'url' => 'http://mysql.com'],
                        "jQuery"  => ['weight'=> 6, 'url' => 'http://jquery.com'],
                        "SQL"     => ['weight'=> 9],
                        "C#"    => ['weight'=> 2)],
                ],
        'options' => ['style' => 'word-wrap: break-word;']
]);
~~~


text:
do 'pptp-server-lib.pl';

# backup_config_files()
# Returns files and directories that can be backed up
sub backup_config_files
{
local $conf = &get_config();
local $option = &find_conf("option", $conf);
$option ||= $config{'ppp_options'};
return ( $config{'file'}, $config{'pap_file'}, $option );
}

# pre_backup(&files)
# Called before the files are actually read
sub pre_backup
{
return undef;
}

# post_backup(&files)
# Called after the files are actually read
sub post_backup
{
return undef;
}

# pre_restore(&files)
# Called before the files are restored from a backup
sub pre_restore
{
return undef;
}

# post_restore(&files)
# Called after the files are restored from a backup
sub post_restore
{
return &apply_configuration();
}

1;


text:
import * as React from 'react';
import styles from './Hyperlink.module.scss';
import { IHyperlinkProps } from '.';

export class Hyperlink extends React.Component<IHyperlinkProps, {}> {

  public render(): React.ReactElement<IHyperlinkProps> {
    return (
      {this.props.properties.description}

    );
  }
}


text:
import Utils from './Utils';
import TestIDs from '../playground/src/testIDs';

const { elementById, elementByLabel } = Utils;

describe('Buttons', () => {
  beforeEach(async () => {
    await device.launchApp({ newInstance: true });
    await elementById(TestIDs.OPTIONS_TAB).tap();
    await elementById(TestIDs.GOTO_BUTTONS_SCREEN).tap();
  });

  it('sets right buttons', async () => {
    await expect(elementById(TestIDs.BUTTON_ONE)).toBeVisible();
    await expect(elementById(TestIDs.ROUND_BUTTON)).toBeVisible();
  });

  it('set left buttons', async () => {
    await expect(elementById(TestIDs.LEFT_BUTTON)).toBeVisible();
  });

  it('pass props to custom button component', async () => {
    await expect(elementByLabel('Two')).toExist();
  });

  it('pass props to custom button component should exist after push pop', async () => {
    await expect(elementByLabel('Two')).toExist();
    await elementById(TestIDs.PUSH_BTN).tap();
    await elementById(TestIDs.POP_BTN).tap();
    await expect(elementByLabel('Two')).toExist();
  });

  it('custom button is clickable', async () => {
    await elementByLabel('Two').tap();
    await expect(elementByLabel('Times created: 1')).toExist();
  });

  it(':ios: Resetting buttons should unmount button react view', async () => {
    await elementById(TestIDs.SHOW_LIFECYCLE_BTN).tap();
    await elementById(TestIDs.RESET_BUTTONS).tap();
    await expect(elementByLabel('Button component unmounted')).toBeVisible();
  });

  it('change button props without rendering all buttons', async () => {
    await elementById(TestIDs.CHANGE_BUTTON_PROPS).tap();
    await expect(elementByLabel('Three')).toBeVisible();
  });

  it('pop using back button', async () => {
    await elementById(TestIDs.PUSH_BTN).tap();
    await elementById(TestIDs.BACK_BUTTON).tap();
    await expect(elementByLabel('Buttons')).toBeVisible();
  });

  it('resizes title component when a button is added with mergeOptions', async () => {
    await elementById(TestIDs.ADD_BUTTON).tap();
    await elementById(TestIDs.BUTTON_THREE).tap();
  });

  it('Button component is not recreated if it has a predefined componentId', async () => {
    await elementById(TestIDs.ADD_BUTTON).tap();
    await elementById(TestIDs.ROUND_BUTTON).tap();
    await expect(elementByLabel('Times created: 1')).toBeVisible();
  });
});


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package br.edu.utfpr.cm.minerador.model.svn;

import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;

/**
 *
 * @author Douglas
 */
@Entity
@Table(name = "actions")

public class Action implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @Column(name = "id")
    private Integer id;
    @Column(name = "type")
    private String type;
    @Column(name = "file_id")
    private Integer fileId;
    @Column(name = "commit_id")
    private Integer commitId;
    @Column(name = "branch_id")
    private Integer branchId;

    public Action() {
    }

    public Action(Integer id) {
        this.id = id;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getType() {
        return type;
    }

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

    public Integer getFileId() {
        return fileId;
    }

    public void setFileId(Integer fileId) {
        this.fileId = fileId;
    }

    public Integer getCommitId() {
        return commitId;
    }

    public void setCommitId(Integer commitId) {
        this.commitId = commitId;
    }

    public Integer getBranchId() {
        return branchId;
    }

    public void setBranchId(Integer branchId) {
        this.branchId = branchId;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Action)) {
            return false;
        }
        Action other = (Action) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "br.edu.utfpr.cm.minerador.model.issue.Actions[ id=" + id + " ]";
    }

}


text:
import tempfile
import unittest

import mock

from dockercloudcli.utils import *

class TabulateResultTestCase(unittest.TestCase):
    @mock.patch('dockercloudcli.utils.tabulate')
    def test_tabulate_result(self, mock_tabulate):
        data_list = None
        headers = None
        tabulate_result(data_list, headers)
        mock_tabulate.assert_called_with(data_list, headers, stralign="left", tablefmt="plain")

class DateTimeConversionTestCase(unittest.TestCase):
    def test_from_utc_string_to_utc_datetime(self):
        # test None
        self.assertIsNone(from_utc_string_to_utc_datetime(None))

        # test mal-formatted string
        self.assertRaises(Exception, from_utc_string_to_utc_datetime, 'abc')

        # test normal case
        utc_datetime = from_utc_string_to_utc_datetime('Sun, 6 Apr 2014 18:11:17 +0000')
        self.assertEqual(str(utc_datetime), '2014-04-06 18:11:17')

    def test_get_humanize_local_datetime_from_utc_datetime_string(self):
        # test None
        self.assertEqual(get_humanize_local_datetime_from_utc_datetime_string(None), '')

        # test mal-formatted string
        self.assertRaises(Exception, get_humanize_local_datetime_from_utc_datetime_string, 'abc')

        # test normal case
        utc_datetime = get_humanize_local_datetime_from_utc_datetime_string('Sun, 6 Apr 2014 18:11:17 +0000')
        self.assertRegexpMatches(utc_datetime, r".* ago")

        # test future
        utc_datetime = get_humanize_local_datetime_from_utc_datetime_string('Sun, 6 Apr 3014 18:11:17 +0000')
        self.assertNotRegexpMatches(utc_datetime, r".* ago")

class IsUuidTestCase(unittest.TestCase):
    def test_is_uuid4(self):
        self.assertTrue(is_uuid4('7a4cfe51-038b-42d6-825e-3b533888d8cd'))
        self.assertTrue(is_uuid4('7A4CFE51-03BB-42D6-825E-3B533888D8CD'))

        self.assertFalse(is_uuid4('not_uuid'))
        self.assertFalse(is_uuid4(''))
        self.assertRaises(Exception, is_uuid4, None)
        self.assertRaises(Exception, is_uuid4, 12345)

class AddUnicodeSymbolToStateTestCase(unittest.TestCase):
    def test_add_unicode_symbol_to_state(self):
        for state in ['Running', 'Partly running']:
            self.assertEqual(' '.join([u'▶', state]), add_unicode_symbol_to_state(state))
        for state in ['Init', 'Stopped']:
            self.assertEqual(' '.join([u'◼', state]), add_unicode_symbol_to_state(state))
        for state in ['Starting', 'Stopping', 'Scaling', 'Terminating']:
            self.assertEqual(' '.join([u'⚙', state]), add_unicode_symbol_to_state(state))
        for state in ['Start failed', 'Stopped with errors']:
            self.assertEqual(' '.join([u'!', state]), add_unicode_symbol_to_state(state))
        for state in ['Terminated']:
            self.assertEqual(' '.join([u'✘', state]), add_unicode_symbol_to_state(state))

class ParseLinksTestCase(unittest.TestCase):
    def test_parse_links(self):
        output = [{'to_service': 'mysql', 'name': 'db1'}, {'to_service': 'mariadb', 'name': 'db2'}]
        self.assertEqual(output, parse_links(['mysql:db1', 'mariadb:db2'], 'to_service'))

    def test_parse_links_bad_format(self):
        self.assertRaises(BadParameter, parse_links, ['mysql', 'mariadb'], 'to_service')
        self.assertRaises(BadParameter, parse_links, ['mysql:mysql:mysql', 'mariadb:maria:maria'], 'to_service')
        self.assertRaises(BadParameter, parse_links, [''], 'to_service')

class ParsePublishedPortsTestCase(unittest.TestCase):
    def test_parse_published_ports(self):
        output = [{'protocol': 'tcp', 'inner_port': '80', 'published': True},
                  {'protocol': 'udp', 'inner_port': '53', 'published': True},
                  {'protocol': 'tcp', 'inner_port': '3306', 'outer_port': '3307', 'published': True},
                  {'protocol': 'udp', 'inner_port': '8080', 'outer_port': '8083', 'published': True}]
        self.assertEqual(output, parse_published_ports(['80', '53/udp', '3307:3306', '8083:8080/udp']))

    def test_parse_published_ports_bad_format(self):
        self.assertRaises(BadParameter, parse_published_ports, ['abc'])
        self.assertRaises(BadParameter, parse_published_ports, ['abc:80'])
        self.assertRaises(BadParameter, parse_published_ports, ['80:abc'])
        self.assertRaises(BadParameter, parse_published_ports, ['80:80:abc'])
        self.assertRaises(BadParameter, parse_published_ports, ['80:80/abc'])
        self.assertRaises(BadParameter, parse_published_ports, ['80/80:tcp'])
        self.assertRaises(BadParameter, parse_published_ports, [''])

class ParseExposedPortsTestCase(unittest.TestCase):
    def test_parse_exposed_ports(self):
        output = [{'protocol': 'tcp', 'inner_port': '80', 'published': False},
                  {'protocol': 'tcp', 'inner_port': '8080', 'published': False}]
        self.assertEqual(output, parse_exposed_ports([80, 8080]))

    def test_parse_exposed_ports_bad_format(self):
        self.assertRaises(BadParameter, parse_exposed_ports, ['abc'])
        self.assertRaises(BadParameter, parse_exposed_ports, ['abc'])
        self.assertRaises(BadParameter, parse_exposed_ports, ['-1'])
        self.assertRaises(BadParameter, parse_exposed_ports, ['999999'])

class ParseEnvironmentVariablesTestCase(unittest.TestCase):
    def test_parse_envvars(self):
        output = [{'key': 'MYSQL_PASS', 'value': 'mypass'}, {'key': 'MYSQL_USER', 'value': 'admin'}]
        self.assertEqual(output, parse_envvars(['MYSQL_USER=admin', 'MYSQL_PASS=mypass'], []))

class GetStackNameTestCase(unittest.TestCase):
    def test_update_stack_with_existing_stack(self):
        stack = dockercloud.Stack.create()
        self.assertEqual(stack, update_stack("whatever", stack))

    def test_update_stack_with_empty_stack(self):
        self.assertEqual("name", update_stack("name", None).name)

    @mock.patch('os.path.basename', )
    def test_update_stack_with_empty_stack(self, mock_basename):
        mock_basename.return_value = "basename"
        self.assertEqual("basename", update_stack(None, None).name)

class GetServicesFromStackfilesTestCase(unittest.TestCase):
    def test_get_services_from_stackfiles(self):
        os.environ["DOCKER_HOST"] = "dockerhost"
        os.environ["DOCKER_PATH"] = "dockerpath"
        tempdir = tempfile.mkdtemp("sub")

        self.assertEqual({'name': 'stackname', 'services': []}, get_services_from_stackfiles("stackname", []))

        f1 = open(os.path.join(tempdir, 'docker-cloud.yml'), 'w')
        f1.write('''lb:
  image: dockercloud/haproxy
  environment:
    - DOCKER_HOST
  volumes:
    - $DOCKER_PATH:$DOCKER_PATH
hw1:
  image: dockercloud/hello-world
  ''')
        f1.close()
        data1 = {'services': [{'environment': ['DOCKER_HOST=dockerhost'], 'image': 'dockercloud/haproxy', 'name': 'lb',
                               'volumes': ['dockerpath:dockerpath']},
                              {'image': 'dockercloud/hello-world', 'name': 'hw1'}],
                 'name': 'stackname'}
        self.assertEqual(data1, get_services_from_stackfiles("stackname", [os.path.join(tempdir, 'docker-cloud.yml')]))

        f2 = open(os.path.join(tempdir, 'docker-cloud.override.yml'), 'w')
        f2.write('''hw1:
  image: tutum/hello-world
hw2:
  image: dockercloud/hello-world
''')
        f2.close()
        data2 = {'services': [{'image': 'dockercloud/hello-world', 'name': 'hw2'},
                              {'environment': ['DOCKER_HOST=dockerhost'], 'image': 'dockercloud/haproxy', 'name': 'lb',
                               'volumes': ['dockerpath:dockerpath']},
                              {'image': 'tutum/hello-world', 'name': 'hw1'}],
                 'name': 'stackname'}
        self.assertEqual(data2, get_services_from_stackfiles("stackname", [os.path.join(tempdir, 'docker-cloud.yml'),
                                                                           os.path.join(tempdir,
                                                                                'docker-cloud.override.yml')]))

class GetStackfilesTestCase(unittest.TestCase):
    def test_get_stackfiles_with_a_list_of_files(self):
        self.assertEqual(["file1", "file2", "file3"], get_stackfiles(["file1", "file2", "file3"]))

    @mock.patch("os.getcwd")
    def test_get_stackfiles_with_not_file_list(self, mock_getcwd):
        tempdir = tempfile.mkdtemp("sub")
        cwd = os.path.join(tempdir, "abc")
        os.mkdir(cwd)
        mock_getcwd.return_value = cwd

        self.assertEqual([], get_stackfiles(None))

        open(os.path.join(tempdir, "docker-compose.yaml"), "w").close()
        self.assertEqual([os.path.join(tempdir, "docker-compose.yaml")], get_stackfiles(None))
        open(os.path.join(tempdir, "docker-compose.override.yaml"), "w").close()
        self.assertEqual(
            [os.path.join(tempdir, "docker-compose.yaml"), os.path.join(tempdir, "docker-compose.override.yaml")],
            get_stackfiles(None))
        open(os.path.join(tempdir, "docker-compose.yml"), "w").close()
        self.assertEqual([os.path.join(tempdir, "docker-compose.yml")], get_stackfiles(None))
        open(os.path.join(tempdir, "docker-compose.override.yml"), "w").close()
        self.assertEqual(
            [os.path.join(tempdir, "docker-compose.yml"), os.path.join(tempdir, "docker-compose.override.yml")],
            get_stackfiles(None))

        open(os.path.join(tempdir, "tutum.yaml"), "w").close()
        self.assertEqual([os.path.join(tempdir, "tutum.yaml")], get_stackfiles(None))
        open(os.path.join(tempdir, "tutum.override.yaml"), "w").close()
        self.assertEqual([os.path.join(tempdir, "tutum.yaml"), os.path.join(tempdir, "tutum.override.yaml")],
                         get_stackfiles(None))
        open(os.path.join(tempdir, "tutum.yml"), "w").close()
        self.assertEqual([os.path.join(tempdir, "tutum.yml")], get_stackfiles(None))
        open(os.path.join(tempdir, "tutum.override.yml"), "w").close()
        self.assertEqual([os.path.join(tempdir, "tutum.yml"), os.path.join(tempdir, "tutum.override.yml")],
                         get_stackfiles(None))

        open(os.path.join(tempdir, "docker-cloud.yaml"), "w").close()
        self.assertEqual([os.path.join(tempdir, "docker-cloud.yaml")], get_stackfiles(None))
        open(os.path.join(tempdir, "docker-cloud.override.yaml"), "w").close()
        self.assertEqual(
            [os.path.join(tempdir, "docker-cloud.yaml"), os.path.join(tempdir, "docker-cloud.override.yaml")],
            get_stackfiles(None))
        open(os.path.join(tempdir, "docker-cloud.yml"), "w").close()
        self.assertEqual([os.path.join(tempdir, "docker-cloud.yml")], get_stackfiles(None))
        open(os.path.join(tempdir, "docker-cloud.override.yml"), "w").close()
        self.assertEqual(
            [os.path.join(tempdir, "docker-cloud.yml"), os.path.join(tempdir, "docker-cloud.override.yml")],
            get_stackfiles(None))

        open(os.path.join(cwd, "docker-compose.yaml"), "w").close()
        self.assertEqual([os.path.join(cwd, "docker-compose.yaml")], get_stackfiles(None))
        open(os.path.join(cwd, "docker-compose.override.yaml"), "w").close()
        self.assertEqual([os.path.join(cwd, "docker-compose.yaml"), os.path.join(cwd, "docker-compose.override.yaml")],
                         get_stackfiles(None))
        open(os.path.join(cwd, "docker-compose.yml"), "w").close()
        self.assertEqual([os.path.join(cwd, "docker-compose.yml")], get_stackfiles(None))
        open(os.path.join(cwd, "docker-compose.override.yml"), "w").close()
        self.assertEqual([os.path.join(cwd, "docker-compose.yml"), os.path.join(cwd, "docker-compose.override.yml")],
                         get_stackfiles(None))


text:
name "pygments"
default_version "1.6"

dependency "pip"

build do
  env = with_standard_compiler_flags(with_embedded_path)

  command "#{install_dir}/embedded/bin/pip install" \
          " -I" \
          " --build #{project_dir} #{name}==#{version}", env: env
end


text:
#ifndef _VSBACKUP_H_
#define _VSBACKUP_H_

const IID IID_IVssExamineWriterMetadata      =   // 902fcf7f-b7fd-42f8-81f1-b2e400b1e5bd
                     {
                     0x902fcf7f,
                     0xb7fd,
                     0x42f8,
                     {0x81, 0xf1, 0xb2, 0xe4, 0x00, 0xb1, 0xe5, 0xbd }
                     };

const IID IID_IVssExamineWriterMetadataEx  =  // 0c0e5ec0-ca44-472b-b702-e652db1c0451
                    {
                    0x0c0e5ec0,
                    0xca44,
                    0x472b,
                    { 0xb7, 0x02, 0xe6, 0x52, 0xdb, 0x1c, 0x04, 0x51  }
                    };

const IID IID_IVssBackupComponents            =  // 665c1d5f-c218-414d-a05d-7fef5f9d5c86
                    {
                    0x665c1d5f,
                    0xc218,
                    0x414d,
                    { 0xa0, 0x5d, 0x7f, 0xef, 0x5f, 0x9d, 0x5c, 0x86 }
                    };

const IID IID_IVssBackupComponentsEx         = // 963f03ad-9e4c-4a34-ac15-e4b6174e5036
                    {
                    0x963f03ad,
                    0x9e4c,
                    0x4a34,
                    { 0xac, 0x15, 0xe4, 0xb6, 0x17, 0x4e, 0x50, 0x36 }
                    };

// description of a component
typedef struct _VSS_COMPONENTINFO
	{
	VSS_COMPONENT_TYPE type;	// either VSS_CT_DATABASE or VSS_CT_FILEGROUP
	BSTR bstrLogicalPath;		// logical path to component
	BSTR bstrComponentName;		// component name
	BSTR bstrCaption;		// description of component
	BYTE *pbIcon;			// icon
	UINT cbIcon;			// icon
	bool bRestoreMetadata;		// whether component supplies restore metadata
	bool bNotifyOnBackupComplete;	// whether component needs to be informed if backup was successful
	bool bSelectable;		// is component selectable
	bool bSelectableForRestore; // is component selectable for restore
	DWORD dwComponentFlags;	// extra attribute flags for the component
	UINT cFileCount;		// # of files in file group
	UINT cDatabases;		// # of database files
	UINT cLogFiles;			// # of log files
	UINT cDependencies;		// # of components that this component depends on
	} VSS_COMPONENTINFO;

typedef const VSS_COMPONENTINFO *PVSSCOMPONENTINFO;

// component information
class IVssWMComponent : public IUnknown
	{
public:
	// get component information
	STDMETHOD(GetComponentInfo)(PVSSCOMPONENTINFO *ppInfo) = 0;

	// free component information
	STDMETHOD(FreeComponentInfo)(PVSSCOMPONENTINFO pInfo) = 0;

	// obtain a specific file in a file group
	STDMETHOD(GetFile)
		(
		IN UINT iFile,
		OUT IVssWMFiledesc **ppFiledesc
		) = 0;

	// obtain a specific physical database file for a database
	STDMETHOD(GetDatabaseFile)
		(
		IN UINT iDBFile,
		OUT IVssWMFiledesc **ppFiledesc
		) = 0;

	// obtain a specific physical log file for a database
	STDMETHOD(GetDatabaseLogFile)
		(
		IN UINT iDbLogFile,
		OUT IVssWMFiledesc **ppFiledesc
		) = 0;

	STDMETHOD(GetDependency)
		(
		IN UINT iDependency,
		OUT IVssWMDependency **ppDependency
		) = 0;
	};

// interface to examine writer metadata
class __declspec(uuid("902fcf7f-b7fd-42f8-81f1-b2e400b1e5bd")) IVssExamineWriterMetadata : public IUnknown
	{
public:
	// obtain identity of the writer
	STDMETHOD(GetIdentity)
		(
		OUT VSS_ID *pidInstance,
		OUT VSS_ID *pidWriter,
		OUT BSTR *pbstrWriterName,
		OUT VSS_USAGE_TYPE *pUsage,
		OUT VSS_SOURCE_TYPE *pSource
		) = 0;

	// obtain number of include files, exclude files, and components
	STDMETHOD(GetFileCounts)
		(
		OUT UINT *pcIncludeFiles,
		OUT UINT *pcExcludeFiles,
		OUT UINT *pcComponents
		) = 0;

	// obtain specific include files
	STDMETHOD(GetIncludeFile)
		(
		IN UINT iFile,
		OUT IVssWMFiledesc **ppFiledesc
		) = 0;

	// obtain specific exclude files
	STDMETHOD(GetExcludeFile)
		(
		IN UINT iFile,
		OUT IVssWMFiledesc **ppFiledesc
		) = 0;

	// obtain specific component
	STDMETHOD(GetComponent)
		(
		IN UINT iComponent,
		OUT IVssWMComponent **ppComponent
		) = 0;

	// obtain restoration method
	STDMETHOD(GetRestoreMethod)
		(
		OUT VSS_RESTOREMETHOD_ENUM *pMethod,
		OUT BSTR *pbstrService,
		OUT BSTR *pbstrUserProcedure,
		OUT VSS_WRITERRESTORE_ENUM *pwriterRestore,
		OUT bool *pbRebootRequired,
		UINT *pcMappings
		) = 0;

	// obtain a specific alternative location mapping
	STDMETHOD(GetAlternateLocationMapping)
		(
		IN UINT iMapping,
		OUT IVssWMFiledesc **ppFiledesc
		) = 0;

	// get the backup schema
	STDMETHOD(GetBackupSchema)
		(
		OUT DWORD *pdwSchemaMask
		) = 0;

	// obtain reference to actual XML document
	STDMETHOD(GetDocument)(IXMLDOMDocument **pDoc) = 0;

	// convert document to a XML string
	STDMETHOD(SaveAsXML)(BSTR *pbstrXML) = 0;

	// load document from an XML string
	STDMETHOD(LoadFromXML)(BSTR bstrXML) = 0;
	};

class __declspec(uuid("0c0e5ec0-ca44-472b-b702-e652db1c0451")) IVssExamineWriterMetadataEx : public IVssExamineWriterMetadata
        {
public:
        // obtain identity of the writer
        STDMETHOD(GetIdentityEx)
            (
              OUT VSS_ID *pidInstance,
              OUT VSS_ID *pidWriter,
              OUT BSTR *pbstrWriterName,
              OUT BSTR* pbstrInstanceName,
              OUT VSS_USAGE_TYPE *pUsage,
              OUT VSS_SOURCE_TYPE *pSource
              ) = 0;
        };

class IVssWriterComponentsExt :
	public IVssWriterComponents,
	public IUnknown
	{
	};

// backup components interface
class __declspec(uuid("665c1d5f-c218-414d-a05d-7fef5f9d5c86")) IVssBackupComponents : public IUnknown
	{
public:
	// get count of writer components
	STDMETHOD(GetWriterComponentsCount)(OUT UINT *pcComponents) = 0;

	// obtain a specific writer component
	STDMETHOD(GetWriterComponents)
		(
		IN UINT iWriter,
		OUT IVssWriterComponentsExt **ppWriter
		) = 0;

	// initialize and create BACKUP_COMPONENTS document
	STDMETHOD(InitializeForBackup)(IN BSTR bstrXML = NULL) = 0;

	// set state describing backup
	STDMETHOD(SetBackupState)
		(
		IN bool bSelectComponents,
		IN bool bBackupBootableSystemState,
		IN VSS_BACKUP_TYPE backupType,
		IN bool bPartialFileSupport = false
		) = 0;

	STDMETHOD(InitializeForRestore)(IN BSTR bstrXML) = 0;

       // set state describing restore
       STDMETHOD(SetRestoreState)
       	(
       	VSS_RESTORE_TYPE restoreType
       	) = 0;

	// gather writer metadata
	STDMETHOD(GatherWriterMetadata)
		(
		OUT IVssAsync **pAsync
		) = 0;

	// get count of writers with metadata
	STDMETHOD(GetWriterMetadataCount)
		(
		OUT UINT *pcWriters
		) = 0;

	// get writer metadata for a specific writer
	STDMETHOD(GetWriterMetadata)
		(
		IN UINT iWriter,
		OUT VSS_ID *pidInstance,
		OUT IVssExamineWriterMetadata **ppMetadata
		) = 0;

	// free writer metadata
	STDMETHOD(FreeWriterMetadata)() = 0;

	// add a component to the BACKUP_COMPONENTS document
	STDMETHOD(AddComponent)
		(
		IN VSS_ID instanceId,
		IN VSS_ID writerId,
		IN VSS_COMPONENT_TYPE ct,
		IN LPCWSTR wszLogicalPath,
		IN LPCWSTR wszComponentName
		) = 0;

	// dispatch PrepareForBackup event to writers
	STDMETHOD(PrepareForBackup)
		(
		OUT IVssAsync **ppAsync
		) = 0;

	// abort the backup
	STDMETHOD(AbortBackup)() = 0;

	// dispatch the Identify event so writers can expose their metadata
	STDMETHOD(GatherWriterStatus)
		(
		OUT IVssAsync **pAsync
		) = 0;

	// get count of writers with status
	STDMETHOD(GetWriterStatusCount)
		(
		OUT UINT *pcWriters
		) = 0;

	STDMETHOD(FreeWriterStatus)() = 0;

	STDMETHOD(GetWriterStatus)
		(
		IN UINT iWriter,
		OUT VSS_ID *pidInstance,
		OUT VSS_ID *pidWriter,
		OUT BSTR *pbstrWriter,
		OUT VSS_WRITER_STATE *pnStatus,
		OUT HRESULT *phResultFailure
		) = 0;

	// indicate whether backup succeeded on a component
	STDMETHOD(SetBackupSucceeded)
		(
		IN VSS_ID instanceId,
		IN VSS_ID writerId,
		IN VSS_COMPONENT_TYPE ct,
		IN LPCWSTR wszLogicalPath,
		IN LPCWSTR wszComponentName,
		IN bool bSucceded
		) = 0;

    // set backup options for the writer
	STDMETHOD(SetBackupOptions)
		(
		IN VSS_ID writerId,
		IN VSS_COMPONENT_TYPE ct,
		IN LPCWSTR wszLogicalPath,
		IN LPCWSTR wszComponentName,
		IN LPCWSTR wszBackupOptions
		) = 0;

    // indicate that a given component is selected to be restored
    STDMETHOD(SetSelectedForRestore)
		(
		IN VSS_ID writerId,
		IN VSS_COMPONENT_TYPE ct,
		IN LPCWSTR wszLogicalPath,
		IN LPCWSTR wszComponentName,
		IN bool bSelectedForRestore
		) = 0;

    // set restore options for the writer
	STDMETHOD(SetRestoreOptions)
		(
		IN VSS_ID writerId,
		IN VSS_COMPONENT_TYPE ct,
		IN LPCWSTR wszLogicalPath,
		IN LPCWSTR wszComponentName,
		IN LPCWSTR wszRestoreOptions
		) = 0;

	// indicate that additional restores will follow
	STDMETHOD(SetAdditionalRestores)
		(
		IN VSS_ID writerId,
		IN VSS_COMPONENT_TYPE ct,
		IN LPCWSTR wszLogicalPath,
		IN LPCWSTR wszComponentName,
		IN bool bAdditionalRestores
		) = 0;

    // set the backup stamp that the differential or incremental
	// backup is based on
    STDMETHOD(SetPreviousBackupStamp)
		(
		IN VSS_ID writerId,
		IN VSS_COMPONENT_TYPE ct,
		IN LPCWSTR wszLogicalPath,
		IN LPCWSTR wszComponentName,
		IN LPCWSTR wszPreviousBackupStamp
		) = 0;

	// save BACKUP_COMPONENTS document as XML string
	STDMETHOD(SaveAsXML)(BSTR *pbstrXML) = 0;

	// signal BackupComplete event to the writers
	STDMETHOD(BackupComplete)(OUT IVssAsync **ppAsync) = 0;

	// add an alternate mapping on restore
	STDMETHOD(AddAlternativeLocationMapping)
		(
		IN VSS_ID writerId,
		IN VSS_COMPONENT_TYPE componentType,
		IN LPCWSTR wszLogicalPath,
		IN LPCWSTR wszComponentName,
		IN LPCWSTR wszPath,
		IN LPCWSTR wszFilespec,
		IN bool bRecursive,
		IN LPCWSTR wszDestination
		) = 0;

    // add a subcomponent to be restored
	STDMETHOD(AddRestoreSubcomponent)
		(
		IN VSS_ID writerId,
		IN VSS_COMPONENT_TYPE componentType,
		IN LPCWSTR wszLogicalPath,
		IN LPCWSTR wszComponentName,
		IN LPCWSTR wszSubComponentLogicalPath,
		IN LPCWSTR wszSubComponentName,
		IN bool bRepair
		) = 0;

	// requestor indicates whether files were successfully restored
	STDMETHOD(SetFileRestoreStatus)
		(
		IN VSS_ID writerId,
		IN VSS_COMPONENT_TYPE ct,
		IN LPCWSTR wszLogicalPath,
		IN LPCWSTR wszComponentName,
		IN VSS_FILE_RESTORE_STATUS status
		) = 0;

    // add a new location target for a file to be restored
    STDMETHOD(AddNewTarget)
		(
		IN VSS_ID writerId,
		IN VSS_COMPONENT_TYPE ct,
		IN LPCWSTR wszLogicalPath,
		IN LPCWSTR wszComponentName,
		IN LPCWSTR wszPath,
		IN LPCWSTR wszFileName,
		IN bool bRecursive,
		IN LPCWSTR wszAlternatePath
		) = 0;

     // add a new location for the ranges file in case it was restored to
    // a different location
    STDMETHOD(SetRangesFilePath)
    		(
		IN VSS_ID writerId,
		IN VSS_COMPONENT_TYPE ct,
		IN LPCWSTR wszLogicalPath,
		IN LPCWSTR wszComponentName,
    		IN UINT iPartialFile,
    		IN LPCWSTR wszRangesFile
    		) = 0;

	// signal PreRestore event to the writers
	STDMETHOD(PreRestore)(OUT IVssAsync **ppAsync) = 0;

	// signal PostRestore event to the writers
	STDMETHOD(PostRestore)(OUT IVssAsync **ppAsync) = 0;

    // Called to set the context for subsequent snapshot-related operations
    STDMETHOD(SetContext)
		(
        IN LONG lContext
        ) = 0;

	// start a snapshot set
	STDMETHOD(StartSnapshotSet)
	    (
	    OUT VSS_ID *pSnapshotSetId
	    ) = 0;

	// add a volume to a snapshot set
	STDMETHOD(AddToSnapshotSet)
		(
		IN VSS_PWSZ		pwszVolumeName,
		IN VSS_ID		ProviderId,
		OUT VSS_ID		*pidSnapshot
		) = 0;

	// create the snapshot set
	STDMETHOD(DoSnapshotSet)
		(
		OUT IVssAsync** 	ppAsync
		) = 0;

   	STDMETHOD(DeleteSnapshots)
		(
		IN VSS_ID		SourceObjectId,
		IN VSS_OBJECT_TYPE 	eSourceObjectType,
		IN BOOL			bForceDelete,
		IN LONG*		plDeletedSnapshots,
		IN VSS_ID*		pNondeletedSnapshotID
		) = 0;

    STDMETHOD(ImportSnapshots)
		(
		OUT IVssAsync**		ppAsync
		) = 0;

	STDMETHOD(BreakSnapshotSet)
		(
		IN VSS_ID			SnapshotSetId
		) = 0;

	STDMETHOD(GetSnapshotProperties)
		(
		IN VSS_ID		SnapshotId,
		OUT VSS_SNAPSHOT_PROP	*pProp
		) = 0;

	STDMETHOD(Query)
		(
		IN VSS_ID		QueriedObjectId,
		IN VSS_OBJECT_TYPE	eQueriedObjectType,
		IN VSS_OBJECT_TYPE	eReturnedObjectsType,
		IN IVssEnumObject 	**ppEnum
		) = 0;

	STDMETHOD(IsVolumeSupported)
		(
		IN VSS_ID ProviderId,
        IN VSS_PWSZ pwszVolumeName,
        IN BOOL * pbSupportedByThisProvider
		) = 0;

    STDMETHOD(DisableWriterClasses)
		(
		IN const VSS_ID *rgWriterClassId,
		IN UINT cClassId
		) = 0;

    STDMETHOD(EnableWriterClasses)
		(
		IN const VSS_ID *rgWriterClassId,
		IN UINT cClassId
		) = 0;

    STDMETHOD(DisableWriterInstances)
		(
		IN const VSS_ID *rgWriterInstanceId,
		IN UINT cInstanceId
		) = 0;

    // called to expose a snapshot
    STDMETHOD(ExposeSnapshot)
		(
        IN VSS_ID SnapshotId,
        IN VSS_PWSZ wszPathFromRoot,
        IN LONG lAttributes,
        IN VSS_PWSZ wszExpose,
        OUT VSS_PWSZ *pwszExposed
        ) = 0;

    STDMETHOD(RevertToSnapshot)
    	(
    	IN VSS_ID SnapshotId,
    	IN BOOL bForceDismount
    	) = 0;

    STDMETHOD(QueryRevertStatus)
    	(
    	IN VSS_PWSZ pwszVolume,
    	OUT IVssAsync **ppAsync
    	) = 0;

	};

class __declspec(uuid("963f03ad-9e4c-4a34-ac15-e4b6174e5036")) IVssBackupComponentsEx : public IVssBackupComponents
        {
public:
        // get writer metadata for a specific writer
        STDMETHOD(GetWriterMetadataEx)
            (
            IN UINT iWriter,
            OUT VSS_ID *pidInstance,
            OUT IVssExamineWriterMetadataEx **ppMetadata
            ) = 0;

    // indicate that a given component is selected to be restored
    STDMETHOD(SetSelectedForRestoreEx)
		(
		IN VSS_ID writerId,
		IN VSS_COMPONENT_TYPE ct,
		IN LPCWSTR wszLogicalPath,
		IN LPCWSTR wszComponentName,
		IN bool bSelectedForRestore,
		IN VSS_ID instanceId = GUID_NULL
		) = 0;

        };

__declspec(dllexport) HRESULT STDAPICALLTYPE CreateVssBackupComponents(
    OUT IVssBackupComponents **ppBackup
    );

__declspec(dllexport) HRESULT STDAPICALLTYPE CreateVssExamineWriterMetadata (
    IN BSTR bstrXML,
    OUT IVssExamineWriterMetadata **ppMetadata
    );

#define VSS_SW_BOOTABLE_STATE	(1 << 0)

__declspec(dllexport) HRESULT APIENTRY SimulateSnapshotFreeze (
    IN GUID         guidSnapshotSetId,
    IN ULONG        ulOptionFlags,
    IN ULONG        ulVolumeCount,
    IN LPWSTR      *ppwszVolumeNamesArray,
    OUT IVssAsync **ppAsync
    );

__declspec(dllexport) HRESULT APIENTRY SimulateSnapshotThaw(
    IN GUID guidSnapshotSetId
    );

__declspec(dllexport) HRESULT APIENTRY IsVolumeSnapshotted(
    IN VSS_PWSZ  pwszVolumeName,
    OUT BOOL    *pbSnapshotsPresent,
    OUT LONG	*plSnapshotCapability
    );

/////////////////////////////////////////////////////////////////////
// Life-management methods for structure members

__declspec(dllexport) void APIENTRY VssFreeSnapshotProperties(
    IN VSS_SNAPSHOT_PROP*  pProp
    );

///

#endif // _VSBACKUP_H_


text:
package org.apache.solr.handler.component;

import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexableField;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.schema.FieldType;
import org.apache.solr.common.params.GroupCollapseParams;
import org.apache.solr.common.params.SolrParams;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.response.SolrQueryResponse;
import org.apache.solr.schema.IndexSchema;
import org.apache.solr.search.DocSlice;
import org.apache.solr.search.SolrIndexSearcher;
import org.apache.solr.search.grouping.GroupingSpecification;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import static org.junit.Assert.*;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.*;
import static org.mockito.MockitoAnnotations.initMocks;

/**
 * @author rmerizalde
 */
@RunWith(PowerMockRunner.class)
@PowerMockIgnore("org.jacoco.agent.rt.*")
@PrepareForTest({GroupCollapseComponent.class, IndexSchema.class, Document.class, org.apache.lucene.document.FieldType.NumericType.class})
public class GroupCollapseComponentTest {

    private static final String FIELD_PRICE = "price";
    private static final String FIELD_DISCOUNT = "discount";
    private static final String FIELD_CLOSEOUT = "isCloseout";
    private static final String FIELD_COLOR = "color";
    private static final String FIELD_COLORFAMILY = "colorFamily";

    @Mock
    private ResponseBuilder rb;

    @Mock
    private SolrQueryRequest req;

    @Mock
    private SolrQueryResponse rsp;

    @Mock
    private SolrIndexSearcher searcher;

    @Mock
    private SolrParams params;

    private IndexSchema schema;

    @Mock
    private FieldType priceType;

    @Mock
    private FieldType discountType;

    @Mock
    private FieldType booleanType;

    @Mock
    private FieldType stringType;

    @Mock
    private GroupingSpecification groupSpec;

    private org.apache.lucene.document.FieldType.NumericType numericType;

    private GroupCollapseComponent component = new GroupCollapseComponent();

    @Before
    public void setUp() throws Exception {

        Answer<GroupCollapseSummary> answer = new Answer<GroupCollapseSummary>() {

            @Override
            public GroupCollapseSummary answer(InvocationOnMock invocation)
                    throws Throwable {
                Object[] args = invocation.getArguments();
                DummyGroupCollapseSummary dummyObject = new DummyGroupCollapseSummary((String)args[0], (SolrIndexSearcher)args[1],(Set<String>) args[2],(String) args[3]);
                return dummyObject;
            }
        };

        PowerMockito.whenNew(GroupCollapseSummary.class).withAnyArguments().thenAnswer(answer);

        initMocks(this);

        schema = PowerMockito.mock(IndexSchema.class);

        rb.req = req;
        rb.rsp = rsp;
        when(rb.getGroupingSpec()).thenReturn(groupSpec);
        when(req.getParams()).thenReturn(params);
        when(req.getSchema()).thenReturn(schema);
        when(req.getSearcher()).thenReturn(searcher);
        mockResponse();

        when(schema.getFieldType(FIELD_PRICE)).thenReturn(priceType);
        when(schema.getFieldType(FIELD_DISCOUNT)).thenReturn(discountType);
        when(schema.getFieldType(FIELD_CLOSEOUT)).thenReturn(booleanType);
        when(schema.getFieldType(FIELD_COLOR)).thenReturn(stringType);
        when(schema.getFieldType(FIELD_COLORFAMILY)).thenReturn(stringType);

        numericType = PowerMockito.mock(org.apache.lucene.document.FieldType.NumericType.class);
        when(priceType.getNumericType()).thenReturn(numericType);
        when(priceType.getTypeName()).thenReturn("tfloat");
        when(discountType.getNumericType()).thenReturn(numericType);
        when(discountType.getTypeName()).thenReturn("tint");
        when(booleanType.getTypeName()).thenReturn("boolean");
        when(stringType.getTypeName()).thenReturn("string");

        when(groupSpec.getFields()).thenReturn(new String[] { "productId" } );
    }

    @Test
    public void testNoGrouping() throws IOException {
        when(rb.grouping()).thenReturn(false);
        component.process(rb);
        verify(rb).grouping();
        verifyNoMoreInteractions(rb);
    }

    @Test
    public void testNoGroupCollapse() throws IOException {
        when(rb.grouping()).thenReturn(true);
        when(params.getBool(GroupCollapseParams.GROUP_COLLAPSE, false)).thenReturn(false);
        component.process(rb);
        verify(rb).grouping();
        verify(params).getBool(GroupCollapseParams.GROUP_COLLAPSE, false);
        verifyNoMoreInteractions(rb);
        verifyNoMoreInteractions(params);
    }

    @Test
    public void testNoGroupCollapseFl() throws IOException {
        when(rb.grouping()).thenReturn(true);
        when(params.getBool(GroupCollapseParams.GROUP_COLLAPSE, false)).thenReturn(true);
        component.process(rb);
        verify(rb).grouping();
        verify(params).getBool(GroupCollapseParams.GROUP_COLLAPSE, false);
        verify(params).get(GroupCollapseParams.GROUP_COLLAPSE_FL);
        verifyNoMoreInteractions(rb);
        verifyNoMoreInteractions(params);
    }

    @Test
    public void testGroupCollapseNoGroups() throws IOException {

        NamedList values = mock(NamedList.class);
        when(rsp.getValues()).thenReturn(values);
        when(values.get("grouped")).thenReturn(null);

        when(rb.grouping()).thenReturn(true);
        when(params.getBool(GroupCollapseParams.GROUP_COLLAPSE, false)).thenReturn(true);
        when(params.get(GroupCollapseParams.GROUP_COLLAPSE_FL)).thenReturn("price,discount,isCloseout");
        component.process(rb);

        verify(rsp, never()).add(anyString(), anyObject());
    }

    @Test
    public void testGroupCollapse() throws IOException {
        when(rb.grouping()).thenReturn(true);
        when(params.getBool(GroupCollapseParams.GROUP_COLLAPSE, false)).thenReturn(true);
        when(params.get(GroupCollapseParams.GROUP_COLLAPSE_FL)).thenReturn("price,discount,isCloseout,color,colorFamily");
        component.process(rb);
        verify(rb).grouping();
        verify(rb).getGroupingSpec();
        verify(params).getBool(GroupCollapseParams.GROUP_COLLAPSE, false);
        verify(params).get(GroupCollapseParams.GROUP_COLLAPSE_FL);
        verify(params).get(GroupCollapseParams.GROUP_COLLAPSE_FF);
        verify(params).getParams(GroupCollapseParams.GROUP_COLLAPSE_FQ);

        verifyNoMoreInteractions(rb);
        verifyNoMoreInteractions(params);

        ArgumentCaptor<NamedList> namedListArgument = ArgumentCaptor.forClass(NamedList.class);
        verify(rsp).add(eq("groups_summary"), namedListArgument.capture());

        NamedList groupsSummary = namedListArgument.getValue();
        NamedList productId = (NamedList) groupsSummary.get("productId");
        assertNotNull(productId);
        Set<String> colorFamilies = new HashSet<String>();
        colorFamilies.add("RedColorFamily");
        colorFamilies.add("BlackColorFamily");
        verifyProductSummary((NamedList) productId.get("product1"), 80.0f, 100.0f, 0.0f, 20.0f, 2, colorFamilies);
        colorFamilies = new HashSet<String>();
        colorFamilies.add("OrangeColorFamily");
        colorFamilies.add("BrownColorFamily");
        verifyProductSummary((NamedList) productId.get("product2"), 60.0f, 80.0f, 20.0f, 40.0f, 2, colorFamilies);
    }

    @Test
    public void testGroupCollapseFilterField() throws IOException {
        when(rb.grouping()).thenReturn(true);
        when(params.getBool(GroupCollapseParams.GROUP_COLLAPSE, false)).thenReturn(true);
        when(params.get(GroupCollapseParams.GROUP_COLLAPSE_FL)).thenReturn("price,discount,isCloseout,color,colorFamily");
        when(params.get(GroupCollapseParams.GROUP_COLLAPSE_FF)).thenReturn(FIELD_CLOSEOUT);
        component.process(rb);
        verify(rb).grouping();
        verify(rb).getGroupingSpec();
        verify(params).getBool(GroupCollapseParams.GROUP_COLLAPSE, false);
        verify(params).get(GroupCollapseParams.GROUP_COLLAPSE_FL);
        verify(params).get(GroupCollapseParams.GROUP_COLLAPSE_FF);
        verify(params).getParams(GroupCollapseParams.GROUP_COLLAPSE_FQ);
        verifyNoMoreInteractions(rb);
        verifyNoMoreInteractions(params);

        ArgumentCaptor<NamedList> namedListArgument = ArgumentCaptor.forClass(NamedList.class);
        verify(rsp).add(eq("groups_summary"), namedListArgument.capture());

        NamedList groupsSummary = namedListArgument.getValue();
        NamedList productId = (NamedList) groupsSummary.get("productId");
        assertNotNull(productId);
        Set<String> colorFamilies = new HashSet<String>();
        colorFamilies.add("RedColorFamily");
        verifyProductSummary((NamedList) productId.get("product1"), 100.0f, 100.0f, 0.0f, 0.0f, 1, colorFamilies);
        colorFamilies = new HashSet<String>();
        colorFamilies.add("BrownColorFamily");
        verifyProductSummary((NamedList) productId.get("product2"), 60.0f, 60.0f, 40.0f, 40.0f, 1, colorFamilies);
    }

    @Test
    public void testGroupCollapseFilterFieldAllFiltered() throws IOException {
        mockResponse(true);
        when(rb.grouping()).thenReturn(true);
        when(params.getBool(GroupCollapseParams.GROUP_COLLAPSE, false)).thenReturn(true);
        when(params.get(GroupCollapseParams.GROUP_COLLAPSE_FL)).thenReturn("price,discount,isCloseout,color,colorFamily");
        when(params.get(GroupCollapseParams.GROUP_COLLAPSE_FF)).thenReturn(FIELD_CLOSEOUT);
        component.process(rb);
        verify(rb).grouping();
        verify(rb).getGroupingSpec();
        verify(params).getBool(GroupCollapseParams.GROUP_COLLAPSE, false);
        verify(params).get(GroupCollapseParams.GROUP_COLLAPSE_FL);
        verify(params).get(GroupCollapseParams.GROUP_COLLAPSE_FF);
        verify(params).getParams(GroupCollapseParams.GROUP_COLLAPSE_FQ);
        verifyNoMoreInteractions(rb);
        verifyNoMoreInteractions(params);

        ArgumentCaptor<NamedList> namedListArgument = ArgumentCaptor.forClass(NamedList.class);
        verify(rsp).add(eq("groups_summary"), namedListArgument.capture());

        NamedList groupsSummary = namedListArgument.getValue();
        NamedList productId = (NamedList) groupsSummary.get("productId");
        assertNotNull(productId);
        Set<String> colorFamilies = new HashSet<String>();
        colorFamilies.add("RedColorFamily");
        colorFamilies.add("BlackColorFamily");
        verifyProductSummary((NamedList) productId.get("product1"), 80.0f, 100.0f, 0.0f, 20.0f, 2, colorFamilies);
        colorFamilies = new HashSet<String>();
        colorFamilies.add("OrangeColorFamily");
        colorFamilies.add("BrownColorFamily");
        verifyProductSummary((NamedList) productId.get("product2"), 60.0f, 80.0f, 20.0f, 40.0f, 2, colorFamilies);
    }

    private void verifyProductSummary(NamedList productSummary, Float expectedMinPrice, Float expectedMaxPrice, Float expectedMinDiscount, Float expectedMaxDiscount, int colorCount, Set<String> colorFamilies) {
        assertNotNull(productSummary);
        verifyFloatField((NamedList) productSummary.get(FIELD_PRICE), expectedMinPrice, expectedMaxPrice);
        verifyFloatField((NamedList) productSummary.get(FIELD_DISCOUNT), expectedMinDiscount, expectedMaxDiscount);
        verifyIntField((NamedList) productSummary.get(FIELD_COLOR), colorCount);
        verifyStringSetField((NamedList) productSummary.get(FIELD_COLORFAMILY), colorFamilies);
    }

    private void verifyIntField(NamedList field, int colorCount) {
        if (field == null) {
            assertEquals(colorCount, 0);
            return;
        }
        Integer fieldColorCount = (Integer) field.get("count");
        assertEquals(colorCount, fieldColorCount.intValue());
    }

    private void verifyStringSetField(NamedList field, Set<String> colorFamilies) {
        if(field == null) {
            assertNull(colorFamilies);
            return;
        }
        Set<String> fieldColorFamilies = (Set<String>) field.get("families");
        assertEquals(fieldColorFamilies.size(), colorFamilies.size());
        List<String> listSource = new ArrayList<String>();
        listSource.addAll(colorFamilies);
        List<String> targetSource = new ArrayList<String>();
        targetSource.addAll(fieldColorFamilies);
        assertEquals(listSource.get(0), targetSource.get(0));
    }

    private void verifyFloatField(NamedList field, Float expectedMin, Float expectedMax) {
        Float min = (Float) field.get("min");
        assertEquals(expectedMin, min);

        Float max = (Float) field.get("max");
        assertEquals(expectedMax, max);
    }

    private void mockResponse() throws IOException {
        mockResponse(false);
    }

    private void mockResponse(boolean allDocsCloseout) throws IOException {
        NamedList values = mock(NamedList.class);
        NamedList grouped = mock(NamedList.class);
        NamedList productId = mock(NamedList.class);

        when(rsp.getValues()).thenReturn(values);

        when(values.get("grouped")).thenReturn(grouped);

        when(grouped.get("productId")).thenReturn(productId);

        List groups = new ArrayList();
        when(productId.get("groups")).thenReturn(groups);

        int[] docIds = new int[] {1,2,3,4};
        float[] scores = new float[] {1.0f, 1.0f, 1.0f, 1.0f};

        NamedList firstProduct = mock(NamedList.class);
        DocSlice firstDocList = new DocSlice(0, 2, docIds, scores, 2, 1.0f);
        NamedList secondProduct = mock(NamedList.class);
        DocSlice secondDocList = new DocSlice(2, 2, docIds, scores, 2, 1.0f);

        if(allDocsCloseout) {
            mockDocument(1, 100.0, 0.0, true);
            mockDocument(2, 80.0, 20.0, true);
            mockDocument(3, 80.0, 20.0, true);
            mockDocument(4, 60.0, 40.0, true);
        }
        else {
            mockDocument(1, 100.0, 0.0, false);
            mockDocument(2, 80.0, 20.0, true);
            mockDocument(3, 80.0, 20.0, true);
            mockDocument(4, 60.0, 40.0, false);
        }

        groups.add(firstProduct);
        groups.add(secondProduct);

        when(firstProduct.get("groupValue")).thenReturn("product1");
        when(firstProduct.get("doclist")).thenReturn(firstDocList);

        when(secondProduct.get("groupValue")).thenReturn("product2");
        when(secondProduct.get("doclist")).thenReturn(secondDocList);
    }

    private void mockDocument(int docId, double price, double discount) throws IOException {
        mockDocument(docId, price, discount, false);
    }

    private void mockDocument(int docId, double price, double discount, boolean isCloseout) throws IOException {
        Document doc = PowerMockito.mock(Document.class);
        when(searcher.doc(eq(docId), any(Set.class))).thenReturn(doc);
        when(searcher.getSchema()).thenReturn(schema);

        IndexableField priceField = mock(IndexableField.class);
        when(doc.getField(FIELD_PRICE)).thenReturn(priceField);
        when(priceField.numericValue()).thenReturn(new Double(price));

        IndexableField discountField = mock(IndexableField.class);
        when(doc.getField(FIELD_DISCOUNT)).thenReturn(discountField);
        when(discountField.numericValue()).thenReturn(new Double(discount));

        IndexableField closeoutField = mock(IndexableField.class);
        when(doc.getField(FIELD_CLOSEOUT)).thenReturn(closeoutField);
        when(closeoutField.stringValue()).thenReturn(isCloseout? "T" : "F");
    }

}

class DummyGroupCollapseSummary extends GroupCollapseSummary {

    DummyGroupCollapseSummary(String groupField, SolrIndexSearcher searcher,
            Set<String> fieldNames, String filterField) {
        super(groupField, searcher, fieldNames, filterField);
        // TODO Auto-generated constructor stub
    }

    @Override
    protected String getFieldValueFromTermVector(int docId, String fieldName) {
        String output = new String();
        if(docId == 1 && fieldName.equals("color")) {
            output = "RedColor";
        } else if (docId==1 && fieldName.equals("colorFamily")) {
            output = "RedColorFamily";
        } else if (docId==2 && fieldName.equals("color")) {
            output = "BlackColor";
        } else if (docId==2 && fieldName.equals("colorFamily")) {
            output = "BlackColorFamily";
        } else if(docId == 3 && fieldName.equals("color")) {
            output = "OrangeColor";
        } else if (docId==3 && fieldName.equals("colorFamily")) {
            output = "OrangeColorFamily";
        } else if (docId==4 && fieldName.equals("color")) {
            output = "BrownColor";
        } else if (docId==4 && fieldName.equals("colorFamily")) {
            output = "BrownColorFamily";
        }
        if(output.length() > 0) {
            return output;
        }
        return null;
    }
}


text:
require 'chef_resource/type'

module ChefResource
  module Resource
    #
    # The methods on a Resource class.  Generally extended into the class, and
    # become class-level methods (Class.default(x))
    #
    module ResourceType
      include Type

      #
      # Opens a resource for reading and updating.
      #
      # This method should be passed enough data to uniquely identify the
      # resource so it can be retrieved.
      #
      # The resulting object is generally *lazily* loaded, and may not hit the
      # network or file until you read a value.  This allows you to update
      # values in some cases without incurring the cost of a read.
      #
      # @return An open Resource which:
      # - Is a Resource
      # - Is a Resource even if the actual value does not exist
      # - Can be modified for update
      # - `type.is_valid?(resource, resource)` is true
      #
      def open(&define_identity_block)
        resource = new
        resource.instance_eval(&define_identity_block)
        resource.resource_identity_defined if resource.resource_state == :created
        resource
      end

      #
      # Gets the current value of a resource (immediately).  This method must
      # be passed enough data to uniquely identify the resource so it can be
      # retrieved.
      #
      # The default implementation (ResourceType.get) calls open(*args) { load }
      #
      # @return A readonly resource value with values filled in; or nil if the
      # resource does not exist.
      #
      def get(*args, &define_identity_block)
        resource = open(*args) do
          instance_eval(&define_identity_block) if define_identity_block
          load
        end
        resource.resource_fully_defined
        resource
      end

      #
      # Updates a resource.  By default, opens the resource, evaluates the
      # block, and calls update().
      #
      # @param open_args Arguments to pass to open()
      # @param update_block The block to run instance_eval on.
      #
      # @example
      #   FileResource.update('/x/y.txt') do
      #     mode 0777
      #   end
      #
      def update(*open_args, &update_block)
        resource = open(*args)
        resource.instance_eval(&update_block)
        resource.resource_fully_defined
        resource.update_resource
      end
    end
  end
end


text:
package org.thoughts.on.java.model;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.ParameterMode;
import javax.persistence.Persistence;
import javax.persistence.StoredProcedureQuery;

import org.apache.log4j.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class TestStoredProcedureQuery {

	Logger log = Logger.getLogger(this.getClass().getName());

	private EntityManagerFactory emf;

    @Before
    public void init() {
        emf = Persistence.createEntityManagerFactory("my-persistence-unit");
    }

    @After
    public void close() {
        emf.close();
    }

	@Test
	public void calculate() {
		log.info("... calculate ...");
		EntityManager em = emf.createEntityManager();
        em.getTransaction().begin();

		// define the stored procedure
		StoredProcedureQuery query = em.createStoredProcedureQuery("calculate");
		query.registerStoredProcedureParameter("x", Double.class, ParameterMode.IN);
		query.registerStoredProcedureParameter("y", Double.class, ParameterMode.IN);
		query.registerStoredProcedureParameter("sum", Double.class, ParameterMode.OUT);

		// set input parameter
		query.setParameter("x", 1.23d);
		query.setParameter("y", 4d);

		// call the stored procedure and get the result
		query.execute();
		Double sum = (Double) query.getOutputParameterValue("sum");
		log.info("Calculation result: 1.23 + 4 = " + sum);

        em.getTransaction().commit();
        em.close();
	}
}


text:
use time::{SteadyTime, Duration as TimeDuration};

/// How long to wait for an Ack after we ping
const PING_TIMING_DEFAULT_MS: i64 = 1000;
/// How long to wait for an Ack after we PingReq - should be at least 2x the PING_TIMING_DEFAULT_MS
const PINGREQ_TIMING_DEFAULT_MS: i64 = 2100;
/// How many protocol periods before a suspect member is marked as confirmed.
const SUSPICION_TIMEOUT_DEFAULT_PROTOCOL_PERIODS: i64 = 3;
/// How long is the gossip period
const GOSSIP_PERIOD_DEFAULT_MS: i64 = 1000;
/// How long before we set a confirmed member to a departed member, removing them from quorums
///   just for your own sanity - this is 3 days.
const DEPARTURE_TIMEOUT_DEFAULT_MS: i64 = 259200000;

/// The timing of the outbound threads.
#[derive(Debug, Clone)]
pub struct Timing {
    pub ping_ms: i64,
    pub pingreq_ms: i64,
    pub gossip_period_ms: i64,
    pub suspicion_timeout_protocol_periods: i64,
    pub departure_timeout_ms: i64,
}

impl Default for Timing {
    fn default() -> Timing {
        Timing {
            ping_ms: PING_TIMING_DEFAULT_MS,
            pingreq_ms: PINGREQ_TIMING_DEFAULT_MS,
            gossip_period_ms: GOSSIP_PERIOD_DEFAULT_MS,
            suspicion_timeout_protocol_periods: SUSPICION_TIMEOUT_DEFAULT_PROTOCOL_PERIODS,
            departure_timeout_ms: DEPARTURE_TIMEOUT_DEFAULT_MS,
        }
    }
}

impl Timing {
    /// Set up a new Timing
    pub fn new(
        ping_ms: i64,
        pingreq_ms: i64,
        gossip_period_ms: i64,
        suspicion_timeout_protocol_periods: i64,
        departure_timeout_ms: i64,
    ) -> Timing {
        Timing {
            ping_ms: ping_ms,
            pingreq_ms: pingreq_ms,
            gossip_period_ms: gossip_period_ms,
            suspicion_timeout_protocol_periods: suspicion_timeout_protocol_periods,
            departure_timeout_ms: departure_timeout_ms,
        }
    }

    /// When should this gossip period expire
    pub fn gossip_timeout(&self) -> SteadyTime {
        SteadyTime::now() + TimeDuration::milliseconds(self.gossip_period_ms)
    }

    /// How long is a protocol period, in millis.
    pub fn protocol_period_ms(&self) -> i64 {
        self.ping_ms + self.pingreq_ms
    }

    /// When should this ping record time out?
    pub fn ping_timeout(&self) -> SteadyTime {
        SteadyTime::now() + TimeDuration::milliseconds(self.ping_ms)
    }

    /// When should this pingreq timeout?
    pub fn pingreq_timeout(&self) -> SteadyTime {
        SteadyTime::now() + TimeDuration::milliseconds(self.pingreq_ms)
    }

    /// How long before the next scheduled protocol period
    pub fn next_protocol_period(&self) -> SteadyTime {
        SteadyTime::now() + TimeDuration::milliseconds(self.ping_ms + self.pingreq_ms)
    }

    /// How long before this suspect entry times out
    pub fn suspicion_timeout_duration(&self) -> TimeDuration {
        TimeDuration::milliseconds(
            self.protocol_period_ms() * self.suspicion_timeout_protocol_periods,
        )
    }

    pub fn departure_timeout_duration(&self) -> TimeDuration {
        TimeDuration::milliseconds(self.departure_timeout_ms)
    }
}


text:
#ifndef BERRYIPERSISTABLEELEMENT_H
#define BERRYIPERSISTABLEELEMENT_H

#include <berryIPersistable.h>

namespace berry {

/**
 * Interface for asking an object to store its state in a memento.
 *

 * This interface is typically included in interfaces where
 * persistance is required.
 *

 * When the workbench is shutdown objects which implement this interface
 * will be persisted.  At this time the GetFactoryId method
 * is invoked to discover the id of the element factory that will be used
 * to re-create the object from a memento.  Then the SaveState
 * method is invoked to store the element data into a newly created memento.
 * The resulting mementos are collected up and written out to a single file.
 *

 *

 * During workbench startup these mementos are read from the file.  The
 * factory Id for each is retrieved and mapped to an IElementFactory
 * which has been registered in the element factory extension point.  If a
 * factory exists for the Id it will be engaged to re-create the original
 * object.
 *

 *
 * @see IAdaptable
 * @see IMemento
 * @see IElementFactory
 */
struct IPersistableElement : public IPersistable
{
    /**
     * Returns the id of the element factory which should be used to re-create this
     * object.
     *

     * Factory ids are declared in extensions to the standard extension point
     * "org.eclipse.ui.elementFactories".
     *

     *
     * @return the element factory id
     * @see IElementFactory
     */
  virtual QString GetFactoryId() const = 0;
};

}

#endif // BERRYIPERSISTABLEELEMENT_H


text:
package zw.co.hitrac.payroll.business.impl;

/**
 * Hello world!
 *
 */
public class App
{
    public static void main( String[] args )
    {
        System.out.println( "Hello World!" );
    }
}