text:
package vsphere

import (
	"context"
	"fmt"
	"path"
	"path/filepath"
	"strings"

	"github.com/libopenstorage/openstorage/pkg/storageops"
	"github.com/sirupsen/logrus"
	"github.com/vmware/govmomi"
	"github.com/vmware/govmomi/find"
	"github.com/vmware/govmomi/object"
	"github.com/vmware/govmomi/property"
	"github.com/vmware/govmomi/vim25/mo"
	"github.com/vmware/govmomi/vim25/types"
	"k8s.io/kubernetes/pkg/cloudprovider/providers/vsphere/vclib"
	"k8s.io/kubernetes/pkg/cloudprovider/providers/vsphere/vclib/diskmanagers"
)

const (
	diskDirectory  = "osd-provisioned-disks"
	dummyDiskName  = "kube-dummyDisk.vmdk"
	diskByIDPath   = "/dev/disk/by-id/"
	diskSCSIPrefix = "wwn-0x"
)

type vsphereOps struct {
	vm   *vclib.VirtualMachine
	conn *vclib.VSphereConnection
	cfg  *VSphereConfig
}

// VirtualDisk encapsulates the existing virtual disk object to add a managed object
// reference to the datastore of the disk
type VirtualDisk struct {
	diskmanagers.VirtualDisk
	// DatastoreRef is the managed object reference of the datastore on which the disk belongs
	DatastoreRef types.ManagedObjectReference
}

// NewClient creates a new vsphere storageops instance
func NewClient(cfg *VSphereConfig) (storageops.Ops, error) {
	vSphereConn := &vclib.VSphereConnection{
		Username:          cfg.User,
		Password:          cfg.Password,
		Hostname:          cfg.VCenterIP,
		Insecure:          cfg.InsecureFlag,
		RoundTripperCount: cfg.RoundTripperCount,
		Port:              cfg.VCenterPort,
	}

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	vmObj, err := GetVMObject(ctx, vSphereConn, cfg.VMUUID)
	if err != nil {
		return nil, err
	}

	logrus.Debugf("Using following configuration for vsphere:")
	logrus.Debugf("  vCenter: %s:%s", cfg.VCenterIP, cfg.VCenterPort)
	logrus.Debugf("  Datacenter: %s", vmObj.Datacenter.Name())
	logrus.Debugf("  VMUUID: %s", cfg.VMUUID)

	return &vsphereOps{
		cfg:  cfg,
		vm:   vmObj,
		conn: vSphereConn,
	}, nil
}

func (ops *vsphereOps) Name() string { return "vsphere" }

func (ops *vsphereOps) InstanceID() string { return ops.cfg.VMUUID }

func (ops *vsphereOps) Create(opts interface{}, labels map[string]string) (interface{}, error) {
	volumeOptions, ok := opts.(*vclib.VolumeOptions)
	if !ok {
		return nil, fmt.Errorf("invalid volume options specified to create: %v", opts)
	}

	if len(volumeOptions.Tags) == 0 {
		volumeOptions.Tags = labels
	} else {
		for k, v := range labels {
			volumeOptions.Tags[k] = v
		}
	}

	if len(volumeOptions.Datastore) == 0 {
		return nil, fmt.Errorf("datastore is required for the create call")
	}

	datastore := strings.TrimSpace(volumeOptions.Datastore)
	logrus.Infof("Given datastore/datastore cluster: %s for new disk", datastore)

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	vmObj, err := ops.renewVM(ctx, ops.vm)
	if err != nil {
		return nil, err
	}

	isPod, storagePod, err := IsStoragePod(ctx, vmObj, volumeOptions.Datastore)
	if err != nil {
		return nil, err
	}

	if isPod {
		datastore, err = ops.getDatastoreToUseInStoragePod(ctx, vmObj, volumeOptions, storagePod)
		if err != nil {
			return nil, err
		}
	}

	logrus.Infof("Using datastore: %s for new disk", datastore)

	ds, err := vmObj.Datacenter.GetDatastoreByName(ctx, datastore)
	if err != nil {
		logrus.Errorf("Failed to get datastore: %s due to: %v", datastore, err)
		return nil, err
	}

	volumeOptions.Datastore = datastore

	diskBasePath := filepath.Clean(ds.Path(diskDirectory)) + "/"
	err = ds.CreateDirectory(ctx, diskBasePath, false)
	if err != nil && err != vclib.ErrFileAlreadyExist {
		logrus.Errorf("Cannot create dir %#v. err %s", diskBasePath, err)
		return nil, err
	}

	diskPath := diskBasePath + volumeOptions.Name + ".vmdk"
	disk := diskmanagers.VirtualDisk{
		DiskPath:      diskPath,
		VolumeOptions: volumeOptions,
	}

	diskPath, err = disk.Create(ctx, ds)
	if err != nil {
		logrus.Errorf("Failed to create a vsphere volume with volumeOptions: %+v on "+
			"datastore: %s. err: %+v", volumeOptions, datastore, err)
		return nil, err
	}

	// Get the canonical path for the volume path.
	canonicalVolumePath, err := getCanonicalVolumePath(ctx, vmObj.Datacenter, diskPath)
	if err != nil {
		logrus.Errorf("Failed to get canonical vsphere disk path for: %s with "+
			"volumeOptions: %+v on datastore: %s. err: %+v", diskPath, volumeOptions, datastore, err)
		return nil, err
	}

	disk.DiskPath = canonicalVolumePath

	return &VirtualDisk{
		VirtualDisk:  disk,
		DatastoreRef: ds.Reference(),
	}, nil
}

func (ops *vsphereOps) GetDeviceID(vDisk interface{}) (string, error) {
	disk, ok := vDisk.(*VirtualDisk)
	if !ok {
		return "", fmt.Errorf("invalid input: %v to GetDeviceID", vDisk)
	}

	return disk.DiskPath, nil
}

// Attach takes in the path of the vmdk file and returns where it is attached inside the vm instance
func (ops *vsphereOps) Attach(diskPath string) (string, error) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	vmObj, err := ops.renewVM(ctx, ops.vm)
	if err != nil {
		return "", err
	}

	diskUUID, err := vmObj.AttachDisk(ctx, diskPath, &vclib.VolumeOptions{SCSIControllerType: vclib.PVSCSIControllerType})
	if err != nil {
		logrus.Errorf("Failed to attach vsphere disk: %s for VM: %s. err: +%v", diskPath, vmObj.Name(), err)
		return "", err
	}

	return path.Join(diskByIDPath, diskSCSIPrefix+diskUUID), nil
}

func (ops *vsphereOps) Detach(diskPath string) error {
	return ops.detachInternal(diskPath, ops.cfg.VMUUID)
}

func (ops *vsphereOps) DetachFrom(diskPath, instanceID string) error {
	return ops.detachInternal(diskPath, instanceID)
}

func (ops *vsphereOps) detachInternal(diskPath, instanceID string) error {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	var vmObj *vclib.VirtualMachine
	var err error
	if instanceID == ops.cfg.VMUUID {
		vmObj, err = ops.renewVM(ctx, ops.vm)
		if err != nil {
			return err
		}
	} else {
		vmObj, err = GetVMObject(ctx, ops.conn, instanceID)
		if err != nil {
			return err
		}
	}

	if err := vmObj.DetachDisk(ctx, diskPath); err != nil {
		logrus.Errorf("Failed to detach vsphere disk: %s for VM: %s. err: +%v", diskPath, vmObj.Name(), err)
		return err
	}

	return nil
}

// Delete virtual disk at given path
func (ops *vsphereOps) Delete(diskPath string) error {
	return ops.deleteInternal(diskPath, ops.cfg.VMUUID)
}

func (ops *vsphereOps) DeleteFrom(diskPath, instanceID string) error {
	return ops.deleteInternal(diskPath, instanceID)
}

func (ops *vsphereOps) deleteInternal(diskPath, instanceID string) error {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	var vmObj *vclib.VirtualMachine
	var err error
	if instanceID == ops.cfg.VMUUID {
		vmObj, err = ops.renewVM(ctx, ops.vm)
		if err != nil {
			return err
		}
	} else {
		vmObj, err = GetVMObject(ctx, ops.conn, instanceID)
		if err != nil {
			return err
		}
	}

	disk := diskmanagers.VirtualDisk{
		DiskPath:      diskPath,
		VolumeOptions: &vclib.VolumeOptions{},
		VMOptions:     &vclib.VMOptions{},
	}

	err = disk.Delete(ctx, vmObj.Datacenter)
	if err != nil {
		logrus.Errorf("Failed to delete vsphere disk: %s. err: %+v", diskPath, err)
	}

	return err
}

// Desribe an instance of the virtual machine object to which ops is connected to
func (ops *vsphereOps) Describe() (interface{}, error) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	return ops.renewVM(ctx, ops.vm)
}

// FreeDevices is not supported by this provider
func (ops *vsphereOps) FreeDevices(blockDeviceMappings []interface{}, rootDeviceName string) ([]string, error) {
	return nil, storageops.ErrNotSupported
}

func (ops *vsphereOps) Inspect(diskPaths []*string) ([]interface{}, error) {
	// TODO find a way to map diskPaths to unattached/attached virtual disks and query info
	// currently returning the disks directly

	return nil, storageops.ErrNotSupported
}

// DeviceMappings returns map[local_attached_volume_path]->volume ID/NAME
func (ops *vsphereOps) DeviceMappings() (map[string]string, error) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	vmObj, err := ops.renewVM(ctx, ops.vm)
	if err != nil {
		return nil, err
	}

	vmDevices, err := vmObj.Device(ctx)
	if err != nil {
		return nil, fmt.Errorf("failed to get devices for vm: %s", vmObj.Name())
	}

	// Go over all the devices attached on this vm and create a map of just the virtual disks and where
	// they are attached on the vm
	m := make(map[string]string)
	for _, device := range vmDevices {
		if vmDevices.TypeName(device) == "VirtualDisk" {
			virtualDevice := device.GetVirtualDevice()
			backing, ok := virtualDevice.Backing.(*types.VirtualDiskFlatVer2BackingInfo)
			if ok {
				devicePath, err := ops.DevicePath(backing.FileName)
				if err == nil && len(devicePath) != 0 { // TODO can ignore errors?
					m[devicePath] = backing.FileName
				}
			}
		}
	}

	return m, nil
}

// DevicePath for the given volume i.e path where it's attached
func (ops *vsphereOps) DevicePath(diskPath string) (string, error) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	vmObj, err := ops.renewVM(ctx, ops.vm)
	if err != nil {
		return "", err
	}

	attached, err := vmObj.IsDiskAttached(ctx, diskPath)
	if err != nil {
		return "", fmt.Errorf("failed to check if disk: %s is attached on vm: %s. err: %v",
			diskPath, vmObj.Name(), err)
	}

	if !attached {
		return "", fmt.Errorf("disk: %s is not attached on vm: %s", diskPath, vmObj.Name())
	}

	diskUUID, err := vmObj.Datacenter.GetVirtualDiskPage83Data(ctx, diskPath)
	if err != nil {
		logrus.Errorf("failed to get device path for disk: %s on vm: %s", diskPath, vmObj.Name())
		return "", err
	}

	return path.Join(diskByIDPath, diskSCSIPrefix+diskUUID), nil
}

func (ops *vsphereOps) Enumerate(volumeIds []*string,
	labels map[string]string,
	setIdentifier string,
) (map[string][]interface{}, error) {
	return nil, storageops.ErrNotSupported
}

// Snapshot the volume with given volumeID
func (ops *vsphereOps) Snapshot(volumeID string, readonly bool) (interface{}, error) {
	return nil, storageops.ErrNotSupported
}

// SnapshotDelete deletes the snapshot with given ID
func (ops *vsphereOps) SnapshotDelete(snapID string) error {
	return storageops.ErrNotSupported
}

// ApplyTags will apply given labels/tags on the given volume
func (ops *vsphereOps) ApplyTags(volumeID string, labels map[string]string) error {
	return storageops.ErrNotSupported
}

// RemoveTags removes labels/tags from the given volume
func (ops *vsphereOps) RemoveTags(volumeID string, labels map[string]string) error {
	return storageops.ErrNotSupported
}

// Tags will list the existing labels/tags on the given volume
func (ops *vsphereOps) Tags(volumeID string) (map[string]string, error) {
	return nil, storageops.ErrNotSupported
}

// GetVMObject fetches the VirtualMachine object corresponding to the given virtual machine uuid
func GetVMObject(ctx context.Context, conn *vclib.VSphereConnection, vmUUID string) (*vclib.VirtualMachine, error) {
	// TODO change impl below using multiple goroutines and sync.WaitGroup to make it faster
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	if err := conn.Connect(ctx); err != nil {
		return nil, err
	}

	if len(vmUUID) == 0 {
		return nil, fmt.Errorf("virtual machine uuid is required")
	}

	datacenterObjs, err := vclib.GetAllDatacenter(ctx, conn)
	if err != nil {
		return nil, err
	}

	// Lookup in each vsphere datacenter for this virtual machine
	for _, dc := range datacenterObjs {
		vm, err := dc.GetVMByUUID(ctx, vmUUID)
		if err != nil {
			if err != vclib.ErrNoVMFound {
				logrus.Warnf("failed to find vm with uuid: %s in datacenter: %s due to err: %v", vmUUID, dc.Name(), err)
				// don't let one bad egg fail entire search. keep looking.
			} else {
				logrus.Debugf("did not find vm with uuid: %s in datacenter: %s", vmUUID, dc.Name())
			}
			continue
		}

		if vm != nil {
			return vm, nil
		}
	}

	return nil, fmt.Errorf("failed to find vm with uuid: %s in any datacenter for vc: %s", vmUUID, conn.Hostname)
}

func (ops *vsphereOps) renewVM(ctx context.Context, vm *vclib.VirtualMachine) (*vclib.VirtualMachine, error) {
	var client *govmomi.Client
	err := ops.conn.Connect(ctx)
	if err != nil {
		client, err = ops.conn.NewClient(ctx)
		if err != nil {
			return nil, err
		}
	} else {
		client = ops.conn.GoVmomiClient
	}

	vmObj := vm.RenewVM(client)
	return &vmObj, nil
}

// getDatastoreToUseInStoragePod asks the storage resource manager to recommend a datastore
// in the given storage pod (datastore cluster) for the required disk spec
func (ops *vsphereOps) getDatastoreToUseInStoragePod(
	ctx context.Context, vmObj *vclib.VirtualMachine,
	volumeOptions *vclib.VolumeOptions, storagePod *object.StoragePod) (string, error) {
	logrus.Infof("Using storage pod: %s", storagePod.Name())

	// devices is a list of devices in the virtual machine (disks and disk controllers) that
	// will be part of the request spec to storage resource manager
	var devices object.VirtualDeviceList
	scsi, err := devices.CreateSCSIController("scsi")
	if err != nil {
		return "", err
	}

	devices = append(devices, scsi)

	controller, err := devices.FindDiskController("scsi")
	if err != nil {
		return "", err
	}

	disk := &types.VirtualDisk{
		VirtualDevice: types.VirtualDevice{
			Key: devices.NewKey(),
			Backing: &types.VirtualDiskFlatVer2BackingInfo{
				DiskMode:        string(types.VirtualDiskModePersistent),
				ThinProvisioned: types.NewBool(true),
			},
		},
		CapacityInKB: int64(volumeOptions.CapacityKB),
	}

	devices = append(devices, disk)
	devices.AssignController(disk, controller)
	deviceChange, err := devices.ConfigSpec(types.VirtualDeviceConfigSpecOperationAdd)
	if err != nil {
		return "", err
	}

	spec := &types.VirtualMachineConfigSpec{
		Name: vmObj.Name(),
	}

	spec.DeviceChange = deviceChange
	recommendedDatastore, err := recommendDatastore(ctx, vmObj, storagePod, spec)
	if err != nil {
		return "", err
	}

	return recommendedDatastore.Name(), nil
}

// recommendedDatastore recommends a datastore to use for the given storage pod by
// quering the storage resource manager
// logic borrowwed from recommendDatastore() at https://github.com/vmware/govmomi/blob/master/govc/vm/create.go#L455
func recommendDatastore(
	ctx context.Context,
	vmObj *vclib.VirtualMachine,
	storagePod *object.StoragePod,
	spec *types.VirtualMachineConfigSpec) (*object.Datastore, error) {
	sp := storagePod.Reference()

	// Build pod selection spec from config spec
	podSelectionSpec := types.StorageDrsPodSelectionSpec{
		StoragePod: &sp,
	}

	for _, deviceConfigSpec := range spec.DeviceChange {
		s := deviceConfigSpec.GetVirtualDeviceConfigSpec()
		if s.Operation != types.VirtualDeviceConfigSpecOperationAdd {
			continue
		}

		if s.FileOperation != types.VirtualDeviceConfigSpecFileOperationCreate {
			continue
		}

		d, ok := s.Device.(*types.VirtualDisk)
		if !ok {
			continue
		}

		podConfigForPlacement := types.VmPodConfigForPlacement{
			StoragePod: sp,
			Disk: []types.PodDiskLocator{
				{
					DiskId:          d.Key,
					DiskBackingInfo: d.Backing,
				},
			},
		}

		podSelectionSpec.InitialVmConfig = append(podSelectionSpec.InitialVmConfig, podConfigForPlacement)
	}

	resourcePool, err := vmObj.ResourcePool(ctx)
	if err != nil {
		return nil, fmt.Errorf("failed to get vm resource pool due to: %v", err)
	}

	if resourcePool == nil {
		return nil, fmt.Errorf("failed to get vm resource pool")
	}

	resourcePoolRef := resourcePool.Reference()

	sps := types.StoragePlacementSpec{
		Type:             string(types.StoragePlacementSpecPlacementTypeCreate),
		PodSelectionSpec: podSelectionSpec,
		ConfigSpec:       spec,
		ResourcePool:     &resourcePoolRef,
	}

	srm := object.NewStorageResourceManager(vmObj.Client())
	result, err := srm.RecommendDatastores(ctx, sps)
	if err != nil {
		logrus.Errorf("failed to get datastore recommendations due to: %v", err)
		return nil, err
	}

	// Use result to pin disks to recommended datastores
	recs := result.Recommendations
	if len(recs) == 0 {
		return nil, fmt.Errorf("no datastores recommendations")
	}

	ds := recs[0].Action[0].(*types.StoragePlacementAction).Destination

	var mds mo.Datastore
	err = property.DefaultCollector(vmObj.Client()).RetrieveOne(ctx, ds, []string{"name"}, &mds)
	if err != nil {
		return nil, err
	}

	datastore := object.NewDatastore(vmObj.Client(), ds)
	datastore.InventoryPath = mds.Name

	return datastore, nil
}

// IsStoragePod checks if the object with given name is a StoragePod (Datastore cluster)
func IsStoragePod(ctx context.Context, vmObj *vclib.VirtualMachine, name string) (bool, *object.StoragePod, error) {
	f := find.NewFinder(vmObj.Client(), true)
	f.SetDatacenter(vmObj.Datacenter.Datacenter)
	sp, err := f.DatastoreCluster(ctx, name)
	if err != nil {
		if strings.Contains(err.Error(), "not found") {
			return false, nil, nil
		}

		logrus.Errorf("got error: %v fetching datastore cluster: %s", err, name)
		return false, nil, err
	}

	if sp == nil {
		return false, nil, nil
	}

	return true, sp, nil
}


text:
using MongoDB.Bson;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyTrattoria.Mongo.Entities
{
    public class Incasso
    {
        public ObjectId Id { get; set; }
        public DateTime DataIncasso { get; set; }
        public double Totale { get; set; }

        public Incasso()
        {
            this.DataIncasso = DateTime.UtcNow;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
(function ($) {
    jQuery.fn.dataContent = function (settings) {
        var config = {
            'loaderDiv': '

',
            'loaderCss': '.spinner {margin: auto auto;width: 50px;height: 30px;text-align: center;font-size: 10px;}.spinner > div {background-color: #ccc;height: 100%;width: 6px;display: inline-block;-webkit-animation: stretchdelay 1.2s infinite ease-in-out;animation: stretchdelay 1.2s infinite ease-in-out;}.spinner .rect2 {-webkit-animation-delay: -1.1s;animation-delay: -1.1s;}.spinner .rect3 {-webkit-animation-delay: -1.0s;animation-delay: -1.0s;}.spinner .rect4 {-webkit-animation-delay: -0.9s;animation-delay: -0.9s;}.spinner .rect5 {-webkit-animation-delay: -0.8s;animation-delay: -0.8s;}@-webkit-keyframes stretchdelay {0%, 40%, 100% { -webkit-transform: scaleY(0.4) }20% { -webkit-transform: scaleY(1.0) }}@keyframes stretchdelay {0%, 40%, 100% {transform: scaleY(0.4);-webkit-transform: scaleY(0.4);}  20% {transform: scaleY(1.0);-webkit-transform: scaleY(1.0);}}'
        };

        if (settings) {
            $.extend(config, settings);
        }

        var methods = {
            setElement: function (element) {
                config.element = element;
            },
            getElement: function () {
                return config.element;
            },

            setUrl: function (url) {
                config.url = url;
            },
            getUrl: function () {
                return config.url;
            },

            setInterval: function (interval) {
                config.interval = interval;
            },
            getInterval: function () {
                return (config.interval * 1000);
            },

            setLoading: function (loading) {
                config.loading = loading;
            },
            getLoading: function () {
                return config.loading;
            },

            load: function () {
                if (this.getLoading()) {
                    $(this.getElement()).html(config.loaderDiv);
                }

                if (this.getElement() && this.getUrl()) {
                    $(this.getElement()).load(this.getUrl());
                }
            },

            run: function () {
                if (this.getInterval()) {
                    this.setLoading(false);
                    this.load();

                    setInterval(function () {
                        methods.load();
                    }, this.getInterval());
                } else {
                    this.load();
                }
            }
        };

        return this.each(function () {
            $('body').append("");
            var $element = $(this);

            methods.setElement($element);
            methods.setUrl($element.data('href'));
            methods.setLoading($element.data('loading'));
            methods.setInterval($element.data('interval'));
            methods.run();
        });
    };

    $('[data-ajax-content="true"]').dataContent();
}(jQuery));


text:
'use strict';

System.register(['./config-builder', './common/polyfills', './exports'], function (_export, _context) {
  "use strict";

  var ConfigBuilder, polyfillElementClosest;

  function applyPolyfills() {
    polyfillElementClosest();
  }

  function configure(aurelia, configCallback) {
    applyPolyfills();
    var builder = new ConfigBuilder();

    if (configCallback !== undefined && typeof configCallback === 'function') {
      configCallback(builder);
    }

    if (builder.useGlobalResources) {
      aurelia.globalResources(builder.globalResources);
    }
  }

  _export('configure', configure);

  return {
    setters: [function (_configBuilder) {
      ConfigBuilder = _configBuilder.ConfigBuilder;
    }, function (_commonPolyfills) {
      polyfillElementClosest = _commonPolyfills.polyfillElementClosest;
    }, function (_exports) {
      var _exportObj = {};

      for (var _key in _exports) {
        if (_key !== "default" && _key !== "__esModule") _exportObj[_key] = _exports[_key];
      }

      _export(_exportObj);
    }],
    execute: function () {}
  };
});


text:
Editable GridView Control Example

This example explains how to create a window with an editable GridView control, bind to the data and show on the screen.
GridView is editable because we use gridviewtextboxcolumn column types.

<button id="EditableGridViewExample" class="try-example-button">Try Example</button>

UI Model

{
    "windows": [
        {
            "name": "EditableGridViewExample",
            "title": "Editable GridView Example",
            "width": 500,
            "height": 300,
            "controls": [
                {
                    "name": "managersGrid",
                    "type": "gridview",
                    "bindsTo": "list",
                    "canUserAddRows": false,
                    "columns": [
                        {
                            "type": "gridviewtextboxcolumn",
                            "name": "title",
                            "label": "Title",
                            "width": 170,
                            "bindsTo": "title"
                        },
                        {
                            "type": "gridviewtextboxcolumn",
                            "name": "name",
                            "label": "Name",
                            "width": 280,
                            "bindsTo": "name"
                        }
                    ]
                },
                {
                    "name": "OKButton",
                    "type": "button",
                    "text": "OK",
                    "isDialogButton": true,
                    "dialogResult": "OK"
                },
                {
                    "name": "CancelButton",
                    "type": "button",
                    "text": "Cancel",
                    "isDialogButton": true,
                    "dialogResult": "Cancel"
                }
            ]
        }
    ]
}

Data Model

var teamManagement = {
	list: [
		{
			id: 7,
			title: "Manager",
			name: "Fiorello Lombardi",
		},
		{
			id: 8,
			title: "Goalkeeping Coach",
			name: "Armando Arcuri",
		},
		{
			id: 9,
			title: "Assistant Manager",
			name: "Alessio Ferri",
		},
		{
			id: 10,
			title: "First-team Coach",
			name: "Giuseppe Milani",
		}
	]
};

var exampleWindow = redui.createNewWindow("EditableGridViewExample");
exampleWindow.bind(teamManagement);
exampleWindow.show();

exampleWindow.closed(function (target, dialogResult) {
	alert("GridView data: " + JSON.stringify(exampleWindow.managersGrid.bindingContext));
});


text:
/*! owl.carousel2.thumbs - v0.1.7 | (c) 2016 @gijsroge | MIT license | https://github.com/gijsroge/OwlCarousel2-Thumbs */
/**
 * Thumbs Plugin
 * @version 2.0.0
 * @author Gijs Rogé
 * @license The MIT License (MIT)
 */
(function ($, window, document, undefined) {
    'use strict';

    /**
     * Creates the thumbs plugin.
     * @class The thumbs Plugin
     * @param {Owl} carousel - The Owl Carousel
     */
    var Thumbs = function (carousel) {

        /**
         * Reference to the core.
         * @protected
         * @type {Owl}
         */
        this.owl = carousel;

        /**
         * All DOM elements for thumbnails
         * @protected
         * @type {Object}
         */
        this._thumbcontent = [];

        /**
         * Instance identiefier
         * @type {number}
         * @private
         */
        this._identifier = 0;

        /**
         * Return current item regardless of clones
         * @protected
         * @type {Object}
         */
        this.owl_currentitem = this.owl.options.startPosition;

        /**
         * The carousel element.
         * @type {jQuery}
         */
        this.$element = this.owl.$element;

        /**
         * All event handlers.
         * @protected
         * @type {Object}
         */
        this._handlers = {
            'prepared.owl.carousel': $.proxy(function (e) {
                if (e.namespace && this.owl.options.thumbs && !this.owl.options.thumbImage && !this.owl.options.thumbsPrerendered && !this.owl.options.thumbImage) {
                    if ($(e.content).find('[data-thumb]').attr('data-thumb') !== undefined) {
                        this._thumbcontent.push($(e.content).find('[data-thumb]').attr('data-thumb'));
                    }
                } else if (e.namespace && this.owl.options.thumbs && this.owl.options.thumbImage) {
                    var innerImage = $(e.content).find('img');
                    this._thumbcontent.push(innerImage);
                }
            }, this),

            'initialized.owl.carousel': $.proxy(function (e) {
                if (e.namespace && this.owl.options.thumbs) {
                    this.render();
                    this.listen();
                    this._identifier = this.owl.$element.data('slider-id');
                    this.setActive();
                }
            }, this),

            'changed.owl.carousel': $.proxy(function (e) {
                if (e.namespace && e.property.name === 'position' && this.owl.options.thumbs) {
                    this._identifier = this.owl.$element.data('slider-id');
                    this.setActive();
                }
            }, this)
        };

        // set default options
        this.owl.options = $.extend(Thumbs.Defaults, this.owl.options);

        // register the event handlers
        this.owl.$element.on(this._handlers);
    };

    /**
     * Default options.
     * @public
     */
    Thumbs.Defaults = {
        thumbs: true,
        thumbImage: false,
        thumbContainerClass: 'owl-thumbs',
        thumbItemClass: 'owl-thumb-item',
        moveThumbsInside: false
    };

    /**
     * Listen for thumbnail click
     * @protected
     */
    Thumbs.prototype.listen = function () {

        //set default options
        var options = this.owl.options;

        if (options.thumbsPrerendered) {
            this._thumbcontent._thumbcontainer = $('.' + options.thumbContainerClass);
        }

        //check what thumbitem has been clicked and move slider to that item
        $(this._thumbcontent._thumbcontainer).on('click', this._thumbcontent._thumbcontainer.children(), $.proxy(function (e) {

            // find relative slider
            this._identifier = $(e.target).closest('.' + options.thumbContainerClass).data('slider-id');

            // get index of clicked thumbnail
            var index = $(e.target).parent().is(this._thumbcontent._thumbcontainer) ? $(e.target).index() : $(e.target).closest('.'+options.thumbItemClass).index();

            if (options.thumbsPrerendered) {
                // slide to slide :)
                $('[data-slider-id=' + this._identifier + ']').trigger('to.owl.carousel', [index, options.dotsSpeed, true]);
            } else {
                this.owl.to(index, options.dotsSpeed);
            }

            e.preventDefault();
        }, this));
    };

    /**
     * Builds thumbnails
     * @protected
     */
    Thumbs.prototype.render = function () {

        //set default options
        var options = this.owl.options;
        $('‹›').appendTo(this.$element);

        //create thumbcontainer
        if (!options.thumbsPrerendered) {
            this._thumbcontent._thumbcontainer = $('
').addClass(options.thumbContainerClass).appendTo(this.$element);
        } else {
            this._thumbcontent._thumbcontainer = $('.' + options.thumbContainerClass + '');
            if(options.moveThumbsInside){
                this._thumbcontent._thumbcontainer.appendTo(this.$element);
            }
        }

        //create thumb items
        var i;
        if (!options.thumbImage) {
            for (i = 0; i < this._thumbcontent.length; ++i) {
                this._thumbcontent._thumbcontainer.append('<button class=' + options.thumbItemClass + '>' + this._thumbcontent[i] + '</button>');
            }
        } else {
            for (i = 0; i < this._thumbcontent.length; ++i) {
                this._thumbcontent._thumbcontainer.append('<button class=' + options.thumbItemClass + '></button>');
            }
        }
    };

    /**
     * Updates active class on thumbnails
     * @protected
     */
    Thumbs.prototype.setActive = function () {

        // get startslide
        this.owl_currentitem = this.owl._current - (this.owl._clones.length / 2);
        if (this.owl_currentitem === this.owl._items.length) {
            this.owl_currentitem = 0;
        }

        //set default options
        var options = this.owl.options;

        // set relative thumbnail container
        var thumbContainer = options.thumbsPrerendered ? $('.' + options.thumbContainerClass + '[data-slider-id="' + this._identifier + '"]') : this._thumbcontent._thumbcontainer;
        thumbContainer.children().filter('.active').removeClass('active');
        thumbContainer.children().eq(this.owl_currentitem).addClass('active');
    };

    /**
     * Destroys the plugin.
     * @public
     */
    Thumbs.prototype.destroy = function () {
        var handler, property;
        for (handler in this._handlers) {
            this.owl.$element.off(handler, this._handlers[handler]);
        }
        for (property in Object.getOwnPropertyNames(this)) {
            typeof this[property] !== 'function' && (this[property] = null);
        }
    };

    $.fn.owlCarousel.Constructor.Plugins.Thumbs = Thumbs;

})(window.Zepto || window.jQuery, window, document);


text:
package org.motechproject.nms.region.csv.impl;

import org.motechproject.nms.csv.utils.GetLong;
import org.motechproject.nms.csv.utils.GetString;
import org.motechproject.nms.csv.utils.Store;
import org.motechproject.nms.region.csv.CensusVillageImportService;
import org.motechproject.nms.region.domain.Village;
import org.motechproject.nms.region.repository.StateDataService;
import org.motechproject.nms.region.service.DistrictService;
import org.motechproject.nms.region.service.TalukaService;
import org.motechproject.nms.region.service.VillageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.supercsv.cellprocessor.ift.CellProcessor;

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

@Service("censusVillageImportService")
public class CensusVillageImportServiceImpl extends BaseLocationImportService<Village>
        implements CensusVillageImportService {

    public static final String VILLAGE_CODE = "VCode";
    public static final String REGIONAL_NAME = "Name_G";
    public static final String NAME = "Name_E";
    public static final String TALUKA_CODE = "TCode";
    public static final String DISTRICT_CODE = "DCode";
    public static final String STATE_ID = "StateID";

    public static final String VILLAGE_CODE_FIELD = "vcode";
    public static final String REGIONAL_NAME_FIELD = "regionalName";
    public static final String NAME_FIELD = "name";
    public static final String TALUKA_FIELD = "taluka";

    private VillageService villageService;
    private DistrictService districtService;
    private StateDataService stateDataService;
    private TalukaService talukaService;

    @Autowired
    public CensusVillageImportServiceImpl(VillageService villageService,
                                          TalukaService talukaService,
                                          DistrictService districtService,
                                          StateDataService stateDataService) {
        super(Village.class);
        this.villageService = villageService;
        this.talukaService = talukaService;
        this.districtService = districtService;
        this.stateDataService = stateDataService;
    }

    @Override
    protected void createOrUpdateInstance(Village instance) {
        Village village = villageService.findByTalukaAndVcodeAndSvid(instance.getTaluka(), instance.getVcode(),
                                                                      instance.getSvid());

        if (village != null) {
            village.setName(instance.getName());
            village.setRegionalName(instance.getRegionalName());

            villageService.update(village);
        } else {
            villageService.create(instance);
        }
    }

    @Override
    protected Map<String, CellProcessor> getProcessorMapping() {
        Map<String, CellProcessor> mapping = new LinkedHashMap<>();
        final Store store = new Store();

        mapping.put(VILLAGE_CODE, new GetLong());
        mapping.put(REGIONAL_NAME, new GetString());
        mapping.put(NAME, new GetString());
        mapping.put(STATE_ID, store.store(STATE, mapState(stateDataService)));
        mapping.put(DISTRICT_CODE, store.store(DISTRICT, mapDistrict(store, districtService)));
        mapping.put(TALUKA_CODE, mapTaluka(store, talukaService));
        return mapping;
    }

    @Override
    protected Map<String, String> getFieldNameMapping() {
        Map<String, String> mapping = new HashMap<>();
        mapping.put(VILLAGE_CODE, VILLAGE_CODE_FIELD);
        mapping.put(REGIONAL_NAME, REGIONAL_NAME_FIELD);
        mapping.put(NAME, NAME_FIELD);
        mapping.put(TALUKA_CODE, TALUKA_FIELD);
        mapping.put(STATE_ID, null);
        mapping.put(DISTRICT_CODE, null);
        return mapping;
    }
}


text:
package org.apache.hadoop.cli;

import java.io.File;
import java.util.ArrayList;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import junit.framework.TestCase;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.cli.util.ComparatorBase;
import org.apache.hadoop.cli.util.ComparatorData;
import org.apache.hadoop.cli.util.CLITestData;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import org.apache.hadoop.cli.util.CommandExecutor;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hdfs.DistributedFileSystem;
import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.apache.hadoop.fs.FileSystem;

/**
 * Tests for the Command Line Interface (CLI)
 */
public class TestCLI extends TestCase {
  private static final Log LOG =
    LogFactory.getLog(TestCLI.class.getName());

  // In this mode, it runs the command and compares the actual output
  // with the expected output
  public static final String TESTMODE_TEST = "test"; // Run the tests

  // If it is set to nocompare, run the command and do not compare.
  // This can be useful populate the testConfig.xml file the first time
  // a new command is added
  public static final String TESTMODE_NOCOMPARE = "nocompare";
  public static final String TEST_CACHE_DATA_DIR =
    System.getProperty("test.cache.data", "build/test/cache");

  //By default, run the tests. The other mode is to run the commands and not
  // compare the output
  public static String testMode = TESTMODE_TEST;

  // Storage for tests read in from the config file
  static ArrayList<CLITestData> testsFromConfigFile = null;
  static ArrayList<ComparatorData> testComparators = null;
  static String testConfigFile = "testConf.xml";
  String thisTestCaseName = null;
  static ComparatorData comparatorData = null;

  private static Configuration conf = null;
  private static MiniDFSCluster cluster = null;
  private static DistributedFileSystem dfs = null;
  private static String namenode = null;
  private static String clitestDataDir = null;
  private static String username = null;

  /**
   * Read the test config file - testConfig.xml
   */
  private void readTestConfigFile() {

    if (testsFromConfigFile == null) {
      boolean success = false;
      testConfigFile = TEST_CACHE_DATA_DIR + File.separator + testConfigFile;
      try {
        SAXParser p = (SAXParserFactory.newInstance()).newSAXParser();
        p.parse(testConfigFile, new TestConfigFileParser());
        success = true;
      } catch (Exception e) {
        LOG.info("File: " + testConfigFile + " not found");
        success = false;
      }
      assertTrue("Error reading test config file", success);
    }
  }

  /*
   * Setup
   */
  public void setUp() throws Exception {
    // Read the testConfig.xml file
    readTestConfigFile();

    // Start up the mini dfs cluster
    boolean success = false;
    conf = new Configuration();
    cluster = new MiniDFSCluster(conf, 1, true, null);
    namenode = conf.get("fs.default.name", "file:///");
    clitestDataDir = new File(TEST_CACHE_DATA_DIR).
      toURI().toString().replace(' ', '+');
    username = System.getProperty("user.name");

    FileSystem fs = cluster.getFileSystem();
    assertTrue("Not a HDFS: "+fs.getUri(),
               fs instanceof DistributedFileSystem);
    dfs = (DistributedFileSystem) fs;
    success = true;

    assertTrue("Error setting up Mini DFS cluster", success);
  }

  /**
   * Tear down
   */
  public void tearDown() throws Exception {
    boolean success = false;
    dfs.close();
    cluster.shutdown();
    success = true;
    Thread.sleep(2000);

    assertTrue("Error tearing down Mini DFS cluster", success);

    displayResults();
  }

  /**
   * Expand the commands from the test config xml file
   * @param cmd
   * @return String expanded command
   */
  private String expandCommand(final String cmd) {
    String expCmd = cmd;
    expCmd = expCmd.replaceAll("NAMENODE", namenode);
    expCmd = expCmd.replaceAll("CLITEST_DATA", clitestDataDir);
    expCmd = expCmd.replaceAll("USERNAME", username);

    return expCmd;
  }

  /**
   * Display the summarized results
   */
  private void displayResults() {
    LOG.info("Detailed results:");
    LOG.info("----------------------------------\n");

    for (int i = 0; i < testsFromConfigFile.size(); i++) {
      CLITestData td = testsFromConfigFile.get(i);

      boolean testResult = td.getTestResult();

      // Display the details only if there is a failure
      if (!testResult) {
        LOG.info("-------------------------------------------");
        LOG.info("                    Test ID: [" + (i + 1) + "]");
        LOG.info("           Test Description: [" + td.getTestDesc() + "]");
        LOG.info("");

        ArrayList<String> testCommands = td.getTestCommands();
        for (int j = 0; j < testCommands.size(); j++) {
          LOG.info("              Test Commands: [" +
              expandCommand((String) testCommands.get(j)) + "]");
        }

        LOG.info("");
        ArrayList<String> cleanupCommands = td.getCleanupCommands();
        for (int j = 0; j < cleanupCommands.size(); j++) {
          LOG.info("           Cleanup Commands: [" +
              expandCommand((String) cleanupCommands.get(j)) + "]");
        }

        LOG.info("");
        ArrayList<ComparatorData> compdata = td.getComparatorData();
        for (int j = 0; j < compdata.size(); j++) {
          boolean resultBoolean = compdata.get(j).getTestResult();
          LOG.info("                 Comparator: [" +
              compdata.get(j).getComparatorType() + "]");
          LOG.info("         Comparision result:   [" +
              (resultBoolean ? "pass" : "fail") + "]");
          LOG.info("            Expected output:   [" +
              compdata.get(j).getExpectedOutput() + "]");
          LOG.info("              Actual output:   [" +
              compdata.get(j).getActualOutput() + "]");
        }
        LOG.info("");
      }
    }

    LOG.info("Summary results:");
    LOG.info("----------------------------------\n");

    boolean overallResults = true;
    int totalPass = 0;
    int totalFail = 0;
    int totalComparators = 0;
    for (int i = 0; i < testsFromConfigFile.size(); i++) {
      CLITestData td = testsFromConfigFile.get(i);
      totalComparators +=
    	  testsFromConfigFile.get(i).getComparatorData().size();
      boolean resultBoolean = td.getTestResult();
      if (resultBoolean) {
        totalPass ++;
      } else {
        totalFail ++;
      }
      overallResults &= resultBoolean;
    }

    LOG.info("               Testing mode: " + testMode);
    LOG.info("");
    LOG.info("             Overall result: " +
    		(overallResults ? "+++ PASS +++" : "--- FAIL ---"));
    LOG.info("               # Tests pass: " + totalPass +
    		" (" + (100 * totalPass / (totalPass + totalFail)) + "%)");
    LOG.info("               # Tests fail: " + totalFail +
    		" (" + (100 * totalFail / (totalPass + totalFail)) + "%)");
    LOG.info("         # Validations done: " + totalComparators +
    		" (each test may do multiple validations)");

    LOG.info("");
    LOG.info("Failing tests:");
    LOG.info("--------------");
    int i = 0;
    boolean foundTests = false;
    for (i = 0; i < testsFromConfigFile.size(); i++) {
      boolean resultBoolean = testsFromConfigFile.get(i).getTestResult();
      if (!resultBoolean) {
        LOG.info((i + 1) + ": " +
        		testsFromConfigFile.get(i).getTestDesc());
        foundTests = true;
      }
    }
    if (!foundTests) {
    	LOG.info("NONE");
    }

    foundTests = false;
    LOG.info("");
    LOG.info("Passing tests:");
    LOG.info("--------------");
    for (i = 0; i < testsFromConfigFile.size(); i++) {
      boolean resultBoolean = testsFromConfigFile.get(i).getTestResult();
      if (resultBoolean) {
        LOG.info((i + 1) + ": " +
        		testsFromConfigFile.get(i).getTestDesc());
        foundTests = true;
      }
    }
    if (!foundTests) {
    	LOG.info("NONE");
    }

    assertTrue("One of the tests failed. " +
    		"See the Detailed results to identify " +
    		"the command that failed", overallResults);

  }

  /**
   * Compare the actual output with the expected output
   * @param compdata
   * @return
   */
  private boolean compareTestOutput(ComparatorData compdata) {
    // Compare the output based on the comparator
    String comparatorType = compdata.getComparatorType();
    Class<?> comparatorClass = null;

    // If testMode is "test", then run the command and compare the output
    // If testMode is "nocompare", then run the command and dump the output.
    // Do not compare

    boolean compareOutput = false;

    if (testMode.equals(TESTMODE_TEST)) {
      try {
    	// Initialize the comparator class and run its compare method
        comparatorClass = Class.forName("org.apache.hadoop.cli.util." +
          comparatorType);
        ComparatorBase comp = (ComparatorBase) comparatorClass.newInstance();
        compareOutput = comp.compare(CommandExecutor.getLastCommandOutput(),
          compdata.getExpectedOutput());
      } catch (Exception e) {
        LOG.info("Error in instantiating the comparator" + e);
      }
    }

    return compareOutput;
  }

  /***********************************
   ************* TESTS
   *********************************/

  public void testAll() {
    LOG.info("TestAll");

    // Run the tests defined in the testConf.xml config file.
    for (int index = 0; index < testsFromConfigFile.size(); index++) {

      CLITestData testdata = (CLITestData) testsFromConfigFile.get(index);

      // Execute the test commands
      ArrayList<String> testCommands = testdata.getTestCommands();
      for (int i = 0; i < testCommands.size(); i++) {
        CommandExecutor.executeFSCommand(testCommands.get(i),
        		namenode);
      }

      boolean overallTCResult = true;
      // Run comparators
      ArrayList<ComparatorData> compdata = testdata.getComparatorData();
      for (int i = 0; i < compdata.size(); i++) {
        final String comptype = compdata.get(i).getComparatorType();

        boolean compareOutput = false;

        if (! comptype.equalsIgnoreCase("none")) {
          compareOutput = compareTestOutput(compdata.get(i));
          overallTCResult &= compareOutput;
        }

        compdata.get(i).setExitCode(CommandExecutor.getLastExitCode());
        compdata.get(i).setActualOutput(
          CommandExecutor.getLastCommandOutput());
        compdata.get(i).setTestResult(compareOutput);
      }
      testdata.setTestResult(overallTCResult);

      // Execute the cleanup commands
      ArrayList<String> cleanupCommands = testdata.getCleanupCommands();
      for (int i = 0; i < cleanupCommands.size(); i++) {
        CommandExecutor.executeFSCommand(cleanupCommands.get(i),
        		namenode);
      }
    }
  }

  /*
   * Parser class for the test config xml file
   */
  static class TestConfigFileParser extends DefaultHandler {
    String charString = null;
    CLITestData td = null;
    ArrayList<String> testCommands = null;
    ArrayList<String> cleanupCommands = null;

    @Override
    public void startDocument() throws SAXException {
      testsFromConfigFile = new ArrayList<CLITestData>();
    }

    @Override
    public void startElement(String uri,
    		String localName,
    		String qName,
    		Attributes attributes) throws SAXException {
      if (qName.equals("test")) {
        td = new CLITestData();
      } else if (qName.equals("test-commands")) {
        testCommands = new ArrayList<String>();
      } else if (qName.equals("cleanup-commands")) {
        cleanupCommands = new ArrayList<String>();
      } else if (qName.equals("comparators")) {
        testComparators = new ArrayList<ComparatorData>();
      } else if (qName.equals("comparator")) {
        comparatorData = new ComparatorData();
      }
      charString = "";
    }

    @Override
    public void endElement(String uri,
    		String localName,
    		String qName) throws SAXException {
      if (qName.equals("description")) {
        td.setTestDesc(charString);
      } else if (qName.equals("test-commands")) {
        td.setTestCommands(testCommands);
        testCommands = null;
      } else if (qName.equals("cleanup-commands")) {
        td.setCleanupCommands(cleanupCommands);
        cleanupCommands = null;
      } else if (qName.equals("command")) {
        if (testCommands != null) {
          testCommands.add(charString);
        } else if (cleanupCommands != null) {
          cleanupCommands.add(charString);
        }
      } else if (qName.equals("comparators")) {
        td.setComparatorData(testComparators);
      } else if (qName.equals("comparator")) {
        testComparators.add(comparatorData);
      } else if (qName.equals("type")) {
        comparatorData.setComparatorType(charString);
      } else if (qName.equals("expected-output")) {
        comparatorData.setExpectedOutput(charString);
      } else if (qName.equals("test")) {
        testsFromConfigFile.add(td);
        td = null;
      } else if (qName.equals("mode")) {
        testMode = charString;
        if (!testMode.equals(TESTMODE_NOCOMPARE) &&
            !testMode.equals(TESTMODE_TEST)) {
          testMode = TESTMODE_TEST;
        }
      }
    }

    @Override
    public void characters(char[] ch,
    		int start,
    		int length) throws SAXException {
      String s = new String(ch, start, length);
      charString += s;
    }
  }
}


text:
#import "AWSRequest.h"

@class NSArray, NSNumber;

@interface AWSEC2DescribeDhcpOptionsRequest : AWSRequest {
	NSArray* _dhcpOptionsIds;
	NSNumber* _dryRun;
	NSArray* _filters;
}
@property(retain, nonatomic) NSArray* dhcpOptionsIds;
@property(retain, nonatomic) NSNumber* dryRun;
@property(retain, nonatomic) NSArray* filters;
+ (id)JSONKeyPathsByPropertyKey;
+ (id)filtersJSONTransformer;
- (void).cxx_destruct;
@end


text:
<?php

require_once 'Mime/Type.php';

class Mime_TypeTest extends PHPUnit_Framework_TestCase {

	protected $_files;
	protected $_data;

	protected function setUp() {
		$this->_files = dirname(dirname(dirname(__FILE__))) . '/data';
		$this->_data = dirname(dirname(dirname(dirname(__FILE__)))) .'/data';

		Mime_Type::config('Magic', array(
			'adapter' => 'Freedesktop',
			'file' => $this->_data . '/magic.db'
		));
		Mime_Type::config('Glob', array(
			'adapter' => 'Freedesktop',
			'file' => $this->_data . '/glob.db'
		));
	}

	protected function tearDown() {
		Mime_Type::reset();
	}

	public function testSimplify() {
		$this->assertEquals(
			'application/pdf',
			Mime_Type::simplify('application/x-pdf')
		);
		$this->assertEquals(
			'inode/directory',
			Mime_Type::simplify('x-inode/x-directory')
		);
		$this->assertEquals(
			'application/octet-stream',
			Mime_Type::simplify('application/octet-stream; encoding=compress')
		);
		$this->assertEquals(
			'application/test',
			Mime_Type::simplify('application/x-test; encoding=compress')
		);
		$this->assertEquals(
			'text/plain',
			Mime_Type::simplify('text/plain; charset=iso-8859-1')
		);
		$this->assertEquals(
			'text/plain',
			Mime_Type::simplify('text/plain charset=us-ascii')
		);
	}

	public function testGuessTypeFile() {
		$files = array(
			'image_gif.gif' => 'image/gif',
			'application_pdf.pdf' => 'application/pdf',
			'postscript_snippet.ps' => 'application/postscript',
			'tar_snippet.tar' => 'application/x-tar',
			'wave_snippet.wav' => 'audio/x-wav',
			'text_html_snippet.html' => 'text/html',
			'code_php.php' => 'application/x-php',
			'image_png.png' => 'image/png',
			'video_flash_snippet.flv' => 'video/x-flv',
			'audio_apple_snippet.aiff' => 'audio/x-aiff',
			'flash_snippet.swf' => 'application/x-shockwave-flash',
			'video_snippet.mp4' => 'video/mp4',
			'audio_mpeg_snippet.m4a' => 'audio/mp4',
			'video_quicktime_snippet.mov' => 'video/quicktime'
		);
		foreach ($files as $file => $mimeType) {
			$this->assertEquals(
				$mimeType,
				Mime_Type::guessType("{$this->_files}/{$file}"),
				"File `{$file}`."
			);
		}
	}

	public function testGuessTypeFilename() {
		$files = array(
			'test.gif' => 'image/gif',
			'test.pdf' => 'application/pdf',
			'test.ps' => 'application/postscript',
			'test.tar' => 'application/x-tar',
			'test.wav' => 'audio/x-wav',
			'test.html' => 'text/html',
			'test.php' => 'application/x-php',
			'test.png' => 'image/png',
			'test.flv' => 'video/x-flv',
			'test.aiff' => 'audio/x-aiff',
			'test.swf' => 'application/x-shockwave-flash',
			'test.mp4' => 'video/mp4',
			'test.m4v' => 'video/mp4',
			'test.m4a' => 'audio/mp4',
			'test.ogg' => 'audio/ogg',
			'test.oga' => 'audio/ogg',
			'test.ogv' => 'video/ogg'
		);
		foreach ($files as $file => $mimeType) {
			$this->assertEquals(
				$mimeType,
				Mime_Type::guessType($file),
				"Filename `{$file}`."
			);
		}
	}

	public function testGuessTypeParanoid() {
		$this->assertEquals(
			'image/png',
			Mime_Type::guessType("{$this->_files}/image_png.jpg", array('paranoid' => true))
		);
		$this->assertEquals(
			'image/jpeg',
			Mime_Type::guessType("{$this->_files}/image_png.jpg", array('paranoid' => false))
		);
	}

	public function testGuessTypeFallback() {
		$files = array(
			'generic_binary' => 'application/octet-stream',
			'generic_text' => 'text/plain'
		);
		foreach ($files as $file => $mimeType) {
			$this->assertEquals(
				$mimeType,
				Mime_Type::guessType("{$this->_files}/{$file}"),
				"File `{$file}`."
			);
		}
	}

	public function testGuessTypePreferredTypes() {
		$result = Mime_Type::guessType('test.ogg');
		$this->assertEquals('audio/ogg', $result);
	}

	public function testGuessExtensionFail() {
		$this->assertNull(Mime_Type::guessExtension('i-m-not-a-mime-type'));
		$this->assertNull(Mime_Type::guessExtension('/tmp/i-do-not-exist'));
	}

	public function testGuessExtensionFilename() {
		$this->assertEquals('txt', Mime_Type::guessExtension('/tmp/i-do-not-exist.txt'));
	}

	public function testGuessExtensionMimeType() {
		$this->assertEquals('jpg', Mime_Type::guessExtension('image/jpeg'));
		$this->assertEquals('xhtml', Mime_Type::guessExtension('application/xhtml+xml'));
		$this->assertEquals('bin', Mime_Type::guessExtension('application/octet-stream'));
		$this->assertEquals('wav', Mime_Type::guessExtension('audio/x-wav'));
		$this->assertEquals('oga', Mime_Type::guessExtension('audio/ogg'));
		$this->assertEquals('ogv', Mime_Type::guessExtension('video/ogg'));
		$this->assertEquals('mp4', Mime_Type::guessExtension('video/mp4'));
		$this->assertEquals('mov', Mime_Type::guessExtension('video/quicktime'));
	}

	public function testGuessExtensionResource() {
		$handleA = fopen("{$this->_files}/application_pdf.pdf", 'rb');
		$handleB = fopen('php://temp', 'rb+');

		stream_copy_to_stream($handleA, $handleB);

		$this->assertEquals('pdf', Mime_Type::guessExtension($handleA));
		$this->assertEquals('pdf', Mime_Type::guessExtension($handleB));

		fclose($handleA);
		fclose($handleB);
	}

	public function testGuessNameMimeType() {
		$map = array(
			'video/webm' => 'video',
			'video/x-msvideo' => 'video',
			'application/ogg' => 'audio',
			'application/octet-stream' => 'generic',
			'text/unknown' => 'generic',
			'image/jpeg' => 'image',
			'image/tiff' => 'image',
			'application/vnd.openxmlformats-officedocument.wordprocessingml.document' => 'document'
		);
		foreach ($map as $mimeType => $name) {
			$this->assertEquals($name, Mime_Type::guessName($mimeType), "MIME type `{$mimeType}`.");
		}
	}

	public function testGuessNameFilename() {
		$map = array(
			'test' => 'generic',
			'test.jpg' => 'image',
			'test.tif' => 'image',
			'test.pdf' => 'document',
			'path/to/test.pdf' => 'document'
		);
		foreach ($map as $mimeType => $name) {
			$this->assertEquals($name, Mime_Type::guessName($mimeType), "MIME type `{$mimeType}`.");
		}
	}

	public function testGuessNameFile() {
		$map = array(
			'video_flash_snippet.flv' => 'video',
			'audio_ogg_snippet.ogg' => 'audio',
			'xml_snippet.xml' => 'generic',
			'image_png.png' => 'image',
		);
		foreach ($map as $file => $name) {
			$this->assertEquals(
				$name,
				Mime_Type::guessName($this->_files . '/' . $file),
				"File `{$file}`."
			);
		}
	}

	public function testGuessNameResource() {
		$handleA = fopen("{$this->_files}/application_pdf.pdf", 'rb');
		$handleB = fopen('php://temp', 'rb+');

		stream_copy_to_stream($handleA, $handleB);

		$this->assertEquals('document', Mime_Type::guessName($handleA));
		$this->assertEquals('document', Mime_Type::guessName($handleB));

		fclose($handleA);
		fclose($handleB);
	}
}

?>


text:
//
//  SWStaticEntity.h
//  SteamedWorlds
//
//  Created by Nils Daumann on 23.08.14.
//  Copyright (c) 2014 GoodyCow. All rights reserved.
//

#ifndef __SWCrashingShip_H__
#define __SWCrashingShip_H__

#include <Rayne/Rayne.h>
#include <RBRigidBody.h>

namespace SW
{
	class CrashingShip : public RN::Entity
	{
	public:
		CrashingShip();
		CrashingShip(RN::Deserializer *deserializer);

		void Initialize();
		void Serialize(RN::Serializer *serializer) override;

		void StartAnimation();
		void Update(float delta) override;

	private:
		float _startCounter;
		bool _isStarted;
		RNDeclareMeta(CrashingShip)
	};
}

#endif /* __SWCrashingShip_H__ */


text:
package course.cloud.computing.service;

import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.xml.ws.BindingType;

@WebService
@BindingType(value="http://schemas.xmlsoap.org/wsdl/soap/http")
public interface Notifications {
	@WebMethod
	public boolean notifyClient(String msg);
}


text:
using namespace std;

int main() {
  double deposit, perYie, matPer;
  cout << "Enter the initial deposit amount: $";
  cin >> deposit;
  cout << "Enter the annual percentage yield: ";
  cin >> perYie;
  cout << "Enter the maturity period (number of months): ";
  cin >> matPer;
  cout << "Month CD Value\n";
  for (int i = 1; i < matPer; i++) {
    deposit = deposit+deposit*(perYie/1200.00);
    cout << setw(2) << i << setw(10) << deposit << endl;
    // cout << deposit << endl;
  }
}


text:
package me.ederign;

public class HelloWorld {

    public static void main(String[] args) throws InterruptedException {
        Thread myThread = new Thread() {
            public void run() {
                System.out.println("Hello from new thread");
            }
        };

        myThread.start();
        Thread.yield();
//        Thread.sleep(1);
        System.out.println("Hello from main thread");
        myThread.join();
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Dasyscyphus inconspicuus Henn.

### Remarks
null


text:
#ifndef __PLAT_NOMADIK_GPIO
#define __PLAT_NOMADIK_GPIO

/*
 * "nmk_gpio" and "NMK_GPIO" stand for "Nomadik GPIO", leaving
 * the "gpio" namespace for generic and cross-machine functions
 */

/* Register in the logic block */
#define NMK_GPIO_DAT	0x00
#define NMK_GPIO_DATS	0x04
#define NMK_GPIO_DATC	0x08
#define NMK_GPIO_PDIS	0x0c
#define NMK_GPIO_DIR	0x10
#define NMK_GPIO_DIRS	0x14
#define NMK_GPIO_DIRC	0x18
#define NMK_GPIO_SLPC	0x1c
#define NMK_GPIO_AFSLA	0x20
#define NMK_GPIO_AFSLB	0x24

#define NMK_GPIO_RIMSC	0x40
#define NMK_GPIO_FIMSC	0x44
#define NMK_GPIO_IS	0x48
#define NMK_GPIO_IC	0x4c
#define NMK_GPIO_RWIMSC	0x50
#define NMK_GPIO_FWIMSC	0x54
#define NMK_GPIO_WKS	0x58

/* Alternate functions: function C is set in hw by setting both A and B */
#define NMK_GPIO_ALT_GPIO	0
#define NMK_GPIO_ALT_A	1
#define NMK_GPIO_ALT_B	2
#define NMK_GPIO_ALT_C	(NMK_GPIO_ALT_A | NMK_GPIO_ALT_B)

/* Pull up/down values */
enum nmk_gpio_pull {
	NMK_GPIO_PULL_NONE,
	NMK_GPIO_PULL_UP,
	NMK_GPIO_PULL_DOWN,
};

/* Sleep mode */
enum nmk_gpio_slpm {
	NMK_GPIO_SLPM_INPUT,
	NMK_GPIO_SLPM_WAKEUP_ENABLE = NMK_GPIO_SLPM_INPUT,
	NMK_GPIO_SLPM_NOCHANGE,
	NMK_GPIO_SLPM_WAKEUP_DISABLE = NMK_GPIO_SLPM_NOCHANGE,
};

extern int nmk_gpio_set_slpm(int gpio, enum nmk_gpio_slpm mode);
extern int nmk_gpio_set_pull(int gpio, enum nmk_gpio_pull pull);
extern int nmk_gpio_set_mode(int gpio, int gpio_mode);
extern int nmk_gpio_get_mode(int gpio);

extern void nmk_gpio_wakeups_suspend(void);
extern void nmk_gpio_wakeups_resume(void);

extern void nmk_gpio_clocks_enable(void);
extern void nmk_gpio_clocks_disable(void);

extern void nmk_gpio_read_pull(int gpio_bank, u32 *pull_up);

/*
 * Platform data to register a block: only the initial gpio/irq number.
 */
struct nmk_gpio_platform_data {
	char *name;
	int first_gpio;
	int first_irq;
	int num_gpio;
	u32 (*get_secondary_status)(unsigned int bank);
	void (*set_ioforce)(bool enable);
	bool supports_sleepmode;
};

#endif /* __PLAT_NOMADIK_GPIO */


text:
var __extends = this.__extends || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
var common = require("ui/label/label-common");
function onTextWrapPropertyChanged(data) {
    var label = data.object;
    if (!label.android) {
        return;
    }
    if (data.newValue) {
        label.android.setSingleLine(false);
        label.android.setEllipsize(null);
    }
    else {
        label.android.setSingleLine(true);
        label.android.setEllipsize(android.text.TextUtils.TruncateAt.END);
    }
}
common.textWrapProperty.metadata.onSetNativeValue = onTextWrapPropertyChanged;
require("utils/module-merge").merge(common, exports);
var Label = (function (_super) {
    __extends(Label, _super);
    function Label() {
        _super.apply(this, arguments);
    }
    Object.defineProperty(Label.prototype, "android", {
        get: function () {
            return this._android;
        },
        enumerable: true,
        configurable: true
    });
    Label.prototype._createUI = function () {
        this._android = new android.widget.TextView(this._context);
        this._android.setSingleLine(true);
        this._android.setEllipsize(android.text.TextUtils.TruncateAt.END);
    };
    return Label;
})(common.Label);
exports.Label = Label;


text:
title: Timeline
---

{{#extend "layout-default"}}
  {{#content "css_vendor" mode="append"}}
    <link rel="stylesheet" href="{{global}}/vendor/plyr/plyr.css">
  {{/content}}

  {{#content "js_vendor" mode="append"}}

  {{/content}}

  {{#content "js" mode="append"}}

  {{/content}}

  {{#content "scripts" mode="replace"}}

  {{/content}}

  {{#content "body"}}

Timeline

Home

Structure

          <form>

              <input type="text" class="form-control" name="" placeholder="Search...">

          </form>

MAY 2016

              <time datetime="2016-05-15">2 Days ago</time>

              <time datetime="2016-05-15">2 Days ago</time>

Lorem Ipsum Dolor

                    MAY 15, 2016

Novum formidines congressus atomorum nam permulta alterum delectatio
                    gaudeat statim. Necessariae dicturam perspexit utrum modo amicitiae
                    malum summumque, multis ante iudicia desiderat, civitas iudicare
                    attingere, amori perpaulum mediocrium, dicere notae litteras
                    plusque appareat, remotis fama futurove quandam assentiar integre
                    poenis.

                        2500

                        20

                    Read More

              <time datetime="2016-05-08">9 Days ago</time>

Asperner solvantur fere queo meam videtur temperantiam. Timorem
                      asperner. Hortensio delicatissimi nihilo disserunt, contemnit
                      mi amentur doctrinis logikh triario, appetendi utamur fames.

Apr 2016

              <time datetime="2016-04-08">1 Month ago</time>

Lorem Ipsum Dolor

                    MAY 08, 2016

Signiferumque dixit, arbitrium iudicia nominis, potione aeterno
                    genus conducunt deinde incidunt horrent forte voluptate pericula,
                    mortis deleniti, circumcisaque mala sentit iucundius pedalis.
                    Claudicare inanium fugiat contenta dixisset animumque iure
                    quoquo dicturam, defendit militaris sollicitudines, verear,
                    amicorum manum discedere indignae loqui.

                        2500

                        20

                    Read More

              <time datetime="2016-04-08">1 Month ago</time>

Ostendis peccandi pertinaces disputandum primus arare morbos
                      noster, privamur alios perpetiuntur nulla est, effecerit
                      corpora doctrina sentiunt hinc quasi, tradere perveniri erigimur.

              <time datetime="2016-04-08">1 Month ago</time>

                  <video poster="{{assets}}/examples/images/poster.jpg" controls crossorigin>

                    <source type="video/mp4" src="https://cdn.selz.com/plyr/1.0/movie.mp4">
                    <source type="video/webm" src="https://cdn.selz.com/plyr/1.0/movie.webm">

                    <track kind="captions" label="English" srclang="en" src="//cdn.selz.com/plyr/1.0/en.vtt"
                    default>

                      Download
                  </video>

  {{/content}}
{{/extend}}


text:
package synergyspace.jme.gfx.twod.utils;

import java.awt.Graphics2D;
import java.awt.RenderingHints;

import com.jme.image.Texture;
import com.jme.image.Texture2D;
import com.jme.image.Texture.WrapMode;
import com.jme.math.Vector3f;
import com.jme.renderer.Renderer;
import com.jme.scene.shape.Disk;
import com.jme.scene.state.BlendState;
import com.jme.scene.state.TextureState;
import com.jme.system.DisplaySystem;
import com.jmex.awt.swingui.ImageGraphics;

public class GraphicsImageDisc extends Disk {

	private static final long serialVersionUID = 64623554610677568L;

	protected ImageGraphics graphics;
	protected TextureState ts;
	protected Texture texture;
	protected float radius;
	protected int concentricCircles;
	protected int radialDivisions;

	public GraphicsImageDisc(String name, float radius) {
		this(name, 16,32, radius);
	}

	public GraphicsImageDisc(String name, int concentricCircles, int radialDivisions, float radius) {
		super(name, concentricCircles, radialDivisions, radius);
		updateGeometry(concentricCircles, radialDivisions, radius);
		this.radius = radius;
		this.concentricCircles = concentricCircles;
		this.radialDivisions = radialDivisions;
		init();
	}

	private void init() {
		recreateImageForSize(this.radius);

		BlendState alpha = DisplaySystem.getDisplaySystem().getRenderer().createBlendState();
		alpha.setEnabled( true );
		alpha.setBlendEnabled( true );
		alpha.setSourceFunction( BlendState.SourceFunction.SourceAlpha);
		alpha.setDestinationFunction( BlendState.DestinationFunction.OneMinusSourceAlpha);
		alpha.setTestEnabled( true );
		alpha.setTestFunction( BlendState.TestFunction.GreaterThan);
		this.setRenderState( alpha );

		this.updateRenderState();

	}

	public void recreateImageForSize(float radius) {
		ts = DisplaySystem.getDisplaySystem().getRenderer().createTextureState();
		ts.setCorrectionType(TextureState.CorrectionType.Perspective);
		texture = new Texture2D();
		texture.setMinificationFilter(Texture.MinificationFilter.NearestNeighborNoMipMaps);
		texture.setMagnificationFilter(Texture.MagnificationFilter.Bilinear);
		texture.setWrap(WrapMode.Repeat);

		int widthPixels = (int) (radius*2);
		int heightPixels = (int) (radius*2);

		graphics = ImageGraphics.createInstance(widthPixels, heightPixels, 0);

		enableAntiAlias(graphics);

		texture.setImage(graphics.getImage());
		texture.setScale(new Vector3f( 1, -1, 1 ));

		ts.setTexture(texture);
		ts.apply();
		setRenderState(ts);
		updateRenderState();
	}

	public ImageGraphics getImageGraphics() {
		return graphics;
	}

	public void updateGraphics() {
		if(graphics != null) {
			graphics.update(texture, false);
		}
	}

	public void updateGeometry(float r){
		this.updateGeometry(this.concentricCircles, this.radialDivisions, r);
	}

	public void draw( Renderer r ) {
		if ( graphics.isDirty()) {
			if ( graphics != null ) {
				graphics.update(texture, false);
			}
		}
		super.draw( r );
	}

	private void enableAntiAlias( Graphics2D graphics ) {
		RenderingHints hints = graphics.getRenderingHints();
		if ( hints == null ) {
			hints = new RenderingHints( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
		}
		else {
			hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
		}
		graphics.setRenderingHints( hints );
	}

	public float getRadius() {
		return radius;
	}

}


text:
using System.Web.Http;
using DataBooster.PSWebApi;

namespace PSWebApi.OwinSample.Controllers
{
	public class MiscController : ApiController
	{
		[AcceptVerbs("GET", "POST")]
		public string WhoAmI()
		{
			string userName = this.GetUserName();
			return string.IsNullOrEmpty(userName) ? "?" : userName;
		}
	}
}


text:
" Implements a CoupledConvection operator "
type CoupledConvection <: Kernel
    u::Variable
    other_var::Variable
end

import MOOSE.computeQpResidual

@inline function computeQpResidual(kernel::CoupledConvection, qp::Int64, i::Int64)
    u = kernel.u

    other_var = kernel.other_var

    return (other_var.grad[qp] ⋅ u.grad[qp]) * u.phi[qp][i]
end

import MOOSE.computeQpJacobian

@inline function computeQpJacobian(kernel::CoupledConvection, v::Variable, qp::Int64, i::Int64, j::Int64)::Float64
    u = kernel.u

    other_var = kernel.other_var

    if u.id == v.id
        return (other_var.grad[qp] ⋅ u.grad_phi[qp][j]) * u.phi[qp][i]
    elseif other_var.id == v.id
        return (other_var.grad_phi[qp][j] ⋅ u.grad[qp]) * u.phi[qp][i]
    end

    return 0
end

import MOOSE.coupledVars

@inline function coupledVars(kernel::CoupledConvection)::Array{Variable}
    return [kernel.u, kernel.other_var]
end


text:
package org.fife.rsta.ac.c;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import org.fife.ui.autocomplete.BasicCompletion;
import org.fife.ui.autocomplete.CompletionProvider;
import org.fife.ui.autocomplete.DefaultCompletionProvider;
import org.fife.ui.autocomplete.LanguageAwareCompletionProvider;
import org.fife.ui.autocomplete.ShorthandCompletion;

/**
 * A completion provider for the C programming language.  It provides
 * code completion support and parameter assistance for the C Standard Library.
 * This information is read from an XML file.
 *
 * @author Robert Futrell
 * @version 1.0
 */
public class CCompletionProvider extends LanguageAwareCompletionProvider {

	/**
	 * Constructor.
	 */
	public CCompletionProvider() {
		setDefaultCompletionProvider(createCodeCompletionProvider());
		setStringCompletionProvider(createStringCompletionProvider());
		setCommentCompletionProvider(createCommentCompletionProvider());
	}

	/**
	 * Adds shorthand completions to the code completion provider.
	 *
	 * @param codeCP The code completion provider.
	 */
	protected void addShorthandCompletions(DefaultCompletionProvider codeCP) {
		codeCP.addCompletion(new ShorthandCompletion(codeCP, "main",
								"int main(int argc, char **argv)"));
//for (int i=0; i<5000; i++) {
//	codeCP.addCompletion(new BasicCompletion(codeCP, "Number" + i));
//}
	}

	/**
	 * Returns the provider to use when editing code.
	 *
	 * @return The provider.
	 * @see #createCommentCompletionProvider()
	 * @see #createStringCompletionProvider()
	 * @see #loadCodeCompletionsFromXml(DefaultCompletionProvider)
	 * @see #addShorthandCompletions(DefaultCompletionProvider)
	 */
	protected CompletionProvider createCodeCompletionProvider() {
		DefaultCompletionProvider cp = new DefaultCompletionProvider();
		loadCodeCompletionsFromXml(cp);
		addShorthandCompletions(cp);
		return cp;

	}

	/**
	 * Returns the provider to use when in a comment.
	 *
	 * @return The provider.
	 * @see #createCodeCompletionProvider()
	 * @see #createStringCompletionProvider()
	 */
	protected CompletionProvider createCommentCompletionProvider() {
		DefaultCompletionProvider cp = new DefaultCompletionProvider();
		cp.addCompletion(new BasicCompletion(cp, "TODO:", "A to-do reminder"));
		cp.addCompletion(new BasicCompletion(cp, "FIXME:", "A bug that needs to be fixed"));
		return cp;
	}

	/**
	 * Returns the completion provider to use when the caret is in a string.
	 *
	 * @return The provider.
	 * @see #createCodeCompletionProvider()
	 * @see #createCommentCompletionProvider()
	 */
	protected CompletionProvider createStringCompletionProvider() {
		DefaultCompletionProvider cp = new DefaultCompletionProvider();
		cp.addCompletion(new BasicCompletion(cp, "%c", "char", "Prints a character"));
		cp.addCompletion(new BasicCompletion(cp, "%i", "signed int", "Prints a signed integer"));
		cp.addCompletion(new BasicCompletion(cp, "%f", "float", "Prints a float"));
		cp.addCompletion(new BasicCompletion(cp, "%s", "string", "Prints a string"));
		cp.addCompletion(new BasicCompletion(cp, "%u", "unsigned int", "Prints an unsigned integer"));
		cp.addCompletion(new BasicCompletion(cp, "\\n", "Newline", "Prints a newline"));
		return cp;
	}

	/**
	 * Returns the name of the XML resource to load (on classpath or a file).
	 *
	 * @return The resource to load.
	 */
	protected String getXmlResource() {
		return "data/c.xml";
	}

	/**
	 * Called from {@link #createCodeCompletionProvider()} to actually load
	 * the completions from XML.  Subclasses that override that method will
	 * want to call this one.
	 *
	 * @param cp The code completion provider.
	 */
	protected void loadCodeCompletionsFromXml(DefaultCompletionProvider cp) {
		// First try loading resource (running from demo jar), then try
		// accessing file (debugging in Eclipse).
		ClassLoader cl = getClass().getClassLoader();
		String res = getXmlResource();
		if (res!=null) { // Subclasses may specify a null value
			InputStream in = cl.getResourceAsStream(res);
			try {
				if (in!=null) {
					cp.loadFromXML(in);
					in.close();
				}
				else {
					cp.loadFromXML(new File(res));
				}
			} catch (IOException ioe) {
				ioe.printStackTrace();
			}
		}
	}

}


text:
package org.apache.maven.building;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

/**
 * Wraps an ordinary {@link URL} as a source.
 *
 * @author Benjamin Bentmann
 */
public class UrlSource
    implements Source
{

    private URL url;

    /**
     * Creates a new source backed by the specified URL.
     *
     * @param url The file, must not be {@code null}.
     */
    public UrlSource( URL url )
    {
        if ( url == null )
        {
            throw new IllegalArgumentException( "no url specified" );
        }
        this.url = url;
    }

    @Override
    public InputStream getInputStream()
        throws IOException
    {
        return url.openStream();
    }

    @Override
    public String getLocation()
    {
        return url.toString();
    }

    /**
     * Gets the URL of this source.
     *
     * @return The underlying URL, never {@code null}.
     */
    public URL getUrl()
    {
        return url;
    }

    @Override
    public String toString()
    {
        return getLocation();
    }

}


text:
#ifndef MESH_H
#define MESH_H

#include <Animator.hpp>
#include <Config.hpp>
#include <Joint.hpp>
#include <Math.hpp>
#include <OpenGL.hpp>

#include <memory>
#include <vector>

class Material;
class Shader;

class Mesh
{
public:

    struct Primitive
    {
        GLuint      VAO;
        GLenum      Mode;
        GLsizei     Count;
        GLenum      Type;
        GLsizei     Offset;

        std::shared_ptr<Material> _Material;
    };

    enum AttributeID : GLint
    {
        POSITION = 0,
        NORMAL = 1,
        TEXCOORD = 2,
        TANGENT = 3,
        JOINTS_0 = 4,
        WEIGHTS_0 = 5,
        COLOR = 6,

    };

    Mesh() = default;

    /* Functions */
    Mesh(GLuint vao, GLenum mode, GLsizei count, GLenum type, GLsizei offset, std::shared_ptr<Material> material);
    Mesh(GLuint vao, GLenum mode, GLsizei count, GLenum type, GLsizei offset, std::shared_ptr<Material> material, Joint rootJoint, int jointCount);
    Mesh(std::vector<Primitive>&&);

    bool LoadFromData(std::vector<Primitive>&& primitives);

    void Update(const float dt);
    void Render(Shader * shader, glm::mat4 modelMat);

    void doAnimation(Animation animation) { _mAnimator.DoAnimation(animation); }

    Joint GetRootJoint() { return _mRootJoint; }

    std::vector<glm::mat4> GetJointTransforms();

    void AddJointsToArray(Joint headJoint, std::vector<glm::mat4> jointMatrices);

private:
    std::vector<Primitive> _mPrimitives;

    // Joints
    Joint _mRootJoint;
    int _mJointCount;

    // Animator
    Animator _mAnimator;

    // Not sure how to handle these yet, they need to be part of the rendering
    //glm::vec3 _mJointIDs; this will be an int
    //glm::vec3 _mVertexWeights; this will be a float

};

#endif // MESH_H


text:
jl_value_t *jl_type_multable_union();
void jl_type_mutable_union_append(jl_value_t *u, jl_value_t *t);

#endif


text:
from __future__ import absolute_import
import unittest

from uncertainties import ufloat

from pychron.experiment.queue.experiment_queue import ExperimentQueue

# ============= local library imports  ==========================

class MockRun(object):
    analysis_type = 'blank_unknown'
    Ar40 = ufloat(0, 0)

class QueueTest(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        p = './data/experiment.txt'
        cls.txt = open(p).read()

    def setUp(self):
        self._queue = ExperimentQueue()
        self._queue.load(self.txt)

    def testLoadActions(self):
        q = self._queue
        self.assertEqual(len(q.queue_actions), 2)

    def testActions(self):
        q = self._queue
        act = q.queue_actions[0]
        self.assertEqual(act.analysis_type, 'blank_unknown')
        self.assertEqual(act.nrepeat, 3)

        act = q.queue_actions[1]
        self.assertEqual(act.nrepeat, 1)

    def testCheckRun(self):
        q = self._queue
        act = q.queue_actions[0]
        run = MockRun()

        run.Ar40 = ufloat(100, 0)
        self.assertTrue(act.check_run(run))

        run.Ar40 = ufloat(10, 0)
        self.assertFalse(act.check_run(run))
#         self.assertEqual(len(q.queue_actions), 2)
# ============= EOF =============================================


text:
from resource import Resource
from path import Path

from cStringIO import StringIO
import mimetypes
import os

class Tree(Resource):
    """ A versioned container of Files - that is, it represents a
    directory or tree in the Repository """

    def __init__(self):
        # super(Tree, self).__init__()
        self._path = Path(self._ra_api, self._revnum, self._branch_path, self._path)

    def get_path(self):
        """ Return the path to this tree in its container Repository """
        return self._path

    def get_contents(self, recursive=True):
        """ Calls the helper function get_data ... whose name matches the File object """
        return get_data(recursive)

    def get_data(self, recursive=True):
        """ Return the contents of a tree as a list of Resources """
        self.dir_paths = []

        if self._path == '':
            abs_path = self._branch_path
        else:
            abs_path = os.path.join(self._branch_path, self._path)

        file_names = file_list(abs_path, self._ra_api, self._revnum)

        for item in file_names:
            full_file_path = os.path.join(self._branch_path,
                                          self._path,
                                          item)

            branch_node_path = os.path.join(self._path, item)

            # Actually appending the path to the list
            self.temp_path = Path(self._ra_api,
                                  self._revnum,
                                  self._branch_path,
                                  branch_node_path)

            self.dir_paths.append(self.temp_path.get_resource(self._revnum,
                                                          self._branch_path,
                                                          self._path))

        return self.dir_paths

    def file_list(path, ra_api, revnum=None):
        """ Return a list of strings representing the contents of a given path """
        if revnum is None:
            revnum = ra_api.get_latest_revnum()

        path_level_info = ra_api.get_dir(path, revnum)

        return path_level_info[0].keys

    def is_tree(self):
        """ Overrides the method from parent (Resource) """
        return True

    def type(self):
        return 'directory'

    path = property(get_path)
    contents = property(get_contents)
    data = property(get_data)


text:
using AspectInjector.Broker;
using System;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text;
using Xunit;

namespace AspectInjector.Tests.Advices
{
    public class AroundTests
    {
        [Fact]
        public void Advices_InjectAroundMethod_StructResult()
        {
            Checker.Passed = false;

            var a = new AroundTests_Target();

            object ref1 = new object();
            int ref2 = 2;
            var str = "";
            var dt = DateTime.Now;
            var arr = new[] {1,2,3 };

            var sb = new StringBuilder();

            a.Do1<StringBuilder>(new object(), 1, str, ref str, dt, ref dt, sb, ref sb, arr, ref arr, ref ref1, out object out1, ref ref2, out int out2, false, false);

            Assert.True(Checker.Passed);
        }

        [Fact]
        public void Advices_InjectAroundMethod()
        {
            Checker.Passed = false;

            var a = new AroundTests_Target();

            object ref1 = new object();
            int ref2 = 2;

            a.Do2(new object(), 1, ref ref1, out object out1, ref ref2, out int out2, false, false);

            Assert.True(Checker.Passed);
        }

        [Fact]
        public void Advices_InjectAroundMethod_ModifyArguments()
        {
            var i = 1;

            Checker.Passed = true;
            new AroundTests_ArgumentsModificationTarget().Fact(ref i);
            Assert.True(Checker.Passed);
        }

        internal class AroundTests_Target
        {
            [AroundTests_Aspect1]
            [AroundTests_Aspect2] //fire first
            public object Do2(object data, int value, ref object testRef, out object testOut, ref int testRefValue, out int testOutValue, bool passed, bool passed2)
            {
                Checker.Passed = passed && passed2;

                testOut = new object();
                testOutValue = 1;

                return new object();
            }

            [AroundTests_Aspect1]
            [AroundTests_Aspect2] //fire first
            public T Do1<T>(object data, int value, string str, ref string rstr, DateTime dt, ref DateTime rdt, T g, ref T rg, int[] arr, ref int[] rarr,  ref object testRef, out object testOut, ref int testRefValue, out int testOutValue, bool passed, bool passed2)
                where T : ISerializable
            {
                var test = new object[] { dt, rdt,arr,rarr,g,rg };

                dt = (DateTime)test[0];
                rdt = (DateTime)test[1];
                arr = (int[])test[2];
                rarr = (int[])test[3];
                g = (T)test[4];
                rg = (T)test[5];

                Checker.Passed = passed && passed2;

                testOut = new object();
                testOutValue = 1;

                return g;
            }

            [AroundTests_Aspect1]
            public object Object(object data)
            {
                Checker.Passed = true;
                return new object();
            }

            [AroundTests_Aspect1]
            public object ObjectRef(ref object data)
            {
                Checker.Passed = true;
                return new object();
            }

            [AroundTests_Aspect1]
            public object ObjectOut(out object data)
            {
                Checker.Passed = true;
                return data = new object();
            }

            [AroundTests_Aspect1]
            public object Value(int data)
            {
                Checker.Passed = true;
                return new object();
            }

            [AroundTests_Aspect1]
            public object ValueRef(ref int data)
            {
                Checker.Passed = true;

                var a = new object[] { 1 };
                data = (int)a[0];

                return new object();
            }

            [AroundTests_Aspect1]
            public object ValueOut(out int data)
            {
                Checker.Passed = true;
                data = 1;
                return new object();
            }

            [AroundTests_Aspect1]
            public object ValueBoxed(Int32 data)
            {
                Checker.Passed = true;
                return new object();
            }

            [AroundTests_Aspect1]
            public object TypedObjectRef(ref StrongNameKeyPair data)
            {
                Checker.Passed = true;

                var a = new object[] { default(StrongNameKeyPair) };
                data = (StrongNameKeyPair)a[0];

                return new object();
            }

            [AroundTests_Aspect1]
            public T GenericRef<T>(ref T data)
            {
                Checker.Passed = true;

                var a = new object[] { default(T) };
                data = (T)a[0];

                return data;
            }

            [AroundTests_Aspect1]
            public T GenericOut<T>(out T data)
            {
                Checker.Passed = true;
                data = default(T);
                return data;
            }

            [AroundTests_Aspect1]
            public T Generic<T>(T data)
            {
                Checker.Passed = true;
                data = default(T);
                return data;
            }
        }

        [Aspect(Scope.Global)]
        [Injection(typeof(AroundTests_Simple))]
        public class AroundTests_Simple : Attribute
        {
            [Advice(Kind.Around, Targets = Target.Method)]
            public object AroundMethod([Argument(Source.Target)] Func<object[], object> target,
                [Argument(Source.Arguments)] object[] arguments)
            {
                return target(arguments);
            }
        }

        [Aspect(Scope.Global)]
        [Injection(typeof(AroundTests_Aspect1))]
        public class AroundTests_Aspect1 : Attribute
        {
            [Advice(Kind.Around, Targets = Target.Method)]
            public object AroundMethod([Argument(Source.Target)] Func<object[], object> target,
                [Argument(Source.Arguments)] object[] arguments)
            {
                return target(arguments.Take(arguments.Length - 2).Concat(new object[] { true, arguments.Last() }).ToArray());
            }
        }

        [Aspect(Scope.Global)]
        [Injection(typeof(AroundTests_Aspect2))]
        public class AroundTests_Aspect2 : Attribute
        {
            [Advice(Kind.Around, Targets = Target.Method)]
            public object AroundMethod([Argument(Source.Target)] Func<object[], object> target,
                [Argument(Source.Arguments)] object[] arguments)
            {
                return target(arguments.Take(arguments.Length - 1).Concat(new object[] { true }).ToArray());
            }
        }

        internal class AroundTests_ArgumentsModificationTarget
        {
            [AroundTests_ArgumentsModificationAspect]
            public void Fact(ref int i)
            {
                if (i == 2)
                    i = 3;
            }
        }

        [Aspect(Scope.Global)]
        [Injection(typeof(AroundTests_ArgumentsModificationAspect))]
        public class AroundTests_ArgumentsModificationAspect : Attribute
        {
            [Advice(Kind.Around, Targets = Target.Method)]
            public object AroundMethod(
                [Argument(Source.Arguments)] object[] args,
                [Argument(Source.Target)] Func<object[], object> target
                )
            {
                args[0] = 2;

                var result = target(args);

                Checker.Passed = (int)args[0] == 3;

                return result;
            }
        }
    }
}


text:
require File.expand_path('../spec_helper', __FILE__)

describe Dynr53 do
end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class com.communote.server.core.converter.blog.BlogToDetailBlogListItemConverter (Communote 3.5 API)</title>
<meta name="date" content="2019-02-02">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
com.communote.server.core.converter.blog.BlogToDetailBlogListItemConverter

Packages that use BlogToDetailBlogListItemConverter

Package
Description

com.communote.server.core.converter.blog

Uses of BlogToDetailBlogListItemConverter in com.communote.server.core.converter.blog

Subclasses of BlogToDetailBlogListItemConverter in com.communote.server.core.converter.blog

Modifier and Type
Class and Description

class
BlogToUserDetailBlogListItemConverter

Converter for converting a blog entity into a list item.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2019 Communote team. All rights reserved.


text:
package org.usc.demo.temp.bak;

import java.util.UUID;

/**
 *
 * @author Shunli
 */
public class UUIDGenerator {

    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
             System.out.println(UUID.randomUUID().toString().replaceAll("-", ""));
            // System.out.println(System.currentTimeMillis());

//            System.out.println("DG" + StringUtils.upperCase(RandomStringUtils.randomAlphanumeric(10)));
        }
    }

}


text:
{-# LANGUAGE TemplateHaskell, RecordWildCards #-}
module AppState where
import Control.Applicative
import Control.Lens
import qualified Data.Set as S
import Linear

import Camera
import qualified Renderer as R

data AppState = AppState { _cam          :: Camera
                         , _prevMouse    :: Maybe (V2 Int)
                         , _saveDepthmap :: AppState -> IO ()
                         , _showGround   :: Bool }
makeLenses ''AppState

keyActions :: AppState -> [(R.Key, Bool)] -> IO AppState
keyActions s keys
  | (R.CharKey 'F', True) `elem` keys = (s^.saveDepthmap) s >> return s
  | (R.CharKey 'C', True) `elem` keys = print (s^.cam) >> return s
  | (R.CharKey 'G', True) `elem` keys = return (showGround %~ not $ s)
  | otherwise = return s

cameraControl :: Float -> Double -> R.UIEvents -> AppState -> (Bool, AppState)
cameraControl scale dt (R.UIEvents{..}) st =
  (stop, ((cam.~c').(prevMouse.~prev')) $ st)
  where c = st^.cam
        prev = st^.prevMouse
        stop = R.KeyEsc `elem` map fst (fst keys)
        c' = auxKey (go (inc*^forward c)) R.KeyUp
           . auxKey (go ((-inc)*^forward c)) R.KeyDown
           . auxKey (go ((-inc)*^right c)) R.KeyLeft
           . auxKey (go (inc*^right c)) R.KeyRight
           -- . auxKeyOnce (roll (pi*0.5)) R.KeyPageup
           -- . auxKeyOnce (roll (-pi * 0.5)) R.KeyPagedown
           . auxKey (roll 0.04) R.KeyPageup
           . auxKey (roll (-0.04)) R.KeyPagedown
           . maybe id (pan . negate . (^._x)) dMouse
           . maybe id (tilt . negate . (^._y)) dMouse
           . slow 0.9
           $ update dt c
        s = 15.0 / scale  -- max speed
        inc = 1.0 / scale -- 0.1
        go = (clampSpeed s .) . deltaV
        auxKey f k = if S.member k (snd keys) then f else id
        -- auxKeyOnce f k = if (k, True) `elem` fst keys then f else id
        dMouse = (\old -> (fromIntegral <$> mousePos ^-^ old) ^* 0.01) <$> prev
        prev' = maybe (const mousePos <$> prev)
                      (bool (Just mousePos) Nothing)
                      (lookup R.MouseButton0 mouseButtons)

bool :: a -> a -> Bool -> a
bool t _ True = t
bool _ f False = f


text:
<?php

namespace vxWeb\Util;

use vxPHP\File\FilesystemFolder;
use vxPHP\File\Exception\FilesystemFileException;
use vxPHP\File\FilesystemFile;
use vxPHP\File\UploadedFile;
use vxPHP\Application\Application;
use vxWeb\Model\MetaFile\MetaFile;
use vxWeb\Model\MetaFile\MetaFolder;

/**
 * this class contains some static methods used in various controllers
 * of vxWeb
 *
 * @author Gregor Kofler, info@gregorkofler.com
 *
 * @version 0.4.0, 2017-03-10
 *
 */
class File
{
    /**
     * add metafolder entries for filesystem subfolders
     * add metafile entries for filesystem files
     * remove metafile entries for missing file system files
     *
     * @param MetaFolder $metaFolder the folder which will be cleaned up
     * @return void
     * @throws FilesystemFileException
     * @throws \vxPHP\Application\Exception\ApplicationException
     * @throws \vxPHP\File\Exception\FilesystemFolderException
     * @throws \vxWeb\Model\MetaFile\Exception\MetaFileException
     * @throws \vxWeb\Model\MetaFile\Exception\MetaFolderException
     */
	public static function cleanupMetaFolder(MetaFolder $metaFolder): void
    {
		$application = Application::getInstance();

		$nestingInfo = $metaFolder->getNestingInformation();

		$db = $application->getVxPDO();
		$fileRoot = $application->getAbsoluteAssetsPath();

		$mFolders = $db->doPreparedQuery('
			SELECT foldersID, Path, l, r FROM folders f WHERE l > ? AND r < ? AND f.level = ?
			', [
				$nestingInfo['l'],
				$nestingInfo['r'],
				$nestingInfo['level'] + 1
		]);

		$db->beginTransaction();

		foreach($mFolders as $d) {
			if(!is_dir($fileRoot . $d['path'])) {

				$l = $d['l'];
				$r = $d['r'];
				$rl = $r - $l + 1;

				// delete "potential" subdirectories

				$db->execute('DELETE FROM folders WHERE l >= ? AND r <= ?', [(int) $l, (int) $r]);

				// update nesting

				$db->execute('UPDATE folders SET r = r - ? WHERE r > ?', [(int) $rl, (int) $l]);
			}
		}

		$db->commit();

		// create metafolder entries for filesystemfolders

		foreach($metaFolder->getFilesystemFolder()->getFolders() as $d) {
			MetaFolder::createMetaFolder($d);
		}

		$mFiles = $db->doPreparedQuery('SELECT filesID, COALESCE(Obscured_Filename, File) AS Filename FROM files f WHERE f.foldersID = ?', [(int) $metaFolder->getId()]);
		$existing = [];

		// delete orphaned metafile entries

		foreach($mFiles as $f) {
			if(! file_exists($metaFolder->getFullPath() . $f['filename'])) {
				$db->deleteRecord('files', $f['filesid']);
			}
			else {
				$existing[] = $f['filename'];
			}
		}

		// add new filesystem files

		$fsFiles = self::getFsFiles($metaFolder->getFullPath());
		$missing = array_diff($fsFiles, $existing);

		foreach($missing as $m) {
			MetaFile::createMetaFile(FilesystemFile::getInstance($metaFolder->getFullPath() . $m));
		}
	}

    /**
     * turns uploaded file into metafile, avoiding filename collisions
     *
     * @param MetaFolder $metaFolder
     * @param UploadedFile $upload
     * @param array metadata
     * @param boolean $unpackArchives unpack zip|gzip files when true
     * @return MetaFile[] | boolean false when failure
     * @throws FilesystemFileException
     * @throws \Exception
     */
	public static function processFileUpload(MetaFolder $metaFolder, UploadedFile $upload, array $metaData = [], $unpackArchives = false)
    {
		$metafiles = [];

		// check for archive

		if(preg_match('~^application/.*?(gz|zip|compressed)~', $upload->getMimeType()) && $unpackArchives) {
			try {
				$uploads = self::extractZip($upload->getPath(), $metaFolder->getFilesystemFolder());
				$upload->delete();
			}
			catch(\Exception $e) {
				return false;
			}
		}

		else {
			$uploads = [$upload];
		}

		foreach($uploads as $upload) {
			try {
				$metaFile = MetaFile::createMetaFile($upload);
				$metaFile->setMetaData($metaData);

				// obscure file if folder has the Obscure_Files attribute set

				if($metaFolder->obscuresFiles()) {
                    $metaFile->obscureTo(bin2hex(random_bytes(16)));
				}
			}

			// error with metafile creation(e.g. duplicate names with obscured files)

			catch(FilesystemFileException $e) {

				if($e->getCode() === FilesystemFileException::METAFILE_ALREADY_EXISTS) {

					preg_match('~^(.*?)(\((\d+)\))?(.[a-z0-9]*)?$~i', $upload->getFilename(), $matches);
					$matches[2] = $matches[2] === '' ? 2 : $matches[2] + 1;

					// check for both alternative filesystem filename and metafile filename

					while(file_exists(sprintf("%s(%d)%s", $matches[1], $matches[2], $matches[4])) || ! MetaFile::isFilenameAvailable(sprintf("%s(%d)%s", $matches[1], $matches[2], $matches[4]), $metaFolder)) {
						++ $matches[2];
					}

					$upload->rename(sprintf("%s(%d)%s", $matches[1], $matches[2], $matches[4]));

					$metaFile = MetaFile::createMetaFile($upload);
					$metaFile->setMetaData($metaData);

					// obscure file if folder has the Obscure_Files attribute set

					if($metaFolder->obscuresFiles()) {
						$metaFile->obscureTo(bin2hex(random_bytes(16)));
					}
				}

				else {
					throw $e;
				}
			}

			// other upload problem

			catch(\Exception $e) {
				return false;
			}

			$metafiles[] = $metaFile;
		}

		return $metafiles;
	}

    /**
     * extract a zip archive and return the extracted
     * FilesystemFiles
     *
     * @param string $zipFilename
     * @param FilesystemFolder $folder
     * @return FilesystemFile[]
     * @throws \Exception
     */
    public static function extractZip($zipFilename, FilesystemFolder $folder)
    {
        $zip = new \ZipArchive();
        $files = [];

        if (true !== ($status = $zip->open($zipFilename))) {
            throw new \Exception(sprintf("Archive file reports error: '%s'.", $status));
        }

        for ($i = 0; $i < $zip->numFiles; ++$i) {

            $name = $zip->getNameIndex($i);

            if (substr($name, -1) === '/') {
                continue;
            }

            $dirname = dirname($name);

            if ($dirname && $dirname !== '.') {
                $dir = $folder->createFolder($dirname);
            } else {
                $dir = $folder;
            }

            $dest = FilesystemFile::sanitizeFilename(basename($name), $dir);

            copy('zip://' . $zipFilename . '#' . $name, $dir->getPath() . $dest);

            $files[] = FilesystemFile::getInstance($dir->getPath() . $dest);

        }

        $zip->close();

        return $files;
    }

    private static function getFsFiles (string $path): ?array
    {
        $dir = rtrim($path, '/') . '/';

        try {
            $i = new \DirectoryIterator($dir);
        } catch (\Exception $e) {
            return null;
        }

        $files = [];

        foreach($i as $file) {
            $fn = $file->getFileName();
            if($fn[0] !== '.' && !$file->isDot() && $file->isFile()) {
                $files[] = $fn;
            }
        }

        return $files;
    }
}