text:
from bottle import request, response
from six.moves.urllib.parse import quote

from webrecorder.basecontroller import BaseController, wr_api_spec
from webrecorder.models import User, Collection, Recording

# ============================================================================
class RecsController(BaseController):
    def init_routes(self):
        wr_api_spec.set_curr_tag('Recordings')

        @self.app.post('/api/v1/recordings')
        @self.api(query=['user', 'coll'],
                  req=['title', 'desc'],
                  resp='recording')
        def create_recording():
            user, collection = self.load_user_coll()

            data = request.json or {}

            title = data.get('title', '')
            desc = data.get('desc', '')

            recording = collection.create_recording(title=title, desc=desc)

            collection.mark_updated()

            return {'recording': recording.serialize()}

        @self.app.get('/api/v1/recordings')
        @self.api(query=['user', 'coll'],
                  resp='recordings')
        def get_recordings():
            user, collection = self.load_user_coll()

            recs = collection.get_recordings()

            return {'recordings': [rec.serialize() for rec in recs]}

        @self.app.get('/api/v1/recording/<rec>')
        @self.api(query=['user', 'coll'],
                  resp='recording')
        def get_recording(rec):
            user, collection, recording = self.load_recording(rec)

            if recording:
                return {'recording': recording.serialize()}
            else:
                self._raise_error(404, 'no_such_recording')

        @self.app.post('/api/v1/recording/<rec>')
        @self.api(query=['user', 'coll'],
                  req=['desc'],
                  resp='recording')
        def update_rec_desc(rec):
            user, collection, recording = self.load_recording(rec)

            user.access.assert_can_write_coll(collection)

            data = request.json or {}

            desc = data.get('desc', '')

            recording['desc'] = desc

            recording.mark_updated()
            return {'recording': recording.serialize()}

        @self.app.delete('/api/v1/recording/<rec>')
        @self.api(query=['user', 'coll'],
                  resp='deleted')
        def delete_recording(rec):
            user, collection, recording = self.load_recording(rec)

            errs = collection.remove_recording(recording, delete=True)
            if errs.get('error'):
                return self._raise_error(400, errs['error'])
            else:
                return {'deleted_id': rec}

        @self.app.post('/api/v1/recording/<rec>/move/<new_coll_name>')
        @self.api(query=['user', 'coll'],
                  resp='rec_move')
        def move_recording(rec, new_coll_name):
            user, collection, recording = self.load_recording(rec)

            new_collection = user.get_collection_by_name(new_coll_name)
            if not new_collection:
                self._raise_error(400, 'no_such_collection')

            user.access.assert_can_admin_coll(new_collection)

            new_rec = collection.move_recording(recording, new_collection)

            if new_rec:
                collection.mark_updated()
                new_collection.mark_updated()
                return {'coll_id': new_coll_name, 'rec_id': new_rec}
            else:
                self._raise_error(400, 'move_error')

        @self.app.post('/api/v1/recording/<rec>/copy/<new_coll_name>')
        @self.api(query=['user', 'coll'],
                  resp='recording')
        def copy_recording(rec, new_coll_name):
            user, collection, recording = self.load_recording(rec)

            new_collection = user.get_collection_by_name(new_coll_name)
            if not new_collection:
                return self._raise_error(400, 'no_such_collection')

            user.access.assert_can_write_coll(collection)
            user.access.assert_can_admin_coll(new_collection)

            new_rec = new_collection.create_recording()

            if new_rec.copy_data_from_recording(recording):
                new_rec.mark_updated()
                return {'recording': new_rec.serialize()}
            else:
                return self._raise_error(400, 'copy_error')

        @self.app.post('/api/v1/recording/<rec>/pages')
        @self.api(query=['user', 'coll'],
                  req=['url', 'timestamp', 'title', 'browser'],
                  resp='page_id')
        def add_page(rec):
            user, collection, recording = self.load_recording(rec)

            page_data = request.json or {}

            page_id = collection.add_page(page_data, recording)
            recording.mark_updated()
            return {'page_id': page_id}

        @self.app.get('/api/v1/recording/<rec>/pages')
        @self.api(query=['user', 'coll'],
                  resp='pages')
        def list_pages(rec):
            user, collection, recording = self.load_recording(rec)

            pages = collection.list_rec_pages(recording)
            return {'pages': pages}

        @self.app.get('/api/v1/recording/<rec>/num_pages')
        @self.api(query=['user', 'coll'],
                  resp='count_pages')
        def get_num_pages(rec):
            user, collection, recording = self.load_recording(rec)

            return {'count': recording.count_pages() }

        @self.app.delete('/api/v1/recording/<rec>/pages')
        @self.api(query=['user', 'coll'],
                  resp='deleted')
        def delete_page(rec):
            user, collection, recording = self.load_recording(rec)

            url = request.json.get('url')
            ts = request.json.get('timestamp')

            return recording.delete_page(url, ts)

        wr_api_spec.set_curr_tag(None)

    def load_recording(self, rec, user=None, coll_name=None):
        user, collection = self.load_user_coll(user=user, coll_name=coll_name)
        if not user or not collection:
            self._raise_error(404, 'no_such_recording')

        recording = collection.get_recording(rec)
        if not recording:
            self._raise_error(404, 'no_such_recording')

        return user, collection, recording


text:
#ifndef ALIDIGIT_H
#define ALIDIGIT_H

/* $Id$ */

////////////////////////////////////////////////
//  Base class for Alice Digits               //
////////////////////////////////////////////////

#include <assert.h>
#include "TObject.h"

class AliDigit : public TObject {
public:
  AliDigit();
  AliDigit(Int_t *track);
  virtual ~AliDigit() {}
  virtual Int_t *GetTracks() {return fTracks;}
  virtual Int_t GetTrack(Int_t i) const
  {assert(0<=i&&i<=2); return fTracks[i];}

protected:
  Int_t     fTracks[3];   //tracks number making this digit (up to 3)

  ClassDef(AliDigit,1)  //Base class for all Alice digits
};
#endif

redpajama_set_name: RedPajamaGithub


text:
echo "Configuring linux.dot.files... started"
for repo in "linux.dot.files"
    do
        ls -a "./repos/${repo}" | grep -E "^\.[a-zA-Z]" >| /tmp/temp

        for each_dot_file in `cat /tmp/temp`; do rm -rf "~/${each_dot_file}"; done

        for each_dot_file in `cat /tmp/temp`; do cp -rf "./repos/${repo}/${each_dot_file}" ~/; done
    done
echo "Configuring linux.dot.files... completed"

# Install all the Debian packages.
dpkg -i ./packages/*.deb


text:
package clientcmd

import (
	"fmt"
	"io"
	"sort"
	"strings"
	"time"

	"github.com/spf13/cobra"
	"github.com/spf13/pflag"

	"k8s.io/apimachinery/pkg/api/meta"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/labels"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/runtime/schema"
	"k8s.io/client-go/discovery"
	"k8s.io/client-go/pkg/apis/apps"
	kclientcmd "k8s.io/client-go/tools/clientcmd"
	"k8s.io/kubernetes/pkg/api"
	"k8s.io/kubernetes/pkg/api/v1"
	"k8s.io/kubernetes/pkg/apis/batch"
	"k8s.io/kubernetes/pkg/apis/extensions"
	kclientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset"
	"k8s.io/kubernetes/pkg/controller"
	kcmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
	"k8s.io/kubernetes/pkg/kubectl/resource"
	"k8s.io/kubernetes/pkg/printers"

	deployapi "github.com/openshift/origin/pkg/apps/apis/apps"
	deployutil "github.com/openshift/origin/pkg/apps/util"
	buildapi "github.com/openshift/origin/pkg/build/apis/build"
	"github.com/openshift/origin/pkg/cmd/util"
	imageapi "github.com/openshift/origin/pkg/image/apis/image"
)

// New creates a default Factory for commands that should share identical server
// connection behavior. Most commands should use this method to get a factory.
func New(flags *pflag.FlagSet) *Factory {
	f := NewFactory(nil)
	f.BindFlags(flags)

	return f
}

// Factory provides common options for OpenShift commands
type Factory struct {
	ClientAccessFactory
	kcmdutil.ObjectMappingFactory
	kcmdutil.BuilderFactory
}

var _ kcmdutil.Factory = &Factory{}

// NewFactory creates an object that holds common methods across all OpenShift commands
func NewFactory(optionalClientConfig kclientcmd.ClientConfig) *Factory {
	clientAccessFactory := NewClientAccessFactory(optionalClientConfig)
	objectMappingFactory := NewObjectMappingFactory(clientAccessFactory)
	builderFactory := kcmdutil.NewBuilderFactory(clientAccessFactory, objectMappingFactory)

	return &Factory{
		ClientAccessFactory:  clientAccessFactory,
		ObjectMappingFactory: objectMappingFactory,
		BuilderFactory:       builderFactory,
	}
}

// PrintResourceInfos receives a list of resource infos and prints versioned objects if a generic output format was specified
// otherwise, it iterates through info objects, printing each resource with a unique printer for its mapping
func (f *Factory) PrintResourceInfos(cmd *cobra.Command, isLocal bool, infos []*resource.Info, out io.Writer) error {
	// mirrors PrintResourceInfoForCommand upstream
	printer, err := f.PrinterForCommand(cmd, isLocal, nil, printers.PrintOptions{})
	if err != nil {
		return nil
	}
	if !printer.IsGeneric() {
		for _, info := range infos {
			mapping := info.ResourceMapping()
			printer, err := f.PrinterForMapping(cmd, isLocal, nil, mapping, false)
			if err != nil {
				return err
			}
			if err := printer.PrintObj(info.Object, out); err != nil {
				return nil
			}
		}
		return nil
	}

	printAsList := len(infos) != 1
	object, err := resource.AsVersionedObject(infos, printAsList, schema.GroupVersion{}, api.Codecs.LegacyCodec())
	if err != nil {
		return err
	}

	return printer.PrintObj(object, out)
}

// FlagBinder represents an interface that allows to bind extra flags into commands.
type FlagBinder interface {
	// Bound returns true if the flag is already bound to a command.
	Bound() bool
	// Bind allows to bind an extra flag to a command
	Bind(*pflag.FlagSet)
}

func ResourceMapper(f kcmdutil.Factory) *resource.Mapper {
	mapper, typer := f.Object()
	return &resource.Mapper{
		RESTMapper:   mapper,
		ObjectTyper:  typer,
		ClientMapper: resource.ClientMapperFunc(f.ClientForMapping),
	}
}

// UpdateObjectEnvironment update the environment variables in object specification.
func (f *Factory) UpdateObjectEnvironment(obj runtime.Object, fn func(*[]api.EnvVar) error) (bool, error) {
	switch t := obj.(type) {
	case *buildapi.BuildConfig:
		if t.Spec.Strategy.CustomStrategy != nil {
			return true, fn(&t.Spec.Strategy.CustomStrategy.Env)
		}
		if t.Spec.Strategy.SourceStrategy != nil {
			return true, fn(&t.Spec.Strategy.SourceStrategy.Env)
		}
		if t.Spec.Strategy.DockerStrategy != nil {
			return true, fn(&t.Spec.Strategy.DockerStrategy.Env)
		}
	}
	return false, fmt.Errorf("object does not contain any environment variables")
}

// ExtractFileContents returns a map of keys to contents, false if the object cannot support such an
// operation, or an error.
func (f *Factory) ExtractFileContents(obj runtime.Object) (map[string][]byte, bool, error) {
	switch t := obj.(type) {
	case *api.Secret:
		return t.Data, true, nil
	case *api.ConfigMap:
		out := make(map[string][]byte)
		for k, v := range t.Data {
			out[k] = []byte(v)
		}
		return out, true, nil
	default:
		return nil, false, nil
	}
}

// ApproximatePodTemplateForObject returns a pod template object for the provided source.
// It may return both an error and a object. It attempt to return the best possible template
// available at the current time.
func (f *Factory) ApproximatePodTemplateForObject(object runtime.Object) (*api.PodTemplateSpec, error) {
	switch t := object.(type) {
	case *imageapi.ImageStreamTag:
		// create a minimal pod spec that uses the image referenced by the istag without any introspection
		// it possible that we could someday do a better job introspecting it
		return &api.PodTemplateSpec{
			Spec: api.PodSpec{
				RestartPolicy: api.RestartPolicyNever,
				Containers: []api.Container{
					{Name: "container-00", Image: t.Image.DockerImageReference},
				},
			},
		}, nil
	case *imageapi.ImageStreamImage:
		// create a minimal pod spec that uses the image referenced by the istag without any introspection
		// it possible that we could someday do a better job introspecting it
		return &api.PodTemplateSpec{
			Spec: api.PodSpec{
				RestartPolicy: api.RestartPolicyNever,
				Containers: []api.Container{
					{Name: "container-00", Image: t.Image.DockerImageReference},
				},
			},
		}, nil
	case *deployapi.DeploymentConfig:
		fallback := t.Spec.Template

		kc, err := f.ClientSet()
		if err != nil {
			return fallback, err
		}

		latestDeploymentName := deployutil.LatestDeploymentNameForConfig(t)
		deployment, err := kc.Core().ReplicationControllers(t.Namespace).Get(latestDeploymentName, metav1.GetOptions{})
		if err != nil {
			return fallback, err
		}

		fallback = deployment.Spec.Template

		pods, err := kc.Core().Pods(deployment.Namespace).List(metav1.ListOptions{LabelSelector: labels.SelectorFromSet(deployment.Spec.Selector).String()})
		if err != nil {
			return fallback, err
		}

		for i := range pods.Items {
			pod := &pods.Items[i]
			if fallback == nil || pod.CreationTimestamp.Before(fallback.CreationTimestamp) {
				fallback = &api.PodTemplateSpec{
					ObjectMeta: pod.ObjectMeta,
					Spec:       pod.Spec,
				}
			}
		}
		return fallback, nil

	default:
		pod, err := f.AttachablePodForObject(object, 1*time.Minute)
		if pod != nil {
			return &api.PodTemplateSpec{
				ObjectMeta: pod.ObjectMeta,
				Spec:       pod.Spec,
			}, err
		}
		switch t := object.(type) {
		case *api.ReplicationController:
			return t.Spec.Template, err
		case *extensions.ReplicaSet:
			return &t.Spec.Template, err
		case *extensions.DaemonSet:
			return &t.Spec.Template, err
		case *batch.Job:
			return &t.Spec.Template, err
		}
		return nil, err
	}
}

func (f *Factory) PodForResource(resource string, timeout time.Duration) (string, error) {
	sortBy := func(pods []*v1.Pod) sort.Interface { return sort.Reverse(controller.ActivePods(pods)) }
	namespace, _, err := f.DefaultNamespace()
	if err != nil {
		return "", err
	}
	mapper, _ := f.Object()
	resourceType, name, err := util.ResolveResource(api.Resource("pods"), resource, mapper)
	if err != nil {
		return "", err
	}

	switch resourceType {
	case api.Resource("pods"):
		return name, nil
	case api.Resource("replicationcontrollers"):
		kc, err := f.ClientSet()
		if err != nil {
			return "", err
		}
		rc, err := kc.Core().ReplicationControllers(namespace).Get(name, metav1.GetOptions{})
		if err != nil {
			return "", err
		}
		selector := labels.SelectorFromSet(rc.Spec.Selector)
		pod, _, err := kcmdutil.GetFirstPod(kc.Core(), namespace, selector, timeout, sortBy)
		if err != nil {
			return "", err
		}
		return pod.Name, nil
	case deployapi.Resource("deploymentconfigs"), deployapi.LegacyResource("deploymentconfigs"):
		appsClient, err := f.OpenshiftInternalAppsClient()
		if err != nil {
			return "", err
		}
		kc, err := f.ClientSet()
		if err != nil {
			return "", err
		}
		dc, err := appsClient.Apps().DeploymentConfigs(namespace).Get(name, metav1.GetOptions{})
		if err != nil {
			return "", err
		}
		selector := labels.SelectorFromSet(dc.Spec.Selector)
		pod, _, err := kcmdutil.GetFirstPod(kc.Core(), namespace, selector, timeout, sortBy)
		if err != nil {
			return "", err
		}
		return pod.Name, nil
	case extensions.Resource("daemonsets"):
		kc, err := f.ClientSet()
		if err != nil {
			return "", err
		}
		ds, err := kc.Extensions().DaemonSets(namespace).Get(name, metav1.GetOptions{})
		if err != nil {
			return "", err
		}
		selector, err := metav1.LabelSelectorAsSelector(ds.Spec.Selector)
		if err != nil {
			return "", err
		}
		pod, _, err := kcmdutil.GetFirstPod(kc.Core(), namespace, selector, timeout, sortBy)
		if err != nil {
			return "", err
		}
		return pod.Name, nil
	case extensions.Resource("deployments"):
		kc, err := f.ClientSet()
		if err != nil {
			return "", err
		}
		d, err := kc.Extensions().Deployments(namespace).Get(name, metav1.GetOptions{})
		if err != nil {
			return "", err
		}
		selector, err := metav1.LabelSelectorAsSelector(d.Spec.Selector)
		if err != nil {
			return "", err
		}
		pod, _, err := kcmdutil.GetFirstPod(kc.Core(), namespace, selector, timeout, sortBy)
		if err != nil {
			return "", err
		}
		return pod.Name, nil
	case apps.Resource("statefulsets"):
		kc, err := f.ClientSet()
		if err != nil {
			return "", err
		}
		s, err := kc.Apps().StatefulSets(namespace).Get(name, metav1.GetOptions{})
		if err != nil {
			return "", err
		}
		selector, err := metav1.LabelSelectorAsSelector(s.Spec.Selector)
		if err != nil {
			return "", err
		}
		pod, _, err := kcmdutil.GetFirstPod(kc.Core(), namespace, selector, timeout, sortBy)
		if err != nil {
			return "", err
		}
		return pod.Name, nil
	case extensions.Resource("replicasets"):
		kc, err := f.ClientSet()
		if err != nil {
			return "", err
		}
		rs, err := kc.Extensions().ReplicaSets(namespace).Get(name, metav1.GetOptions{})
		if err != nil {
			return "", err
		}
		selector, err := metav1.LabelSelectorAsSelector(rs.Spec.Selector)
		if err != nil {
			return "", err
		}
		pod, _, err := kcmdutil.GetFirstPod(kc.Core(), namespace, selector, timeout, sortBy)
		if err != nil {
			return "", err
		}
		return pod.Name, nil
	case batch.Resource("jobs"):
		kc, err := f.ClientSet()
		if err != nil {
			return "", err
		}
		job, err := kc.Batch().Jobs(namespace).Get(name, metav1.GetOptions{})
		if err != nil {
			return "", err
		}
		return podNameForJob(job, kc, timeout, sortBy)
	default:
		return "", fmt.Errorf("remote shell for %s is not supported", resourceType)
	}
}

func podNameForJob(job *batch.Job, kc kclientset.Interface, timeout time.Duration, sortBy func(pods []*v1.Pod) sort.Interface) (string, error) {
	selector, err := metav1.LabelSelectorAsSelector(job.Spec.Selector)
	if err != nil {
		return "", err
	}
	pod, _, err := kcmdutil.GetFirstPod(kc.Core(), job.Namespace, selector, timeout, sortBy)
	if err != nil {
		return "", err
	}
	return pod.Name, nil
}

// FindAllCanonicalResources returns all resource names that map directly to their kind (Kind -> Resource -> Kind)
// and are not subresources. This is the closest mapping possible from the client side to resources that can be
// listed and updated. Note that this may return some virtual resources (like imagestreamtags) that can be otherwise
// represented.
// TODO: add a field to APIResources for "virtual" (or that points to the canonical resource).
// TODO: fallback to the scheme when discovery is not possible.
func FindAllCanonicalResources(d discovery.DiscoveryInterface, m meta.RESTMapper) ([]schema.GroupResource, error) {
	set := make(map[schema.GroupResource]struct{})
	all, err := d.ServerResources()
	if err != nil {
		return nil, err
	}
	for _, serverResource := range all {
		gv, err := schema.ParseGroupVersion(serverResource.GroupVersion)
		if err != nil {
			continue
		}
		for _, r := range serverResource.APIResources {
			// ignore subresources
			if strings.Contains(r.Name, "/") {
				continue
			}
			// because discovery info doesn't tell us whether the object is virtual or not, perform a lookup
			// by the kind for resource (which should be the canonical resource) and then verify that the reverse
			// lookup (KindsFor) does not error.
			if mapping, err := m.RESTMapping(schema.GroupKind{Group: gv.Group, Kind: r.Kind}, gv.Version); err == nil {
				if _, err := m.KindsFor(mapping.GroupVersionKind.GroupVersion().WithResource(mapping.Resource)); err == nil {
					set[schema.GroupResource{Group: mapping.GroupVersionKind.Group, Resource: mapping.Resource}] = struct{}{}
				}
			}
		}
	}
	var groupResources []schema.GroupResource
	for k := range set {
		groupResources = append(groupResources, k)
	}
	sort.Sort(groupResourcesByName(groupResources))
	return groupResources, nil
}

type groupResourcesByName []schema.GroupResource

func (g groupResourcesByName) Len() int { return len(g) }
func (g groupResourcesByName) Less(i, j int) bool {
	if g[i].Resource < g[j].Resource {
		return true
	}
	if g[i].Resource > g[j].Resource {
		return false
	}
	return g[i].Group < g[j].Group
}
func (g groupResourcesByName) Swap(i, j int) { g[i], g[j] = g[j], g[i] }


text:
1. Make sure that the escape str for Succubus is set to something else.
2. Make Sure that SF Credentials are changed.
3. Make Sure that Succubus & Chubbs have a new Postgres username & PW.
4. Prune out credentials from Git.


text: export type ConnectionType = 'WORKER' | 'SOURCE';


text:
package com.mgaetan89.showsrage.databinding;

import android.databinding.BindingAdapter;
import android.graphics.drawable.Drawable;
import android.support.annotation.ColorRes;
import android.support.annotation.StringRes;
import android.support.v4.content.ContextCompat;
import android.support.v4.graphics.drawable.DrawableCompat;
import android.widget.ImageView;
import android.widget.TextView;

import com.mgaetan89.showsrage.helper.ImageLoader;

public class Setters {
	@BindingAdapter("android:backgroundTint")
	public static void setBackgroundTint(TextView textView, @ColorRes int tint) {
		if (tint != 0) {
			Drawable background = DrawableCompat.wrap(textView.getBackground());
			DrawableCompat.setTint(background, ContextCompat.getColor(textView.getContext(), tint));
		}
	}

	@BindingAdapter({"bind:imageUrl", "bind:circle"})
	public static void setImageUrl(ImageView imageView, String imageUrl, boolean circle) {
		ImageLoader.load(imageView, imageUrl, circle);
	}

	@BindingAdapter("bind:selected")
	public static void setSelected(TextView textView, boolean selected) {
		textView.setSelected(selected);
	}

	@BindingAdapter("bind:textColorRes")
	public static void setTextColorRes(TextView textView, @ColorRes int colorRes) {
		textView.setTextColor(ContextCompat.getColor(textView.getContext(), colorRes));
	}

	@BindingAdapter("bind:textRes")
	public static void setTextRes(TextView textView, @StringRes int textRes) {
		if (textRes == 0) {
			textView.setText("");
		} else {
			textView.setText(textRes);
		}
	}
}


text:
const { DefinePlugin } = require('webpack');

module.exports = {
  onCreateWebpackChain(config) {
    config
      .plugin('define-plugin')
      // Add global env variable so we know that we are in
      // docz when the library is included in the build (allows
      // us to preconfigure library for the docs)
      .use(DefinePlugin, [{ __DOCZ__: JSON.stringify(true) }]);
  },

  // It doesn't work :'(
  codeSandbox: false,

  // Sort menu in a more appropriate order
  menu: [
    'Getting Started',
    'Core Principles',
    'FAQ',
    'Map',
    'Panorama',
    'GeoObjects',
    'Clusterization',
    'Controls',
    'YMaps Context',
    'Migration Guide',
  ],
};


text:
package me.jervyshi;

import java.util.List;

import me.jervyshi.repositories.UserRepository;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import me.jervyshi.entities.User;
import me.jervyshi.services.UserService;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations= "classpath:spring/spring-config.xml")
public class UserServiceTest
{
	@Autowired
	private UserService userService;

	@Test
	public void testFindAllusers() {
        UserRepository userRepository = mock(UserRepository.class);

        when(userRepository.findAllUsers()).thenThrow(new RuntimeException(""));

        userService.setUserRepository(userRepository);

		List<User> users = userService.findAllUsers();
		Assert.assertNotNull(users);
		for (User user : users) {
			System.err.println(user);
		}
        verify(userRepository).findAllUsers();
	}

    @Test
    public void testFindUser() {
        Integer id = 1;
        User user = userService.findUserById(id);
        Assert.assertNotNull(user);
        System.err.println(user);
    }
}


text:
package protohash

import (
	"crypto/sha256"
	"fmt"
	"math"
)

const hashLength int = sha256.Size

const (
	// Sorted alphabetically by value.
	boolIdentifier     = `b`
	mapIdentifier      = `d`
	floatIdentifier    = `f`
	intIdentifier      = `i`
	listIdentifier     = `l`
	nilIdentifier      = `n`
	byteIdentifier     = `r`
	unicodeIndentifier = `u`
)

func hash(t string, b []byte) ([]byte, error) {
	h := sha256.New()

	if _, err := h.Write([]byte(t)); err != nil {
		return nil, err
	}

	if _, err := h.Write(b); err != nil {
		return nil, err
	}

	return h.Sum(nil), nil
}

func hashBool(b bool) ([]byte, error) {
	bb := []byte(`0`)
	if b {
		bb = []byte(`1`)
	}
	return hash(boolIdentifier, bb)
}

func hashBytes(bs []byte) ([]byte, error) {
	return hash(byteIdentifier, bs)
}

func hashFloat(f float64) ([]byte, error) {
	var normalizedFloat string

	switch {
	case math.IsInf(f, 1):
		normalizedFloat = "Infinity"
	case math.IsInf(f, -1):
		normalizedFloat = "-Infinity"
	case math.IsNaN(f):
		normalizedFloat = "NaN"
	default:
		var err error
		normalizedFloat, err = floatNormalize(f)
		if err != nil {
			return nil, err
		}
	}

	return hash(floatIdentifier, []byte(normalizedFloat))
}

func hashInt64(i int64) ([]byte, error) {
	return hash(intIdentifier, []byte(fmt.Sprintf("%d", i)))
}

func hashNil() ([]byte, error) {
	return hash(nilIdentifier, []byte(``))
}

func hashUint64(i uint64) ([]byte, error) {
	return hash(intIdentifier, []byte(fmt.Sprintf("%d", i)))
}

func hashUnicode(s string) ([]byte, error) {
	return hash(unicodeIndentifier, []byte(s))
}


text:
package com.microsoftopentechnologies.intellij.actions;

import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.LangDataKeys;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleTypeId;
import com.microsoftopentechnologies.intellij.ui.components.DefaultDialogWrapper;
import com.microsoftopentechnologies.intellij.ui.libraries.ApplicationInsightsPanel;

public class ApplicatioInsightsAction extends AnAction {
    @Override
    public void actionPerformed(AnActionEvent event) {
        final Module module = event.getData(LangDataKeys.MODULE);
        DefaultDialogWrapper dialog = new DefaultDialogWrapper(module.getProject(), new ApplicationInsightsPanel(module));
        dialog.show();
    }

    @Override
    public void update(AnActionEvent event) {
        final Module module = event.getData(LangDataKeys.MODULE);
        event.getPresentation().setEnabledAndVisible(module != null && ModuleTypeId.JAVA_MODULE.equals(module.getOptionValue(Module.ELEMENT_TYPE)));
    }
}


text:
using System.Data.Entity.ModelConfiguration;
using Server.Game.Database.Models;

namespace Server.Game.Database.Maps
{

    public class UserAccounConfiguration : EntityTypeConfiguration<UserAccount>
    {
        public UserAccounConfiguration()
        {
            // Primary Key
            HasKey(t => t.AccountId);

            // Properties
            Property(t => t.Username)
                .IsRequired()
                .HasMaxLength(45);

            // Properties
            Property(t => t.Password)
                .IsRequired()
                .HasMaxLength(45);

            // Properties
            Property(t => t.Email)
                .IsRequired()
                .HasMaxLength(45);

            Property(t => t.IsOnline)
                .IsRequired();

            HasMany(u => u.Heroes)
                .WithRequired(x => x.Account)
                .HasForeignKey(h => h.AccountId);
        }
    }
}


text:
<?php

namespace Acme\AnkBundle\Form\EventListener;

use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Acme\AnkBundle\Entity\Types\TreeQestionTypes;

class AddChoiseSubsriber implements EventSubscriberInterface {

    public static function getSubscribedEvents() {
        return array(FormEvents::PRE_SET_DATA => 'preSetData');
    }

    public function preSetData(FormEvent $event) {
        $questionType = new TreeQestionTypes();
        $data = $event->getData();
        $form = $event->getForm();

        if (is_null($data)) {
            return;
        }

        if ($data->getType() == TreeQestionTypes::PULSE_QUEST) {
            $form->add('choise', 'choice', array('choices' => array('n' => 'No', 'y' => 'Yes'),
                'multiple' => false,
                'expanded' => true,
                'required' => false,
                'label' => false));
        }
    }

}

?>


text:
class TestInteger : public CxxTest::TestSuite, public VMTest {
public:

  void setUp() {
    create();
  }

  void tearDown() {
    destroy();
  }

  void test_from_zero_yields_fixnum() {
    TS_ASSERT(kind_of<Fixnum>(Integer::from(state, 0)));
  }

  void test_kind_of_numeric() {
    Fixnum* fix = Fixnum::from(13);
    Bignum* big = Bignum::from(state, (native_int)14);
    Float*  flt = Float::create(state, 15.0);
    Object* obj = state->new_object<Object>(G(object));

    TS_ASSERT(kind_of<Numeric>(fix));
    TS_ASSERT(kind_of<Numeric>(big));
    TS_ASSERT(kind_of<Numeric>(flt));
    TS_ASSERT(!kind_of<Numeric>(obj));
    TS_ASSERT(!kind_of<Numeric>(cTrue));
    TS_ASSERT(!kind_of<Numeric>(cFalse));
    TS_ASSERT(!kind_of<Numeric>(cNil));
  }

  void test_from_native_int() {
    Integer* obj = Integer::from(state, (native_int)13);
    TS_ASSERT_EQUALS(obj->to_native(), (native_int) 13);

    obj = Integer::from(state, (native_int)-13);
    TS_ASSERT_EQUALS(obj->to_native(), (native_int)-13);

    obj = Integer::from(state, (native_int)2147483647);
    TS_ASSERT_EQUALS(obj->to_native(), (native_int)2147483647);
  }

  void test_from_int() {
    Integer* obj = Integer::from(state, (int)13);
    TS_ASSERT_EQUALS(obj->to_native(), (native_int) 13);

    obj = Integer::from(state, (int)-13);
    TS_ASSERT_EQUALS(obj->to_native(), (native_int)-13);

    obj = Integer::from(state, (int)2147483647);
    TS_ASSERT_EQUALS(obj->to_native(), (native_int)2147483647);
  }

  void test_from_unsigned_int() {
    Integer* obj = Integer::from(state, (unsigned int)13);
    TS_ASSERT_EQUALS(obj->to_native(), (native_int) 13);

    obj = Integer::from(state, (unsigned int)2147483647);
    TS_ASSERT_EQUALS(obj->to_native(), (native_int)2147483647);
  }

  void test_from_unsigned_long() {
    Integer* obj = Integer::from(state, (unsigned long)13);
    TS_ASSERT_EQUALS(obj->to_native(), (native_int) 13);

    obj = Integer::from(state, (unsigned long)2147483647);
    TS_ASSERT_EQUALS(obj->to_native(), (native_int)2147483647);
  }

  void test_from_long_long() {
    Integer* obj = Integer::from(state, (long long)13);
    TS_ASSERT_EQUALS(obj->to_native(), (native_int) 13);

    obj = Integer::from(state, (long long)-13);
    TS_ASSERT_EQUALS(obj->to_native(), (native_int)-13);

    obj = Integer::from(state, 9223372036854775807LL);
    TS_ASSERT_EQUALS(as<Bignum>(obj)->to_long_long(), 9223372036854775807LL);
  }

  void test_from_unsigned_long_long() {
    Integer* obj = Integer::from(state, (unsigned long long)13);
    TS_ASSERT_EQUALS(obj->to_native(), (native_int) 13);

    obj = Integer::from(state, (unsigned long long)-13);
    TS_ASSERT_EQUALS(obj->to_native(), (native_int)-13);

    obj = Integer::from(state, 9223372036854775808ULL);
    TS_ASSERT_EQUALS(as<Bignum>(obj)->to_ulong_long(), 9223372036854775808ULL);
  }
};


text:
package org.apache.flink.runtime.rest.handler.util;

import org.apache.flink.runtime.rest.handler.HandlerRequest;
import org.apache.flink.runtime.rest.handler.RestHandlerException;
import org.apache.flink.runtime.rest.messages.MessageParameters;
import org.apache.flink.runtime.rest.messages.MessageQueryParameter;
import org.apache.flink.runtime.rest.messages.RequestBody;
import org.apache.flink.util.function.SupplierWithException;

import org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpResponseStatus;

import org.slf4j.Logger;

import java.util.List;

/** Utils for getting query parameters from {@link HandlerRequest}. */
public class HandlerRequestUtils {

    /**
     * Returns the value of a query parameter, or {@code null} if the query parameter is not set.
     *
     * @throws RestHandlerException If the query parameter is repeated.
     */
    public static <
                    X,
                    P extends MessageQueryParameter<X>,
                    R extends RequestBody,
                    M extends MessageParameters>
            X getQueryParameter(
                    final HandlerRequest<R, M> request, final Class<P> queryParameterClass)
                    throws RestHandlerException {

        return getQueryParameter(request, queryParameterClass, null);
    }

    public static <
                    X,
                    P extends MessageQueryParameter<X>,
                    R extends RequestBody,
                    M extends MessageParameters>
            X getQueryParameter(
                    final HandlerRequest<R, M> request,
                    final Class<P> queryParameterClass,
                    final X defaultValue)
                    throws RestHandlerException {

        final List<X> values = request.getQueryParameter(queryParameterClass);
        final X value;
        if (values.size() > 1) {
            throw new RestHandlerException(
                    String.format("Expected only one value %s.", values),
                    HttpResponseStatus.BAD_REQUEST);
        } else if (values.size() == 1) {
            value = values.get(0);
        } else {
            value = defaultValue;
        }
        return value;
    }

    /**
     * Returns {@code requestValue} if it is not null, otherwise returns the query parameter value
     * if it is not null, otherwise returns the default value.
     */
    public static <T> T fromRequestBodyOrQueryParameter(
            T requestValue,
            SupplierWithException<T, RestHandlerException> queryParameterExtractor,
            T defaultValue,
            Logger log)
            throws RestHandlerException {
        if (requestValue != null) {
            return requestValue;
        } else {
            T queryParameterValue = queryParameterExtractor.get();
            if (queryParameterValue != null) {
                log.warn(
                        "Configuring the job submission via query parameters is deprecated."
                                + " Please migrate to submitting a JSON request instead.");
                return queryParameterValue;
            } else {
                return defaultValue;
            }
        }
    }
}


text:
// mqueue.h
// Copyright 2016 Robin.Rowe@Cinepaint.org
// License open source MIT

#ifndef mqueue_h
#define mqueue_h

#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include "../portable/SystemLog.h"

#ifndef __cplusplus
#error
#endif

struct mq_attr
{	int mq_flags;
	int mq_maxmsg;
	int mq_msgsize;
	int mq_curmsgs;
};

typedef intptr_t mqd_t;

inline
int MultiByteToWideChar(LPCSTR lpMultiByteStr,LPWSTR lpWideCharStr,int bufsize)
{	UINT codePage=CP_UTF8;
	DWORD dwFlags=0;
	int cbMultiByte=-1;
	return MultiByteToWideChar(codePage,
		dwFlags,
		lpMultiByteStr,
		cbMultiByte,
		lpWideCharStr,
		bufsize);
}

/* man mq_open:
Each message queue is identified by a name of the form '/somename'.
That is, a null-terminated string of up to NAME_MAX (i.e., 255)
characters consisting of an initial slash, followed by one or
more characters, none of which are slashes.
*/

inline
mqd_t mq_open(const char *name,int oflag,mode_t mode,mq_attr* attr=0)
{	const size_t bufsize=80;
	char pipeName[bufsize];
#pragma warning(disable:4996)
// This name must have the following form:
// LPTSTR lpszPipename = TEXT("\\\\.\\pipe\\mynamedpipe");
	strcpy(pipeName,"\\\\.\\pipe\\");
	strcat(pipeName,name+1);
	if(strchr(pipeName,'/'))
	{	TRACE("Invalid mq_open");
		return -1;
	}
	if(oflag & O_CREAT)
	{	DWORD openMode = 0;
		switch(oflag)
		{	default:
				return (mqd_t) -1;
			case O_CREAT | O_RDONLY:
				openMode = PIPE_ACCESS_INBOUND;
				break;
			case O_CREAT | O_WRONLY:
				openMode = PIPE_ACCESS_OUTBOUND;
				break;
			case O_CREAT | O_RDWR:
				openMode = PIPE_ACCESS_DUPLEX;
				break;
		}
		DWORD pipeMode = PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT | PIPE_REJECT_REMOTE_CLIENTS;
		DWORD kernelBufsize = 512;
		HANDLE hPipe = CreateNamedPipe(
			pipeName,
			openMode,
			pipeMode,
			PIPE_UNLIMITED_INSTANCES,
			kernelBufsize,
			kernelBufsize,
			NULL,
			NULL);
		if (hPipe == INVALID_HANDLE_VALUE)
		{	TRACE(0);
			return -1;
		}
		BOOL ok = ConnectNamedPipe(hPipe,NULL);
		if(!ok)
		{	TRACE(0);
			return -1;
		}
		return (mqd_t) hPipe;
	}
	DWORD dwDesiredAccess=0;
	DWORD dwShareMode=0;
	switch(oflag)
	{	case O_RDONLY:
			dwDesiredAccess|=GENERIC_READ;
			dwShareMode|=FILE_SHARE_READ;
			break;
		case O_WRONLY:
			dwDesiredAccess|=GENERIC_WRITE;
			dwShareMode|=FILE_SHARE_WRITE;
			break;
		case O_RDWR:
			dwDesiredAccess=GENERIC_READ | GENERIC_WRITE;
			dwShareMode=FILE_SHARE_READ | FILE_SHARE_WRITE;
			break;
    }
	HANDLE hPipe = CreateFileA(pipeName,
		dwDesiredAccess,
		dwShareMode,
		NULL,
		OPEN_EXISTING,
		FILE_ATTRIBUTE_NORMAL,
		NULL);
	if(hPipe == INVALID_HANDLE_VALUE)
	{	TRACE(0);
		return -1;
	}
	return (mqd_t) hPipe;
}

inline
int mq_send(mqd_t mqdes, const char *buffer,size_t bufsize, unsigned msg_prio)
{	if(msg_prio!=0)
	{	return -1;
	}
	HANDLE h = (HANDLE) mqdes;
	DWORD cbWritten;
	const BOOL ok = WriteFile(h,buffer,(DWORD)bufsize,&cbWritten,NULL);
	if (!ok)
	{	TRACE(0);
		return -1;
	}
	return cbWritten;
}

inline
ssize_t mq_receive(mqd_t mqdes,char* buffer,size_t bufsize,unsigned* msg_prio)
{   if(msg_prio!=0)
	{	TRACE(0);
		return -1;
	}
	HANDLE h = (HANDLE) mqdes;
	DWORD numRead;
	const BOOL ok = ReadFile(h,buffer,(DWORD) bufsize,&numRead,NULL);
	if(!ok) // || msgSize != numRead)
	{	TRACE(0);
		return -1;
	}
	return numRead;
}

inline
int mq_close(mqd_t mqdes)
{	if(mqdes < 0)
	{	return -1;
	}
	const BOOL ok = CloseHandle((HANDLE)mqdes);
	return ok ? 0:-1;
}

inline
int mq_unlink(const char* name)
{	(void) name;
	return 0;
}

#endif


text:
/* eslint-disable css-modules/no-unused-class */

import PropTypes from 'prop-types';
import React from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from '../NotificationContent.scss';

const TagDeleted = ({ loggedIn, user, tagName }) => {
  if (loggedIn) {
    return (

        {user}
        {' '}
deleted tag
        {' '}

“
          {tagName}
”

.

    );
  }
  return (

Tag

“
        {tagName}
”

      {' '}
was deleted.

  );
};

TagDeleted.propTypes = {
  loggedIn: PropTypes.bool.isRequired,
  user: PropTypes.string,
  tagName: PropTypes.string.isRequired
};

TagDeleted.defaultProps = {
  user: ''
};

export default withStyles(s)(TagDeleted);


text:
var slice = Array.prototype.slice;

function logger(namespace) {
	return function () {
		console.log.apply(console, [namespace].concat(slice.call(arguments)));
	};
}

module.exports = logger;


text:
import hammerhead from '../../deps/hammerhead';
import testCafeCore from '../../deps/testcafe-core';
import nextTick from '../../utils/next-tick';

var browserUtils   = hammerhead.utils.browser;
var eventSandbox   = hammerhead.sandbox.event;
var eventSimulator = hammerhead.eventSandbox.eventSimulator;
var listeners      = hammerhead.eventSandbox.listeners;

var domUtils        = testCafeCore.domUtils;
var contentEditable = testCafeCore.contentEditable;
var textSelection   = testCafeCore.textSelection;

const WHITE_SPACES_RE = / /g;

function _getSelectionInElement (element) {
    var currentSelection   = textSelection.getSelectionByElement(element);
    var isInverseSelection = textSelection.hasInverseSelectionContentEditable(element);

    if (textSelection.hasElementContainsSelection(element))
        return contentEditable.getSelection(element, currentSelection, isInverseSelection);

    // NOTE: if we type text to an element that doesn't contain selection we
    // assume the selectionStart and selectionEnd positions are null in this
    // element. So we calculate the necessary start and end nodes and offsets
    return {
        startPos: contentEditable.calculateNodeAndOffsetByPosition(element, 0),
        endPos:   contentEditable.calculateNodeAndOffsetByPosition(element, 0)
    };
}

function _updateSelectionAfterDeletionContent (element, selection) {
    var startNode      = selection.startPos.node;
    var hasStartParent = startNode.parentNode && startNode.parentElement;

    var browserRequiresSelectionUpdating = browserUtils.isChrome && browserUtils.version < 58 || browserUtils.isSafari;

    if (browserRequiresSelectionUpdating || !hasStartParent || !domUtils.isElementContainsNode(element, startNode)) {
        selection = _getSelectionInElement(element);

        if (textSelection.hasInverseSelectionContentEditable(element)) {
            selection = {
                startPos: selection.endPos,
                endPos:   selection.startPos
            };
        }
    }

    selection.endPos.offset = selection.startPos.offset;

    return selection;
}

function _typeTextInElementNode (elementNode, text, offset) {
    var nodeForTyping  = document.createTextNode(text);
    var textLength     = text.length;
    var selectPosition = { node: nodeForTyping, offset: textLength };

    if (domUtils.getTagName(elementNode) === 'br')
        elementNode.parentNode.insertBefore(nodeForTyping, elementNode);
    else if (offset > 0)
        elementNode.insertBefore(nodeForTyping, elementNode.childNodes[offset]);
    else
        elementNode.appendChild(nodeForTyping);

    textSelection.selectByNodesAndOffsets(selectPosition, selectPosition);
}

function _typeTextInChildTextNode (element, selection, text) {
    let startNode = selection.startPos.node;

    // NOTE: startNode could be moved or deleted on textInput event. Need ensure startNode.
    if (!domUtils.isElementContainsNode(element, startNode)) {
        selection = _excludeInvisibleSymbolsFromSelection(_getSelectionInElement(element));
        startNode = selection.startPos.node;
    }

    const startOffset    = selection.startPos.offset;
    const endOffset      = selection.endPos.offset;
    const nodeValue      = startNode.nodeValue;
    const selectPosition = { node: startNode, offset: startOffset + text.length };

    startNode.nodeValue = nodeValue.substring(0, startOffset) + text +
                          nodeValue.substring(endOffset, nodeValue.length);

    textSelection.selectByNodesAndOffsets(selectPosition, selectPosition);
}

function _excludeInvisibleSymbolsFromSelection (selection) {
    var startNode   = selection.startPos.node;
    var startOffset = selection.startPos.offset;
    var endOffset   = selection.endPos.offset;

    var firstNonWhitespaceSymbolIndex = contentEditable.getFirstNonWhitespaceSymbolIndex(startNode.nodeValue);
    var lastNonWhitespaceSymbolIndex  = contentEditable.getLastNonWhitespaceSymbolIndex(startNode.nodeValue);

    if (startOffset < firstNonWhitespaceSymbolIndex && startOffset !== 0) {
        selection.startPos.offset = firstNonWhitespaceSymbolIndex;
        selection.endPos.offset   = endOffset + firstNonWhitespaceSymbolIndex - startOffset;
    }
    else if (endOffset > lastNonWhitespaceSymbolIndex && endOffset !== startNode.nodeValue.length) {
        selection.startPos.offset = startNode.nodeValue.length;
        selection.endPos.offset   = endOffset + startNode.nodeValue.length - startOffset;
    }

    return selection;
}

// NOTE: Typing can be prevented in Chrome/Edge but can not be prevented in IE11 or Firefox
// Firefox does not support TextInput event
// Safari supports the TextInput event but has a bug: e.data is added to the node value.
// So in Safari we need to call preventDefault in the last textInput handler but not prevent the Input event

function simulateTextInput (element, text) {
    let forceInputInSafari;

    function onSafariTextInput (e) {
        e.preventDefault();

        forceInputInSafari = true;
    }

    function onSafariPreventTextInput (e) {
        if (e.type === 'textInput')
            forceInputInSafari = false;
    }

    if (browserUtils.isSafari) {
        listeners.addInternalEventListener(window, ['textInput'], onSafariTextInput);
        eventSandbox.on(eventSandbox.EVENT_PREVENTED_EVENT, onSafariPreventTextInput);
    }

    const isInputEventRequired = browserUtils.isFirefox || eventSimulator.textInput(element, text) || forceInputInSafari;

    if (browserUtils.isSafari) {
        listeners.removeInternalEventListener(window, ['textInput'], onSafariTextInput);
        eventSandbox.off(eventSandbox.EVENT_PREVENTED_EVENT, onSafariPreventTextInput);
    }

    return isInputEventRequired || browserUtils.isIE11;
}

function _typeTextToContentEditable (element, text) {
    var currentSelection    = _getSelectionInElement(element);
    var startNode           = currentSelection.startPos.node;
    var endNode             = currentSelection.endPos.node;
    var needProcessInput    = true;
    var needRaiseInputEvent = true;
    var textInputData       = text;

    text = text.replace(WHITE_SPACES_RE, String.fromCharCode(160));

    // NOTE: some browsers raise the 'input' event after the element
    // content is changed, but in others we should do it manually.

    var onInput = () => {
        needRaiseInputEvent = false;
    };

    // NOTE: IE11 raises the 'textinput' event many times after the element changed.
    // The 'textinput' should be called only once

    function onTextInput (event, dispatched, preventEvent) {
        preventEvent();
    }

    // NOTE: IE11 does not raise input event when type to contenteditable

    var beforeContentChanged = () => {
        needProcessInput    = simulateTextInput(element, textInputData);
        needRaiseInputEvent = needProcessInput && !browserUtils.isIE11;

        listeners.addInternalEventListener(window, ['input'], onInput);
        listeners.addInternalEventListener(window, ['textinput'], onTextInput);
    };

    var afterContentChanged = () => {
        nextTick()
            .then(() => {
                if (needRaiseInputEvent)
                    eventSimulator.input(element);

                listeners.removeInternalEventListener(window, ['input'], onInput);
                listeners.removeInternalEventListener(window, ['textinput'], onTextInput);
            });
    };

    if (!startNode || !endNode || !domUtils.isContentEditableElement(startNode) ||
        !domUtils.isContentEditableElement(endNode))
        return;

    if (!domUtils.isTheSameNode(startNode, endNode)) {
        textSelection.deleteSelectionContents(element);

        // NOTE: after deleting the selection contents we should refresh the stored startNode because
        // contentEditable element's content could change and we can no longer find parent elements
        // of the nodes. In MSEdge, 'parentElement' for the deleted element isn't undefined
        currentSelection = _updateSelectionAfterDeletionContent(element, currentSelection);
        startNode        = currentSelection.startPos.node;
    }

    if (!startNode || !domUtils.isContentEditableElement(startNode) || !domUtils.isRenderedNode(startNode))
        return;

    beforeContentChanged();

    if (needProcessInput) {
        // NOTE: we can type only to the text nodes; for nodes with the 'element-node' type, we use a special behavior
        if (domUtils.isElementNode(startNode))
            _typeTextInElementNode(startNode, text);
        else
            _typeTextInChildTextNode(element, _excludeInvisibleSymbolsFromSelection(currentSelection), text);
    }

    afterContentChanged();
}

function _typeTextToTextEditable (element, text) {
    var elementValue      = domUtils.getElementValue(element);
    var textLength        = text.length;
    var startSelection    = textSelection.getSelectionStart(element);
    var endSelection      = textSelection.getSelectionEnd(element);
    var isInputTypeNumber = domUtils.isInputElement(element) && element.type === 'number';
    var needProcessInput  = simulateTextInput(element, text);

    if (!needProcessInput)
        return;

    // NOTE: the 'maxlength' attribute doesn't work in all browsers. IE still doesn't support input with the 'number' type
    var elementMaxLength = !browserUtils.isIE && isInputTypeNumber ? null : parseInt(element.maxLength, 10);

    if (elementMaxLength < 0)
        elementMaxLength = browserUtils.isIE && browserUtils.version < 17 ? 0 : null;

    if (elementMaxLength === null || isNaN(elementMaxLength) || elementMaxLength > elementValue.length) {
        // NOTE: B254013
        if (isInputTypeNumber && browserUtils.isIOS && elementValue[elementValue.length - 1] === '.') {
            startSelection += 1;
            endSelection += 1;
        }

        domUtils.setElementValue(element, elementValue.substring(0, startSelection) + text +
                          elementValue.substring(endSelection, elementValue.length));

        textSelection.select(element, startSelection + textLength, startSelection + textLength);
    }

    // NOTE: We should simulate the 'input' event after typing a char (B253410, T138385)
    eventSimulator.input(element);
}

function _typeTextToNonTextEditable (element, text, caretPos) {
    if (caretPos !== null) {
        var elementValue = domUtils.getElementValue(element);

        domUtils.setElementValue(element, elementValue.substr(0, caretPos) + text + elementValue.substr(caretPos + text.length));
    }
    else
        domUtils.setElementValue(element, text);

    eventSimulator.change(element);
    eventSimulator.input(element);
}

export default function (element, text, caretPos) {
    if (domUtils.isContentEditableElement(element))
        _typeTextToContentEditable(element, text);

    if (!domUtils.isElementReadOnly(element)) {
        if (domUtils.isTextEditableElement(element))
            _typeTextToTextEditable(element, text);

        else if (domUtils.isInputElement(element))
            _typeTextToNonTextEditable(element, text, caretPos);
    }
}


text:
class ScenarioDeleteLandLandDoesNotExist
    : public IntegrationTest
{
protected:
    ScenarioDeleteLandLandDoesNotExist()
    {
        mClient.send(mRequestBuilder.buildCreateUserRequest("Login", "Password"));
        mClient.send(mRequestBuilder.buildCreateWorldRequest("modbot", "modbotpass", "World"));
        mClient.send(mRequestBuilder.buildCreateEpochRequest("modbot", "modbotpass", "World", "Epoch"));
        mClient.send(mRequestBuilder.buildActivateEpochRequest("modbot", "modbotpass", "World"));
        mCommandReply = mClient.send(mRequestBuilder.buildDeleteLandRequest("Login", "Password", "Land"));
    }

    Client mClient;

    Language::RequestBuilder  mRequestBuilder;
    Language::Command::Handle mCommandReply;
};

TEST_F(ScenarioDeleteLandLandDoesNotExist, ReturnsProperID)
{
    ASSERT_EQ(Language::ID_COMMAND_DELETE_LAND_REPLY, mCommandReply->getID());
}

TEST_F(ScenarioDeleteLandLandDoesNotExist, ReturnsProperCode)
{
    ASSERT_EQ(Game::REPLY_STATUS_UNAUTHORIZED, mCommandReply->getCode());
}

class ScenarioDeleteLand
    : public IntegrationTest
{
protected:
    ScenarioDeleteLand()
    {
        mClient.send(mRequestBuilder.buildCreateUserRequest("Login", "Password"));
        mClient.send(mRequestBuilder.buildCreateWorldRequest("modbot", "modbotpass", "World"));
        mClient.send(mRequestBuilder.buildCreateEpochRequest("modbot", "modbotpass", "World", "Epoch"));
        mClient.send(mRequestBuilder.buildActivateEpochRequest("modbot", "modbotpass", "World"));
        mClient.send(mRequestBuilder.buildCreateLandRequest("Login", "Password", "World", "Land"));
        mCommandReply = mClient.send(mRequestBuilder.buildDeleteLandRequest("Login", "Password", "Land"));
    }

    Client mClient;

    Language::RequestBuilder  mRequestBuilder;
    Language::Command::Handle mCommandReply;
};

TEST_F(ScenarioDeleteLand, ReturnsProperID)
{
    ASSERT_EQ(Language::ID_COMMAND_DELETE_LAND_REPLY, mCommandReply->getID());
}

TEST_F(ScenarioDeleteLand, ReturnsProperCode)
{
    ASSERT_EQ(Game::REPLY_STATUS_OK, mCommandReply->getCode());
}

TEST_F(ScenarioDeleteLand, ReturnsProperMessage)
{
    ASSERT_STREQ(Game::DELETE_LAND_LAND_HAS_BEEN_DELETED.c_str(), mCommandReply->getMessage().c_str());
}

class ScenarioDeleteLandTwice
    : public IntegrationTest
{
protected:
    ScenarioDeleteLandTwice()
    {
        mClient.send(mRequestBuilder.buildCreateUserRequest("Login", "Password"));
        mClient.send(mRequestBuilder.buildCreateWorldRequest("modbot", "modbotpass", "World"));
        mClient.send(mRequestBuilder.buildCreateEpochRequest("modbot", "modbotpass", "World", "Epoch"));
        mClient.send(mRequestBuilder.buildActivateEpochRequest("modbot", "modbotpass", "World"));
        mClient.send(mRequestBuilder.buildCreateLandRequest("Login", "Password", "World", "Land"));
        mClient.send(mRequestBuilder.buildDeleteLandRequest("Login", "Password", "Land"));
        mCommandReply = mClient.send(mRequestBuilder.buildDeleteLandRequest("Login", "Password", "Land"));
    }

    Client mClient;

    Language::RequestBuilder  mRequestBuilder;
    Language::Command::Handle mCommandReply;
};

TEST_F(ScenarioDeleteLandTwice, ReturnsProperID)
{
    ASSERT_EQ(Language::ID_COMMAND_DELETE_LAND_REPLY, mCommandReply->getID());
}

TEST_F(ScenarioDeleteLandTwice, ReturnsProperCode)
{
    ASSERT_EQ(Game::REPLY_STATUS_UNAUTHORIZED, mCommandReply->getCode());
}

class ScenarioDeleteLandUnauthenticated
    : public IntegrationTest
{
protected:
    ScenarioDeleteLandUnauthenticated()
    {
        mClient.send(mRequestBuilder.buildCreateUserRequest("Login", "Password"));
        mClient.send(mRequestBuilder.buildCreateWorldRequest("modbot", "modbotpass", "World"));
        mClient.send(mRequestBuilder.buildCreateEpochRequest("modbot", "modbotpass", "World", "Epoch"));
        mClient.send(mRequestBuilder.buildActivateEpochRequest("modbot", "modbotpass", "World"));
        mClient.send(mRequestBuilder.buildCreateLandRequest("Login", "Password", "World", "Land"));
        mCommandReply = mClient.send(mRequestBuilder.buildDeleteLandRequest("Login", "BadPassword", "Land"));
    }

    Client mClient;

    Language::RequestBuilder  mRequestBuilder;
    Language::Command::Handle mCommandReply;
};

TEST_F(ScenarioDeleteLandUnauthenticated, ReturnsProperID)
{
    ASSERT_EQ(Language::ID_COMMAND_DELETE_LAND_REPLY, mCommandReply->getID());
}

TEST_F(ScenarioDeleteLandUnauthenticated, ReturnsProperCode)
{
    ASSERT_EQ(Game::REPLY_STATUS_UNAUTHENTICATED, mCommandReply->getCode());
}

class ScenarioDeleteLandUnauthorized
    : public IntegrationTest
{
protected:
    ScenarioDeleteLandUnauthorized()
    {
        mClient.send(mRequestBuilder.buildCreateUserRequest("Login1", "Password"));
        mClient.send(mRequestBuilder.buildCreateUserRequest("Login2", "Password"));
        mClient.send(mRequestBuilder.buildCreateWorldRequest("modbot", "modbotpass", "World"));
        mClient.send(mRequestBuilder.buildCreateEpochRequest("modbot", "modbotpass", "World", "Epoch"));
        mClient.send(mRequestBuilder.buildActivateEpochRequest("modbot", "modbotpass", "World"));
        mClient.send(mRequestBuilder.buildCreateLandRequest("Login", "Password", "World", "Land"));
        mCommandReply = mClient.send(mRequestBuilder.buildDeleteLandRequest("Login2", "Password", "Land"));
    }

    Client mClient;

    Language::RequestBuilder  mRequestBuilder;
    Language::Command::Handle mCommandReply;
};

TEST_F(ScenarioDeleteLandUnauthorized, ReturnsProperID)
{
    ASSERT_EQ(Language::ID_COMMAND_DELETE_LAND_REPLY, mCommandReply->getID());
}

TEST_F(ScenarioDeleteLandUnauthorized, ReturnsProperCode)
{
    ASSERT_EQ(Game::REPLY_STATUS_UNAUTHORIZED, mCommandReply->getCode());
}

class ScenarioDeleteLandEpochIsNotActive
    : public IntegrationTest
{
protected:
    ScenarioDeleteLandEpochIsNotActive()
    {
        mClient.send(mRequestBuilder.buildCreateUserRequest("Login", "Password"));
        mClient.send(mRequestBuilder.buildCreateWorldRequest("modbot", "modbotpass", "World"));
        mClient.send(mRequestBuilder.buildCreateEpochRequest("modbot", "modbotpass", "World", "Epoch"));
        mClient.send(mRequestBuilder.buildActivateEpochRequest("modbot", "modbotpass", "World"));
        mClient.send(mRequestBuilder.buildCreateLandRequest("Login", "Password", "World", "Land"));
        mClient.send(mRequestBuilder.buildDeactivateEpochRequest("modbot", "modbotpass", "World"));
        mCommandReply = mClient.send(mRequestBuilder.buildDeleteLandRequest("Login", "Password", "Land"));
    }

    Client mClient;

    Language::RequestBuilder  mRequestBuilder;
    Language::Command::Handle mCommandReply;
};

TEST_F(ScenarioDeleteLandEpochIsNotActive, ReturnsProperID)
{
    ASSERT_EQ(Language::ID_COMMAND_DELETE_LAND_REPLY, mCommandReply->getID());
}

TEST_F(ScenarioDeleteLandEpochIsNotActive, ReturnsProperCode)
{
    ASSERT_EQ(Game::REPLY_STATUS_EPOCH_IS_NOT_ACTIVE, mCommandReply->getCode());
}


text: export * from 'rxjs-compat/operators/startWith';


text:
cask "locklizard-safeguard-viewer" do
  version "2.5.81"
  sha256 "d77a65e7f19aae939c5bbe2eb0db4ac7e678d6aa9dde6a9fdfd55964673bd08c"

  url "https://downloads.locklizard.com/PDCViewerSetupOSX.zip"
  appcast "https://www.locklizard.com/download_pdf_viewers/#mac-viewer"
  name "LockLizard Safeguard Viewer"
  name "PDC Viewer"
  homepage "https://www.locklizard.com/"

  auto_updates true
  depends_on arch: ":x86_64"

  pkg "PDCViewerSetup#{version.no_dots}_x64_Mac.pkg"

  uninstall pkgutil: "com.locklizard.pkg.LockLizardSafeguardViewer"
end


text:
package com.thinkbiganalytics.kylo.catalog.spark.sources.jdbc;

import org.apache.spark.sql.SQLContext;
import org.apache.spark.sql.sources.BaseRelation;
import org.apache.spark.sql.sources.DataSourceRegister;
import org.apache.spark.sql.sources.RelationProvider;
import org.apache.spark.util.Utils;

import java.util.ServiceLoader;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

import scala.collection.immutable.Map;

/**
 * Factory for Spark data sources that can read from and write to JDBC tables.
 */
public class JdbcRelationProvider implements RelationProvider {

    @Nonnull
    @Override
    public BaseRelation createRelation(@Nonnull final SQLContext sqlContext, @Nonnull final Map<String, String> parameters) {
        final RelationProvider provider = findProvider();
        if (provider != null) {
            final BaseRelation relation = provider.createRelation(sqlContext, parameters);
            return new JdbcRelation(relation, Thread.currentThread().getContextClassLoader());
        } else {
            throw new IllegalStateException("Cannot find Spark JDBC relation provider");
        }
    }

    /**
     * Locates Spark's JDBC relation provider.
     */
    @Nullable
    private RelationProvider findProvider() {
        final ServiceLoader<DataSourceRegister> serviceLoader = ServiceLoader.load(DataSourceRegister.class, Utils.getContextOrSparkClassLoader());

        for (final DataSourceRegister register : serviceLoader) {
            if ("jdbc".equalsIgnoreCase(register.shortName()) && register instanceof RelationProvider) {
                return (RelationProvider) register;
            }
        }

        return null;
    }
}


text:
<?xml version="1.0"?>

<config>
    <sections>
        <system>
            <groups>
                <guidance_cachebuster translate="label">
                    Cachebuster Settings
                    <show_in_default>1</show_in_default>
                    <show_in_website>1</show_in_website>
                    <show_in_store>1</show_in_store>
                    <sort_order>800</sort_order>
                    <fields>
                        <is_enabled translate="label">
                            Enable cachebuster
                            <frontend_type>select</frontend_type>
                            <source_model>adminhtml/system_config_source_yesno</source_model>
                            <backend_model>adminhtml/system_config_backend_cache</backend_model>
                            <sort_order>5</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>1</show_in_store>
                        </is_enabled>
                        <url_keys translate="label">
                            URL map
                            <frontend_type>multiselect</frontend_type>
                            <source_model>guidance_cachebuster/source_urlmap</source_model>
                            <sort_order>10</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>1</show_in_store>
                        </url_keys>
                        <file_extensions translate="label">
                            File extensions
                            <frontend_type>text</frontend_type>
                            <sort_order>20</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>1</show_in_store>
                            <comment>List of file extensions to add cachebusting timestamps to, comma-separated
                                (ex: js,css,png,jpg,gif).  This should match the file extensions declared in your .htaccess file</comment>
                        </file_extensions>
                    </fields>
                </guidance_cachebuster>
            </groups>
        </system>
    </sections>
</config>


text:
package boofcv.alg.feature.disparity.impl;

import boofcv.alg.feature.disparity.SelectSparseStandardWta;
import org.junit.Test;

import java.util.Arrays;

import static org.junit.Assert.assertTrue;

/**
 * @author Peter Abeles
 */
public class TestSelectSparseStandardSubpixel_S32 extends ChecksSelectSparseStandardWta<int[]>{

	public TestSelectSparseStandardSubpixel_S32() {
		super(int[].class);
	}

	@Override
	protected SelectSparseStandardWta<int[]> createAlg(int maxError, double texture) {
		return new SelectSparseStandardSubpixel.S32(maxError,texture);
	}

	/**
	 * Given different local error values see if it is closer to the value with a smaller error
	 */
	@Test
	public void addSubpixelBias() {

		SelectSparseStandardSubpixel.S32 alg = new SelectSparseStandardSubpixel.S32(-1,-1);

		int scores[] = new int[30];
		Arrays.fill(scores,0,10,500);

		// should be biased towards 4
		scores[4] = 100;
		scores[5] = 50;
		scores[6] = 200;

		assertTrue(alg.select(scores, 10));

		double found = alg.getDisparity();
		assertTrue( found < 5 && found > 4);

		// now biased towards 6
		scores[4] = 200;
		scores[6] = 100;
		assertTrue(alg.select(scores, 10));
		found = alg.getDisparity();

		assertTrue( found < 6 && found > 5);
	}
}


text:
/* @migen@ */
/*
**==============================================================================
**
** WARNING: THIS FILE WAS AUTOMATICALLY GENERATED. PLEASE DO NOT EDIT.
**
**==============================================================================
*/
#ifndef _MSFT_nxOMSPerfCounterObject_h
#define _MSFT_nxOMSPerfCounterObject_h

#include <MI.h>

/*
**==============================================================================
**
** MSFT_nxOMSPerfCounterObject [MSFT_nxOMSPerfCounterObject]
**
** Keys:
**    ObjectName
**
**==============================================================================
*/

typedef struct _MSFT_nxOMSPerfCounterObject
{
    MI_Instance __instance;
    /* MSFT_nxOMSPerfCounterObject properties */
    /*KEY*/ MI_ConstStringField ObjectName;
    MI_ConstStringField InstanceName;
    MI_ConstBooleanField AllInstances;
    MI_ConstUint16Field IntervalSeconds;
    MI_ConstStringAField PerformanceCounter;
}
MSFT_nxOMSPerfCounterObject;

typedef struct _MSFT_nxOMSPerfCounterObject_Ref
{
    MSFT_nxOMSPerfCounterObject* value;
    MI_Boolean exists;
    MI_Uint8 flags;
}
MSFT_nxOMSPerfCounterObject_Ref;

typedef struct _MSFT_nxOMSPerfCounterObject_ConstRef
{
    MI_CONST MSFT_nxOMSPerfCounterObject* value;
    MI_Boolean exists;
    MI_Uint8 flags;
}
MSFT_nxOMSPerfCounterObject_ConstRef;

typedef struct _MSFT_nxOMSPerfCounterObject_Array
{
    struct _MSFT_nxOMSPerfCounterObject** data;
    MI_Uint32 size;
}
MSFT_nxOMSPerfCounterObject_Array;

typedef struct _MSFT_nxOMSPerfCounterObject_ConstArray
{
    struct _MSFT_nxOMSPerfCounterObject MI_CONST* MI_CONST* data;
    MI_Uint32 size;
}
MSFT_nxOMSPerfCounterObject_ConstArray;

typedef struct _MSFT_nxOMSPerfCounterObject_ArrayRef
{
    MSFT_nxOMSPerfCounterObject_Array value;
    MI_Boolean exists;
    MI_Uint8 flags;
}
MSFT_nxOMSPerfCounterObject_ArrayRef;

typedef struct _MSFT_nxOMSPerfCounterObject_ConstArrayRef
{
    MSFT_nxOMSPerfCounterObject_ConstArray value;
    MI_Boolean exists;
    MI_Uint8 flags;
}
MSFT_nxOMSPerfCounterObject_ConstArrayRef;

MI_EXTERN_C MI_CONST MI_ClassDecl MSFT_nxOMSPerfCounterObject_rtti;

MI_INLINE MI_Result MI_CALL MSFT_nxOMSPerfCounterObject_Construct(
    _Out_ MSFT_nxOMSPerfCounterObject* self,
    _In_ MI_Context* context)
{
    return MI_Context_ConstructInstance(context, &MSFT_nxOMSPerfCounterObject_rtti,
        (MI_Instance*)&self->__instance);
}

MI_INLINE MI_Result MI_CALL MSFT_nxOMSPerfCounterObject_Clone(
    _In_ const MSFT_nxOMSPerfCounterObject* self,
    _Outptr_ MSFT_nxOMSPerfCounterObject** newInstance)
{
    return MI_Instance_Clone(
        &self->__instance, (MI_Instance**)newInstance);
}

MI_INLINE MI_Boolean MI_CALL MSFT_nxOMSPerfCounterObject_IsA(
    _In_ const MI_Instance* self)
{
    MI_Boolean res = MI_FALSE;
    return MI_Instance_IsA(self, &MSFT_nxOMSPerfCounterObject_rtti, &res) == MI_RESULT_OK && res;
}

MI_INLINE MI_Result MI_CALL MSFT_nxOMSPerfCounterObject_Destruct(_Inout_ MSFT_nxOMSPerfCounterObject* self)
{
    return MI_Instance_Destruct(&self->__instance);
}

MI_INLINE MI_Result MI_CALL MSFT_nxOMSPerfCounterObject_Delete(_Inout_ MSFT_nxOMSPerfCounterObject* self)
{
    return MI_Instance_Delete(&self->__instance);
}

MI_INLINE MI_Result MI_CALL MSFT_nxOMSPerfCounterObject_Post(
    _In_ const MSFT_nxOMSPerfCounterObject* self,
    _In_ MI_Context* context)
{
    return MI_Context_PostInstance(context, &self->__instance);
}

MI_INLINE MI_Result MI_CALL MSFT_nxOMSPerfCounterObject_Set_ObjectName(
    _Inout_ MSFT_nxOMSPerfCounterObject* self,
    _In_z_ const MI_Char* str)
{
    return self->__instance.ft->SetElementAt(
        (MI_Instance*)&self->__instance,
        0,
        (MI_Value*)&str,
        MI_STRING,
        0);
}

MI_INLINE MI_Result MI_CALL MSFT_nxOMSPerfCounterObject_SetPtr_ObjectName(
    _Inout_ MSFT_nxOMSPerfCounterObject* self,
    _In_z_ const MI_Char* str)
{
    return self->__instance.ft->SetElementAt(
        (MI_Instance*)&self->__instance,
        0,
        (MI_Value*)&str,
        MI_STRING,
        MI_FLAG_BORROW);
}

MI_INLINE MI_Result MI_CALL MSFT_nxOMSPerfCounterObject_Clear_ObjectName(
    _Inout_ MSFT_nxOMSPerfCounterObject* self)
{
    return self->__instance.ft->ClearElementAt(
        (MI_Instance*)&self->__instance,
        0);
}

MI_INLINE MI_Result MI_CALL MSFT_nxOMSPerfCounterObject_Set_InstanceName(
    _Inout_ MSFT_nxOMSPerfCounterObject* self,
    _In_z_ const MI_Char* str)
{
    return self->__instance.ft->SetElementAt(
        (MI_Instance*)&self->__instance,
        1,
        (MI_Value*)&str,
        MI_STRING,
        0);
}

MI_INLINE MI_Result MI_CALL MSFT_nxOMSPerfCounterObject_SetPtr_InstanceName(
    _Inout_ MSFT_nxOMSPerfCounterObject* self,
    _In_z_ const MI_Char* str)
{
    return self->__instance.ft->SetElementAt(
        (MI_Instance*)&self->__instance,
        1,
        (MI_Value*)&str,
        MI_STRING,
        MI_FLAG_BORROW);
}

MI_INLINE MI_Result MI_CALL MSFT_nxOMSPerfCounterObject_Clear_InstanceName(
    _Inout_ MSFT_nxOMSPerfCounterObject* self)
{
    return self->__instance.ft->ClearElementAt(
        (MI_Instance*)&self->__instance,
        1);
}

MI_INLINE MI_Result MI_CALL MSFT_nxOMSPerfCounterObject_Set_AllInstances(
    _Inout_ MSFT_nxOMSPerfCounterObject* self,
    _In_ MI_Boolean x)
{
    ((MI_BooleanField*)&self->AllInstances)->value = x;
    ((MI_BooleanField*)&self->AllInstances)->exists = 1;
    return MI_RESULT_OK;
}

MI_INLINE MI_Result MI_CALL MSFT_nxOMSPerfCounterObject_Clear_AllInstances(
    _Inout_ MSFT_nxOMSPerfCounterObject* self)
{
    memset((void*)&self->AllInstances, 0, sizeof(self->AllInstances));
    return MI_RESULT_OK;
}

MI_INLINE MI_Result MI_CALL MSFT_nxOMSPerfCounterObject_Set_IntervalSeconds(
    _Inout_ MSFT_nxOMSPerfCounterObject* self,
    _In_ MI_Uint16 x)
{
    ((MI_Uint16Field*)&self->IntervalSeconds)->value = x;
    ((MI_Uint16Field*)&self->IntervalSeconds)->exists = 1;
    return MI_RESULT_OK;
}

MI_INLINE MI_Result MI_CALL MSFT_nxOMSPerfCounterObject_Clear_IntervalSeconds(
    _Inout_ MSFT_nxOMSPerfCounterObject* self)
{
    memset((void*)&self->IntervalSeconds, 0, sizeof(self->IntervalSeconds));
    return MI_RESULT_OK;
}

MI_INLINE MI_Result MI_CALL MSFT_nxOMSPerfCounterObject_Set_PerformanceCounter(
    _Inout_ MSFT_nxOMSPerfCounterObject* self,
    _In_reads_opt_(size) const MI_Char** data,
    _In_ MI_Uint32 size)
{
    MI_Array arr;
    arr.data = (void*)data;
    arr.size = size;
    return self->__instance.ft->SetElementAt(
        (MI_Instance*)&self->__instance,
        4,
        (MI_Value*)&arr,
        MI_STRINGA,
        0);
}

MI_INLINE MI_Result MI_CALL MSFT_nxOMSPerfCounterObject_SetPtr_PerformanceCounter(
    _Inout_ MSFT_nxOMSPerfCounterObject* self,
    _In_reads_opt_(size) const MI_Char** data,
    _In_ MI_Uint32 size)
{
    MI_Array arr;
    arr.data = (void*)data;
    arr.size = size;
    return self->__instance.ft->SetElementAt(
        (MI_Instance*)&self->__instance,
        4,
        (MI_Value*)&arr,
        MI_STRINGA,
        MI_FLAG_BORROW);
}

MI_INLINE MI_Result MI_CALL MSFT_nxOMSPerfCounterObject_Clear_PerformanceCounter(
    _Inout_ MSFT_nxOMSPerfCounterObject* self)
{
    return self->__instance.ft->ClearElementAt(
        (MI_Instance*)&self->__instance,
        4);
}

#endif /* _MSFT_nxOMSPerfCounterObject_h */


text:
package hr.foi.rsc.lifeline.mvp.listeners;

/**
 * Created by dino on 22/11/14.
 */
public interface BaseListener {

    public void onFailure(String message);
}


text:
module Ezine::Addon
  module SubscriptionConstraint
    extend ActiveSupport::Concern
    extend SS::Addon

    included do
      field :subscription_constraint, type: String
      validates :subscription_constraint, inclusion: { in: %w(optional required), allow_blank: true }
      permit_params :subscription_constraint
      after_save :update_members_subscription
      scope :and_subscription_required, ->{ where(subscription_constraint: 'required') }
    end

    private
      def update_members_subscription
        return unless subscription_requried?

        Cms::Member.site(site).each do |member|
          subscription_ids = member.subscription_ids
          subscription_ids ||= []
          subscription_ids << self.id
          subscription_ids = subscription_ids.uniq
          member.subscription_ids = subscription_ids
          member.save!
        end
      end

    public
      def subscription_constraint_options
        %w(optional required).map { |m| [ I18n.t("inquiry.options.required.#{m}"), m ] }.to_a
      end

      def subscription_requried?
        subscription_constraint == 'required'
      end
  end
end


text:
class BaseRegister:
    """
    Represents an ISA register.  Fields:

    - name: a name displayed for this register, should be unique.
    - width: width in bits.
    """

    def __init__(self, name, width):
        self.name = name
        self.width = width

    def __str__(self):
        return "${}".format(self.name)

    __repr__ = __str__

class Register(BaseRegister):
    """
    Represents a general-purpose, top-level ISA register.  Writes to this
    register will not be considered interesting on their own, and will be
    converted wholly to SSA.
    """

class RegisterPC(BaseRegister):
    """
    Represents a program counter register, ie. one that always points to
    some place in the current bundle, and thus will return a known value
    when read.
    """

    def __init__(self, name, width, anchor='start', offset=0):
        super().__init__(name, width)
        self.anchor = anchor
        self.offset = offset

class RegisterSP(BaseRegister):
    """
    Represents a hardware stack pointer register.
    """

    # XXX: does this warrant a special class?  Might be better to handle it
    # elsewhere.

# "You know what "special" means, right?" -- mupuf
class RegisterSpecial(BaseRegister):
    """
    Represents a special register.  Reads and writes of this register will be
    considered to be interesting events, and will not be converted to SSA.
    """

class RegisterSplit(BaseRegister):
    """
    Represents a split register, ie. one that is really multiple other
    registers accessed together as a single entity.  ``parts`` is a list
    of (start bit, register) tuples.  When accessed, the access is converted
    to multiple smaller accesses to the parts.
    """

    def __init__(self, name, width, parts):
        super().__init__(name, width)
        self.parts = parts

class SubRegister(BaseRegister):
    """
    Represents a subregister of another register.  Defined by starting bit
    position in the parent and width.
    """

    def __init__(self, name, parent, start, width):
        super().__init__(name, width)
        self.parent = parent
        self.start = start


text:
This is a simple [AngularJS](http://angularjs.org/) web app base on the [TodoMVC](http://todomvc.com/), which allows you to add/remove tasks, mark has done, view only concluded/active tasks.

It's a front-end served by a [Expressjs](http://expressjs.com/) server, and deployed on heroku:

[myangulartodo.herokuapp.com](http://myangulartodo.herokuapp.com/)


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

public class SwipeGesture : MonoBehaviour, IGUIScreenLayout {

	public SwipeGestureSettings settings;
	public bool debug;

	private List<SwipeGestureListener> onRightSwipeListeners;
	private List<SwipeGestureListener> onLeftSwipeListeners;
	private List<SwipeGestureListener> onUpSwipeListeners;
	private List<SwipeGestureListener> onDownSwipeListeners;
	private float swipeStartTime;
	private bool couldBeSwipe;
	private Vector2 startPos;
	private int stationaryForFrames;
	private TouchPhase lastPhase;
	private Vector3 posInverted = Vector3.zero;

	void Awake () {
		// register this class with ScreenLayoutManager for screen resize event
		GUIScreenLayoutManager.Instance.register(this as IGUIScreenLayout);

		onRightSwipeListeners = new List<SwipeGestureListener>(2);
		onLeftSwipeListeners = new List<SwipeGestureListener>(2);
		onUpSwipeListeners = new List<SwipeGestureListener>(2);
		onDownSwipeListeners = new List<SwipeGestureListener>(2);
	}

	void OnDestroy () {
		onRightSwipeListeners = null;
		onLeftSwipeListeners = null;
		onUpSwipeListeners = null;
		onDownSwipeListeners = null;
		GUIScreenLayoutManager.Instance.remove(this as IGUIScreenLayout);
	}

	public void setup () {
		settings.setup();
		// add here other initializations
	}

	public void setup (SwipeGestureSettings gestureSettings) {
		this.settings = gestureSettings;
		setup();
	}

	public void updateForGUI () {
		// if screen is resized then need update the active area, if necessary
		settings.recalculateArea();
	}

	void Update() {
		processTouch();
	}

#if UNITY_EDITOR
	void OnGUI () {
		if (debug)
			GUI.Box(settings.activeArea, GUIContent.none);
	}
#endif

	private void processTouch () {
		foreach (Touch touch in Input.touches)
		{
			posInverted.x = touch.position.x;
			posInverted.y = Screen.height - touch.position.y;
			if (!settings.activeArea.Contains(posInverted))
				continue;

			switch (touch.phase)
			{
				case TouchPhase.Began: //The finger first touched the screen --> It could be(come) a swipe
					couldBeSwipe = true;
					startPos = touch.position;  //Position where the touch started
					swipeStartTime = Time.time; //The time it started
					stationaryForFrames = 0;
					break;

				case TouchPhase.Stationary: //Is the touch stationary? --> No swipe then!
					if (isContinouslyStationary(15))
						couldBeSwipe = false;
					break;

				case TouchPhase.Canceled:
				case TouchPhase.Ended:
					if (isASwipe(touch))
					{
						couldBeSwipe = false; //<-- Otherwise this part would be called over and over again.
						if (Mathf.Abs(touch.position.x - startPos.x) > settings.minSwipeDist) {
							if (Mathf.Sign(touch.position.x - startPos.x) == 1f) {
								for (int i=0, c=onRightSwipeListeners.Count; i < c; ++i)
									onRightSwipeListeners[i].notifyRight();
							} else {
								for (int i=0, c=onLeftSwipeListeners.Count; i < c; ++i)
									onLeftSwipeListeners[i].notifyLeft();
							}
						}

						if (Mathf.Abs(touch.position.y - startPos.y) > settings.minSwipeDist) {
							if (Mathf.Sign(touch.position.y - startPos.y) == 1f) {
								for (int i=0, c=onUpSwipeListeners.Count; i < c; ++i)
									onUpSwipeListeners[i].notifyUp();
							} else {
								for (int i=0, c=onDownSwipeListeners.Count; i < c; ++i)
									onDownSwipeListeners[i].notifyDown();
							}
						}
					}
					break;
			}
			lastPhase = touch.phase;
		}
	}

	private bool isContinouslyStationary(int frames)
	{
		if (lastPhase == TouchPhase.Stationary)
			stationaryForFrames++;
		else
			stationaryForFrames = 1;

		return stationaryForFrames > frames;
	}

	private bool isASwipe(Touch touch)
	{
		float swipeTime = Time.time - swipeStartTime;
		float swipeDist = Mathf.Sqrt((touch.position - startPos).sqrMagnitude);
		return couldBeSwipe && swipeTime < settings.maxSwipeTime && swipeDist > settings.minSwipeDist;
	}

	public void registerOnRightSwipe (SwipeGestureListener listener) {
		onRightSwipeListeners.Add(listener);
	}

	public void registerOnLeftSwipe (SwipeGestureListener listener) {
		onLeftSwipeListeners.Add(listener);
	}

	public void registerOnUpSwipe (SwipeGestureListener listener) {
		onUpSwipeListeners.Add(listener);
	}

	public void registerOnDownSwipe (SwipeGestureListener listener) {
		onDownSwipeListeners.Add(listener);
	}
}


text:
package org.synopia.audio.model;

import org.synopia.audio.core.Band3Eq;
import org.synopia.audio.core.Gain;
import org.synopia.audio.core.Patch;
import org.synopia.shadow.Parameter;

/**
 * Created by synopia on 19.09.2015.
 */
public class Deck extends Patch implements ADeck {
    @Parameter
    private float bpm = 170f;
    @Parameter
    private Track track;
    @Parameter
    private Clip clip;
    @Parameter
    private ClipPlayer clipPlayer;

    @Parameter
    private Band3Eq eq;
    @Parameter
    private Gain gain;

    private TrackDatabase db;

    public Deck(TrackDatabase db, Patch parent) {
        super(parent);
        this.db = db;
        clipPlayer = new ClipPlayer(this);
        eq = new Band3Eq(this);
        gain = new Gain(this);
        connect(clipPlayer, eq);
        connect(eq, gain);
    }

    @Override
    public ClipPlayer getClipPlayer() {
        return clipPlayer;
    }

    @Override
    public void setClipPlayer(AClipPlayer clipPlayer) {
        this.clipPlayer = (ClipPlayer) clipPlayer;
    }

    @Override
    public Band3Eq getEq() {
        return eq;
    }

    @Override
    public Gain getGain() {
        return gain;
    }

    @Override
    public float getBpm() {
        return bpm;
    }

    @Override
    public Track getTrack() {
        return track;
    }

    @Override
    public Clip getClip() {
        return clip;
    }

    @Override
    public void setBpm(float bpm) {
        this.bpm = bpm;
        float targetBpm = ((ADecks) parent()).getBpm();
        if (track != null) {
            getClipPlayer().setSpeed(targetBpm / bpm);
        }
    }

    @Override
    public void setTrack(ATrack track) {
        this.track = (Track) track;
        clipPlayer.setClip(null);
        if (track != null) {
            db.load(this.track).whenComplete((clip, e) -> {
                bpm = track.getBpm();
                setClip(clip);
            });
        }
    }

    @Override
    public void setClip(AClip clip) {
        this.clip = (Clip) clip;
        clipPlayer.setClip(this.clip);
        clipPlayer.setSpeed(((ADecks) parent()).getBpm() / bpm);
    }

    @Override
    public void setEq(ABand3Eq eq) {
        this.eq = (Band3Eq) eq;
    }

    @Override
    public void setGain(AGain gain) {
        this.gain = (Gain) gain;
    }
}


text:
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE ScopedTypeVariables, MultiParamTypeClasses #-}

module Main where

import Funciones

import System.Environment

import System.Console.CmdArgs
import Foreign.Marshal.Unsafe

import Pdf
import Graphics.PDF
import Graphics.PDF.Typesetting

data Parametros = Parametros {arc :: String, det :: Int, pal :: Int, ora :: Int, sal :: String, for :: String}
     deriving (Show, Data, Typeable)

params = Parametros{ arc = "" &= help "Archivo de entrada" &= typ "String",
                     det = 10 &= help "Precision de deteccion de idioma" &= typ "Int",
                     pal = 5 &= help "Cantidad de palabras clave" &= typ "Int",
                     ora = 3 &= help "Cantidad de oraciones clave" &= typ "Int",
                     sal = "Resultados" &= help "Nombre del archivo de salida" &= typ "String",
                     for = "html" &= help "Formato de salida" &= typ "String" }

-- Main

main :: IO ()
main = do

    -- Obtenemos los argumentos
    let args = cmdArgs params
    let arg_a = arc (unsafeLocalState args)
    let arg_d = det (unsafeLocalState args)
    let arg_p = pal (unsafeLocalState args)
    let arg_o = ora (unsafeLocalState args)
    let arg_s = sal (unsafeLocalState args)
    let arg_f = for (unsafeLocalState args)

    -- Leemos archivo
    cont <- readFile arg_a

    -- Obtenemos datos
    let tp = top_palabras cont arg_d       -- Obtenemos el arreglo de top words
    let id = idioma tp                     -- Detectamos idioma
    let pc = palabras_clave id cont arg_p  -- Obtenemos palabras clave
    let oc = oraciones_clave cont pc arg_o -- Obtenemos oraciones clave

    if( arg_f == "html" )
         then do
                let html = mostrar_html id pc oc -- Generamos codigo html
                writeFile (arg_s ++ ".html") html -- Grabamos los datos
         else do

    if( arg_f == "txt" )
         then do
                let txt = mostrar_txt id pc oc -- Preparamos el texto
                writeFile (arg_s ++ ".txt") txt -- Grabamos los datos
         else do

    if( arg_f == "cmd" )
         then do
                let cmd = arreglar_cmd $ mostrar_cmd id pc oc -- Preparamos el texto
                putStrLn $ show cmd  -- Muestra palabras clave
         else do

    if( arg_f == "pdf" )
         then do
			let rect = PDFRect 0 0 600 400
			runPdf (arg_s ++ ".pdf") (standardDocInfo { author=toPDFString "", compressed = False}) rect $ do
				resultado_pdf id pc oc
         else do

    print $ show ( "No se pudo realizar el resumen" )