text:
package gift

import (
	"image"
	"image/draw"
	"math"
)

type uweight struct {
	u      int
	weight float32
}

type uvweight struct {
	u      int
	v      int
	weight float32
}

func prepareConvolutionWeights(kernel []float32, normalize bool) (int, []uvweight) {
	size := int(math.Sqrt(float64(len(kernel))))
	if size%2 == 0 {
		size--
	}
	if size < 1 {
		return 0, []uvweight{}
	}
	center := size / 2

	weights := []uvweight{}
	for i := 0; i < size; i++ {
		for j := 0; j < size; j++ {
			k := j*size + i
			w := float32(0)
			if k < len(kernel) {
				w = kernel[k]
			}
			if w != 0 {
				weights = append(weights, uvweight{u: i - center, v: j - center, weight: w})
			}
		}
	}

	if !normalize {
		return size, weights
	}

	var sum, sumpositive float32
	for _, w := range weights {
		sum += w.weight
		if w.weight > 0 {
			sumpositive += w.weight
		}
	}

	var div float32
	if sum != 0 {
		div = sum
	} else if sumpositive != 0 {
		div = sumpositive
	} else {
		return size, weights
	}

	for i := 0; i < len(weights); i++ {
		weights[i].weight /= div
	}

	return size, weights
}

type convolutionFilter struct {
	kernel    []float32
	normalize bool
	alpha     bool
	abs       bool
	delta     float32
}

func (p *convolutionFilter) Bounds(srcBounds image.Rectangle) (dstBounds image.Rectangle) {
	dstBounds = image.Rect(0, 0, srcBounds.Dx(), srcBounds.Dy())
	return
}

func (p *convolutionFilter) Draw(dst draw.Image, src image.Image, options *Options) {
	if options == nil {
		options = &defaultOptions
	}

	srcb := src.Bounds()
	dstb := dst.Bounds()

	if srcb.Dx() <= 0 || srcb.Dy() <= 0 {
		return
	}

	ksize, weights := prepareConvolutionWeights(p.kernel, p.normalize)
	kcenter := ksize / 2

	if ksize < 1 {
		copyimage(dst, src, options)
		return
	}

	pixGetter := newPixelGetter(src)
	pixSetter := newPixelSetter(dst)

	parallelize(options.Parallelization, srcb.Min.Y, srcb.Max.Y, func(start, stop int) {
		// Init temporary rows.
		starty := start
		rows := make([][]pixel, ksize)
		for i := 0; i < ksize; i++ {
			rowy := starty + i - kcenter
			if rowy < srcb.Min.Y {
				rowy = srcb.Min.Y
			} else if rowy > srcb.Max.Y-1 {
				rowy = srcb.Max.Y - 1
			}
			row := make([]pixel, srcb.Dx())
			pixGetter.getPixelRow(rowy, &row)
			rows[i] = row
		}

		for y := start; y < stop; y++ {
			// Calculate dst row.
			for x := srcb.Min.X; x < srcb.Max.X; x++ {
				var r, g, b, a float32
				for _, w := range weights {
					wx := x + w.u
					if wx < srcb.Min.X {
						wx = srcb.Min.X
					} else if wx > srcb.Max.X-1 {
						wx = srcb.Max.X - 1
					}
					rowsx := wx - srcb.Min.X
					rowsy := kcenter + w.v

					px := rows[rowsy][rowsx]
					r += px.r * w.weight
					g += px.g * w.weight
					b += px.b * w.weight
					if p.alpha {
						a += px.a * w.weight
					}
				}
				if p.abs {
					r = absf32(r)
					g = absf32(g)
					b = absf32(b)
					if p.alpha {
						a = absf32(a)
					}
				}
				if p.delta != 0 {
					r += p.delta
					g += p.delta
					b += p.delta
					if p.alpha {
						a += p.delta
					}
				}
				if !p.alpha {
					a = rows[kcenter][x-srcb.Min.X].a
				}
				pixSetter.setPixel(dstb.Min.X+x-srcb.Min.X, dstb.Min.Y+y-srcb.Min.Y, pixel{r, g, b, a})
			}

			// Rotate temporary rows.
			if y < stop-1 {
				tmprow := rows[0]
				for i := 0; i < ksize-1; i++ {
					rows[i] = rows[i+1]
				}
				nextrowy := y + ksize/2 + 1
				if nextrowy > srcb.Max.Y-1 {
					nextrowy = srcb.Max.Y - 1
				}
				pixGetter.getPixelRow(nextrowy, &tmprow)
				rows[ksize-1] = tmprow
			}
		}
	})
}

// Convolution creates a filter that applies a square convolution kernel to an image.
// The length of the kernel slice must be the square of an odd kernel size (e.g. 9 for 3x3 kernel, 25 for 5x5 kernel).
// Excessive slice members will be ignored.
// If normalize parameter is true, the kernel will be normalized before applying the filter.
// If alpha parameter is true, the alpha component of color will be filtered too.
// If abs parameter is true, absolute values of color components will be taken after doing calculations.
// If delta parameter is not zero, this value will be added to the filtered pixels.
//
// Example:
//
//	// Apply the emboss filter to an image.
//	g := gift.New(
//		gift.Convolution(
//			[]float32{
//				-1, -1, 0,
//				-1, 1, 1,
//				0, 1, 1,
//			},
//			false, false, false, 0,
//		),
//	)
//	dst := image.NewRGBA(g.Bounds(src.Bounds()))
//	g.Draw(dst, src)
//
func Convolution(kernel []float32, normalize, alpha, abs bool, delta float32) Filter {
	return &convolutionFilter{
		kernel:    kernel,
		normalize: normalize,
		alpha:     alpha,
		abs:       abs,
		delta:     delta,
	}
}

// prepareConvolutionWeights1d prepares pixel weights using a convolution kernel.
// Weights equal to 0 are excluded.
func prepareConvolutionWeights1d(kernel []float32) (int, []uweight) {
	size := len(kernel)
	if size%2 == 0 {
		size--
	}
	if size < 1 {
		return 0, []uweight{}
	}
	center := size / 2
	weights := []uweight{}
	for i := 0; i < size; i++ {
		w := float32(0)
		if i < len(kernel) {
			w = kernel[i]
		}
		if w != 0 {
			weights = append(weights, uweight{i - center, w})
		}
	}
	return size, weights
}

// convolveLine convolves a single line of pixels according to the given weights.
func convolveLine(dstBuf []pixel, srcBuf []pixel, weights []uweight) {
	max := len(srcBuf) - 1
	if max < 0 {
		return
	}
	for dstu := 0; dstu < len(srcBuf); dstu++ {
		var r, g, b, a float32
		for _, w := range weights {
			k := dstu + w.u
			if k < 0 {
				k = 0
			} else if k > max {
				k = max
			}
			c := srcBuf[k]
			wa := c.a * w.weight
			r += c.r * wa
			g += c.g * wa
			b += c.b * wa
			a += wa
		}
		if a != 0 {
			r /= a
			g /= a
			b /= a
		}
		dstBuf[dstu] = pixel{r, g, b, a}
	}
}

// convolve1dv performs a fast vertical 1d convolution.
func convolve1dv(dst draw.Image, src image.Image, kernel []float32, options *Options) {
	srcb := src.Bounds()
	dstb := dst.Bounds()
	if srcb.Dx() <= 0 || srcb.Dy() <= 0 {
		return
	}
	if kernel == nil || len(kernel) < 1 {
		copyimage(dst, src, options)
		return
	}
	_, weights := prepareConvolutionWeights1d(kernel)
	pixGetter := newPixelGetter(src)
	pixSetter := newPixelSetter(dst)
	parallelize(options.Parallelization, srcb.Min.X, srcb.Max.X, func(start, stop int) {
		srcBuf := make([]pixel, srcb.Dy())
		dstBuf := make([]pixel, srcb.Dy())
		for x := start; x < stop; x++ {
			pixGetter.getPixelColumn(x, &srcBuf)
			convolveLine(dstBuf, srcBuf, weights)
			pixSetter.setPixelColumn(dstb.Min.X+x-srcb.Min.X, dstBuf)
		}
	})
}

// convolve1dh performs afast horizontal 1d convolution.
func convolve1dh(dst draw.Image, src image.Image, kernel []float32, options *Options) {
	srcb := src.Bounds()
	dstb := dst.Bounds()
	if srcb.Dx() <= 0 || srcb.Dy() <= 0 {
		return
	}
	if kernel == nil || len(kernel) < 1 {
		copyimage(dst, src, options)
		return
	}
	_, weights := prepareConvolutionWeights1d(kernel)
	pixGetter := newPixelGetter(src)
	pixSetter := newPixelSetter(dst)
	parallelize(options.Parallelization, srcb.Min.Y, srcb.Max.Y, func(start, stop int) {
		srcBuf := make([]pixel, srcb.Dx())
		dstBuf := make([]pixel, srcb.Dx())
		for y := start; y < stop; y++ {
			pixGetter.getPixelRow(y, &srcBuf)
			convolveLine(dstBuf, srcBuf, weights)
			pixSetter.setPixelRow(dstb.Min.Y+y-srcb.Min.Y, dstBuf)
		}
	})
}

func gaussianBlurKernel(x, sigma float32) float32 {
	return float32(math.Exp(-float64(x*x)/float64(2*sigma*sigma)) / (float64(sigma) * math.Sqrt(2*math.Pi)))
}

type gausssianBlurFilter struct {
	sigma float32
}

func (p *gausssianBlurFilter) Bounds(srcBounds image.Rectangle) (dstBounds image.Rectangle) {
	dstBounds = image.Rect(0, 0, srcBounds.Dx(), srcBounds.Dy())
	return
}

func (p *gausssianBlurFilter) Draw(dst draw.Image, src image.Image, options *Options) {
	if options == nil {
		options = &defaultOptions
	}

	srcb := src.Bounds()
	if srcb.Dx() <= 0 || srcb.Dy() <= 0 {
		return
	}

	if p.sigma <= 0 {
		copyimage(dst, src, options)
		return
	}

	radius := int(math.Ceil(float64(p.sigma * 3)))
	size := 2*radius + 1
	center := radius
	kernel := make([]float32, size)

	kernel[center] = gaussianBlurKernel(0, p.sigma)
	sum := kernel[center]

	for i := 1; i <= radius; i++ {
		f := gaussianBlurKernel(float32(i), p.sigma)
		kernel[center-i] = f
		kernel[center+i] = f
		sum += 2 * f
	}

	for i := 0; i < len(kernel); i++ {
		kernel[i] /= sum
	}

	tmp := createTempImage(srcb)
	convolve1dh(tmp, src, kernel, options)
	convolve1dv(dst, tmp, kernel, options)
}

// GaussianBlur creates a filter that applies a gaussian blur to an image.
// The sigma parameter must be positive and indicates how much the image will be blurred.
// Blur affected radius roughly equals 3 * sigma.
//
// Example:
//
//	g := gift.New(
//		gift.GaussianBlur(1.5),
//	)
//	dst := image.NewRGBA(g.Bounds(src.Bounds()))
//	g.Draw(dst, src)
//
func GaussianBlur(sigma float32) Filter {
	return &gausssianBlurFilter{
		sigma: sigma,
	}
}

type unsharpMaskFilter struct {
	sigma     float32
	amount    float32
	threshold float32
}

func (p *unsharpMaskFilter) Bounds(srcBounds image.Rectangle) (dstBounds image.Rectangle) {
	dstBounds = image.Rect(0, 0, srcBounds.Dx(), srcBounds.Dy())
	return
}

func unsharp(orig, blurred, amount, threshold float32) float32 {
	dif := (orig - blurred) * amount
	if absf32(dif) > absf32(threshold) {
		return orig + dif
	}
	return orig
}

func (p *unsharpMaskFilter) Draw(dst draw.Image, src image.Image, options *Options) {
	if options == nil {
		options = &defaultOptions
	}

	srcb := src.Bounds()
	dstb := dst.Bounds()

	if srcb.Dx() <= 0 || srcb.Dy() <= 0 {
		return
	}

	blurred := createTempImage(srcb)
	blur := GaussianBlur(p.sigma)
	blur.Draw(blurred, src, options)

	pixGetterOrig := newPixelGetter(src)
	pixGetterBlur := newPixelGetter(blurred)
	pixelSetter := newPixelSetter(dst)

	parallelize(options.Parallelization, srcb.Min.Y, srcb.Max.Y, func(start, stop int) {
		for y := start; y < stop; y++ {
			for x := srcb.Min.X; x < srcb.Max.X; x++ {
				pxOrig := pixGetterOrig.getPixel(x, y)
				pxBlur := pixGetterBlur.getPixel(x, y)

				r := unsharp(pxOrig.r, pxBlur.r, p.amount, p.threshold)
				g := unsharp(pxOrig.g, pxBlur.g, p.amount, p.threshold)
				b := unsharp(pxOrig.b, pxBlur.b, p.amount, p.threshold)
				a := unsharp(pxOrig.a, pxBlur.a, p.amount, p.threshold)

				pixelSetter.setPixel(dstb.Min.X+x-srcb.Min.X, dstb.Min.Y+y-srcb.Min.Y, pixel{r, g, b, a})
			}
		}
	})
}

// UnsharpMask creates a filter that sharpens an image.
// The sigma parameter is used in a gaussian function and affects the radius of effect.
// Sigma must be positive. Sharpen radius roughly equals 3 * sigma.
// The amount parameter controls how much darker and how much lighter the edge borders become. Typically between 0.5 and 1.5.
// The threshold parameter controls the minimum brightness change that will be sharpened. Typically between 0 and 0.05.
//
// Example:
//
//	g := gift.New(
//		gift.UnsharpMask(1, 1, 0),
//	)
//	dst := image.NewRGBA(g.Bounds(src.Bounds()))
//	g.Draw(dst, src)
//
func UnsharpMask(sigma, amount, threshold float32) Filter {
	return &unsharpMaskFilter{
		sigma:     sigma,
		amount:    amount,
		threshold: threshold,
	}
}

type meanFilter struct {
	ksize int
	disk  bool
}

func (p *meanFilter) Bounds(srcBounds image.Rectangle) (dstBounds image.Rectangle) {
	dstBounds = image.Rect(0, 0, srcBounds.Dx(), srcBounds.Dy())
	return
}

func (p *meanFilter) Draw(dst draw.Image, src image.Image, options *Options) {
	if options == nil {
		options = &defaultOptions
	}

	srcb := src.Bounds()
	if srcb.Dx() <= 0 || srcb.Dy() <= 0 {
		return
	}

	ksize := p.ksize
	if ksize%2 == 0 {
		ksize--
	}

	if ksize <= 1 {
		copyimage(dst, src, options)
		return
	}

	if p.disk {
		diskKernel := genDisk(p.ksize)
		f := Convolution(diskKernel, true, true, false, 0)
		f.Draw(dst, src, options)
	} else {
		kernel := make([]float32, ksize*ksize)
		for i := range kernel {
			kernel[i] = 1
		}
		f := Convolution(kernel, true, true, false, 0)
		f.Draw(dst, src, options)
	}
}

// Mean creates a local mean image filter.
// Takes an average across a neighborhood for each pixel.
// The ksize parameter is the kernel size. It must be an odd positive integer (for example: 3, 5, 7).
// If the disk parameter is true, a disk-shaped neighborhood will be used instead of a square neighborhood.
func Mean(ksize int, disk bool) Filter {
	return &meanFilter{
		ksize: ksize,
		disk:  disk,
	}
}

type hvConvolutionFilter struct {
	hkernel, vkernel []float32
}

func (p *hvConvolutionFilter) Bounds(srcBounds image.Rectangle) (dstBounds image.Rectangle) {
	dstBounds = image.Rect(0, 0, srcBounds.Dx(), srcBounds.Dy())
	return
}

func (p *hvConvolutionFilter) Draw(dst draw.Image, src image.Image, options *Options) {
	if options == nil {
		options = &defaultOptions
	}

	srcb := src.Bounds()
	dstb := dst.Bounds()

	if srcb.Dx() <= 0 || srcb.Dy() <= 0 {
		return
	}

	tmph := createTempImage(srcb)
	Convolution(p.hkernel, false, false, true, 0).Draw(tmph, src, options)
	pixGetterH := newPixelGetter(tmph)

	tmpv := createTempImage(srcb)
	Convolution(p.vkernel, false, false, true, 0).Draw(tmpv, src, options)
	pixGetterV := newPixelGetter(tmpv)

	pixSetter := newPixelSetter(dst)

	parallelize(options.Parallelization, srcb.Min.Y, srcb.Max.Y, func(start, stop int) {
		for y := start; y < stop; y++ {
			for x := srcb.Min.X; x < srcb.Max.X; x++ {
				pxh := pixGetterH.getPixel(x, y)
				pxv := pixGetterV.getPixel(x, y)
				r := sqrtf32(pxh.r*pxh.r + pxv.r*pxv.r)
				g := sqrtf32(pxh.g*pxh.g + pxv.g*pxv.g)
				b := sqrtf32(pxh.b*pxh.b + pxv.b*pxv.b)
				pixSetter.setPixel(dstb.Min.X+x-srcb.Min.X, dstb.Min.Y+y-srcb.Min.Y, pixel{r, g, b, pxh.a})
			}
		}
	})

}

// Sobel creates a filter that applies a sobel operator to an image.
func Sobel() Filter {
	return &hvConvolutionFilter{
		hkernel: []float32{-1, 0, 1, -2, 0, 2, -1, 0, 1},
		vkernel: []float32{-1, -2, -1, 0, 0, 0, 1, 2, 1},
	}
}


text:
namespace Kitchen
{
    using System;
    using System.Collections.Generic;

    using Kitchen.Contracts;
    using Kitchen.Models;
    using Kitchen.Models.Products;
    using Kitchen.Models.Utensils;

    public class StartUp
    {
        public static void Main()
        {
            var vegetables = new List<IVegetable>()
            {
                new Potato(),
                new Carrot(),
                new Potato(),
                new Carrot(),
                new Carrot()
            };

            var bowl = new Bowl();
            var chef = new Chef();
            chef.Cook(vegetables, bowl);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.hyracks.hdfs;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.mapreduce.JobContext;
import org.apache.hadoop.mapreduce.JobID;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hadoop.mapreduce.TaskAttemptID;
import org.apache.hyracks.api.exceptions.HyracksDataException;

/**
 * The wrapper to generate TaskTattemptContext
 */
public class ContextFactory {

    @SuppressWarnings({ "unchecked", "rawtypes" })
    public TaskAttemptContext createContext(Configuration conf, TaskAttemptID tid) throws HyracksDataException {
        try {
            return new Mapper().new Context(conf, tid, null, null, null, null, null);
        } catch (Exception e) {
            throw HyracksDataException.create(e);
        }
    }

    public TaskAttemptContext createContext(Configuration conf, int partition) throws HyracksDataException {
        try {
            TaskAttemptID tid = new TaskAttemptID("", 0, true, partition, 0);
            return new TaskAttemptContext(conf, tid);
        } catch (Exception e) {
            throw HyracksDataException.create(e);
        }
    }

    public JobContext createJobContext(Configuration conf) {
        return new JobContext(conf, new JobID("0", 0));
    }

}


text:
package org.onosproject.net.group.impl;

import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.ReferenceCardinality;
import org.apache.felix.scr.annotations.Service;
import org.onosproject.net.provider.AbstractListenerProviderRegistry;
import org.onosproject.core.ApplicationId;
import org.onosproject.net.DeviceId;
import org.onosproject.net.device.DeviceEvent;
import org.onosproject.net.device.DeviceListener;
import org.onosproject.net.device.DeviceService;
import org.onosproject.net.group.Group;
import org.onosproject.net.group.GroupBuckets;
import org.onosproject.net.group.GroupDescription;
import org.onosproject.net.group.GroupEvent;
import org.onosproject.net.group.GroupKey;
import org.onosproject.net.group.GroupListener;
import org.onosproject.net.group.GroupOperation;
import org.onosproject.net.group.GroupOperations;
import org.onosproject.net.group.GroupProvider;
import org.onosproject.net.group.GroupProviderRegistry;
import org.onosproject.net.group.GroupProviderService;
import org.onosproject.net.group.GroupService;
import org.onosproject.net.group.GroupStore;
import org.onosproject.net.group.GroupStore.UpdateType;
import org.onosproject.net.group.GroupStoreDelegate;
import org.onosproject.net.provider.AbstractProviderService;
import org.slf4j.Logger;

import java.util.Collection;
import java.util.Collections;

import static org.onosproject.security.AppGuard.checkPermission;
import static org.slf4j.LoggerFactory.getLogger;
import static org.onosproject.security.AppPermission.Type.*;

/**
 * Provides implementation of the group service APIs.
 */
@Component(immediate = true)
@Service
public class GroupManager
        extends AbstractListenerProviderRegistry<GroupEvent, GroupListener,
        GroupProvider, GroupProviderService>
        implements GroupService, GroupProviderRegistry {

    private final Logger log = getLogger(getClass());

    private final GroupStoreDelegate delegate = new InternalGroupStoreDelegate();
    private final DeviceListener deviceListener = new InternalDeviceListener();

    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
    protected GroupStore store;

    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
    protected DeviceService deviceService;

    @Activate
    public void activate() {
        store.setDelegate(delegate);
        eventDispatcher.addSink(GroupEvent.class, listenerRegistry);
        deviceService.addListener(deviceListener);
        log.info("Started");
    }

    @Deactivate
    public void deactivate() {
        store.unsetDelegate(delegate);
        eventDispatcher.removeSink(GroupEvent.class);
        log.info("Stopped");
    }

    /**
     * Create a group in the specified device with the provided parameters.
     *
     * @param groupDesc group creation parameters
     */
    @Override
    public void addGroup(GroupDescription groupDesc) {
        checkPermission(GROUP_WRITE);
        store.storeGroupDescription(groupDesc);
    }

    /**
     * Return a group object associated to an application cookie.
     * <p>
     * NOTE1: The presence of group object in the system does not
     * guarantee that the "group" is actually created in device.
     * GROUP_ADDED notification would confirm the creation of
     * this group in data plane.
     *
     * @param deviceId  device identifier
     * @param appCookie application cookie to be used for lookup
     * @return group associated with the application cookie or
     * NULL if Group is not found for the provided cookie
     */
    @Override
    public Group getGroup(DeviceId deviceId, GroupKey appCookie) {
        checkPermission(GROUP_READ);
        return store.getGroup(deviceId, appCookie);
    }

    /**
     * Append buckets to existing group. The caller can optionally
     * associate a new cookie during this updation. GROUP_UPDATED or
     * GROUP_UPDATE_FAILED notifications would be provided along with
     * cookie depending on the result of the operation on the device.
     *
     * @param deviceId  device identifier
     * @param oldCookie cookie to be used to retrieve the existing group
     * @param buckets   immutable list of group bucket to be added
     * @param newCookie immutable cookie to be used post update operation
     * @param appId     Application Id
     */
    @Override
    public void addBucketsToGroup(DeviceId deviceId,
                                  GroupKey oldCookie,
                                  GroupBuckets buckets,
                                  GroupKey newCookie,
                                  ApplicationId appId) {
        checkPermission(GROUP_WRITE);
        store.updateGroupDescription(deviceId,
                                     oldCookie,
                                     UpdateType.ADD,
                                     buckets,
                                     newCookie);
    }

    /**
     * Remove buckets from existing group. The caller can optionally
     * associate a new cookie during this updation. GROUP_UPDATED or
     * GROUP_UPDATE_FAILED notifications would be provided along with
     * cookie depending on the result of the operation on the device.
     *
     * @param deviceId  device identifier
     * @param oldCookie cookie to be used to retrieve the existing group
     * @param buckets   immutable list of group bucket to be removed
     * @param newCookie immutable cookie to be used post update operation
     * @param appId     Application Id
     */
    @Override
    public void removeBucketsFromGroup(DeviceId deviceId,
                                       GroupKey oldCookie,
                                       GroupBuckets buckets,
                                       GroupKey newCookie,
                                       ApplicationId appId) {
        checkPermission(GROUP_WRITE);
        store.updateGroupDescription(deviceId,
                                     oldCookie,
                                     UpdateType.REMOVE,
                                     buckets,
                                     newCookie);
    }

    /**
     * Delete a group associated to an application cookie.
     * GROUP_DELETED or GROUP_DELETE_FAILED notifications would be
     * provided along with cookie depending on the result of the
     * operation on the device.
     *
     * @param deviceId  device identifier
     * @param appCookie application cookie to be used for lookup
     * @param appId     Application Id
     */
    @Override
    public void removeGroup(DeviceId deviceId,
                            GroupKey appCookie,
                            ApplicationId appId) {
        checkPermission(GROUP_WRITE);
        store.deleteGroupDescription(deviceId, appCookie);
    }

    /**
     * Retrieve all groups created by an application in the specified device
     * as seen by current controller instance.
     *
     * @param deviceId device identifier
     * @param appId    application id
     * @return collection of immutable group objects created by the application
     */
    @Override
    public Iterable<Group> getGroups(DeviceId deviceId,
                                     ApplicationId appId) {
        checkPermission(GROUP_READ);
        return store.getGroups(deviceId);
    }

    @Override
    public Iterable<Group> getGroups(DeviceId deviceId) {
        checkPermission(GROUP_READ);
        return store.getGroups(deviceId);
    }

    @Override
    protected GroupProviderService createProviderService(GroupProvider provider) {
        return new InternalGroupProviderService(provider);
    }

    private class InternalGroupStoreDelegate implements GroupStoreDelegate {
        @Override
        public void notify(GroupEvent event) {
            final Group group = event.subject();
            GroupProvider groupProvider =
                    getProvider(group.deviceId());
            GroupOperations groupOps = null;
            switch (event.type()) {
                case GROUP_ADD_REQUESTED:
                    log.debug("GROUP_ADD_REQUESTED for Group {} on device {}",
                              group.id(), group.deviceId());
                    GroupOperation groupAddOp = GroupOperation.
                            createAddGroupOperation(group.id(),
                                                    group.type(),
                                                    group.buckets());
                    groupOps = new GroupOperations(
                            Collections.singletonList(groupAddOp));
                    groupProvider.performGroupOperation(group.deviceId(), groupOps);
                    break;

                case GROUP_UPDATE_REQUESTED:
                    log.debug("GROUP_UPDATE_REQUESTED for Group {} on device {}",
                              group.id(), group.deviceId());
                    GroupOperation groupModifyOp = GroupOperation.
                            createModifyGroupOperation(group.id(),
                                                       group.type(),
                                                       group.buckets());
                    groupOps = new GroupOperations(
                            Collections.singletonList(groupModifyOp));
                    groupProvider.performGroupOperation(group.deviceId(), groupOps);
                    break;

                case GROUP_REMOVE_REQUESTED:
                    log.debug("GROUP_REMOVE_REQUESTED for Group {} on device {}",
                              group.id(), group.deviceId());
                    GroupOperation groupDeleteOp = GroupOperation.
                            createDeleteGroupOperation(group.id(),
                                                       group.type());
                    groupOps = new GroupOperations(
                            Collections.singletonList(groupDeleteOp));
                    groupProvider.performGroupOperation(group.deviceId(), groupOps);
                    break;

                case GROUP_ADDED:
                case GROUP_UPDATED:
                case GROUP_REMOVED:
                case GROUP_ADD_FAILED:
                case GROUP_UPDATE_FAILED:
                case GROUP_REMOVE_FAILED:
                    post(event);
                    break;

                default:
                    break;
            }
        }
    }

    private class InternalGroupProviderService
            extends AbstractProviderService<GroupProvider>
            implements GroupProviderService {

        protected InternalGroupProviderService(GroupProvider provider) {
            super(provider);
        }

        @Override
        public void groupOperationFailed(DeviceId deviceId, GroupOperation operation) {
            store.groupOperationFailed(deviceId, operation);
        }

        @Override
        public void pushGroupMetrics(DeviceId deviceId,
                                     Collection<Group> groupEntries) {
            log.trace("Received group metrics from device {}", deviceId);
            checkValidity();
            store.pushGroupMetrics(deviceId, groupEntries);
        }
    }

    private class InternalDeviceListener implements DeviceListener {

        @Override
        public void event(DeviceEvent event) {
            switch (event.type()) {
                case DEVICE_REMOVED:
                case DEVICE_AVAILABILITY_CHANGED:
                    if (!deviceService.isAvailable(event.subject().id())) {
                        log.debug("Device {} became un available; clearing initial audit status",
                                  event.type(), event.subject().id());
                        store.deviceInitialAuditCompleted(event.subject().id(), false);
                    }
                    break;

                default:
                    break;
            }
        }
    }
}


text:
package org.livingdoc.engine.execution.examples.decisiontables;

import static org.mockito.Mockito.mock;

import org.livingdoc.api.fixtures.decisiontables.AfterRow;
import org.livingdoc.api.fixtures.decisiontables.AfterTable;
import org.livingdoc.api.fixtures.decisiontables.BeforeFirstCheck;
import org.livingdoc.api.fixtures.decisiontables.BeforeRow;
import org.livingdoc.api.fixtures.decisiontables.BeforeTable;
import org.livingdoc.api.fixtures.decisiontables.Check;
import org.livingdoc.api.fixtures.decisiontables.Input;
import org.mockito.Mockito;

public class ExtendedLifeCycleFixture {

    public static Callback callback = mock(Callback.class);

    @BeforeTable
    static void beforeTable1() {
        callback.beforeTable1();
    }

    @BeforeTable
    static void beforeTable2() {
        callback.beforeTable2();
    }

    @BeforeRow
    void beforeRow1() {
        callback.beforeRow1();
    }

    @BeforeRow
    void beforeRow2() {
        callback.beforeRow2();
    }

    @Input("input")
    void input(String value) {
        callback.input(value);
    }

    @BeforeFirstCheck
    void beforeFirstCheck1() {
        callback.beforeFirstCheck1();
    }

    @BeforeFirstCheck
    void beforeFirstCheck2() {
        callback.beforeFirstCheck2();
    }

    @Check("check")
    void check(String value) {
        callback.check(value);
    }

    @AfterRow
    void afterRow1() {
        callback.afterRow1();
    }

    @AfterRow
    void afterRow2() {
        callback.afterRow2();
    }

    @AfterTable
    static void afterTable1() {
        callback.afterTable1();
    }

    @AfterTable
    static void afterTable2() {
        callback.afterTable2();
    }

    public static void reset() {
        Mockito.reset(callback);
    }

    public interface Callback {

        void beforeTable1();

        void beforeTable2();

        void beforeRow1();

        void beforeRow2();

        void input(String value);

        void beforeFirstCheck1();

        void beforeFirstCheck2();

        void check(String value);

        void afterRow1();

        void afterRow2();

        void afterTable1();

        void afterTable2();

    }

}


text:
package com.kduda.battleships.model.unit;

import javafx.geometry.Orientation;

public class GroundLevelUnit extends Unit {
    private final int LENGTH;
    private Orientation orientation;

    public GroundLevelUnit(int size) {
        super(size);
        this.LENGTH = size;
        this.orientation = Orientation.VERTICAL;
    }

    @Override
    public void rotateUnit() {
        if (this.LENGTH == 1) return;

        if (this.orientation == Orientation.VERTICAL)
            this.orientation = Orientation.HORIZONTAL;
        else
            this.orientation = Orientation.VERTICAL;
    }

    @Override
    public int getLength() {
        return this.LENGTH;
    }

    public Orientation getOrientation() {
        return orientation;
    }

    public void setOrientation(Orientation orientation) {
        this.orientation = orientation;
    }
}


text:
"""
Define the list of internal 'special' variables that TeX requires to run. TeX
uses these to keep track of what's going on, such as the height of the current
page so far. These may vary while TeX runs, as opposed to the more static
'Parameters'. However, they are similar in many ways.
They have two types: integers, and dimensions (physical lengths).
"""
from typing import Dict, Tuple

from enum import Enum

from .instructions import Instructions
from ..utils import enums_to_values

class Specials(Enum):
    space_factor = 'SPACE_FACTOR'
    # The number of lines in the paragraph most recently completed or partially
    # completed.
    prev_graf = 'PREV_GRAF'
    # The number of times \output was called since the last \shipout.
    dead_cycles = 'DEAD_CYCLES'
    # Means different things:
    # 1. In the ouput routine, the total number of held-over insertions. For
    #    each class of insertions this includes the unused part of a split
    #    insertion and all other insertions which don't appear on the current
    #    page.
    # 2. In the page-making routine, the total of the \floatingpenalty for each
    #    unsplit insertion which is carried over to the next page.
    insert_penalties = 'INSERT_PENALTIES'

    # The depth of the last box added to the current vertical list.
    prev_depth = 'PREV_DEPTH'
    # The actual depth of the last box on the main page.
    page_depth = 'PAGE_DEPTH'
    # The desired height of the current page.
    page_goal = 'PAGE_GOAL'
    # The accumulated height of the current page.
    page_total = 'PAGE_TOTAL'
    # The amount of finite stretchability in the current page.
    page_stretch = 'PAGE_STRETCH'
    # The amount of first-order infinite stretchability in the current page.
    page_fil_stretch = 'PAGE_FIL_STRETCH'
    # The amount of second-order infinite stretchability in the current page.
    page_fill_stretch = 'PAGE_FILL_STRETCH'
    # The amount of third-order infinite stretchability in the current page.
    page_filll_stretch = 'PAGE_FILLL_STRETCH'
    # The amount of finite shrinkability in the current page.
    page_shrink = 'PAGE_SHRINK'

special_to_instr: Dict[Specials, Instructions] = {
    Specials.space_factor: Instructions.special_integer,
    # The number of lines in the paragraph most recently completed or partially
    # completed.
    Specials.prev_graf: Instructions.special_integer,
    # The number of times \output was called since the last \shipout.
    Specials.dead_cycles: Instructions.special_integer,
    # Means different things:
    # 1. In the ouput routine, the total number of held-over insertions. For
    #    each class of insertions this includes the unused part of a split
    #    insertion and all other insertions which don't appear on the current
    #    page.
    # 2. In the page-making routine, the total of the \floatingpenalty for each
    #    unsplit insertion which is carried over to the next page.
    Specials.insert_penalties: Instructions.special_integer,

    # The depth of the last box added to the current vertical list.
    Specials.prev_depth: Instructions.special_dimen,
    # The actual depth of the last box on the main page.
    Specials.page_depth: Instructions.special_dimen,
    # The desired height of the current page.
    Specials.page_goal: Instructions.special_dimen,
    # The accumulated height of the current page.
    Specials.page_total: Instructions.special_dimen,
    # The amount of finite stretchability in the current page.
    Specials.page_stretch: Instructions.special_dimen,
    # The amount of first-order infinite stretchability in the current page.
    Specials.page_fil_stretch: Instructions.special_dimen,
    # The amount of second-order infinite stretchability in the current page.
    Specials.page_fill_stretch: Instructions.special_dimen,
    # The amount of third-order infinite stretchability in the current page.
    Specials.page_filll_stretch: Instructions.special_dimen,
    # The amount of finite shrinkability in the current page.
    Specials.page_shrink: Instructions.special_dimen,
}

special_to_type: Dict[Specials, str] = {
    s: instr.value
    for s, instr in special_to_instr.items()
}

special_instrs: Tuple[Instructions, ...] = (
    Instructions.special_integer,
    Instructions.special_dimen,
)

special_instr_types: Tuple[str, ...] = enums_to_values(special_instrs)

def is_special_type(type_: str) -> bool:
    return type_ in special_instr_types


text:
<md-card>
  <md-card-content>
<form name="logEntry" ng-submit="addLog()">

Write a quick note.

    <md-input-container class="md-block">
        Write a note, e.g. "Blossomed today!"
        <textarea ng-model="log_body" columns="1" rows="5" required></textarea>
    </md-input-container>
    <md-input-container>
        <md-button class="md-raised md-accent" type="submit">Make Entry</md-button>
    </md-input-container>
</form>
  </md-card-content>
</md-card>

<md-card ng-if="model.log_entries.length">
  <md-card-content>

Notes: {{model.common_name}}

  <md-list>
  <md-list-item class="md-3-line" ng-repeat="log_entry in model.log_entries | orderBy:'-id'" ng-click="editLog($event, log_entry)">

{{log_entry.pub_date | amDateFormat:'dddd, MMMM Do YYYY'}}

{{log_entry.body}}

<md-divider></md-divider>
      </md-list-item>
  </md-list>
  </md-card-content>
  </md-card>


text:
package test.obv;

//
// IDL:TestFixStructBox:1.0
//
final public class TestFixStructBoxHolder implements org.omg.CORBA.portable.Streamable
{
    public TestFixStruct value;

    public
    TestFixStructBoxHolder()
    {
    }

    public
    TestFixStructBoxHolder(TestFixStruct initial)
    {
        value = initial;
    }

    public void
    _read(org.omg.CORBA.portable.InputStream in)
    {
        value = TestFixStructBoxHelper.read(in);
    }

    public void
    _write(org.omg.CORBA.portable.OutputStream out)
    {
        TestFixStructBoxHelper.write(out, value);
    }

    public org.omg.CORBA.TypeCode
    _type()
    {
        return TestFixStructBoxHelper.type();
    }
}


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Jacksonia compressa Turcz.

### Remarks
null


text:
package test;

/**
 * @auther xzl on 11:55 2018/1/30
 */
class Person {
    public String gentle = "Father";
}

public class Student extends Person {

    public String gentle = "Son";

    public String print(){
        return super.gentle;       // 在子类中访问父类中同名成员变
    }

    public static void main(String[] args) throws ClassNotFoundException {
        Student student = new Student();
        System.out.println("##### " + student.gentle);
        Person p = student;
        System.out.println("***** " + p.gentle);    //隐藏:编译时决定,不会发生多态

        System.out.println("----- " + student.print());
        Person p1 = new Student();
        System.out.println("----- " + ((Student)p1).print());    //Error:Person 中未定义该方法
    }
}


text:
from django import template
register = template.Library()
import re

class RenderDataNode(template.Node):
    def __init__(self, content):
        self.content = template.Variable(content)

    def render(self, context):
        try:
            actual_content = self.content.resolve(context)
            if actual_content.find('{{') != -1:
                variables = re.findall(r"{{.*}}", actual_content)
                for var in variables:
                    try:
                        actual_var = template.Variable(var.strip('{{').strip('}}')).resolve(context)
                        actual_content = actual_content.replace(var,actual_var)
                    except template.VariableDoesNotExist:
                        pass
            actual_content = actual_content.replace("\n", '<br/>')
            return actual_content
        except template.VariableDoesNotExist:
            return ''

@register.tag
def render_data(parser, token):
    tag_name, content = token.split_contents()
    return RenderDataNode(content)


text:
TIDComponent DDDriverFileCommands::<BIG>SetFileProtections</BIG>

TID
SDC

<short_desc xmlns="">
          Change the file attribute for the file name provided to the value of the new file protection provided.
        </short_desc>

<detailed_desc xmlns="">
          Change the file attribute for the file name provided to the value of the new file protection provided. An integer containing the new attributes for the file. Here is a description of attributes that can be modified:

0 Normal file (Windows PC Only)

1 Read-only file

2 Hidden file (Windows PC Only)

4 System file (Windows PC Only)

32 Archive - file has changed since last backup (Windows PC Only)

Note: Java-based support like RJ, TID, SDC currently only support setting one
          file protection at a time--0, 1, 2, 3, 32. They do not yet support Integer values OR'd
          together to combine settings in a single call.

Note: On platforms other than windows we currently only support setting the READ-ONLY
          attribute.

</detailed_desc>

Fields: [ ]=Optional with Default Value

FileName

<short_desc xmlns="">
              The file path and file name of the file change the file attribute.
            </short_desc>

FileProtection

<short_desc xmlns="">
              New value of the attribute of the file to be changed
            </short_desc>

Examples:

<usage xmlns="">
            C, SetFileProtections, "Test1.txt" , 1
          </usage>

<short_desc xmlns="">
              File attribute of the file Project/Datapool/Test1.txt is changed to 1 (read-only)
            </short_desc>

<usage xmlns="">
            C, SetFileProtections, "C:Test1.txt" , 0
          </usage>

<short_desc xmlns="">
              File attribute of the file C:Test1.txt is change to 0 (read-write)
            </short_desc>

[How To Read This Reference]


text:
"use strict";

var sinon = require('sinon');
var chai = require('chai');
chai.use(require('chai-fuzzy'));
var sinonChai = require("sinon-chai");
chai.use(sinonChai);
var should = chai.should();
var expect = require('chai').expect;

var ChainLogger = require('./../../../lib/Logging/ChainLogger');
var EchoSQLLogger = require('./../../../lib/Logging/EchoSQLLogger');
var DebugStackLogger = require('./../../../lib/Logging/DebugStackLogger');

describe('ChainLogger', function () {
    describe('#addLogger()', function () {
        it('should throw an error since logger param is missing', function () {
            let chainLogger = new ChainLogger();
            expect(function () {
                chainLogger.addLogger();
            }).to.throw('logger parameter is missing.');
        });
        it('should throw an error since logger param is not an object', function () {
            let chainLogger = new ChainLogger();
            expect(function () {
                chainLogger.addLogger('');
            }).to.throw('logger expected to be object got string.');
        });
        it('should add the logger', function () {
            let echoSQLLogger = new EchoSQLLogger();
            let debugStackLogger = new DebugStackLogger();
            let chainLogger = new ChainLogger();
            chainLogger.loggers.should.have.length(0);
            chainLogger.addLogger(echoSQLLogger);
            chainLogger.loggers.should.have.length(1);
            chainLogger.loggers[0].should.equal(echoSQLLogger);
            chainLogger.addLogger(debugStackLogger);
            chainLogger.loggers.should.have.length(2);
            chainLogger.loggers[1].should.equal(debugStackLogger);
        });
    });
    describe('#startQuery()', function () {
        it('should throw an error since sql param is missing', function () {
            let chainLogger = new ChainLogger();
            expect(function () {
                chainLogger.startQuery();
            }).to.throw('sql parameter is missing.');
        });
        it('should throw an error since params param is not an array', function () {
            let chainLogger = new ChainLogger();
            expect(function () {
                chainLogger.startQuery('');
            }).to.throw('params expected to be array got object.');
        });
        it('should start logging', function () {
            let echoSQLLogger = new EchoSQLLogger();
            let debugStackLogger = new DebugStackLogger();
            let chainLogger = new ChainLogger();
            chainLogger.addLogger(echoSQLLogger);
            chainLogger.addLogger(debugStackLogger);
            let sql = 'SELECT * FROM user';
            let params = [1, 2, 3];
            sinon.spy(console, 'log');
            chainLogger.startQuery(sql, params);
            expect(console.log).to.have.been.calledOne;
            expect(console.log).to.have.been.calledWith(`${sql} [${params.join(', ')}]`);
            chainLogger.loggers[1].queries[0]['start'].should.be.a('array');
            chainLogger.loggers[1].currentQuery.should.equal(1);
            console.log.restore();
        });
    });
    describe('#stopQuery()', function () {
        it('should stop logging', function (done) {
            let echoSQLLogger = new EchoSQLLogger();
            let debugStackLogger = new DebugStackLogger();
            let chainLogger = new ChainLogger();
            chainLogger.addLogger(echoSQLLogger);
            chainLogger.addLogger(debugStackLogger);
            let sql = 'SELECT * FROM user';
            let params = [1, 2, 3];
            sinon.spy(console, 'log');
            chainLogger.startQuery(sql, params);
            setTimeout(function () {
                chainLogger.stopQuery();
                chainLogger.loggers[1].queries[0]['start'].should.be.a('array');
                chainLogger.loggers[1].queries[0]['executionMS'].should.be.a('array');
                console.log.restore();
                done();
            }, 500);
        });
    });
});


text:
namespace
{
    // The shared display and its reference counter
    Display* sharedDisplay = NULL;
    unsigned int referenceCount = 0;

    typedef std::map<std::string, xcb_atom_t> AtomMap;
    AtomMap atoms;
}

namespace sf
{
namespace priv
{
////////////////////////////////////////////////////////////
Display* OpenDisplay()
{
    if (referenceCount == 0)
    {
        sharedDisplay = XOpenDisplay(NULL);

        // Opening display failed: The best we can do at the moment is to output a meaningful error message
        // and cause an abnormal program termination
        if (!sharedDisplay)
        {
            err() << "Failed to open X11 display; make sure the DISPLAY environment variable is set correctly" << std::endl;
            std::abort();
        }
    }

    referenceCount++;
    return sharedDisplay;
}

////////////////////////////////////////////////////////////
xcb_connection_t* OpenConnection()
{
    return XGetXCBConnection(OpenDisplay());
}

////////////////////////////////////////////////////////////
void CloseDisplay(Display* display)
{
    assert(display == sharedDisplay);

    referenceCount--;
    if (referenceCount == 0)
        XCloseDisplay(display);
}

////////////////////////////////////////////////////////////
void CloseConnection(xcb_connection_t* connection)
{
    assert(connection == XGetXCBConnection(sharedDisplay));
    return CloseDisplay(sharedDisplay);
}

////////////////////////////////////////////////////////////
xcb_screen_t* XCBScreenOfDisplay(xcb_connection_t* connection, int screen_nbr)
{
    xcb_screen_iterator_t iter = xcb_setup_roots_iterator(xcb_get_setup(connection));

    for (; iter.rem; --screen_nbr, xcb_screen_next (&iter))
    {
        if (screen_nbr == 0)
            return iter.data;
    }

    return NULL;
}

////////////////////////////////////////////////////////////
xcb_screen_t* XCBDefaultScreen(xcb_connection_t* connection)
{
    assert(connection == XGetXCBConnection(sharedDisplay));
    return XCBScreenOfDisplay(connection, XDefaultScreen(sharedDisplay));
}

////////////////////////////////////////////////////////////
xcb_window_t XCBDefaultRootWindow(xcb_connection_t* connection)
{
    assert(connection == XGetXCBConnection(sharedDisplay));
    xcb_screen_t* screen = XCBScreenOfDisplay(connection, XDefaultScreen(sharedDisplay));
    if (screen)
        return screen->root;
    return 0;
}

////////////////////////////////////////////////////////////
xcb_atom_t getAtom(const std::string& name, bool onlyIfExists)
{
    AtomMap::const_iterator iter = atoms.find(name);

    if (iter != atoms.end())
        return iter->second;

    ScopedXcbPtr<xcb_generic_error_t> error(NULL);

    xcb_connection_t* connection = OpenConnection();

    ScopedXcbPtr<xcb_intern_atom_reply_t> reply(xcb_intern_atom_reply(
        connection,
        xcb_intern_atom(
            connection,
            onlyIfExists,
            name.size(),
            name.c_str()
        ),
        &error
    ));

    CloseConnection(connection);

    if (error || !reply)
    {
        err() << "Failed to get " << name << " atom." << std::endl;
        return XCB_ATOM_NONE;
    }

    atoms[name] = reply->atom;

    return reply->atom;
}

} // namespace priv

} // namespace sf


text:
#ifndef __RotationAffectorFactory_H__
#define __RotationAffectorFactory_H__

#include "OgreParticleFXPrerequisites.h"
#include "OgreParticleAffectorFactory.h"
#include "OgreRotationAffector.h"

namespace Ogre {

    /** Factory class for RotationAffector. */
    class _OgreParticleFXExport RotationAffectorFactory : public ParticleAffectorFactory
    {
        /** See ParticleAffectorFactory */
        String getName() const { return "Rotator"; }

        /** See ParticleAffectorFactory */
        ParticleAffector* createAffector(ParticleSystem* psys)
        {
            ParticleAffector* p = OGRE_NEW RotationAffector(psys);
            mAffectors.push_back(p);
            return p;
        }
    };

}

#endif


text:
class Spam:
    numInstances = 0
    def count(cls):                    # Per-class instance counters
        cls.numInstances += 1          # cls is lowest class above instance
    def __init__(self):
        self.count()                   # Passes self.__class__ to count
    count = classmethod(count)

class Sub(Spam):
    numInstances = 0
    def __init__(self):                # Redefines __init__
        Spam.__init__(self)

class Other(Spam):                     # Inherits __init__
    numInstances = 0


text:
lib\nant\nant -buildfile:default.build debug quick all
pause


text:
import {html, css, LitElement} from 'lit';
import {styleMap} from 'lit/directives/style-map';
import '@lit-labs/virtualizer';

// import {FlowLayout} from '@lit-labs/virtualizer';

import { runBenchmarkIfRequested } from '../../lib/benchmark.js';

class ContactCard extends LitElement {
    static get properties() {
        return {
            contact: {type: Object},
            open: {type: Boolean}
        };
    }

    static get styles() {
        return css`
            :host {
                display: block;
                width: 100%;
                margin: 0.5em 0;
            }
            div, details {
                padding: 1em;
                color: white;
                display: block;
            }
        `;
    }

    constructor() {
        super();
        this.open = false;
        this._details = 'HTMLDetailsElement' in window;
    }

    render() {
        const { mediumText, color, name } = this.contact || {};
        return html`

                ${name}

${mediumText}

        `;
    }

    _summaryStyle() {
        return (!this._details && !this.open) ? { display: 'none' } : { display: 'block' };
    }

    _handleSummaryClick() {
        if (!this._details) {
            this.open = !this.open;
        }
    }
}

customElements.define('contact-card', ContactCard);

class ContactList extends LitElement {
    static get properties() {
        return {
            data: {type: Array}
        };
    }

    static get styles() {
        return css`
        :host {
            display: block;
            position: absolute;
            top: 0;
            right: 0;
            bottom: 0;
            left: 0;
        }
        lit-virtualizer {
            height: 100%;
        }
        `
    }

    constructor() {
        super();
        this.data = [];
    }

    async firstUpdated() {
        const resp = await fetch('../shared/contacts.json');
        this.data = await resp.json();
        runBenchmarkIfRequested(this.shadowRoot.querySelector('lit-virtualizer'));
    }

    _renderContact(contact) {
        return html`
            <contact-card .contact=${contact}></contact-card>
        `;
    }

    render() {
        return html`
            <lit-virtualizer scroller
                .items=${this.data}
                .renderItem=${this._renderContact}>
            </lit-virtualizer>
        `;
    }
}

window.html = html;

customElements.define('contact-list', ContactList);


text:
package org.code.Realm;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.code.mvc.model.User;
import org.code.mvc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

/**
 * Created by s on 2017/9/26.
 */
public class MyRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;
    //授权 subject进行权限或者角色判断的时候就会执行这里
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String username = (String) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        Set<String> temp=userService.findRoles(username);
        simpleAuthorizationInfo.setRoles(temp);
        temp=userService.findPermissions(username);
        simpleAuthorizationInfo.setStringPermissions(temp);

        return simpleAuthorizationInfo;
    }
    //Authentication(认证)(认证身份)(登陆)
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String username= (String) authenticationToken.getPrincipal();
        User user=userService.getUserByUsername(username);
        if(user == null) {
            throw new UnknownAccountException();//没找到帐号
        }

        if(Boolean.TRUE.equals(user.getLocked())) {
            throw new LockedAccountException(); //帐号锁定
        }
        //交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配,如果觉得人家的不好可以自定义实现
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                user.getUsername(), //用户名
                user.getPassword(), //密码
                ByteSource.Util.bytes(user.getCredentialsSalt()),//salt=username+salt
                getName()  //realm name
        );
        return authenticationInfo;
    }
}


text:
#pragma once

#include <aws/core/client/CoreErrors.h>
#include <aws/rds/RDS_EXPORTS.h>

namespace Aws
{
namespace RDS
{
enum class RDSErrors
{
  //From Core//
  //////////////////////////////////////////////////////////////////////////////////////////
  INCOMPLETE_SIGNATURE = 0,
  INTERNAL_FAILURE = 1,
  INVALID_ACTION = 2,
  INVALID_CLIENT_TOKEN_ID = 3,
  INVALID_PARAMETER_COMBINATION = 4,
  INVALID_QUERY_PARAMETER = 5,
  INVALID_PARAMETER_VALUE = 6,
  MISSING_ACTION = 7, // SDK should never allow
  MISSING_AUTHENTICATION_TOKEN = 8, // SDK should never allow
  MISSING_PARAMETER = 9, // SDK should never allow
  OPT_IN_REQUIRED = 10,
  REQUEST_EXPIRED = 11,
  SERVICE_UNAVAILABLE = 12,
  THROTTLING = 13,
  VALIDATION = 14,
  ACCESS_DENIED = 15,
  RESOURCE_NOT_FOUND = 16,
  UNRECOGNIZED_CLIENT = 17,
  MALFORMED_QUERY_STRING = 18,
  SLOW_DOWN = 19,
  REQUEST_TIME_TOO_SKEWED = 20,
  INVALID_SIGNATURE = 21,
  SIGNATURE_DOES_NOT_MATCH = 22,
  NETWORK_CONNECTION = 99,

  UNKNOWN = 100,
  ///////////////////////////////////////////////////////////////////////////////////////////

  AUTHORIZATION_ALREADY_EXISTS_FAULT= static_cast<int>(Client::CoreErrors::SERVICE_EXTENSION_START_RANGE) + 1,
  AUTHORIZATION_NOT_FOUND_FAULT,
  AUTHORIZATION_QUOTA_EXCEEDED_FAULT,
  CERTIFICATE_NOT_FOUND_FAULT,
  DOMAIN_NOT_FOUND_FAULT,
  D_B_CLUSTER_ALREADY_EXISTS_FAULT,
  D_B_CLUSTER_NOT_FOUND_FAULT,
  D_B_CLUSTER_PARAMETER_GROUP_NOT_FOUND_FAULT,
  D_B_CLUSTER_QUOTA_EXCEEDED_FAULT,
  D_B_CLUSTER_ROLE_ALREADY_EXISTS_FAULT,
  D_B_CLUSTER_ROLE_NOT_FOUND_FAULT,
  D_B_CLUSTER_ROLE_QUOTA_EXCEEDED_FAULT,
  D_B_CLUSTER_SNAPSHOT_ALREADY_EXISTS_FAULT,
  D_B_CLUSTER_SNAPSHOT_NOT_FOUND_FAULT,
  D_B_INSTANCE_ALREADY_EXISTS_FAULT,
  D_B_INSTANCE_NOT_FOUND_FAULT,
  D_B_LOG_FILE_NOT_FOUND_FAULT,
  D_B_PARAMETER_GROUP_ALREADY_EXISTS_FAULT,
  D_B_PARAMETER_GROUP_NOT_FOUND_FAULT,
  D_B_PARAMETER_GROUP_QUOTA_EXCEEDED_FAULT,
  D_B_SECURITY_GROUP_ALREADY_EXISTS_FAULT,
  D_B_SECURITY_GROUP_NOT_FOUND_FAULT,
  D_B_SECURITY_GROUP_NOT_SUPPORTED_FAULT,
  D_B_SECURITY_GROUP_QUOTA_EXCEEDED_FAULT,
  D_B_SNAPSHOT_ALREADY_EXISTS_FAULT,
  D_B_SNAPSHOT_NOT_FOUND_FAULT,
  D_B_SUBNET_GROUP_ALREADY_EXISTS_FAULT,
  D_B_SUBNET_GROUP_DOES_NOT_COVER_ENOUGH_A_ZS,
  D_B_SUBNET_GROUP_NOT_ALLOWED_FAULT,
  D_B_SUBNET_GROUP_NOT_FOUND_FAULT,
  D_B_SUBNET_GROUP_QUOTA_EXCEEDED_FAULT,
  D_B_SUBNET_QUOTA_EXCEEDED_FAULT,
  D_B_UPGRADE_DEPENDENCY_FAILURE_FAULT,
  EVENT_SUBSCRIPTION_QUOTA_EXCEEDED_FAULT,
  INSTANCE_QUOTA_EXCEEDED_FAULT,
  INSUFFICIENT_D_B_CLUSTER_CAPACITY_FAULT,
  INSUFFICIENT_D_B_INSTANCE_CAPACITY_FAULT,
  INSUFFICIENT_STORAGE_CLUSTER_CAPACITY_FAULT,
  INVALID_D_B_CLUSTER_SNAPSHOT_STATE_FAULT,
  INVALID_D_B_CLUSTER_STATE_FAULT,
  INVALID_D_B_INSTANCE_STATE_FAULT,
  INVALID_D_B_PARAMETER_GROUP_STATE_FAULT,
  INVALID_D_B_SECURITY_GROUP_STATE_FAULT,
  INVALID_D_B_SNAPSHOT_STATE_FAULT,
  INVALID_D_B_SUBNET_GROUP_FAULT,
  INVALID_D_B_SUBNET_GROUP_STATE_FAULT,
  INVALID_D_B_SUBNET_STATE_FAULT,
  INVALID_EVENT_SUBSCRIPTION_STATE_FAULT,
  INVALID_OPTION_GROUP_STATE_FAULT,
  INVALID_RESTORE_FAULT,
  INVALID_S3_BUCKET_FAULT,
  INVALID_SUBNET,
  INVALID_V_P_C_NETWORK_STATE_FAULT,
  K_M_S_KEY_NOT_ACCESSIBLE_FAULT,
  OPTION_GROUP_ALREADY_EXISTS_FAULT,
  OPTION_GROUP_NOT_FOUND_FAULT,
  OPTION_GROUP_QUOTA_EXCEEDED_FAULT,
  POINT_IN_TIME_RESTORE_NOT_ENABLED_FAULT,
  PROVISIONED_IOPS_NOT_AVAILABLE_IN_A_Z_FAULT,
  RESERVED_D_B_INSTANCES_OFFERING_NOT_FOUND_FAULT,
  RESERVED_D_B_INSTANCE_ALREADY_EXISTS_FAULT,
  RESERVED_D_B_INSTANCE_NOT_FOUND_FAULT,
  RESERVED_D_B_INSTANCE_QUOTA_EXCEEDED_FAULT,
  RESOURCE_NOT_FOUND_FAULT,
  SHARED_SNAPSHOT_QUOTA_EXCEEDED_FAULT,
  SNAPSHOT_QUOTA_EXCEEDED_FAULT,
  SOURCE_NOT_FOUND_FAULT,
  STORAGE_QUOTA_EXCEEDED_FAULT,
  STORAGE_TYPE_NOT_SUPPORTED_FAULT,
  SUBNET_ALREADY_IN_USE,
  SUBSCRIPTION_ALREADY_EXIST_FAULT,
  SUBSCRIPTION_CATEGORY_NOT_FOUND_FAULT,
  SUBSCRIPTION_NOT_FOUND_FAULT,
  S_N_S_INVALID_TOPIC_FAULT,
  S_N_S_NO_AUTHORIZATION_FAULT,
  S_N_S_TOPIC_ARN_NOT_FOUND_FAULT
};
namespace RDSErrorMapper
{
  AWS_RDS_API Client::AWSError<Client::CoreErrors> GetErrorForName(const char* errorName);
}

} // namespace RDS
} // namespace Aws


text:
from astral import Astral, Location

from idiotic.config import config as global_config
from idiotic import block
from datetime import date, datetime, timedelta
import logging
import asyncio
import pytz

log = logging.getLogger(__name__)

def construct_location(info):
    if "city" in info:
        a = Astral()
        a.solar_depression = "civil"
        return a[info["city"]]

    loc = Location()

    if "name" in info:
        loc.name = info["name"]

    if "latitude" in info and "longitude" in info:
        loc.latitude = info["latitude"]
        loc.longitude = info["longitude"]

    if "elevation" in info:
        loc.elevation = info["elevation"]

    if "timezone" in info:
        loc.timezone = info["timezone"]

    return loc

class Sun(block.Block):
    def __init__(self, name, **params):
        super().__init__(name, **params)

        default_location = global_config.get("modules", {}).get("suntime", {}).get("location")

        if "location" in params:
            self.location = construct_location(params["location"])
        else:
            self.location = construct_location(default_location)

        self._next_calculate = datetime.now()

    async def _recalculate(self):
        sun = self.location.sun(date.today(), local=True)
        dawn, sunrise, noon, sunset, dusk = sun['dawn'], sun['sunrise'], sun['noon'], sun['sunset'], sun['dusk']

        now = self._localtime()

        state = None
        sun_up = False
        next_event = None

        if dawn < now < sunrise:
            state = 'dawn'
            sun_up = True
            next_event = sunrise
        elif sunrise < now < noon:
            state = 'morning'
            sun_up = True
            next_event = noon
        elif noon < now < sunset:
            state = 'afternoon'
            sun_up = True
            next_event = sunset
        elif sunset < now < dusk:
            state = 'dusk'
            sun_up = False
            next_event = dusk
        elif dusk < now or now < dawn:
            state = 'night'
            sun_up = False

            tomorrow_sun = self.location.sun(date.today() + timedelta(days=1), local=True)
            next_event = tomorrow_sun['dawn']

        self._next_calculate = next_event

        log.debug("Next calculate at" + str(self._next_calculate))

        await self.output(sun_up)
        await self.output(state, 'period_of_day')
        await self.output(sun_up, 'up')
        await self.output(not sun_up, 'down')

    def _localtime(self):
        return pytz.timezone(self.location.timezone).localize(datetime.now())

    async def run(self):
        await self._recalculate()
        while True:
            if self._next_calculate:
                await asyncio.sleep((self._next_calculate - self._localtime()).seconds)

            await self._recalculate()