text:
package cromwell.filesystems.s3

import java.net.URI

import com.google.common.net.UrlEscapers
import cromwell.cloudsupport.aws.auth.AwsAuthMode
import cromwell.core.WorkflowOptions
import cromwell.core.path.{NioPath, Path, PathBuilder}
import cromwell.filesystems.s3.S3PathBuilder._
import org.lerch.s3fs.{AmazonS3ClientFactory, S3FileSystemProvider}
import org.lerch.s3fs.util.S3Utils
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider
import software.amazon.awssdk.regions.Region
import software.amazon.awssdk.services.s3.{S3Client, S3Configuration}

import scala.concurrent.{ExecutionContext, Future}
import scala.language.postfixOps
import scala.util.{Failure, Try}

object S3PathBuilder {

  // Provides some level of validation of bucket names
  // This is meant to alert the user early if they mistyped a path in their workflow / inputs and not to validate
  // exact bucket syntax.
  // See https://docs.aws.amazon.com/AmazonS3/latest/dev/BucketRestrictions.html
  val S3BucketPattern =
    """
      (?x)                                      # Turn on comments and whitespace insensitivity
      ^s3://
      (                                         # Begin capturing group for bucket name
        [a-z0-9][a-z0-9-_\.]+[a-z0-9]           # Regex for bucket name - soft validation, see comment above
      )                                         # End capturing group for bucket name
      (?:
        /.*                                     # No validation here
      )?
    """.trim.r

  sealed trait S3PathValidation
  case class ValidFullS3Path(bucket: String, path: String) extends S3PathValidation
  case object PossiblyValidRelativeS3Path extends S3PathValidation
  sealed trait InvalidS3Path extends S3PathValidation {
    def pathString: String
    def errorMessage: String
  }
  final case class InvalidScheme(pathString: String) extends InvalidS3Path {
    override def errorMessage: String = s"S3 URIs must have 's3' scheme: $pathString"
  }
  final case class InvalidFullS3Path(pathString: String) extends InvalidS3Path {
    override def errorMessage: String = {
      s"""
         |The path '$pathString' does not seem to be a valid S3 path.
         |Please check that it starts with s3:// and that the bucket and object follow S3 naming guidelines at
         |https://docs.aws.amazon.com/AmazonS3/latest/dev/BucketRestrictions.html
      """.stripMargin.replace("\n", " ").trim
    }
  }
  final case class UnparseableS3Path(pathString: String, throwable: Throwable) extends InvalidS3Path {
    override def errorMessage: String =
      List(s"The specified S3 path '$pathString' does not parse as a URI.", throwable.getMessage).mkString("\n")
  }

  // Tries to extract a bucket name out of the provided string
  private def softBucketParsing(string: String): Option[String] = string match {
    case S3BucketPattern(bucket) => Option(bucket)
    case _ => None
  }

  def pathToUri(string: String): URI =
    URI.create(UrlEscapers.urlFragmentEscaper.escape(string))

  def validatePath(string: String): S3PathValidation = {
    Try {
      val uri = pathToUri(string)
      if (uri.getScheme == null) { PossiblyValidRelativeS3Path }
      else if (uri.getScheme.equalsIgnoreCase("s3")) {
        if (uri.getHost == null) {
          softBucketParsing(string) map { ValidFullS3Path(_, uri.getPath) } getOrElse InvalidFullS3Path(string)
        } else { ValidFullS3Path(uri.getHost, uri.getPath) }
      } else { InvalidScheme(string) }
    } recover { case t => UnparseableS3Path(string, t) } get
  }

  def fromAuthMode(authMode: AwsAuthMode,
                   configuration: S3Configuration,
                   options: WorkflowOptions,
                   storageRegion: Option[Region])(implicit ec: ExecutionContext): Future[S3PathBuilder] = {
    val provider = authMode.provider()

    // Other backends needed retry here. In case we need retry, we'll return
    // a future. This will allow us to add capability without changing signature
    Future(fromProvider(provider,
      configuration,
      options,
      storageRegion
    ))
  }

  def fromProvider(provider: AwsCredentialsProvider,
                   configuration: S3Configuration,
                   options: WorkflowOptions,
                   storageRegion: Option[Region]): S3PathBuilder = {
    new S3PathBuilder(configuration)
  }
}

class S3PathBuilder(configuration: S3Configuration
                     ) extends PathBuilder {
  // Tries to create a new S3Path from a String representing an absolute s3 path: s3://<bucket>[/<key>].
  def build(string: String): Try[S3Path] = {
    validatePath(string) match {
      case ValidFullS3Path(bucket, path) =>
        Try {
          val s3Path = new S3FileSystemProvider()
            .getFileSystem(URI.create("s3:////"), System.getenv)
            .getPath(s"""/$bucket/$path""")
          S3Path(s3Path, bucket,
            new AmazonS3ClientFactory().getS3Client(URI.create("s3:////"), System.getProperties))
        }
      case PossiblyValidRelativeS3Path => Failure(new IllegalArgumentException(s"$string does not have a s3 scheme"))
      case invalid: InvalidS3Path => Failure(new IllegalArgumentException(invalid.errorMessage))
    }
  }

  override def name: String = "s3"
}

case class S3Path private[s3](nioPath: NioPath,
                               bucket: String,
                               client: S3Client
                               ) extends Path {
  override protected def newPath(nioPath: NioPath): S3Path = S3Path(nioPath, bucket, client)

  override def pathAsString: String = s"s3://$pathWithoutScheme"

  override def pathWithoutScheme: String = safeAbsolutePath.stripPrefix("s3://s3.amazonaws.com/")

  def key: String = safeAbsolutePath

  /*
    This is a bit of a headache. We could make S3Path in S3PathBuilder as that can fulfill all usages of
    nioPath. However cromwell.core.path.Path requires the NioPath argument. Further we already know that
    nioPath is a valid S3Path by nature of how it was created in S3PathBuilder.build. However, better safe than
    sorry
   */
  lazy val s3Path = nioPath match {
    case s3Path: org.lerch.s3fs.S3Path => s3Path
    case _ => throw new RuntimeException("Internal path was not an S3 path: " + nioPath)
  }

  lazy val eTag = new S3Utils().getS3ObjectSummary(s3Path).eTag()

  /** Gets an absolute path for multiple forms of input. The FS provider does
   *  not support "toAbsolutePath" on forms such as "mypath/" or "foo.bar"
   *  So this function will prepend a forward slash for input that looks like this
   *  while leaving properly rooted input or input beginning with s3:// alone
   */
  def safeAbsolutePath: String = {
    val originalPath = s3Path.toString
    if (originalPath.startsWith("s3")) return s3Path.toAbsolutePath.toString
    originalPath.charAt(0) match {
      case '/' =>  s3Path.toAbsolutePath.toString
      case _ => s3Path.resolve(s"/$bucket/$originalPath").toAbsolutePath.toString
    }
  }
}


text:
<?php

namespace App\Statics\Contracts;

interface StaticsContract
{

	/**
	* Calls a method statically.
	*
	* @param 	$method <String>
	* @param 	$arguments <Array>
	* @access 	public
	* @return 	Mixed
	*/
	public static function __callStatic(String $method, Array $arguments);

}

redpajama_set_name: RedPajamaGithub


text:
FactoryGirl.define do
  factory :user do
    sequence(:name) { |n| "User#{n}" }
    sequence(:email) { |n| "user#{n}@example.com" }
    password 'password'
  end

  trait :admin do
    admin true
  end

  trait :quiz_scorer do
    quiz_scorer true
  end

  trait :judge do
    judge true
  end

  trait :circle_check_scorer do
    circle_check_scorer true
  end

  trait :master_of_ceremonies do
    master_of_ceremonies true
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<project>
  <property name="jnlp.title"    value="JST NonEditableCellEditor" />
  <property name="jnlp.Name"     value="NonEditableCellEditor" />
  <property name="jnlp.name"     value="noneditablecelleditor" />
  <property name="jnlp.codebase" value="https://ateraimemo.com/swing/noneditablecelleditor/" />
  <property name="jnlp.homepage" value="https://ateraimemo.com/Swing/NonEditableCellEditor.html" />
</project>


text:
package virthandler

import (
	"encoding/base64"
	goerror "errors"
	"fmt"
	"net"
	"strings"
	"time"

	"github.com/jeevatkm/go-model"
	k8sv1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/api/errors"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/client-go/kubernetes/scheme"
	"k8s.io/client-go/rest"
	"k8s.io/client-go/tools/cache"
	"k8s.io/client-go/tools/record"
	"k8s.io/client-go/util/workqueue"

	"kubevirt.io/kubevirt/pkg/api/v1"
	cloudinit "kubevirt.io/kubevirt/pkg/cloud-init"
	configdisk "kubevirt.io/kubevirt/pkg/config-disk"
	"kubevirt.io/kubevirt/pkg/kubecli"
	"kubevirt.io/kubevirt/pkg/logging"
	registrydisk "kubevirt.io/kubevirt/pkg/registry-disk"
	"kubevirt.io/kubevirt/pkg/virt-handler/virtwrap"
	"kubevirt.io/kubevirt/pkg/virt-handler/virtwrap/api"
)

func NewVMController(lw cache.ListerWatcher,
	domainManager virtwrap.DomainManager,
	recorder record.EventRecorder,
	restClient rest.RESTClient,
	clientset kubecli.KubevirtClient,
	host string,
	configDiskClient configdisk.ConfigDiskClient) (cache.Store, workqueue.RateLimitingInterface, *kubecli.Controller) {
	queue := workqueue.NewRateLimitingQueue(workqueue.DefaultControllerRateLimiter())

	dispatch := NewVMHandlerDispatch(domainManager, recorder, &restClient, clientset, host, configDiskClient)

	indexer, informer := kubecli.NewController(lw, queue, &v1.VM{}, dispatch)
	return indexer, queue, informer

}
func NewVMHandlerDispatch(domainManager virtwrap.DomainManager,
	recorder record.EventRecorder,
	restClient *rest.RESTClient,
	clientset kubecli.KubevirtClient,
	host string,
	configDiskClient configdisk.ConfigDiskClient) kubecli.ControllerDispatch {
	return &VMHandlerDispatch{
		domainManager: domainManager,
		recorder:      recorder,
		restClient:    *restClient,
		clientset:     clientset,
		host:          host,
		configDisk:    configDiskClient,
	}
}

type VMHandlerDispatch struct {
	domainManager virtwrap.DomainManager
	recorder      record.EventRecorder
	restClient    rest.RESTClient
	clientset     kubecli.KubevirtClient
	host          string
	configDisk    configdisk.ConfigDiskClient
}

func (d *VMHandlerDispatch) getVMNodeAddress(vm *v1.VM) (string, error) {
	node, err := d.clientset.CoreV1().Nodes().Get(vm.Status.NodeName, metav1.GetOptions{})
	if err != nil {
		logging.DefaultLogger().Error().Reason(err).Msgf("fetching source node %s failed", vm.Status.NodeName)
		return "", err
	}

	addrStr := ""
	for _, addr := range node.Status.Addresses {
		if (addr.Type == k8sv1.NodeInternalIP) && (addrStr == "") {
			addrStr = addr.Address
			break
		}
	}
	if addrStr == "" {
		err := fmt.Errorf("VM node is unreachable")
		logging.DefaultLogger().Error().Msg("VM node is unreachable")
		return "", err
	}

	return addrStr, nil
}

func (d *VMHandlerDispatch) updateVMStatus(vm *v1.VM, cfg *api.DomainSpec) error {
	obj, err := scheme.Scheme.Copy(vm)
	if err != nil {
		return err
	}
	vm = obj.(*v1.VM)

	// XXX When we start supporting hotplug, this needs to be altered.
	// Check if the VM is already marked as running. If yes, don't update the VM.
	// Otherwise we end up in endless controller requeues.
	if vm.Status.Phase == v1.Running {
		return nil
	}

	vm.Status.Phase = v1.Running

	vm.Status.Graphics = []v1.VMGraphics{}

	podIP, err := d.getVMNodeAddress(vm)
	if err != nil {
		return err
	}

	for _, src := range cfg.Devices.Graphics {
		if (src.Type != "spice" && src.Type != "vnc") || src.Port == -1 {
			continue
		}
		dst := v1.VMGraphics{
			Type: src.Type,
			Host: podIP,
			Port: src.Port,
		}
		vm.Status.Graphics = append(vm.Status.Graphics, dst)
	}

	return d.restClient.Put().Resource("vms").Body(vm).
		Name(vm.ObjectMeta.Name).Namespace(vm.ObjectMeta.Namespace).Do().Error()

}

func (d *VMHandlerDispatch) Execute(store cache.Store, queue workqueue.RateLimitingInterface, key interface{}) {

	shouldDeleteVm := false

	// Fetch the latest Vm state from cache
	obj, exists, err := store.GetByKey(key.(string))

	if err != nil {
		queue.AddRateLimited(key)
		return
	}

	// Retrieve the VM
	var vm *v1.VM
	if !exists {
		namespace, name, err := cache.SplitMetaNamespaceKey(key.(string))
		if err != nil {
			// TODO do something more smart here
			queue.AddRateLimited(key)
			return
		}
		vm = v1.NewVMReferenceFromNameWithNS(namespace, name)
	} else {
		vm = obj.(*v1.VM)
	}

	// Check For Migration before processing vm not in our cache
	if !exists {
		// If we don't have the VM in the cache, it could be that it is currently migrating to us
		isDestination, err := d.isMigrationDestination(vm.GetObjectMeta().GetNamespace(), vm.GetObjectMeta().GetName())
		if err != nil {
			// unable to determine migration status, we'll try again later.
			queue.AddRateLimited(key)
			return
		}

		if isDestination {
			// OK, this VM is migrating to us, don't interrupt it.
			queue.Forget(key)
			return
		}
		// The VM is deleted on the cluster, continue with processing the deletion on the host.
		shouldDeleteVm = true
	}
	logging.DefaultLogger().V(3).Info().Object(vm).Msg("Processing VM update.")

	// Process the VM
	isPending, err := d.processVmUpdate(vm, shouldDeleteVm)
	if err != nil {
		// Something went wrong, reenqueue the item with a delay
		logging.DefaultLogger().Error().Object(vm).Reason(err).Msg("Synchronizing the VM failed.")
		d.recorder.Event(vm, k8sv1.EventTypeWarning, v1.SyncFailed.String(), err.Error())
		queue.AddRateLimited(key)
		return
	} else if isPending {
		// waiting on an async action to complete
		logging.DefaultLogger().V(3).Info().Object(vm).Reason(err).Msg("Synchronizing is in a pending state.")
		queue.AddAfter(key, 1*time.Second)
		queue.Forget(key)
		return
	}

	logging.DefaultLogger().V(3).Info().Object(vm).Msg("Synchronizing the VM succeeded.")
	queue.Forget(key)
	return
}

// Almost everything in the VM object maps exactly to its domain counterpart
// One exception is persistent volume claims. This function looks up each PV
// and inserts a corrected disk entry into the VM's device map.
func MapPersistentVolumes(vm *v1.VM, restClient cache.Getter, namespace string) (*v1.VM, error) {
	vmCopy := &v1.VM{}
	model.Copy(vmCopy, vm)

	for idx, disk := range vmCopy.Spec.Domain.Devices.Disks {
		if disk.Type == "PersistentVolumeClaim" {
			logging.DefaultLogger().V(3).Info().Object(vm).Msgf("Mapping PersistentVolumeClaim: %s", disk.Source.Name)

			// Look up existing persistent volume
			obj, err := restClient.Get().Namespace(namespace).Resource("persistentvolumeclaims").Name(disk.Source.Name).Do().Get()

			if err != nil {
				logging.DefaultLogger().Error().Reason(err).Msg("unable to look up persistent volume claim")
				return vm, fmt.Errorf("unable to look up persistent volume claim: %v", err)
			}

			pvc := obj.(*k8sv1.PersistentVolumeClaim)
			if pvc.Status.Phase != k8sv1.ClaimBound {
				logging.DefaultLogger().Error().Msg("attempted use of unbound persistent volume")
				return vm, fmt.Errorf("attempted use of unbound persistent volume claim: %s", pvc.Name)
			}

			// Look up the PersistentVolume this PVC is bound to
			// Note: This call is not namespaced!
			obj, err = restClient.Get().Resource("persistentvolumes").Name(pvc.Spec.VolumeName).Do().Get()

			if err != nil {
				logging.DefaultLogger().Error().Reason(err).Msg("unable to access persistent volume record")
				return vm, fmt.Errorf("unable to access persistent volume record: %v", err)
			}
			pv := obj.(*k8sv1.PersistentVolume)

			if pv.Spec.ISCSI != nil {
				logging.DefaultLogger().Object(vm).Info().Msg("Mapping iSCSI PVC")
				newDisk := v1.Disk{}

				newDisk.Type = "network"
				newDisk.Device = "disk"
				newDisk.Target = disk.Target
				newDisk.Driver = new(v1.DiskDriver)
				newDisk.Driver.Type = "raw"
				newDisk.Driver.Name = "qemu"

				newDisk.Source.Name = fmt.Sprintf("%s/%d", pv.Spec.ISCSI.IQN, pv.Spec.ISCSI.Lun)
				newDisk.Source.Protocol = "iscsi"

				hostPort := strings.Split(pv.Spec.ISCSI.TargetPortal, ":")
				ipAddrs, err := net.LookupIP(hostPort[0])
				if err != nil || len(ipAddrs) < 1 {
					logging.DefaultLogger().Error().Reason(err).Msgf("Unable to resolve host '%s'", hostPort[0])
					return vm, fmt.Errorf("Unable to resolve host '%s': %s", hostPort[0], err)
				}

				newDisk.Source.Host = &v1.DiskSourceHost{}
				newDisk.Source.Host.Name = ipAddrs[0].String()
				if len(hostPort) > 1 {
					newDisk.Source.Host.Port = hostPort[1]
				}

				// This iscsi device has auth associated with it.
				if pv.Spec.ISCSI.SecretRef != nil && pv.Spec.ISCSI.SecretRef.Name != "" {
					newDisk.Auth = &v1.DiskAuth{
						Secret: &v1.DiskSecret{
							Type:  "iscsi",
							Usage: pv.Spec.ISCSI.SecretRef.Name,
						},
					}
				}

				vmCopy.Spec.Domain.Devices.Disks[idx] = newDisk
			} else {
				logging.DefaultLogger().Object(vm).Error().Msg(fmt.Sprintf("Referenced PV %v is backed by an unsupported storage type", pv))
			}
		} else if disk.Type == "network" {
			newDisk := v1.Disk{}
			model.Copy(&newDisk, disk)

			if disk.Source.Host == nil {
				logging.DefaultLogger().Error().Msg("Missing disk source host")
				return vm, fmt.Errorf("Missing disk source host")
			}

			ipAddrs, err := net.LookupIP(disk.Source.Host.Name)
			if err != nil || ipAddrs == nil || len(ipAddrs) < 1 {
				logging.DefaultLogger().Error().Reason(err).Msgf("Unable to resolve host '%s'", disk.Source.Host.Name)
				return vm, fmt.Errorf("Unable to resolve host '%s': %s", disk.Source.Host.Name, err)
			}

			newDisk.Source.Host.Name = ipAddrs[0].String()

			vmCopy.Spec.Domain.Devices.Disks[idx] = newDisk
		}
	}

	return vmCopy, nil
}

func (d *VMHandlerDispatch) injectDiskAuth(vm *v1.VM) (*v1.VM, error) {
	for idx, disk := range vm.Spec.Domain.Devices.Disks {
		if disk.Auth == nil || disk.Auth.Secret == nil || disk.Auth.Secret.Usage == "" {
			continue
		}

		usageIDSuffix := fmt.Sprintf("-%s-%s---", vm.GetObjectMeta().GetNamespace(), vm.GetObjectMeta().GetName())
		usageID := disk.Auth.Secret.Usage
		usageType := disk.Auth.Secret.Type
		secretID := usageID

		if strings.HasSuffix(usageID, usageIDSuffix) {
			secretID = strings.TrimSuffix(usageID, usageIDSuffix)
		} else {
			usageID = fmt.Sprintf("%s%s", usageID, usageIDSuffix)
		}

		secret, err := d.clientset.CoreV1().Secrets(vm.ObjectMeta.Namespace).Get(secretID, metav1.GetOptions{})
		if err != nil {
			logging.DefaultLogger().Error().Reason(err).Msg("Defining the VM secret failed unable to pull corresponding k8s secret value")
			return nil, err
		}

		secretBase64, ok := secret.Data["node.session.auth.password"]
		if ok == false {
			return nil, goerror.New(fmt.Sprintf("No password value found in k8s secret %s %v", secretID, err))
		}
		secretValue, err := base64.StdEncoding.DecodeString(string(secretBase64[:]))
		if err != nil {
			return nil, goerror.New(fmt.Sprintf("Failed to base64 decode k8s secret %s %v", secretID, err))
		}

		userBase64, ok := secret.Data["node.session.auth.username"]
		if ok == false {
			return nil, goerror.New(fmt.Sprintf("Failed to find username for disk auth %s", secretID))
		}
		userValue, err := base64.StdEncoding.DecodeString(string(userBase64[:]))
		if err != nil {
			return nil, goerror.New(fmt.Sprintf("Failed to base64 decode k8s secret username data field %s %v", secretID, err))
		}
		vm.Spec.Domain.Devices.Disks[idx].Auth.Username = string(userValue)

		// override the usage id on the VM with the VM specific one.
		// By decoupling usage from the k8s secret name here, this allows
		// multiple VMs to reference the same k8s secret without conflicting
		// with one another.
		vm.Spec.Domain.Devices.Disks[idx].Auth.Secret.Usage = usageID
		err = d.domainManager.SyncVMSecret(vm, usageType, usageID, string(secretValue))
		if err != nil {
			return nil, err
		}
	}

	return vm, nil
}

func (d *VMHandlerDispatch) processVmUpdate(vm *v1.VM, shouldDeleteVm bool) (bool, error) {

	if shouldDeleteVm {
		// Since the VM was not in the cache, we delete it
		err := d.domainManager.KillVM(vm)
		if err != nil {
			return false, err
		}

		// remove any defined libvirt secrets associated with this vm
		err = d.domainManager.RemoveVMSecrets(vm)
		if err != nil {
			return false, err
		}
		return false, d.configDisk.Undefine(vm)
	} else if isWorthSyncing(vm) == false {
		// nothing to do here.
		return false, nil
	}

	isPending, err := d.configDisk.Define(vm)
	if err != nil || isPending == true {
		return isPending, err
	}

	// Synchronize the VM state
	vm, err = MapPersistentVolumes(vm, d.clientset.CoreV1().RESTClient(), vm.ObjectMeta.Namespace)
	if err != nil {
		return false, err
	}

	// Map Container Registry Disks to block devices Libvirt can consume
	vm, err = registrydisk.MapRegistryDisks(vm)
	if err != nil {
		return false, err
	}

	vm, err = d.injectDiskAuth(vm)
	if err != nil {
		return false, err
	}

	// Map whatever devices are being used for config-init
	vm, err = cloudinit.MapCloudInitDisks(vm)
	if err != nil {
		return false, err
	}

	// TODO MigrationNodeName should be a pointer
	if vm.Status.MigrationNodeName != "" {
		// Only sync if the VM is not marked as migrating.
		// Everything except shutting down the VM is not
		// permitted when it is migrating.
		return false, nil
	}

	// TODO check if found VM has the same UID like the domain,
	// if not, delete the Domain first
	newCfg, err := d.domainManager.SyncVM(vm)
	if err != nil {
		return false, err
	}

	return false, d.updateVMStatus(vm, newCfg)
}

func (d *VMHandlerDispatch) isMigrationDestination(namespace string, vmName string) (bool, error) {

	// If we don't have the VM in the cache, it could be that it is currently migrating to us
	result := d.restClient.Get().Name(vmName).Resource("vms").Namespace(namespace).Do()
	if result.Error() == nil {
		// So the VM still seems to exist
		fetchedVM, err := result.Get()
		if err != nil {
			return false, err
		}
		if fetchedVM.(*v1.VM).Status.MigrationNodeName == d.host {
			return true, nil
		}
	} else if !errors.IsNotFound(result.Error()) {
		// Something went wrong, let's try again later
		return false, result.Error()
	}

	// VM object was not found.
	return false, nil
}

func isWorthSyncing(vm *v1.VM) bool {
	return vm.Status.Phase != v1.Succeeded && vm.Status.Phase != v1.Failed
}


text:
using UnityEngine;
using System.Collections;

namespace BT.Ex {

	public class BTCheckWithinDistance : BTConditional {
		private string _readDataName;
		private int _readDataId;
		private DataOpt _dataOpt;
		private float _distance;
		private Transform _targetTrans;
		private Transform _trans;

		public BTCheckWithinDistance (Transform trans, float distance, string readDataName, DataOpt dataOpt) {
			_trans = trans;
			_distance = distance;
			_readDataName = readDataName;
			_dataOpt = dataOpt;
		}

		public BTCheckWithinDistance (Transform trans, float distance, Transform targetTrans) : this ( trans, distance, null, DataOpt.ProvidedTrans) {
			_targetTrans = targetTrans;
		}

		public override void Activate (BTDatabase database) {
			base.Activate (database);

			if (_dataOpt != DataOpt.ProvidedTrans) {
				_readDataId = _database.GetDataId(_readDataName);
			}
		}

		public override bool Check () {
			Vector3 dataPosition = Vector3.zero;

			switch (_dataOpt) {
			case DataOpt.Vec3:
				dataPosition = _database.GetData<Vector3>(_readDataId);
				break;
			case DataOpt.Trans:
				Transform trans = _database.GetData<Transform>(_readDataId);
				dataPosition = trans.position;
				break;
			case DataOpt.ProvidedTrans:
				dataPosition = _targetTrans.position;
				break;
			}

			Vector3 offset = dataPosition - _trans.position;
			return offset.sqrMagnitude <= _distance * _distance;
		}

		public enum DataOpt {
			Vec3,
			Trans,
			ProvidedTrans,
		}
	}
}


text:
fabric.Image.fromImgData = function(imgData, callback) {
	var canvas = document.createElement('canvas');
	canvas.width = imgData.width;
	canvas.height = imgData.height;

	var ctx = canvas.getContext('2d');
	ctx.putImageData(imgData, 0, 0);

	fabric.Image.fromURL(canvas.toDataURL(), callback);
}

// This class handles the last page that allows the user to perform Poisson
// Image editing.
function PagePoisson(overlayData, backgroundData) {

	// Data members.
	var contents = $.parseHTML(''+
		'
4. Move, scale, rotate the overlay and click render when you are ready.
'
		);

	var canvas = document.createElement('canvas');
	canvas.width = 100;
	canvas.height = 100;
	canvas.id = 'myCanvas';

	var processingScreen = $('#block');

	var uiDisabler = $('#disabler');

	var popup = $('#popup');
	popup.slideIn = function() {
		popup.show();
		popup.css({bottom: -popup.outerHeight()});
		popup.animate({bottom: 0});
	}
	popup.slideOut = function(callback) {
		popup.animate({
				bottom: -popup.outerHeight()
			}, function(){
				if (typeof callback !== 'undefined') callback();
			});
	}

	var metadata = false;

	var overlay = false;

	var background = false;

	var boundingBox = false;

	this.render = function() {
		// Populate the page with contents.
		$('#content').append(contents);
		$('#content').append(canvas);

		// Wrap the <canvas> with Fabric canvas object.
		canvas = new fabric.Canvas('myCanvas', {selection: false});
		canvas.setHeight(backgroundData.height);
		canvas.setWidth(backgroundData.width);

		// Load the background image.
		fabric.Image.fromImgData(backgroundData, function(dummy){
			background = dummy;
			background.set('selectable', false);
			setupImages();
		});

		// Load the overlay image.
		fabric.Image.fromImgData(overlayData, function(dummy){
			overlay = dummy;
			setupImages();
		});
	}

	// This function sets up the canvas. The function will run its
	// main subroutine only when both images are loaded.
	function setupImages() {
		// Return if both images are not loaded.
		if (!overlay) return;
		if (!background) return;

		// Ensure that the overlay is small enough to fit within the canvas.
		var widthFactor = overlay.width / background.width;
		var heightFactor = overlay.height / background.height;
		var maxFactor = Math.max(widthFactor, heightFactor);
		if (maxFactor > 0.8) {
			overlay.height *= 0.8 / maxFactor;
			overlay.width *= 0.8 / maxFactor;
		}

		initializeCanvas();
	}

	// This function restore the canvas and the page to the initial state.
	function initializeCanvas() {
		// Add both images onto the canvas
		canvas.clear();
		canvas.add(background);
		canvas.add(overlay);

		// Popup the render button
		popup.html('
Render
');
		popup.slideIn();
		$('#popup div.yes-btn').click(function() {
			popup.slideOut();
			processingScreen.fadeIn(300, applyPoisson);
		});
	}

	// This function fires when the user clicks the 'Render' button. It calls the other
	// function that contains the algorithm for Poisson Image Editing. Once the algorithm
	// finishes, this function presents its output onto the canvas.
	var solution = [false, false, false];
	function applyPoisson() {
		// Create a bounding box.
		boundingBox = overlay.getBoundingRect();
		boundingBox.left = Math.floor(boundingBox.left);
		boundingBox.top = Math.floor(boundingBox.top);
		boundingBox.width = Math.ceil(boundingBox.width);
		boundingBox.height = Math.ceil(boundingBox.height);

		// Get the imageData of the overlay.
		var ctx = canvas.getContext('2d');
		canvas.remove(background);
		canvas.deactivateAll().renderAll(); // Removes the image controller before saving the image.
		var overlayData = ctx.getImageData(boundingBox.left, boundingBox.top, boundingBox.width, boundingBox.height);
		canvas.add(background);

		// Get the imageData of the background.
		canvas.remove(overlay);
		var backgroundData = ctx.getImageData(boundingBox.left, boundingBox.top, boundingBox.width, boundingBox.height);
		canvas.add(overlay);

		// Setup the metadata.
		metadata = setupMeta(overlayData);

		// Build the matrix
		var equation = matrixBuilder(metadata, overlayData, backgroundData);

		// Create 3 different workers, each solves the equation for one color channel.
		for (var c = 0; c < 3; c++) {
			solution[c] = false;
			var worker = new Worker('scripts/sor.js');
			worker.addEventListener('message', function(e) {
				storeSolution(e.data.sol, e.data.c);
			});
			worker.postMessage({
				A: equation.A,
				b: equation.b[c],
				omega: 1.9,
				initialSol: equation.initialGuess[c],
				color: c
			});
		}
	}

	// This callback function executes whenever the worker finished solving an equation.
	// After all of the workers have solved their equation, the function calls displaySolution().
	function storeSolution(sol, c) {
		console.log('fired', solution.length);
		solution[c] = sol;
		for (var i = 0; i < solution.length; i++) {
			if (!solution[i]) return;
		}
		displaySolution();
	}

	// Display the solution and the pop-up prompt.
	function displaySolution() {
		// Get the background imageData within the bounding box.
		var ctx = canvas.getContext('2d');
		canvas.remove(overlay);
		var backgroundData = ctx.getImageData(boundingBox.left, boundingBox.top, boundingBox.width, boundingBox.height);

		// Convert the solution into imageData.  Paint the solution on top of the background.
		var indexMap = metadata.indexMap;
		var solutionData = ctx.createImageData(backgroundData.width, backgroundData.height);
		solutionData.data.set(backgroundData.data);
		var dataI = 0;
		for (var y = 0, lenY = backgroundData.height; y < lenY; y++) {
			for (var x = 0, lenX = backgroundData.width; x < lenX; x++, dataI += 4) {
				var solI = indexMap.get(x, y);
				if (solI >= 0) {
					for (var c = 0; c < 3; c++) {
						solutionData.data[dataI + c] = solution[c][solI];
					}
				}
			}
		}

		// Put the solution onto the main canvas.
		canvas.remove(overlay);
		uiDisabler.show();
		ctx.putImageData(solutionData, boundingBox.left, boundingBox.top);
		processingScreen.hide();

		// Prompt the user for what to do next (save or re-do).
		popup.html('The image is ready! What would you like to do next?
' +
		'
Save

Reposition
' +
		'
Make more!
');
		popup.slideIn();
		$('#popup div.no-btn').click(function() {
			uiDisabler.hide();
			popup.slideOut(initializeCanvas);
		});
		$('#popup div.yes-btn').click(function() {
			var domCanvas = document.getElementById('myCanvas');
			window.open(domCanvas.toDataURL('image/png'));
		})
		$('#popup div.blue-btn').click(function() {
			uiDisabler.hide();
			restart();
		})
	}

	function restart() {
		$('#content').empty();
		popup.slideOut(function() {
			popup.empty();
			var nextPage = new PageFilePrompt;
			nextPage.render();
		});
	}

	// Below are methods that are responsible for figuring out the imageData of the
	// rendered image.
	function setupMeta(overlayData) {
		// Fill in the values of the indexMap by processing the imageData.
		var indexMap = new Int32Array2D(overlayData.height, overlayData.width);
		// Iterate through each pixel.
		var count = 0,
			i = 0;
		for (var y = 0, lenY = overlayData.height; y < lenY; y++) {
			for (var x = 0, lenX = overlayData.width; x < lenX; x++, i += 4) {
				// If the current pixel is not fully opaque, its index = -1
				if (overlayData.data[i + 3] < 250) {
					indexMap.set(x, y, -100);
					continue;
				}
				// Loop through top, right, down, left neighboring pixels.
				var dx = [0, 1, 0, -1];
				var dy = [-1, 0, 1, 0];
				var internal = true; // internal = false means the pixel is on the boundary.
				for (var n = 0; n < 4; n++) {
					var neiX = x + dx[n];
					var neiY = y + dy[n];
					var neiI = neiX + neiY * overlayData.width;
					// Skip if out-of-bound.
					if (neiX < 0 || neiX >= overlayData.width || neiY < 0 || neiY >= overlayData.height) {
						continue;
					}
					// If any of the neighbor is not fully opaque, then we're a boundary pixel.
					if (overlayData.data[4 * neiI + 3] < 250) {
						internal = false;
						break;
					}
				}
				if (internal) {
					indexMap.set(x, y, count);
					count++;
				} else {
					indexMap.set(x, y, -1);
				}
			}
		}

		return {
			indexMap : indexMap,
			n : count
		};
	}

	function matrixBuilder(metadata, overlayData, backgroundData) {
		var indexMap = metadata.indexMap,
			n = metadata.n;

		// Declare the matrix A, vector b, and the initial solution.
		var A = new Int32Array2D(5, n),
			b = [];
		for (var i = 3; i--;) {
			b[i] = [];
			for (var j = n; j--;) {
				b[i][j] = 0;
			}
		}
		var initialSol = [];
		for (var i = 3; i--;) {
			initialSol[i] = [];
		}

		// For each pixel in the overlay.
		var dataI = 0; // Index into the ImageData for pixel (x, y)
		for (var y = 0, lenY = overlayData.height; y < lenY; y++) {
			for (var x = 0, lenX = overlayData.width; x < lenX; x++, dataI += 4) {
				// Get the pixel's index.
				var pixIndex = indexMap.get(x, y);
				// Don't set an equation for no-op or boundary pixels.
				if (pixIndex < 0) {
					continue;
				}
				// Sets up a row of equation if it's an internal pixel.
				var neiCount = 0,
					writeIndex = 0,
					pixColor = [];
					for (var c = 0; c < 3; c++) {
						pixColor[c] = overlayData.data[dataI + c];
					}

				// Loops through the 4 adjacent neighbors (U, R, D, L).
				for (var n = 0, dx = [0, 1, 0, -1], dy = [-1, 0, 1, 0]; n < 4; n++) {
					var neiX = x + dx[n];
					var neiY = y + dy[n];
					// Skip out-of-bound neighbors.
					if (!indexMap.inBound(neiX, neiY)) {
						continue;
					}
					// Process the in-bound neighbors.
					var neiIndex = indexMap.get(neiX, neiY),
						neiDataIndex = dataI + 4 * (dx[n] + lenX * dy[n]);
					// If the neighbor is a boundary pixel, add the background color value
					// to b.
					if (neiIndex == -1) {
						for (var c = 0; c < 3; c++) {
							b[c][pixIndex] += backgroundData.data[neiDataIndex + c];
						}
						neiCount++;
						continue;
					}
					// Sets the row of A and b.
					for (var c = 0; c < 3; c++) {
						neiColor = overlayData.data[neiDataIndex + c];
						b[c][pixIndex] += pixColor[c] - neiColor;
					}
					neiCount++;
					writeIndex++;
					A.set(pixIndex, writeIndex, neiIndex);
				}

				A.set(pixIndex, 0, neiCount);
				// Fill in the remaining spot of A with -1.
				for (var n = writeIndex + 1; n < 5; n++) {
					A.set(pixIndex, n, -1);
				}
				for (var c = 0; c < 3; c++) {
					initialSol[c][pixIndex] = backgroundData.data[dataI + c];
				}
			}
		}

		return {
			A : A,
			b : b,
			initialGuess : initialSol
		};
	}

	function Int32Array2D(width, height) {
		this.width = width;
		this.height = height;
		this.data = new Int32Array(width * height);
	}
	Int32Array2D.prototype.get = function(x, y) {
		var i = x * this.width + y;
		return this.data[i];
	}
	Int32Array2D.prototype.set = function(x, y, val) {
		var i = x * this.width + y;
		this.data[i] = val;
	}
	Int32Array2D.prototype.inBound = function(x, y) {
		if (x < 0 || x >= this.height || y < 0 || y >= this.width) return false;
		return true;
	}
}


text:
function es_submit_page(url)
{
	es_email = document.getElementById("es_txt_email");
	es_name = document.getElementById("es_txt_name");
	es_group = document.getElementById("es_txt_group");
    if( es_email.value == "" )
    {
        alert(es_widget_notices.es_email_notice);
        es_email.focus();
        return false;
    }
	if( es_email.value!="" && ( es_email.value.indexOf("@",0) == -1 || es_email.value.indexOf(".",0) == -1 ))
    {
        alert(es_widget_notices.es_incorrect_email);
        es_email.focus();
        es_email.select();
        return false;
    }

	document.getElementById("es_msg").innerHTML = es_widget_notices.es_load_more;
	var date_now = "";
    var mynumber = Math.random();
	var str= "es_email="+ encodeURI(es_email.value) + "&es_name=" + encodeURI(es_name.value) + "&es_group=" + encodeURI(es_group.value) + "&timestamp=" + encodeURI(date_now) + "&action=" + encodeURI(mynumber);
	es_submit_request(url+'/?es=subscribe', str);
	//alert(url+'/?es=subscribe' + str);
}

var http_req = false;
function es_submit_request(url, parameters)
{
	http_req = false;
	if (window.XMLHttpRequest)
	{
		http_req = new XMLHttpRequest();
		if (http_req.overrideMimeType)
		{
			http_req.overrideMimeType('text/html');
		}
	}
	else if (window.ActiveXObject)
	{
		try
		{
			http_req = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e)
		{
			try
			{
				http_req = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e)
			{

			}
		}
	}
	if (!http_req)
	{
		alert(es_widget_notices.es_ajax_error);
		return false;
	}
	http_req.onreadystatechange = eemail_submitresult;
	http_req.open('POST', url, true);
	http_req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	// http_req.setRequestHeader("Content-length", parameters.length);
	// http_req.setRequestHeader("Connection", "close");
	http_req.send(parameters);
}

function eemail_submitresult()
{
	//alert(http_req.readyState);
	//alert(http_req.responseText);
	if (http_req.readyState == 4)
	{
		if (http_req.status == 200)
		{
		 	if (http_req.readyState==4 || http_req.readyState=="complete")
			{
				if((http_req.responseText).trim() == "subscribed-successfully")
				{
					document.getElementById("es_msg").innerHTML = es_widget_notices.es_success_message;
					document.getElementById("es_txt_email").value="";
				}
				else if((http_req.responseText).trim() == "subscribed-pending-doubleoptin")
				{
					alert(es_widget_notices.es_success_notice);
					document.getElementById("es_msg").innerHTML = es_widget_notices.es_success_message;
					document.getElementById("es_txt_email").value="";
					document.getElementById("es_txt_name").value="";
				}
				else if((http_req.responseText).trim() == "already-exist")
				{
					document.getElementById("es_msg").innerHTML = es_widget_notices.es_email_exists;
				}
				else if((http_req.responseText).trim() == "unexpected-error")
				{
					document.getElementById("es_msg").innerHTML = es_widget_notices.es_error;
				}
				else if((http_req.responseText).trim() == "invalid-email")
				{
					document.getElementById("es_msg").innerHTML = es_widget_notices.es_invalid_email;
				}
				else
				{
					document.getElementById("es_msg").innerHTML = es_widget_notices.es_try_later;
					document.getElementById("es_txt_email").value="";
					document.getElementById("es_txt_name").value="";
				}
			}
		}
		else
		{
			alert(es_widget_notices.es_problem_request);
		}
	}
}


text:
<?php
namespace tzfrs\URLPruner\Pruners;

/**
 * This class is used to handle pruning of an URL with regex
 *
 * Class RegexPruner
 * @package tzfrs\URLPruner\Pruners
 * @author Theo Tzaferis <theo.tzaferis@active-value.de>
 * @license MIT
 *
 */
class RegexPruner
{
    /**
     * This method removes a string based on a Regex from an URL
     *
     * @param string $url The URL that will be pruned
     * @param string $value The Regex
     * @return mixed
     */
    public static function replace($url, $value)
    {
        return preg_replace('#' . preg_quote($value, '#') . '#', '', $url);
    }

}


text:
/* simu not js */

require( ["jquery", "bootstrap", "bootstrap-select","alljs"],
	function() {

	}
);


text:
package io.github.jokoframework.porandu.enums;

/**
 * Created by afeltes on 24/07/16.
 */
public enum TipoParametroEnum {
    INTEGER, BOOLEAN, LONG, STRING, LIST

}


text:
git add -A
git commit -m "Изменения на сервере app-web.ru"
#git reset --hard


text:
Projects

Just some open source projects

JavaScript / Node

Reflection

Screenshot taking API, built on top of Node.js, MongoDB and PhantomJS

* If you are interested in more JavaScript / CoffeeScript projects, let me know there are several non open source ones I can show

Go

Goumi

Simple framework to build modular web applications on top of Go, inspired by KoaJS

Gibbon

Chain middleware helper

PHP

Poseidon

Poken API client library, built to work with KohanaPHP

Librarian

PSR-0 SPL autoloader, built with PHP 5.3


text:
package aws

import (
	"crypto/md5"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"os"
	"path"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/awserr"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/s3"
	"github.com/aws/aws-sdk-go/service/s3/s3iface"
	"github.com/aws/aws-sdk-go/service/s3/s3manager"
	"github.com/stelligent/mu/common"
)

type s3ArtifactManager struct {
	s3API      s3iface.S3API
	sess       *session.Session
	dryrunPath string
}

func newArtifactManager(sess *session.Session, dryrunPath string) (common.ArtifactManager, error) {
	log.Debug("Connecting to S3 service")
	s3API := s3.New(sess)

	return &s3ArtifactManager{
		s3API:      s3API,
		sess:       sess,
		dryrunPath: dryrunPath,
	}, nil
}

// CreateArtifact get the instances for a specific cluster
func (s3Mgr *s3ArtifactManager) CreateArtifact(body io.ReadSeeker, destURL string, kmsKey string) error {
	s3API := s3Mgr.s3API

	s3URL, err := url.Parse(destURL)
	if err != nil {
		return err
	}
	if s3URL.Scheme != "s3" {
		return fmt.Errorf("destURL must have scheme of 's3', received '%s'", s3URL.Scheme)
	}

	// start from the begining
	body.Seek(0, 0)

	if s3Mgr.dryrunPath != "" {
		err := os.MkdirAll(s3Mgr.dryrunPath, 0700)
		if err != nil {
			return err
		}
		artifactFile := fmt.Sprintf("%s/%s-%s", s3Mgr.dryrunPath, s3URL.Host, path.Base(s3URL.Path))
		f, err := os.OpenFile(artifactFile, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
		if err != nil {
			return err
		}
		_, err = io.Copy(f, body)
		if err != nil {
			return err
		}

		log.Infof("  DRYRUN: Skipping PUT of artifact '%s'. Written to '%s'", destURL, artifactFile)
		return nil
	}

	params := &s3.PutObjectInput{
		Bucket: aws.String(s3URL.Host),
		Key:    aws.String(s3URL.Path),
		Body:   body,
	}

	if kmsKey != "" {
		params.SSEKMSKeyId = aws.String(kmsKey)
		params.ServerSideEncryption = aws.String("aws:kms")
	}

	log.Debugf("Creating artifact at '%s'", destURL)

	_, err = s3API.PutObject(params)
	if err != nil {
		return err
	}

	return nil
}

func (s3Mgr *s3ArtifactManager) getArtifactS3(url *url.URL, etag string) (io.ReadCloser, string, error) {
	region, err := s3manager.GetBucketRegionWithClient(aws.BackgroundContext(), s3Mgr.s3API, url.Host)
	if err != nil {
		return nil, "", err
	}
	s3api := s3Mgr.s3API
	if aws.StringValue(s3Mgr.sess.Config.Region) != region {
		s3api = s3.New(s3Mgr.sess, aws.NewConfig().WithRegion(region))
	}
	input := &s3.GetObjectInput{
		Bucket:      aws.String(url.Host),
		Key:         aws.String(url.Path),
		IfNoneMatch: aws.String(etag),
	}
	resp, err := s3api.GetObject(input)
	if err != nil {
		if aerr, ok := err.(awserr.Error); ok {
			if aerr.Code() == "NotModified" {
				return resp.Body, etag, nil
			}
		}
		return nil, "", err
	}

	return resp.Body, aws.StringValue(resp.ETag), nil
}

func (s3Mgr *s3ArtifactManager) getArtifactHTTP(url *url.URL, etag string) (io.ReadCloser, string, error) {
	req, err := http.NewRequest("GET", url.String(), nil)
	if err != nil {
		return nil, "", err
	}

	client := &http.Client{}
	req.Header.Add("If-None-Match", etag)
	resp, err := client.Do(req)
	if err != nil {
		return nil, "", err
	}

	if resp.StatusCode == 304 {
		return nil, etag, nil
	}

	return resp.Body, resp.Header.Get(http.CanonicalHeaderKey("etag")), nil
}

func (s3Mgr *s3ArtifactManager) getArtifactFile(url *url.URL, etag string) (io.ReadCloser, string, error) {
	newEtag, err := md5File(url.Path)
	if err != nil {
		return nil, "", err
	}

	if etag == "" || etag != newEtag {
		body, err := os.Open(url.Path)
		return body, newEtag, err
	}
	return nil, newEtag, nil
}

// GetArtifact get the artifact conditionally by etag.
func (s3Mgr *s3ArtifactManager) GetArtifact(uri string, etag string) (body io.ReadCloser, etagRet string, err error) {
	url, err := url.Parse(uri)
	if err != nil {
		return nil, "", err
	}

	switch url.Scheme {
	case "s3":
		body, etagRet, err = s3Mgr.getArtifactS3(url, etag)
	case "http":
		fallthrough
	case "https":
		body, etagRet, err = s3Mgr.getArtifactHTTP(url, etag)
	case "file":
		body, etagRet, err = s3Mgr.getArtifactFile(url, etag)
	default:
		body = nil
		etagRet = ""
		err = fmt.Errorf("unknown scheme on URL '%s'", url)
	}
	return
}

func md5File(path string) (string, error) {
	f, err := os.Open(path)
	if err != nil {
		return "", err
	}
	defer f.Close()

	h := md5.New()
	if _, err := io.Copy(h, f); err != nil {
		return "", err
	}

	return fmt.Sprintf("%x", h.Sum(nil)), nil
}

// EmptyBucket to empty bucket
func (s3Mgr *s3ArtifactManager) EmptyBucket(bucketName string) error {
	if s3Mgr.dryrunPath != "" {
		log.Infof("  DRYRUN: Skipping emptying of bucket '%s'", bucketName)
		return nil
	}
	log.Infof("  Emptying bucket '%s'", bucketName)
	params := &s3.ListObjectsInput{
		Bucket: aws.String(bucketName),
	}
	for {
		//Requesting for batch of objects from s3 bucket
		objects, err := s3Mgr.s3API.ListObjects(params)
		if err != nil {
			return err
		}
		//Checks if the bucket is already empty
		if len((*objects).Contents) == 0 {
			log.Debug("Bucket is already empty")
			return nil
		}
		log.Debug("First object in batch | ", *(objects.Contents[0].Key))

		//creating an array of pointers of ObjectIdentifier
		objectsToDelete := make([]*s3.ObjectIdentifier, 0, 1000)
		for _, object := range (*objects).Contents {
			obj := s3.ObjectIdentifier{
				Key: object.Key,
			}
			objectsToDelete = append(objectsToDelete, &obj)
		}
		//Creating JSON payload for bulk delete
		deleteArray := s3.Delete{Objects: objectsToDelete}
		deleteParams := &s3.DeleteObjectsInput{
			Bucket: aws.String(bucketName),
			Delete: &deleteArray,
		}
		//Running the Bulk delete job (limit 1000)
		_, err = s3Mgr.s3API.DeleteObjects(deleteParams)
		if err != nil {
			return err
		}
		if *(*objects).IsTruncated { //if there are more objects in the bucket, IsTruncated = true
			params.Marker = (*deleteParams).Delete.Objects[len((*deleteParams).Delete.Objects)-1].Key
			log.Debug("Requesting next batch | ", *(params.Marker))
		} else { //if all objects in the bucket have been cleaned up.
			break
		}
	}
	return nil
}


text:
require 'test_helper'

class Admin::PagesControllerTest < ActionController::TestCase
  context "with administrator logged in" do
    setup do
      login_as(:admin)
      on_site(:with_content)
    end

    context "on GET to :index" do
      setup { get :index }
      should_render_with :application, :index
      should_not_set_the_flash
      should_assign_to :pages
    end

    context "on GET to :new" do
      setup { get :new }
      should_render_with :application, :new
      should_not_set_the_flash
      should "assign to @page with show_in_navigation and published set to true" do
        assert assigns(:page)
        assert_equal true, assigns(:page).show_in_navigation
        assert_equal true, assigns(:page).published
      end
    end

    context "on POST to :create with valid attributes" do
      setup do
        Page.any_instance.expects(:save).returns(true).once
        Page.any_instance.stubs(:id).returns(1)
        post :create, :page => {}
      end
      should_redirect_to("pages listing"){ admin_pages_path }
      should_assign_to :page
      should "set the site_id on the page to the current_site" do
        assert_equal sites(:with_content).id, assigns(:page).site_id
      end
      should_set_the_flash_to I18n.t("page.create.success")
    end

    context "on POST to :create with invalid attributes" do
      setup do
        Page.any_instance.expects(:save).returns(false).once
        post :create, :page => {}
      end

      should_render_with :application, :new
      should_assign_to :page
      should_set_the_flash_to I18n.t("page.create.fail")
    end

    context "on GET to :edit" do
      setup { get :edit, :id => items(:about_page) }
      should_render_with :application, :edit
      should_assign_to :page
    end

    should "raise an error when attempting to :edit a page belonging to other site" do
      assert_raise ActiveRecord::RecordNotFound do
        get :edit, :id => 1
      end
    end

    context "on PUT to :update with valid attributes" do
      setup do
        Page.any_instance.expects(:update_attributes).returns(true).once
        put :update, :id => items(:about_page), :page => {}
      end
      should_redirect_to("pages listing"){ admin_pages_path }
      should_assign_to :page
      should_set_the_flash_to I18n.t("page.update.success")
    end

    context "on PUT to :update with invalid attributes" do
      setup do
        Page.any_instance.expects(:update_attributes).returns(false).once
        put :update, :id => items(:about_page), :page => {}
      end

      should_render_with :application, :edit
      should_assign_to :page
      should_set_the_flash_to I18n.t("page.update.fail")
    end

    should "raise an error when attempting to :update a page belonging to other site" do
      assert_raise ActiveRecord::RecordNotFound do
        put :update, :id => 1
      end
    end

    context "on DELETE to :destroy" do
      setup do
        Page.any_instance.expects(:destroy).returns(true)
        delete :destroy, :id => items(:about_page)
      end
      should_redirect_to("pages listing"){ admin_pages_path }
    end

    should_eventually "on DELETE to :destroy that fails"
  end

  context "with authorized user but non-administrator logged in" do
    setup do
      login_as(:authorized)
      on_site(:with_content)
    end

    context "on GET to :index" do
      setup { get :index }
      should_render_with :application, :index
      should_not_set_the_flash
      should_assign_to :pages
    end

    context "on GET to :new" do
      setup { get :new }
      should_render_with :application, :new
      should_not_set_the_flash
      should "assign to @page with show_in_navigation and published set to true" do
        assert assigns(:page)
        assert_equal true, assigns(:page).show_in_navigation
        assert_equal true, assigns(:page).published
      end
    end

    context "on POST to :create with valid attributes" do
      setup do
        Page.any_instance.expects(:save).returns(true).once
        Page.any_instance.stubs(:id).returns(1)
        post :create, :page => {}
      end
      should_redirect_to("pages listing"){ admin_pages_path }
      should_assign_to :page
      should "set the site_id on the page to the current_site" do
        assert_equal sites(:with_content).id, assigns(:page).site_id
      end
      should_set_the_flash_to I18n.t("page.create.success")
    end

    context "on POST to :create with invalid attributes" do
      setup do
        Page.any_instance.expects(:save).returns(false).once
        post :create, :page => {}
      end

      should_render_with :application, :new
      should_assign_to :page
      should_set_the_flash_to I18n.t("page.create.fail")
    end

    context "on GET to :edit" do
      setup { get :edit, :id => items(:about_page) }
      should_render_with :application, :edit
      should_assign_to :page
    end

    should "raise an error when attempting to :edit a page belonging to other site" do
      assert_raise ActiveRecord::RecordNotFound do
        get :edit, :id => 1
      end
    end

    context "on PUT to :update with valid attributes" do
      setup do
        Page.any_instance.expects(:update_attributes).returns(true).once
        put :update, :id => items(:about_page), :page => {}
      end
      should_redirect_to("pages listing"){ admin_pages_path }
      should_assign_to :page
      should_set_the_flash_to I18n.t("page.update.success")
    end

    context "on PUT to :update with invalid attributes" do
      setup do
        Page.any_instance.expects(:update_attributes).returns(false).once
        put :update, :id => items(:about_page), :page => {}
      end

      should_render_with :application, :edit
      should_assign_to :page
      should_set_the_flash_to I18n.t("page.update.fail")
    end

    should "raise an error when attempting to :update a page belonging to other site" do
      assert_raise ActiveRecord::RecordNotFound do
        put :update, :id => 1
      end
    end

    context "on DELETE to :destroy" do
      setup do
        Page.any_instance.expects(:destroy).returns(true)
        delete :destroy, :id => items(:about_page)
      end
      should_redirect_to("pages listing"){ admin_pages_path }
    end

    should_eventually "on DELETE to :destroy that fails"
  end

  context "with unauthorized user logged in" do
    setup do
      login_as(:unauthorized)
      on_site(:with_content)
    end

    context "on GET to :index" do
      setup { get :index }
      should_redirect_to("super admin login"){ admin_login_path }
    end

    context "on GET to :new" do
      setup { get :new }
      should_redirect_to("super admin login"){ admin_login_path }
    end

    context "on POST to :create" do
      setup { post :create }
      should_redirect_to("super admin login"){ admin_login_path }
    end

    context "on GET to :edit" do
      setup { get :edit, :id => 1 }
      should_redirect_to("super admin login"){ admin_login_path }
    end

    context "on PUT to :update" do
      setup { put :update, :id => 1 }
      should_redirect_to("super admin login"){ admin_login_path }
    end

    context "on DELETE to :destroy" do
      setup { delete :destroy, :id => 1 }
      should_redirect_to("super admin login"){ admin_login_path }
    end
  end
end


text:
@interface WAJSEventHandler_removeSavedFile : WAJSEventHandler_BaseEvent
{
}

- (void)handleJSEvent:(id)arg1;

@end


text:
package org.jbpm.workbench.forms.display.backend.provider.task;

import org.jbpm.workbench.forms.display.backend.provider.KieWorkbenchFormsProvider;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;

@RunWith( MockitoJUnitRunner.class )
public class DefaultTaskFormProvidingTest extends AbstractTaskFormProvidingTest<KieWorkbenchFormsProvider> {

    @Override
    protected void initFormsProvider() {
        this.workbenchFormsProvider = new KieWorkbenchFormsProvider( null, processor );
    }
}


text:
{* This is a comment block

Use vars: {{var var_name}}
*}

        Une transaction de paiement est en attente de validation.

                Raison

                {{var reason}}

                Client :

                {{var customer}} <{{var customerEmail}}>

Articles :

                {{var items}}

                Total :

                {{var total}}

                Adresse de facturation :

                {{var billingAddress.format('html')}}

                Adresse de livraison :

                {{var shippingAddress.format('html')}}

                Mode de livraison :

                {{var shippingMethod}}

                Mode de paiement :

                {{var paymentMethod}}

                Date & Heure :

                {{var dateAndTime}}


text:
import { createSelector } from 'reselect'

import { getData } from '../firebase'

export const getStadiums = createSelector(getData, ({ stadiums }) => stadiums)


text:
<#
.SYNOPSIS
    Checks whether the .NET Core SDK required by this repo is installed.
#>
[CmdletBinding()]
Param (
)

$dotnet = Get-Command dotnet -ErrorAction SilentlyContinue
if (!$dotnet) {
    # Nothing is installed.
    Write-Output $false
    exit 1
}

# We need to set the current directory so dotnet considers the SDK required by our global.json file.
Push-Location "$PSScriptRoot\.."
try {
    dotnet -h 2>&1 | Out-Null
    if (($LASTEXITCODE -eq 129) -or      # On Linux
        ($LASTEXITCODE -eq -2147450751)  # On Windows
        ) {
        # These exit codes indicate no matching SDK exists.
        Write-Output $false
        exit 2
    }

    # The required SDK is already installed!
    Write-Output $true
    exit 0
} catch {
    # I don't know why, but on some build agents (e.g. MicroBuild), an exception is thrown from the `dotnet` invocation when a match is not found.
    Write-Output $false
    exit 3
} finally {
    Pop-Location
}