text:
package kubegraph

import (
	"encoding/json"
	"strings"

	"github.com/gonum/graph"

	"k8s.io/apimachinery/pkg/api/meta"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/labels"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/runtime/schema"
	kapi "k8s.io/kubernetes/pkg/apis/core"
	"k8s.io/kubernetes/pkg/apis/extensions"

	oapps "github.com/openshift/api/apps"
	"github.com/openshift/origin/pkg/api/legacy"
	appsapi "github.com/openshift/origin/pkg/apps/apis/apps"
	imageapi "github.com/openshift/origin/pkg/image/apis/image"
	triggerapi "github.com/openshift/origin/pkg/image/apis/image/v1/trigger"
	"github.com/openshift/origin/pkg/image/trigger/annotations"
	appsgraph "github.com/openshift/origin/pkg/oc/lib/graph/appsgraph/nodes"
	osgraph "github.com/openshift/origin/pkg/oc/lib/graph/genericgraph"
	imagegraph "github.com/openshift/origin/pkg/oc/lib/graph/imagegraph/nodes"
	kubegraph "github.com/openshift/origin/pkg/oc/lib/graph/kubegraph/nodes"
)

const (
	// ExposedThroughServiceEdgeKind goes from a PodTemplateSpec or a Pod to Service.  The head should make the service's selector.
	ExposedThroughServiceEdgeKind = "ExposedThroughService"
	// ManagedByControllerEdgeKind goes from Pod to controller when the Pod satisfies a controller's label selector
	ManagedByControllerEdgeKind = "ManagedByController"
	// MountedSecretEdgeKind goes from PodSpec to Secret indicating that is or will be a request to mount a volume with the Secret.
	MountedSecretEdgeKind = "MountedSecret"
	// MountableSecretEdgeKind goes from ServiceAccount to Secret indicating that the SA allows the Secret to be mounted
	MountableSecretEdgeKind = "MountableSecret"
	// ReferencedServiceAccountEdgeKind goes from PodSpec to ServiceAccount indicating that Pod is or will be running as the SA.
	ReferencedServiceAccountEdgeKind = "ReferencedServiceAccount"
	// ScalingEdgeKind goes from HorizontalPodAutoscaler to scaled objects indicating that the HPA scales the object
	ScalingEdgeKind = "Scaling"
	// TriggersDeploymentEdgeKind points from DeploymentConfigs to ImageStreamTags that trigger the deployment
	TriggersDeploymentEdgeKind = "TriggersDeployment"
	// UsedInDeploymentEdgeKind points from DeploymentConfigs to DockerImageReferences that are used in the deployment
	UsedInDeploymentEdgeKind = "UsedInDeployment"
	// DeploymentEdgeKind points from Deployment to the ReplicaSet that are fulfilling the deployment
	DeploymentEdgeKind = "Deployment"
)

// AddExposedPodTemplateSpecEdges ensures that a directed edge exists between a service and all the PodTemplateSpecs
// in the graph that match the service selector
func AddExposedPodTemplateSpecEdges(g osgraph.MutableUniqueGraph, node *kubegraph.ServiceNode) {
	if node.Service.Spec.Selector == nil {
		return
	}
	query := labels.SelectorFromSet(node.Service.Spec.Selector)
	for _, n := range g.(graph.Graph).Nodes() {
		switch target := n.(type) {
		case *kubegraph.PodTemplateSpecNode:
			if target.Namespace != node.Namespace {
				continue
			}

			if query.Matches(labels.Set(target.PodTemplateSpec.Labels)) {
				g.AddEdge(target, node, ExposedThroughServiceEdgeKind)
			}
		}
	}
}

// AddAllExposedPodTemplateSpecEdges calls AddExposedPodTemplateSpecEdges for every ServiceNode in the graph
func AddAllExposedPodTemplateSpecEdges(g osgraph.MutableUniqueGraph) {
	for _, node := range g.(graph.Graph).Nodes() {
		if serviceNode, ok := node.(*kubegraph.ServiceNode); ok {
			AddExposedPodTemplateSpecEdges(g, serviceNode)
		}
	}
}

// AddExposedPodEdges ensures that a directed edge exists between a service and all the pods
// in the graph that match the service selector
func AddExposedPodEdges(g osgraph.MutableUniqueGraph, node *kubegraph.ServiceNode) {
	if node.Service.Spec.Selector == nil {
		return
	}
	query := labels.SelectorFromSet(node.Service.Spec.Selector)
	for _, n := range g.(graph.Graph).Nodes() {
		switch target := n.(type) {
		case *kubegraph.PodNode:
			if target.Namespace != node.Namespace {
				continue
			}
			if query.Matches(labels.Set(target.Labels)) {
				g.AddEdge(target, node, ExposedThroughServiceEdgeKind)
			}
		}
	}
}

// AddAllExposedPodEdges calls AddExposedPodEdges for every ServiceNode in the graph
func AddAllExposedPodEdges(g osgraph.MutableUniqueGraph) {
	for _, node := range g.(graph.Graph).Nodes() {
		if serviceNode, ok := node.(*kubegraph.ServiceNode); ok {
			AddExposedPodEdges(g, serviceNode)
		}
	}
}

// AddManagedByControllerPodEdges ensures that a directed edge exists between a controller and all the pods
// in the graph that match the label selector
func AddManagedByControllerPodEdges(g osgraph.MutableUniqueGraph, to graph.Node, namespace string, selector map[string]string) {
	if selector == nil {
		return
	}
	query := labels.SelectorFromSet(selector)
	for _, n := range g.(graph.Graph).Nodes() {
		switch target := n.(type) {
		case *kubegraph.PodNode:
			if target.Namespace != namespace {
				continue
			}
			if query.Matches(labels.Set(target.Labels)) {
				g.AddEdge(target, to, ManagedByControllerEdgeKind)
			}
		}
	}
}

// AddAllManagedByControllerPodEdges calls AddManagedByControllerPodEdges for every node in the graph
// TODO: should do this through an interface (selects pods)
func AddAllManagedByControllerPodEdges(g osgraph.MutableUniqueGraph) {
	for _, node := range g.(graph.Graph).Nodes() {
		switch cast := node.(type) {
		case *kubegraph.ReplicationControllerNode:
			AddManagedByControllerPodEdges(g, cast, cast.ReplicationController.Namespace, cast.ReplicationController.Spec.Selector)
		case *kubegraph.ReplicaSetNode:
			AddManagedByControllerPodEdges(g, cast, cast.ReplicaSet.Namespace, cast.ReplicaSet.Spec.Selector.MatchLabels)
		case *kubegraph.StatefulSetNode:
			// TODO: refactor to handle expanded selectors (along with ReplicaSets and Deployments)
			AddManagedByControllerPodEdges(g, cast, cast.StatefulSet.Namespace, cast.StatefulSet.Spec.Selector.MatchLabels)
		case *kubegraph.DaemonSetNode:
			AddManagedByControllerPodEdges(g, cast, cast.DaemonSet.Namespace, cast.DaemonSet.Spec.Selector.MatchLabels)
		}
	}
}

func AddMountedSecretEdges(g osgraph.Graph, podSpec *kubegraph.PodSpecNode) {
	//pod specs are always contained.  We'll get the toplevel container so that we can pull a namespace from it
	containerNode := osgraph.GetTopLevelContainerNode(g, podSpec)
	containerObj := g.GraphDescriber.Object(containerNode)

	meta, err := meta.Accessor(containerObj.(runtime.Object))
	if err != nil {
		// this should never happen.  it means that a podSpec is owned by a top level container that is not a runtime.Object
		panic(err)
	}

	for _, volume := range podSpec.Volumes {
		source := volume.VolumeSource
		if source.Secret == nil {
			continue
		}

		// pod secrets must be in the same namespace
		syntheticSecret := &kapi.Secret{}
		syntheticSecret.Namespace = meta.GetNamespace()
		syntheticSecret.Name = source.Secret.SecretName

		secretNode := kubegraph.FindOrCreateSyntheticSecretNode(g, syntheticSecret)
		g.AddEdge(podSpec, secretNode, MountedSecretEdgeKind)
	}
}

func AddAllMountedSecretEdges(g osgraph.Graph) {
	for _, node := range g.Nodes() {
		if podSpecNode, ok := node.(*kubegraph.PodSpecNode); ok {
			AddMountedSecretEdges(g, podSpecNode)
		}
	}
}

func AddMountableSecretEdges(g osgraph.Graph, saNode *kubegraph.ServiceAccountNode) {
	for _, mountableSecret := range saNode.ServiceAccount.Secrets {
		syntheticSecret := &kapi.Secret{}
		syntheticSecret.Namespace = saNode.ServiceAccount.Namespace
		syntheticSecret.Name = mountableSecret.Name

		secretNode := kubegraph.FindOrCreateSyntheticSecretNode(g, syntheticSecret)
		g.AddEdge(saNode, secretNode, MountableSecretEdgeKind)
	}
}

func AddAllMountableSecretEdges(g osgraph.Graph) {
	for _, node := range g.Nodes() {
		if saNode, ok := node.(*kubegraph.ServiceAccountNode); ok {
			AddMountableSecretEdges(g, saNode)
		}
	}
}

func AddRequestedServiceAccountEdges(g osgraph.Graph, podSpecNode *kubegraph.PodSpecNode) {
	//pod specs are always contained.  We'll get the toplevel container so that we can pull a namespace from it
	containerNode := osgraph.GetTopLevelContainerNode(g, podSpecNode)
	containerObj := g.GraphDescriber.Object(containerNode)

	meta, err := meta.Accessor(containerObj.(runtime.Object))
	if err != nil {
		panic(err)
	}

	// if no SA name is present, admission will set 'default'
	name := "default"
	if len(podSpecNode.ServiceAccountName) > 0 {
		name = podSpecNode.ServiceAccountName
	}

	syntheticSA := &kapi.ServiceAccount{}
	syntheticSA.Namespace = meta.GetNamespace()
	syntheticSA.Name = name

	saNode := kubegraph.FindOrCreateSyntheticServiceAccountNode(g, syntheticSA)
	g.AddEdge(podSpecNode, saNode, ReferencedServiceAccountEdgeKind)
}

func AddAllRequestedServiceAccountEdges(g osgraph.Graph) {
	for _, node := range g.Nodes() {
		if podSpecNode, ok := node.(*kubegraph.PodSpecNode); ok {
			AddRequestedServiceAccountEdges(g, podSpecNode)
		}
	}
}

func AddHPAScaleRefEdges(g osgraph.Graph, restMapper meta.RESTMapper) {
	for _, node := range g.NodesByKind(kubegraph.HorizontalPodAutoscalerNodeKind) {
		hpaNode := node.(*kubegraph.HorizontalPodAutoscalerNode)

		syntheticMeta := metav1.ObjectMeta{
			Name:      hpaNode.HorizontalPodAutoscaler.Spec.ScaleTargetRef.Name,
			Namespace: hpaNode.HorizontalPodAutoscaler.Namespace,
		}

		var groupVersionResource schema.GroupVersionResource
		resource := strings.ToLower(hpaNode.HorizontalPodAutoscaler.Spec.ScaleTargetRef.Kind)
		if groupVersion, err := schema.ParseGroupVersion(hpaNode.HorizontalPodAutoscaler.Spec.ScaleTargetRef.APIVersion); err == nil {
			groupVersionResource = groupVersion.WithResource(resource)
		} else {
			groupVersionResource = schema.GroupVersionResource{Resource: resource}
		}

		groupVersionResource, err := restMapper.ResourceFor(groupVersionResource)
		if err != nil {
			continue
		}

		var syntheticNode graph.Node
		r := groupVersionResource.GroupResource()
		switch r {
		case kapi.Resource("replicationcontrollers"):
			syntheticNode = kubegraph.FindOrCreateSyntheticReplicationControllerNode(g, &kapi.ReplicationController{ObjectMeta: syntheticMeta})
		case oapps.Resource("deploymentconfigs"),
			// we need the legacy resource until we stop supporting HPA having old refs
			legacy.Resource("deploymentconfigs"):
			syntheticNode = appsgraph.FindOrCreateSyntheticDeploymentConfigNode(g, &appsapi.DeploymentConfig{ObjectMeta: syntheticMeta})
		case extensions.Resource("deployments"):
			syntheticNode = kubegraph.FindOrCreateSyntheticDeploymentNode(g, &extensions.Deployment{ObjectMeta: syntheticMeta})
		case extensions.Resource("replicasets"):
			syntheticNode = kubegraph.FindOrCreateSyntheticReplicaSetNode(g, &extensions.ReplicaSet{ObjectMeta: syntheticMeta})
		default:
			continue
		}

		g.AddEdge(hpaNode, syntheticNode, ScalingEdgeKind)
	}
}

func addTriggerEdges(obj runtime.Object, podTemplate kapi.PodTemplateSpec, addEdgeFn func(image appsapi.TemplateImage, err error)) {
	m, err := meta.Accessor(obj)
	if err != nil {
		return
	}
	triggerAnnotation, ok := m.GetAnnotations()[triggerapi.TriggerAnnotationKey]
	if !ok {
		return
	}
	triggers := []triggerapi.ObjectFieldTrigger{}
	if err := json.Unmarshal([]byte(triggerAnnotation), &triggers); err != nil {
		return
	}
	triggerFn := func(container *kapi.Container) (appsapi.TemplateImage, bool) {
		from := kapi.ObjectReference{}
		for _, trigger := range triggers {
			c, remainder, err := annotations.ContainerForObjectFieldPath(obj, trigger.FieldPath)
			if err != nil || remainder != "image" {
				continue
			}
			from.Namespace = trigger.From.Namespace
			if len(from.Namespace) == 0 {
				from.Namespace = m.GetNamespace()
			}
			from.Name = trigger.From.Name
			from.Kind = trigger.From.Kind
			if len(from.Kind) == 0 {
				from.Kind = "ImageStreamTag"
			}
			return appsapi.TemplateImage{
				Image: c.GetImage(),
				From:  &from,
			}, true
		}
		return appsapi.TemplateImage{}, false
	}
	appsapi.EachTemplateImage(&podTemplate.Spec, triggerFn, addEdgeFn)
}

func AddTriggerStatefulSetsEdges(g osgraph.MutableUniqueGraph, node *kubegraph.StatefulSetNode) *kubegraph.StatefulSetNode {
	addTriggerEdges(node.StatefulSet, node.StatefulSet.Spec.Template, func(image appsapi.TemplateImage, err error) {
		if err != nil {
			return
		}
		if image.From != nil {
			if len(image.From.Name) == 0 {
				return
			}
			name, tag, _ := imageapi.SplitImageStreamTag(image.From.Name)
			in := imagegraph.FindOrCreateSyntheticImageStreamTagNode(g, imagegraph.MakeImageStreamTagObjectMeta(image.From.Namespace, name, tag))
			g.AddEdge(in, node, TriggersDeploymentEdgeKind)
			return
		}

		tag := image.Ref.Tag
		image.Ref.Tag = ""
		in := imagegraph.EnsureDockerRepositoryNode(g, image.Ref.String(), tag)
		g.AddEdge(in, node, UsedInDeploymentEdgeKind)
	})
	return node
}

func AddAllTriggerStatefulSetsEdges(g osgraph.MutableUniqueGraph) {
	for _, node := range g.(graph.Graph).Nodes() {
		if sNode, ok := node.(*kubegraph.StatefulSetNode); ok {
			AddTriggerStatefulSetsEdges(g, sNode)
		}
	}
}

func AddTriggerDeploymentsEdges(g osgraph.MutableUniqueGraph, node *kubegraph.DeploymentNode) *kubegraph.DeploymentNode {
	addTriggerEdges(node.Deployment, node.Deployment.Spec.Template, func(image appsapi.TemplateImage, err error) {
		if err != nil {
			return
		}
		if image.From != nil {
			if len(image.From.Name) == 0 {
				return
			}
			name, tag, _ := imageapi.SplitImageStreamTag(image.From.Name)
			in := imagegraph.FindOrCreateSyntheticImageStreamTagNode(g, imagegraph.MakeImageStreamTagObjectMeta(image.From.Namespace, name, tag))
			g.AddEdge(in, node, TriggersDeploymentEdgeKind)
			return
		}
		tag := image.Ref.Tag
		image.Ref.Tag = ""
		in := imagegraph.EnsureDockerRepositoryNode(g, image.Ref.String(), tag)
		g.AddEdge(in, node, UsedInDeploymentEdgeKind)
	})
	return node
}

func AddAllTriggerDeploymentsEdges(g osgraph.MutableUniqueGraph) {
	for _, node := range g.(graph.Graph).Nodes() {
		if dNode, ok := node.(*kubegraph.DeploymentNode); ok {
			AddTriggerDeploymentsEdges(g, dNode)
		}
	}
}

func AddDeploymentEdges(g osgraph.MutableUniqueGraph, node *kubegraph.DeploymentNode) *kubegraph.DeploymentNode {
	for _, n := range g.(graph.Graph).Nodes() {
		if rsNode, ok := n.(*kubegraph.ReplicaSetNode); ok {
			if rsNode.ReplicaSet.Namespace != node.Deployment.Namespace {
				continue
			}
			if BelongsToDeployment(node.Deployment, rsNode.ReplicaSet) {
				g.AddEdge(node, rsNode, DeploymentEdgeKind)
				g.AddEdge(rsNode, node, ManagedByControllerEdgeKind)
			}
		}
	}

	return node
}

func BelongsToDeployment(config *extensions.Deployment, b *extensions.ReplicaSet) bool {
	if b.OwnerReferences == nil {
		return false
	}
	for _, ref := range b.OwnerReferences {
		if ref.Kind == "Deployment" && ref.Name == config.Name {
			return true
		}
	}
	return false
}

func AddAllDeploymentEdges(g osgraph.MutableUniqueGraph) {
	for _, node := range g.(graph.Graph).Nodes() {
		if dNode, ok := node.(*kubegraph.DeploymentNode); ok {
			AddDeploymentEdges(g, dNode)
		}
	}
}


text:
<?php
/**
 * BuddyPress Messages Notifications.
 *
 * @package BuddyPress
 * @subpackage MessagesNotifications
 * @since 1.0.0
 */

// Exit if accessed directly.
defined( 'ABSPATH' ) || exit;

/** Email *********************************************************************/

/**
 * Email message recipients to alert them of a new unread private message.
 *
 * @since 1.0.0
 *
 * @param array|BP_Messages_Message $raw_args {
 *     Array of arguments. Also accepts a BP_Messages_Message object.
 *     @type array  $recipients    User IDs of recipients.
 *     @type string $email_subject Subject line of message.
 *     @type string $email_content Content of message.
 *     @type int    $sender_id     User ID of sender.
 * }
 */
function messages_notification_new_message( $raw_args = array() ) {
	if ( is_object( $raw_args ) ) {
		$args = (array) $raw_args;
	} else {
		$args = $raw_args;
	}

	// These should be extracted below.
	$recipients    = array();
	$email_subject = $email_content = '';
	$sender_id     = 0;

	// Barf.
	extract( $args );

	if ( empty( $recipients ) ) {
		return;
	}

	$sender_name = bp_core_get_user_displayname( $sender_id );

	// Send an email to each recipient.
	foreach ( $recipients as $recipient ) {
		if ( $sender_id == $recipient->user_id || 'no' == bp_get_user_meta( $recipient->user_id, 'notification_messages_new_message', true ) ) {
			continue;
		}

		// User data and links.
		$ud = get_userdata( $recipient->user_id );
		if ( empty( $ud ) ) {
			continue;
		}

		$args = array(
			'tokens' => array(
				'usermessage' => wp_strip_all_tags( stripslashes( $message ) ),
				'message.url' => esc_url( bp_core_get_user_domain( $recipient->user_id ) . bp_get_messages_slug() . '/view/' . $thread_id . '/' ),
				'sender.name' => $sender_name,
				'usersubject' => sanitize_text_field( stripslashes( $subject ) ),
			),
		);
		bp_send_email( 'messages-unread', $ud, $args );
	}

	/**
	 * Fires after the sending of a new message email notification.
	 *
	 * @since 1.5.0
	 * @deprecated 2.5.0 Use the filters in BP_Email.
	 *                   $email_subject and $email_content arguments unset and deprecated.
	 *
	 * @param array  $recipients    User IDs of recipients.
	 * @param string $email_subject Deprecated in 2.5; now an empty string.
	 * @param string $email_content Deprecated in 2.5; now an empty string.
	 * @param array  $args          Array of originally provided arguments.
	 */
	do_action( 'bp_messages_sent_notification_email', $recipients, '', '', $args );
}
add_action( 'messages_message_sent', 'messages_notification_new_message', 10 );

/** Notifications *************************************************************/

/**
 * Format notifications for the Messages component.
 *
 * @since 1.0.0
 *
 * @param string $action            The kind of notification being rendered.
 * @param int    $item_id           The primary item id.
 * @param int    $secondary_item_id The secondary item id.
 * @param int    $total_items       The total number of messaging-related notifications
 *                                  waiting for the user.
 * @param string $format            Return value format. 'string' for BuddyBar-compatible
 *                                  notifications; 'array' for WP Toolbar. Default: 'string'.
 * @return string|array Formatted notifications.
 */
function messages_format_notifications( $action, $item_id, $secondary_item_id, $total_items, $format = 'string' ) {
	$total_items = (int) $total_items;
	$link        = trailingslashit( bp_loggedin_user_domain() . bp_get_messages_slug() . '/inbox' );
	$title       = __( 'Inbox', 'buddypress' );
	$amount      = 'single';

	if ( 'new_message' === $action ) {
		if ( $total_items > 1 ) {
			$amount = 'multiple';
			$text   = sprintf( __( 'You have %d new messages', 'buddypress' ), $total_items );
		} else {
			$amount = 'single';

			// Get message thread ID.
			$message   = new BP_Messages_Message( $item_id );
			$thread_id = $message->thread_id;
			$link      = ( ! empty( $thread_id ) )
				? bp_get_message_thread_view_link( $thread_id )
				: false;

			if ( ! empty( $secondary_item_id ) ) {
				$text = sprintf( __( '%s sent you a new private message', 'buddypress' ), bp_core_get_user_displayname( $secondary_item_id ) );
			} else {
				$text = sprintf( _n( 'You have %s new private message', 'You have %s new private messages', $total_items, 'buddypress' ), bp_core_number_format( $total_items ) );
			}
		}
	}

	if ( 'string' === $format ) {
		if ( ! empty( $link ) ) {
			$retval = '' . esc_html( $text ) . '';
		} else {
			$retval = esc_html( $text );
		}

		/**
		 * Filters the new message notification text before the notification is created.
		 *
		 * This is a dynamic filter. Possible filter names are:
		 *   - 'bp_messages_multiple_new_message_notification'.
		 *   - 'bp_messages_single_new_message_notification'.
		 *
		 * @param string $retval            Notification text.
		 * @param int    $total_items       Number of messages referred to by the notification.
		 * @param string $text              The raw notification test (ie, not wrapped in a link).
		 * @param int    $item_id           ID of the associated item.
		 * @param int    $secondary_item_id ID of the secondary associated item.
		 */
		$return = apply_filters( 'bp_messages_' . $amount . '_new_message_notification', $retval, (int) $total_items, $text, $link, $item_id, $secondary_item_id );
	} else {
		/** This filter is documented in bp-messages/bp-messages-notifications.php */
		$return = apply_filters( 'bp_messages_' . $amount . '_new_message_notification', array(
			'text' => $text,
			'link' => $link
		), $link, (int) $total_items, $text, $link, $item_id, $secondary_item_id );
	}

	/**
	 * Fires right before returning the formatted message notifications.
	 *
	 * @since 1.0.0
	 *
	 * @param string $action            The type of message notification.
	 * @param int    $item_id           The primary item ID.
	 * @param int    $secondary_item_id The secondary item ID.
	 * @param int    $total_items       Total amount of items to format.
	 */
	do_action( 'messages_format_notifications', $action, $item_id, $secondary_item_id, $total_items );

	return $return;
}

/**
 * Send notifications to message recipients.
 *
 * @since 1.9.0
 *
 * @param BP_Messages_Message $message Message object.
 */
function bp_messages_message_sent_add_notification( $message ) {
	if ( bp_is_active( 'notifications' ) && ! empty( $message->recipients ) ) {
		foreach ( (array) $message->recipients as $recipient ) {
			bp_notifications_add_notification( array(
				'user_id'           => $recipient->user_id,
				'item_id'           => $message->id,
				'secondary_item_id' => $message->sender_id,
				'component_name'    => buddypress()->messages->id,
				'component_action'  => 'new_message',
				'date_notified'     => bp_core_current_time(),
				'is_new'            => 1,
			) );
		}
	}
}
add_action( 'messages_message_sent', 'bp_messages_message_sent_add_notification', 10 );

/**
 * Mark new message notification when member reads a message thread directly.
 *
 * @since 1.9.0
 */
function bp_messages_screen_conversation_mark_notifications() {
	if ( bp_is_active( 'notifications' ) ) {
		global $thread_template;

		// Get unread PM notifications for the user.
		$new_pm_notifications = BP_Notifications_Notification::get( array(
			'user_id'           => bp_loggedin_user_id(),
			'component_name'    => buddypress()->messages->id,
			'component_action'  => 'new_message',
			'is_new'            => 1,
		) );
		$unread_message_ids = wp_list_pluck( $new_pm_notifications, 'item_id' );

		// No unread PMs, so stop!
		if ( empty( $unread_message_ids ) ) {
			return;
		}

		// Get the unread message ids for this thread only.
		$message_ids = array_intersect( $unread_message_ids, wp_list_pluck( $thread_template->thread->messages, 'id' ) );

		// Mark each notification for each PM message as read.
		foreach ( $message_ids as $message_id ) {
			bp_notifications_mark_notifications_by_item_id( bp_loggedin_user_id(), (int) $message_id, buddypress()->messages->id, 'new_message' );
		}
	}
}
add_action( 'thread_loop_start', 'bp_messages_screen_conversation_mark_notifications', 10 );

/**
 * When a message is deleted, delete corresponding notifications.
 *
 * @since 2.0.0
 *
 * @param int   $thread_id   ID of the thread.
 * @param array $message_ids IDs of the messages.
 */
function bp_messages_message_delete_notifications( $thread_id, $message_ids ) {
	if ( ! bp_is_active( 'notifications' ) ) {
		return;
	}

	// For each recipient, delete notifications corresponding to each message.
	$thread = new BP_Messages_Thread( $thread_id );
	foreach ( $thread->get_recipients() as $recipient ) {
		foreach ( $message_ids as $message_id ) {
			bp_notifications_delete_notifications_by_item_id( $recipient->user_id, (int) $message_id, buddypress()->messages->id, 'new_message' );
		}
	}
}
add_action( 'bp_messages_thread_after_delete', 'bp_messages_message_delete_notifications', 10, 2 );

redpajama_set_name: RedPajamaGithub


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Persoonia 11(3): 386 (1981)

#### Original name
Clitocybe vibecina var. pseudo-obbata J.E. Lange, 1930

### Remarks
null


text:
var mongoose = require('mongoose');
var async = require('async');
var models = require('../models');

var manageCode = new models.ManagerCode({
   code: 'dzygood'
});

// Close DB connection
var closeDbConnection = function (conn) {
    conn.close(function () {
        console.log('DB is disconnected.');
    });
};

var conn = mongoose.connection;
var db = conn.db;
conn.once('open', function () {
    manageCode.save(function(err) {
        if (err) {
            console.log(err);
        } else {
            console.log('Insert new manager code successfully.');
        }
        closeDbConnection(conn);
    });
});


text:
  Vaux-en-Dieulet est
       un village
       géographiquement positionné dans le département des Ardennes en Champagne-Ardenne. On dénombrait 71 habitants en 2008.

Si vous envisagez de venir habiter à Vaux-en-Dieulet, vous pourrez facilement trouver une maison à acheter.

Le nombre de logements, à Vaux-en-Dieulet, se décomposait en 2011 en deux appartements et 38 maisons soit
 un marché relativement équilibré.

À proximité de Vaux-en-Dieulet sont localisées les villes de
Bar-lès-Buzancy localisée à 6 km, 109 habitants,
Belval-Bois-des-Dames à 3 km, 42 habitants,
Buzancy localisée à 6 km, 368 habitants,
La Berlière située à 6 km, 44 habitants,
Oches à 5 km, 33 habitants,
Fossé située à 4 km, 56 habitants,
 entre autres. De plus, Vaux-en-Dieulet est située à seulement 24 km de Sedan.


text:
<catalog>
  <catalogItems>
    <catalogItem>
      <categoryId>org.eclipse.m2e.discovery.category.lifecycles</categoryId>
      <m2e-versions>1.0</m2e-versions>
      <description>buildhelper</description>
      <groupId>lifecycles</groupId>
      <id>org.eclipse.m2e.discovery.lifecyclemapping.buildhelper</id>
      <kind>lifecycles</kind>
      <license>EPL</license>
      <name>buildhelper</name>
      <provider>Marvinformatics Ltda</provider>
      <p2>
        <repositoryUrl>https://repository.sonatype.org/content/repositories/forge-sites/m2e-extras/0.14.0/N/0.14.0.201109282148/</repositoryUrl>
        <iuId>com.marvinformatics.formatter.feature.feature.group</iuId>
        <lifecycleMappingIU>
          <iuId>com.marvinformatics.formatter</iuId>
        </lifecycleMappingIU>
      </p2>
      <overview>
        buildhelper
      </overview>
    </catalogItem>
    <catalogItem>
      <categoryId>org.eclipse.m2e.discovery.category.lifecycles</categoryId>
      <m2e-versions>1.1</m2e-versions>
      <description>buildhelper</description>
      <groupId>lifecycles</groupId>
      <id>org.eclipse.m2e.discovery.lifecyclemapping.buildhelper</id>
      <kind>lifecycles</kind>
      <license>EPL</license>
      <name>buildhelper</name>
      <provider>Marvinformatics Ltda</provider>
      <p2>
        <repositoryUrl>https://repository.sonatype.org/content/repositories/forge-sites/m2e-extras/0.15.0/N/0.15.0.201109282249/</repositoryUrl>
        <iuId>com.marvinformatics.formatter.feature.feature.group</iuId>
        <lifecycleMappingIU>
          <iuId>com.marvinformatics.formatter</iuId>
        </lifecycleMappingIU>
      </p2>
      <overview>
        buildhelper
      </overview>
    </catalogItem>
  </catalogItems>
</catalog>


text:
module.exports = function (req, res, next) {

	var findParticipant = function (where, cb) { Participant.findOne(where).done(cb); }
	var findTopic = function (where, cb) { Topic.findOne(where).done(cb); }
	var findMessage = function (where, cb) { Message.findOne(where).done(cb); }

	var check = function (find, where, test, cb) {
		find(where, function (err, participant) {
			if (err) return cb(err);
			if (participant) return test(participant, cb);
			return cb(null, false);
		});
	}

	var isMetaMember = function (participant, cb) { return cb(null, participant.isMetaMember()); };
	var isMember = function(participant, cb) { return cb(null, participant.isMember()); };
	var isStaff = function(participant, cb) { return cb(null, participant.isStaff()); };

	return Bouncer()
		.when('chat/read', function (param, cb) {
			check(findParticipant, { user: param('me').id, chat: param('chat') }, isMetaMember, cb);
		})

		.when('chat/participants', function (param, cb) {
			check(findParticipant, { user: param('me').id, chat: param('chat') }, isMetaMember, cb);
		})

		.when('chat/topics', function (param, cb) {
			check(findParticipant, { user: param('me').id, chat: param('chat') }, isMember, cb);
		})

		.when('chat/messages', function (param, cb) {
			check(findParticipant, { user: param('me').id, chat: param('chat') }, isMember, cb);
		})

		.when('chat/invite', function (param, cb) {
			check(findParticipant, { user: param('me').id, chat: param('chat') }, isStaff, cb);
		})

		.when('participant/read', function (param, cb) {
			check(findParticipant, param('participant'), function (participant, ok) {
				check(findParticipant, { user: param('me').id, chat: participant.chat }, isMember, ok);
			}, cb);
		})

		.when('participant/join', function (param, cb) {
			check(findParticipant, param('participant'), function (participant, ok) { return ok(null, participant.user == param('me').id); }, cb);
		})

		.when('participant/leave', function (param, cb) {
			check(findParticipant, param('participant'), function (participant, ok) { return ok(null, participant.user == param('me').id); }, cb);
		})

		.when('participant/connect', function (param, cb) {
			check(findParticipant, param('participant'), function (participant, ok) { return ok(null, participant.user == param('me').id); }, cb);
		})

		.when('participant/disconnect', function (param, cb) {
			check(findParticipant, param('participant'), function (participant, ok) { return ok(null, participant.user == param('me').id); }, cb);
		})

		.when('participant/promote', function (param, cb) {
			check(findParticipant, param('participant'), function (participant, done) {
				check(findParticipant, {user: param('me').id }, function (me, ok) { return ok(null, me.isHigherThan(participant)); }, done);
			}, cb);
		})

		.when('participant/revoke', function (param, cb) {
			check(findParticipant, param('participant'), function (participant, done) {
				check(findParticipant, {user: param('me').id }, function (me, ok) { return ok(null, me.isHigherThan(participant)); }, done);
			}, cb);
		})

		.when('topic/create', function (param, cb) {
			check(findParticipant, param('participant'), function (participant, ok) { return ok(null, participant.isMember() && participant.user == param('me').id); }, cb);
		})

		.when('topic/destroy', function (param, cb) {
			check(findTopic, param('topic'), function (topic, done) {
				check(findParticipant, topic.participant, function (participant, ok) { return ok(null, participant.user == param('me').id); }, done);
			}, cb);
		})

		.when('message/create', function (param, cb) {
			check(findParticipant, param('participant'), function (participant, ok) { return ok(null, participant.isMember() && participant.user == param('me').id); }, cb);
		})

		.when('message/subjects', function (param, cb) {
			check(findMessage, param('message'), function (message, ok) {
				check(findParticipant, message.participant, isMember, ok);
			}, cb);
		})

		.when('message/recipients', function (param, cb) {
			check(findMessage, param('message'), function (message, ok) {
				check(findParticipant, message.participant, isMember, ok);
			}, cb);
		})

	.bounce(req, res, next);
};


text:
from lib import ncr

# The number of ways that k tiles  of length l can be placed in
# a row of n tiles is nCr(n - k * (l - 1), k)
# We simply sum these for all viable k and 2 <= l <= 4
def compute():
	sum = 0
	for length in range(2, 5):
		tiles_left = 50
		num_tiles = 0
		while tiles_left - length >= num_tiles:
			tiles_left -= length - 1
			num_tiles += 1
			sum += ncr(tiles_left, num_tiles)

	return sum

if __name__ == "__main__":
	print(compute())


text:
package com.intel.analytics.bigdl.nn.ops

import com.intel.analytics.bigdl.tensor.Tensor
import com.intel.analytics.bigdl.tensor.TensorNumericMath.TensorNumeric
import com.intel.analytics.bigdl.utils.{T, Table}

import scala.reflect.ClassTag

class TopK[T: ClassTag, D: ClassTag](
  val k: Int,
  val sorted: Boolean = true,
  val startIndex: Int = 1,
  val dim: Int = -1,
  val increase: Boolean = false)
(implicit ev: TensorNumeric[T], ev2: TensorNumeric[D])
  extends Operation[Tensor[D], Table, T] {

  private val indices = Tensor[Int]()
  private val values = Tensor[D]()
  private val indicesD = Tensor[D]()

  output = T(values, indices)

  override def updateOutput(input: Tensor[D]): Table = {
    input.topk(
      k = k,
      dim = dim,
      increase = increase,
      result = values,
      indices = indicesD,
      sortedResult = sorted)
    indices.resizeAs(indicesD)
    indices.zipWith[Int, D](indices, indicesD, (a, b) => {
      ev2.toType[Int](b) + startIndex - 1
    })
    output
  }

  override def getClassTagNumerics() : (Array[ClassTag[_]], Array[TensorNumeric[_]]) = {
    (Array[ClassTag[_]](scala.reflect.classTag[T], scala.reflect.classTag[D]),
      Array[TensorNumeric[_]](ev, ev2))
  }
}

object TopK {
  def apply[T: ClassTag, D: ClassTag](
  k: Int,
  sorted: Boolean = true,
  startIndex : Int = 1,
  dim: Int = -1,
  increase: Boolean = false)
  (implicit ev: TensorNumeric[T], ev2: TensorNumeric[D]):
  TopK[T, D] = new TopK(k, sorted, startIndex, dim, increase)
}


text:
load(libdir + "asserts.js");

/*
 * Throw a TypeError if the trap skips an existing own property on a
 * non-extensible object
 */
var target = {};
Object.defineProperty(target, 'foo', {
    configurable: true
});
Object.preventExtensions(target);
assertThrowsInstanceOf(function () {
    Object.getOwnPropertyNames(new Proxy(target, {
        getOwnPropertyNames: function (target) {
            return [];
        }
    }));
}, TypeError);


text:
// Constants
var currentLevel = 1,
    PLANE_MOVE_SPEED = 0,
    BIRD_MOVE_SPEED = 50,
    DEFAULT_SPEED = 500,
    ANGLE_FACTOR = 0.1,
    DIRECTION_LEFT = 1,
    DIRECTION_RIGHT = 2,
    UNIT = 30,
    showZoomLevel = false,
    lastZoom = App.physicsTimeElapsed,
    numScrollEvents=0,
    aTimer = new Timer(),
    swipeCount = 0,
    MAX_FUEL = 200,
    lastSwipe = 0,
    lastSwipeTime = 0,
    score,
    allowLeapStart;

var player,
    showDir = true,
    dirSignal,
    inProcess=false,
    takeoff = false,
    fuelTank,
    dragOverlay;

// Controls
var keysCustom = {
  up: ['up', 'w'],
  down: ['down', 's'],
  left: ['left', 'a'],
  right: ['right', 'd'],
  takeoff: ['takeoff', 't'],
  vision: ['vision', 'v'],
  escape: ['escape', 'e'],
  balance: ['balance', 'b']
};

Leap.loop({enableGestures: true}, function(frame) {
    frame.hands.forEach(function(hand, index) {
        rotationalAngle = -hand.roll();
        MAX_ROTATIONAL_ANGLE=1.2;
        MIN_ROTATIONAL_ANGLE=0.1;
        ROLL_FACTOR=0.11;

        if (!inProcess && frame.gestures.length == 0){
            if (rotationalAngle>0) {//right
                if (rotationalAngle<-MAX_ROTATIONAL_ANGLE)
                    move(DIRECTION_RIGHT, ANGLE_FACTOR*MAX_ROTATIONAL_ANGLE*MAX_ROTATIONAL_ANGLE*ROLL_FACTOR);
                else if (rotationalAngle>MIN_ROTATIONAL_ANGLE)
                    move(DIRECTION_RIGHT, ANGLE_FACTOR*rotationalAngle*rotationalAngle*ROLL_FACTOR);
                else if (activeThunderstorm){
                    activeThunderstormCounter--;
                    if (activeThunderstormCounter<=0) player.withinThunderstorm(false);
                }
            }
            else
                if (rotationalAngle<MAX_ROTATIONAL_ANGLE)
                    move(DIRECTION_LEFT, ANGLE_FACTOR*MAX_ROTATIONAL_ANGLE*MAX_ROTATIONAL_ANGLE*ROLL_FACTOR);
                else if (rotationalAngle<-MIN_ROTATIONAL_ANGLE)
                    move(DIRECTION_LEFT, ANGLE_FACTOR*rotationalAngle*rotationalAngle*ROLL_FACTOR);

            //if (hand.pitch()>0.2 && PLANE_MOVE_SPEED>1*hand.pitch()) PLANE_MOVE_SPEED-=1*hand.pitch(); //lift the tip of the hand to slow down
            //else if (hand.pitch()<-0.2 && PLANE_MOVE_SPEED<DEFAULT_SPEED) PLANE_MOVE_SPEED-=1.1*hand.pitch();

            //if (screenPosition[1]>0)

            zoom=-hand.screenPosition()[1];
            if (zoom>200)// || zoom<-200)
                if (!takeoff )
                    takeOffPlane();
            //leapZoom(zoom);
            //console.log(zoom);

        }
    });

    if(frame.valid && frame.gestures.length > 0 && !inProcess){
        inProcess=true;
        frame.gestures.forEach(function(gesture){
            switch (gesture.type){
                case "circle":
                    console.log("Circle Gesture");
                    /*var circleProgress = gesture.progress;
                    //var completeCircles = Math.floor(circleProgress);
                    console.log(circleProgress);
                    //tmp=PLANE_MOVE_SPEED;
                    //PLANE_MOVE_SPEED=tmp;
                    var clockwise = false;
                    var pointableID = gesture.pointableIds[0];
                    var direction = frame.pointable(pointableID).direction;
                    var dotProduct = Leap.vec3.dot(direction, gesture.normal);
                    if (dotProduct  >  0) clockwise = true;
                    for (i=0;i<90;i++){
                        if (clockwise)
                            move(DIRECTION_RIGHT, ANGLE_FACTOR/160);
                        else move(DIRECTION_LEFT, ANGLE_FACTOR/160);
                        //update();
                    }*/
                    player.loseControl(false)
                    inProcess=false;
                    //PLANE_MOVE_SPEED=tmp;
                    break;
                case "keyTap":
                    console.log("Key Tap Gesture");
                    break;
                case "screenTap":
                    console.log("Screen Tap Gesture");
                    break;
                case "swipe":
                    console.log("Swipe Gesture");
                    if (allowLeapStart) startNewLevel(1);
                    if (App.physicsTimeElapsed-lastSwipeTime>1000){
                        lastSwipe=0;
                        lastSwipeTime=App.physicsTimeElapsed;
                    }
                    else {
                        //delta=aTimer.getDelta();
                        //if (delta>0.05 && delta<0.5) {
                        //  console.log(delta);

                        //Classify swipe as either horizontal or vertical
                        //var isHorizontal = Math.abs(gesture.direction[0]) > Math.abs(gesture.direction[1]);
                        //Classify as right-left or up-down
                        //if (isHorizontal) {
                            if (gesture.direction[0] > 0) {
                                swipeDirection = "right";
                                nowSwipe = DIRECTION_RIGHT;
                            } else {
                                swipeDirection = "left";
                                nowSwipe = DIRECTION_LEFT;
                            }
                        //} else { //vertical
                        //    if (gesture.direction[1] > 0) {
                        //        swipeDirection = "up";
                        //    } else {
                        //        swipeDirection = "down";
                        //    }
                        //}
                        var duration = gesture.duration;
                        console.log(swipeDirection + " " + duration);
                        if (nowSwipe!=lastSwipe){
                            if (App.physicsTimeElapsed-lastSwipeTime<800){
                                player.toggleVision(true);
                            }
                            lastSwipe=nowSwipe;
                            lastSwipeTime=App.physicsTimeElapsed;
                        }
                        //}
                    }
                    break;
            }
        });
        inProcess=false;
    }
}).use('screenPosition', {scale: 0.5});

/**
 * Resources and Images Part
 * Jinyao
 * @type {Array}
 */
var background;
var mapWidth = 8;   // in 1024x1024 tiles
var mapHeight = 6;  // in 1024x1024 tiles

var startGrid, endGrid;
var startPoint, endPoint;
var endPointReal;

var birdFlocks;
var tornados;
var storms;
var activeThunderstorm = false;
var activeThunderstormCounter=0;

var gameBgMusic;
var sndGameLevelComplete, sndGameLevelFailed;

var preloadables = ['js/app/images/skyTile.png',
                    'js/app/images/Aeroplane.png',
                    'js/app/images/startEnd.png',
                    'js/app/images/startPoint.png',
                    'js/app/images/endPoint.png',
                    'js/app/images/planeArrowMap.png',
                    'js/app/images/BirdFlockMap.png',
                    'js/app/images/TornadoMap.png',
                    'js/app/images/storm.png'];

/**
 * Game logic
 * Zhu Liang
 */

var Destination = Box.extend({
    // Check whether a Box is within some distance of this dot
    near: function(otherBox, units) {
        return this.nearX(otherBox, units) && this.nearY(otherBox, units);
    },
    nearX: function(otherBox, units) {
        return this.x + this.width + units > otherBox.x && otherBox.x + otherBox.width + units > this.x;
    },
    nearY: function(otherBox, units) {
        return this.y + this.height + units > otherBox.y && otherBox.y + otherBox.height + units > this.y;
    }
    // Initialize the Dot in a random location that doesn't overlap the snake
    //init: function() {
    //    var x, y;
    //    do {
    //        x = this.getRand(world.width);
    //        y = this.getRand(world.height);
    //    } while (this.near(player, UNIT*5) || this.overlapsPieces());
    //    this._super.call(this, x, y, UNIT, UNIT);
    //},
});

/**
 * Bird
 * @type {void|*}
 */
var Bird = Actor.extend({
    BIRD_MOVE_SPEED: 0,
    CONTINUOUS_MOVEMENT: true,
    orientation: 0,
    valid: true,
    src: new SpriteMap('js/app/images/BirdFlockMap.png',
        {stand:[0, 0, 0, 9]}, {frameW: 512, frameH: 512, interval: 40,
            useTimer: false}),
    updateOrientaion: function(fraction){
        this.radians = fraction * Math.PI;
        this.orientation = fraction;
    },
    init: function(x, y, sizex, sizey, speed, orientaion) {
        this.updateOrientaion(orientaion);
        this.BIRD_MOVE_SPEED = speed;
        this._super.call(this, x, y, sizex, sizey);
        this.valid = true;
    }
});

/**
 * Tornado
 */
var Tornado = Actor.extend({
    active: true,
    src: new SpriteMap('js/app/images/TornadoMap.png',
    {stand:[0, 0, 0, 10]}, {frameW: 512, frameH: 512, interval: 20, useTimer: false}),
    init: function(x, y, sizeX, sizeY) {
        this._super.call(this, x, y, sizeX, sizeY);
    }
});

/**
 * Storm
 */
var Storm = Actor.extend({
    active: true,
    src: new SpriteMap('js/app/images/storm.png',
        {stand:[0, 0, 3, 0]}, {frameW: 256, frameH: 256, interval: 40, useTimer: false}),
    init: function(x, y, sizeX, sizeY) {
        this._super.call(this, x, y, sizeX, sizeY);
    }
});

/**
 * Aeroplane
 */
var Plane = Player.extend({
    MOVEAMOUNT: PLANE_MOVE_SPEED,
    CONTINUOUS_MOVEMENT: true,
    MOVEWORLD: 0.4,
    //DEFAULT_WIDTH: SOLDIER_SIZE,
    //DEFAULT_HEIGHT: SOLDIER_SIZE,
    //NEAR_THRESHOLD: SHOOT_NEAR_THRESHOLD,
    //SHOOT_DELAY: RELOAD_DELAY,
    team: null,
    selected: false,
    moveToX: 0,
    moveToY: 0,
    //health: SOLDIER_MAX_HEALTH,
    lastShot: 0,
    //Orientation of the plane, to be multiplied to PI
    orientation: 0,
    fuel: 0,
    vision: true,
    draggedByTornado: false,
    init: function(team, x, y) {
        this._super.call(this, x, y);
        this.team = team;
        this.lastShot = App.physicsTimeElapsed;
        this.orientation = 0;
        this.fuel = MAX_FUEL;
        //if (team != myTeam) return; // Only allow selecting the player's team
        var t = this;
        // Allow selecting soldiers by clicking on them
        this.listen('mousedown.select touchstart.select', function(e) {
            // Left click or touch only
            if (typeof e !== 'undefined' && e.type == 'mousedown' && e.which !== 1) {
                return;
            }
            // Holding down CTRL allows selecting multiple soldiers.
            //if (!jQuery.hotkeys.areKeysDown('ctrl')) {
            //    t.team.soldiers.forEach(function(soldier) {
            //        soldier.selected = false;
            //    });
            //}
            console.log("selected");
            t.toggleSelected.call(t);
            // Don't bubble the event
            e.stopPropagation();
        });
    },
    toggleVision: function(allow_vision) {
        if(allow_vision){
            this.vision = true;
            game.destroyBirdShit();
            ui.hidePrompt();
        }else{
            if(this.vision == true){
                this.vision = false;
                if(!game.birdShit()) {
                    var canvas = background.canvas;
                    game.createBirdShit($(window).height(),$(window).width());
                }
                if(! ui.hasVisionPromptDisplayed){
                    ui.displayPrompt("Shake the birds off", "hand-o-up", "shake");
                    ui.hasVisionPromptDisplayed = true;
                }

            }
        }
    },
    directionToDest: function(){
        var xDist = endPoint.xC() - this.x;
        var yDist = endPoint.yC() - this.y;

        // angle in radians
        var angleRadians = Math.atan2(yDist, xDist);
        return angleRadians;
    },
    loseControl: function(bLostControl) {
        if(bLostControl) {
            ui.displayPrompt("Move your hand in a circle","hand-o-up","circle");

            this.draggedByTornado = true;

            // Slow down the plane's speed
            PLANE_MOVE_SPEED = DEFAULT_SPEED / 10;

            // Ask player to do something to get rid of the tornado
        }
        else {
            ui.hidePrompt();
            this.draggedByTornado = false;
        }
    },
    withinThunderstorm: function(bInThunderstorm) {
        if(bInThunderstorm) {
            ui.displayPrompt("Keep your hand steady in the thunderstrom",null,"circle");
            activeThunderstorm = true;
            PLANE_MOVE_SPEED = DEFAULT_SPEED / 5;
            ANGLE_FACTOR = 0.25;
            console.log("IN THUNDERSTORM!!!!");
            activeThunderstormCounter=20;
            // Ask player to do something to get rid of the storm
            // ...
        }
        else {
            ui.hidePrompt();
            ANGLE_FACTOR = 0.1;
            activeThunderstormCounter=0;
            activeThunderstorm = false;
            console.log("OUT OF THUNDERSTORM!!!!");
        }
    }
});

function move(direction, turn_angle) {
    if(!takeoff || !player.vision){
        return;
    }
    if(direction == DIRECTION_LEFT){
        player.orientation -= turn_angle;
        player.radians-= turn_angle*Math.PI;
    }else{
        player.orientation += turn_angle;
        player.radians+= turn_angle*Math.PI;
    }
    if (player.orientation <= -2 || player.orientation >= 2) {
        player.orientation = 0;
        player.radians = 0;
    }
    //console.log(player.orientation);
}

function startNewLevel(level) {
    allowLeapStart = false;
    setup(false);
    console.log("finished set up for level " + level);
    App.isGameOver = false;
    startAnimating();
}
function displayHighscore(data, textStatus, jqXHR) {console.log(data);
    $.get("http://highscoreserver.herokuapp.com/api/entries", function (data) {
        data = data.slice(1,8);
        var elem = $('#highScore ul');
        elem.empty();

        data.forEach(function(entry){
            var html = '
' + entry.name + '' + entry.score + '
';

            elem.append(html);
        })

        ui.displayHighScore();
    });
}
reachDist = function(level) {
    console.log("reach level " + level);
    if(level > 0){
        score += currentLevel * player.fuel.round();
    }
    App.isGameOver = true;
    stopAnimating();
    gameBgMusic.pause();
    gameBgMusic.currentTime = 0;

    if (player) {
        player.destroy();
    }

    var text = "Level " + level + " completed!";
    var text2 = "Current score: " + score;
    console.log(text);
    if(level == 0) {
        text = "Failed!"; // What is this for?
    }
    else if(level == -1) {
        // Play 'level failed' sound
        sndGameLevelFailed.play();
        text = "You ran out of fuel!";
        text2 = "Final score: " + score;
        level = 0;
        var person = prompt("Please enter your name", "ZZZ");
        var a = {name: person,score:score};
        if (person != null) {
            $.ajax({
                type: "POST",
                url: "http://highscoreserver.herokuapp.com/api/entries",
                data: a,
                success: displayHighscore,
                dataType: 'json'
            });
        }

    }
    else {
        // Made it to next level
        // Play 'level complete' sound
        sndGameLevelComplete.play();
    }

    changeLevel(level + 1);

    // This runs during update() before the final draw(), so we have to delay it.
    setTimeout(function() {
        context.save();
        context.font = '80px Arial';
        context.fillStyle = 'black';
        context.strokeStyle = 'white';
        context.textBaseline = 'middle';
        context.textAlign = 'center';
        context.shadowColor = 'black';
        context.shadowBlur = 8;
        context.lineWidth = 5;
        var x = Math.round(world.xOffset+canvas.width/2);
        var y = Math.round(world.yOffset+canvas.height/2);
        context.strokeText(text, x, y-100);
        context.strokeText(text2, x, y+100);
        context.fillText(text, x, y-100);
        context.fillText(text2, x, y+100);
        context.restore();
    }, 100);
    $canvas.css('cursor', 'pointer');
    allowLeapStart = true;
    $canvas.one('click.gameover', function(e) {
        e.preventDefault();
        $canvas.css('cursor', 'auto');
        //App.reset();
        startNewLevel(level);
    });
};

/**
 * KEYBOARD
 * Record the last key pressed so the player moves in the correct direction.
 */
jQuery(document).keydown(keysCustom.up.concat(keysCustom.down, keysCustom.left, keysCustom.right, keysCustom.takeoff,
    keysCustom.vision, keysCustom.escape, keysCustom.balance).join(' '), function(e) {

    if(e.keyPressed == keysCustom.right[1]){
        move(DIRECTION_RIGHT, ANGLE_FACTOR);
    }else if(e.keyPressed == keysCustom.left[1]){
        move(DIRECTION_LEFT, ANGLE_FACTOR);
    }else if(e.keyPressed == keysCustom.takeoff[1]){
        takeOffPlane();
    }else if(e.keyPressed == keysCustom.vision[1]){
        //TODO: Yiyang, use this method for clearing the vision
        //TODO: Also create correspond methods for circling the tornado
        player.toggleVision(true);
    }else if(e.keyPressed == keysCustom.escape[1]){
        player.loseControl(false);
    }else if(e.keyPressed == keysCustom.balance[1]){
        player.withinThunderstorm(false);
    }
});

/**
 * A magic-named function where all updates should occur.
 */
function update() {

    if(!App.isGameOver && takeoff){
        player.fuel -= 0.025 + 0.025 * currentLevel;

        if(!player.draggedByTornado && !activeThunderstorm && PLANE_MOVE_SPEED < DEFAULT_SPEED) {
            PLANE_MOVE_SPEED += 2;
        }

        //Offset for the default orientation towards the right
        player.setVelocityVector(Math.PI * (player.orientation), PLANE_MOVE_SPEED);
        player.update();

        if(player.fuel < 0){
            reachDist(-1);
        }

        birdFlocks.forEach(function(bird){
            bird.setVelocityVector(Math.PI * (bird.orientation), bird.BIRD_MOVE_SPEED);
            bird.update();
            if(bird.valid && bird.collides(player)){
                player.toggleVision(false);
                bird.valid = false;
            }
        });

        var inSomeTornado = false;
        tornados.forEach(function(tornado) {
            if(!player.draggedByTornado && tornado.active && tornado.collides(player)) {
                player.loseControl(true);
                console.log("Player lost control!");

                // Deactivate the tornado, prevent getting stuck in again
                tornado.active = false;
            }
            if(player.draggedByTornado && tornado.collides(player)) {
                inSomeTornado = true;
            }
        });

        if(player.draggedByTornado && !inSomeTornado) {
            player.loseControl(false);
            console.log("Player regained control!");
        }

        var inSomeThunderstorm = false;
        storms.forEach(function(storm) {
            if(storm.active && storm.collides(player) && !activeThunderstorm) {
                storm.active = false;
                player.withinThunderstorm(true);
                console.log("Within thunderstorm!");
            }
            if(storm.collides(player)) {
                inSomeThunderstorm = true;
            }
        });

        if(activeThunderstorm && !inSomeThunderstorm) {
            player.withinThunderstorm(false);
        }

        //console.log("fuel:" + player.fuel);
        //console.log(player.x + " " + player.y);

        if(player.collides(endPointReal)){
            reachDist(currentLevel);
        }

        var dir = player.directionToDest();
        dirSignal.x = player.x-144;
        dirSignal.y = player.y-144;
        dirSignal.radians = dir;
        var diff_in_angle = dir - player.radians;
        if(diff_in_angle < -Math.PI/6 || diff_in_angle > Math.PI/6){
            showDir = true;
        }else{
            showDir = false;
        }
    }
}

function changeLevel(level){
    currentLevel = level;
    var $level = jQuery('#level .level').text(level);
}

/**
 * A magic-named function where all drawing should occur.
 */
function draw() {

    //console.log("drawing");
  // Draw the background layer
  background.draw();

  // Draw a different 'grid' for start & end points
  startGrid.draw();
  endGrid.draw();

  // Draw a different start & end point
  startPoint.draw();
  endPoint.draw();
  //endPointReal.draw();

	player.draw();
    if(takeoff && showDir){
        dirSignal.draw();
    }
    birdFlocks.forEach(function(bird){
        bird.draw();
    });

    tornados.forEach(function(tornado){
        tornado.draw();
    });

    storms.forEach(function(storm){
        storm.draw();
    });

    dragOverlay.context.clear();
    if(game.birdShit())
        game.birdShit().draw(dragOverlay.context);
    fuelTank.draw();
}

function takeOffPlane() {
    takeoff = true;
    PLANE_MOVE_SPEED = DEFAULT_SPEED;
    ui.hidePrompt();
}
/**
 * Zooming with Leap Motion
 * @param direction
 * <0 means zoom in, >0 means zoom out
 */
function leapZoom(direction) {
    // Avoid overzealous scrolling causing unexpected zooming
    if (lastZoom + Mouse.Zoom.ZOOM_TIMEOUT > App.physicsTimeElapsed) return;
    if (++numScrollEvents < Mouse.Zoom.MIN_SCROLL_EVENTS) return;
    lastZoom = App.physicsTimeElapsed;
    numScrollEvents = 0;

    // Get an indication of the direction of the scroll.
    // Depending on the browser, OS, and device settings, the actual value
    // could be in pixels, lines, pages, degrees, or arbitrary units, so all
    // we can consistently deduce from this is the direction.
    //var delta = e.originalEvent.deltaY || -e.originalEvent.wheelDelta;
    // We want to scroll in around the mouse coordinates.
    var mx = player.x,
        my = player.y;
    // Scroll up; zoom in
    if (direction < 0) {
        if (world.scale > Mouse.Zoom.MIN_ZOOM) {
            world.scaleResolution(world.scale - Mouse.Zoom.ZOOM_STEP, mx, my);
            /**
             * @event zoom
             *   Fires on the document when the user zooms in or out.
             *
             * @param {Boolean} zoomIn
             *   Whether the user zoomed in or out.
             *
             * @member global
             */
            jQuery(document).trigger('zoom', true);
        }
    }
    // Scroll down; zoom out
    else {
        if(!takeoff){
            takeOffPlane();
        }
        if (world.scale < Mouse.Zoom.MAX_ZOOM) {
            world.scaleResolution(world.scale + Mouse.Zoom.ZOOM_STEP, mx, my);
            jQuery(document).trigger('zoom', false);
        }
    }
}

/**
 * A magic-named function for one-time setup.
 *
 * @param {Boolean} first
 *   true if the app is being set up for the first time; false if the app has
 *   been reset and is starting over.
 */
function setup(first) {
    //App.debugMode = true;
  // Change the size of the playable area. Do this before placing items!
  if(first) {
        //Level related
      changeLevel(1);
      score = 0;
      dragOverlay = new Layer({relative: 'canvas'});
      dragOverlay.positionOverCanvas();
  }
    world.resize(1024 * mapWidth, 1024 * mapHeight);
    takeoff = false;
    PLANE_MOVE_SPEED = 0;

  $('#highScore').hide();

  // Switch from side view to top-down.
  Actor.prototype.GRAVITY = false;

  // Set up the background layer
  background = new Layer();
  background.context.drawPattern('js/app/images/skyTile.png', 0, 0, world.width, world.height);

  startGrid = new Box(0, (world.height - 1024), 1024, 1024);
  startGrid.src = 'js/app/images/startEnd.png';

  endGrid = new Box((world.width - 1024), 0, 1024, 1024);
  endGrid.src = 'js/app/images/startEnd.png';

  startPoint = new Box((1024-512)/2, (world.height - 768), 512, 512);
  startPoint.src = 'js/app/images/startPoint.png';

  endPoint = new Box((world.width - 768), (1024-512)/2, 512, 512);
  endPoint.src = 'js/app/images/endPoint.png';
  endPointReal = new Box((world.width - 640), (1024-256)/2, 256, 256);
  //endPointReal.src = 'js/app/images/endPoint.png';

  birdFlocks = new Collection();
  var birdFlock = new Bird(1536, (world.height - 1536), 512, 512, 75, 1/4);
  var birdFlock2 = new Bird((world.height/2), (world.height/2), 512, 512, 100, 3/4);
  var birdFlock3 = new Bird((world.height/2 + 200), (world.height/2 - 100), 512, 512, 30, 1/4);
  birdFlocks.add(birdFlock);
  birdFlocks.add(birdFlock2);
  birdFlocks.add(birdFlock3);

    tornados = new Collection();

  // Create a tornado
  var tornado1 = new Tornado(2196, world.height-1792, 512, 512);
  var tornado2;

  tornados.add(tornado1);

    if(currentLevel == 2){
        tornado2= new Tornado(startPoint.xC() + 500, startPoint.yC() -500, 512, 512);
        tornados.add(tornado2);
    }

  // Create storms
  var storm1 = new Storm(world.width - 1200, 1200, 256, 256);
  var storm2 = new Storm(world.width - 1600, 1800, 256, 256);
  var storm3 = new Storm(world.width - 2000, 1000, 256, 256);
  var storm4 = new Storm(world.width - 1000, 2200, 256, 256);
  storms = new Collection();
  storms.add(storm1);
  storms.add(storm2);
  storms.add(storm3);
  storms.add(storm4);

  // Initialize the player.
  player = new Plane(null, startPoint.xC() - 200, startPoint.yC() + 30);
  player.src = new SpriteMap('js/app/images/Aeroplane.png',
  {stand: [0, 0, 3, 0]},
  {frameW: 256, frameH: 256,
  interval: 20, useTimer: false});
    console.log("set up: " + player.x +"  "+ player.y);

  //New Direction signal
  dirSignal = new Box(player.xC(), player.yC(), 400, 400);
  dirSignal.src = new SpriteMap('js/app/images/planeArrowMap.png',
  {stand:[0, 0, 0, 9]}, {frameW: 400, frameH: 400, interval: 20,
  useTimer: false});

  fuelTank = new FuelTank(40, 76, 60, 400);

  // Set velocity vector for player
  player.setVelocityVector(Math.PI * player.orientation, PLANE_MOVE_SPEED);

  //console.log(player.getVelocityVector());

// Enable zooming, and display the zoom level indicator
    Mouse.Zoom.enable(showZoomLevel);
    aTimer.start();

    gameBgMusic = document.getElementById('gameBgMusic');
    gameBgMusic.setAttribute("preload", "auto");
    gameBgMusic.autobuffer = true;
    gameBgMusic.load();
    gameBgMusic.play();

    sndGameLevelComplete = document.getElementById('gameLevelComplete');
    sndGameLevelComplete.setAttribute("preload", "auto");
    sndGameLevelComplete.autobuffer = true;
    sndGameLevelComplete.load();

    sndGameLevelFailed = document.getElementById('gameLevelFailed');
    sndGameLevelFailed.setAttribute("preload", "auto");
    sndGameLevelFailed.autobuffer = true;
    sndGameLevelFailed.load();
}

/**
 * Draw a progress bar.
 *
 * @param {CanvasRenderingContext2D} ctx
 *   A canvas graphics context onto which this progress bar should be drawn.
 * @param {Number} x
 *   The x-coordinate of the upper-left corner of the progress bar.
 * @param {Number} y
 *   The y-coordinate of the upper-left corner of the progress bar.
 * @param {Number} w
 *   The width of the progress bar.
 * @param {Number} h
 *   The height of the progress bar.
 * @param {Number} pct
 *   The fractional percent that the progress bar is complete.
 * @param {String} doneColor
 *   The CSS color of the completed portion of the progress bar.
 * @param {String} [remainingColor='transparent']
 *   The CSS color of the remaining portion of the progress bar.
 * @param {String} [borderColor='black']
 *   The CSS color of the border of the progress bar.
 */
function drawProgressBar(ctx, x, y, w, h, pct, doneColor, remainingColor, borderColor) {
    pct = 1 - pct;
    var radius = 10;

    ctx.lineWidth = 1;

    // Draw Empty Gauge
    ctx.fillStyle = remainingColor || 'transparent';
    ctx.strokeStyle = borderColor || 'black';

    utilities.drawRoundRect(ctx,x,y,w,h,radius,true,true);

    // Draw Remaining Fuel
    ctx.fillStyle = doneColor;
    if(h*pct < radius){
        utilities.drawRoundRect(ctx,x,y+h*pct,w,h*(1-pct),radius,true,true);
    }else{
        utilities.drawTopHalfRoundRect(ctx,x,y+h*pct,w,h*(1-pct),radius,true,true);
    }
}

var FuelTank = Box.extend({
    progressBarColor: '#D76930',
    drawDefault: function(ctx, x, y, w, h) {
        console.log("fuel left: " + player.fuel/MAX_FUEL);
        drawProgressBar(dragOverlay.context, x, y, w, h, player.fuel/MAX_FUEL,
            this.progressBarColor, 'rgba(0,0,0,0.5);', this.progressBarBorderColor);
    }
});


text:
title: "Links for 2018-06-19"
layout: post
date: 2018-06-19
---

* [Heroku CLI: Completing Autocomplete](https://blog.heroku.com/completing-autocomplete)
* [Railway oriented development with Erlang](https://www.erlang-solutions.com/blog/railway-oriented-development-with-erlang.html)
* [How to Fix Your Git Branches After a Rebase](https://www.viget.com/articles/how-to-fix-your-git-branches-after-a-rebase/)
* [Microservices for Startups](https://buttercms.com/books/microservices-for-startups/breaking-up-a-monolith/)


text:
from __future__ import absolute_import, division, print_function, unicode_literals

def prepare_dependencies(self):
  self.add_to_build_file('a', 'java_library(name="a")')
  self.add_to_build_file('b', 'java_library(name="b", dependencies=["a:a"])')
  self.add_to_build_file('c', 'java_library(name="c", dependencies=["a:a"])')
  self.add_to_build_file('d', 'java_library(name="d", dependencies=["a:a", "b"])')

  targets = { 'a': self.make_target('a') }
  targets['b'] = self.make_target('b', dependencies=[targets['a']])
  targets['c'] = self.make_target('c', dependencies=[targets['a'], targets['b']])
  targets['d'] = self.make_target('d', dependencies=[targets['a'], targets['b']])

  return targets


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using LanExchange.Misc;

namespace LanExchange.Ioc
{
    public class SimpleIocContainer : IIocContainer
    {
        private readonly IList<RegisteredObject> m_Objects = new List<RegisteredObject>();

        [Localizable(false)]
        public void Register<TTypeToResolve, TConcrete>(LifeCycle lifeCycle = LifeCycle.Singleton)
        {
            m_Objects.Add(new RegisteredObject(typeof (TTypeToResolve), typeof (TConcrete), lifeCycle));
            Debug.Print("IoC: Registering type #{0} {1} : {2}", m_Objects.Count, typeof(TConcrete).FullName, typeof(TTypeToResolve).Name);
        }

        [Localizable(false)]
        public void Unregister<TTypeToResolve>()
        {
            for (int index = m_Objects.Count - 1; index >= 0; index--)
            {
                var obj = m_Objects[index];
                if (obj.TypeToResolve == typeof (TTypeToResolve))
                {
                    Debug.Print("IoC: Unregistering type {0}", obj.TypeToResolve.Name);
                    m_Objects.RemoveAt(index);
                }
            }
        }

        [Localizable(false)]
        public object Resolve(Type typeToResolve)
        {
            RegisteredObject registeredObject = null;
            foreach(var obj in m_Objects)
                if (obj.TypeToResolve == typeToResolve)
                {
                    registeredObject = obj;
                    break;
                }

            if (registeredObject == null)
                throw new TypeNotRegisteredException(string.Format(CultureInfo.InvariantCulture,
                    "The type {0} has not been registered", typeToResolve.Name));
            Debug.Print("IoC: Resolving {0} : {1}", registeredObject.ConcreteType.Name, typeToResolve.Name);
            return GetInstance(registeredObject);
        }

        private object GetInstance(RegisteredObject registeredObject)
        {
            if (registeredObject.Instance == null || registeredObject.LifeCycle == LifeCycle.Transient)
                registeredObject.CreateInstance(ResolveConstructorParameters(registeredObject).ToArray());
            return registeredObject.Instance;
        }

        [Localizable(false)]
        private IEnumerable<object> ResolveConstructorParameters(RegisteredObject registeredObject)
        {
            var constructors = registeredObject.ConcreteType.GetConstructors();

            if (constructors.Length == 0)
                throw new ApplicationException("Constructor is not implemented or non-public in class " + registeredObject.ConcreteType.Name);

            var constructorInfo = constructors[0];
            var result = new List<object>();
            foreach(var parameter in constructorInfo.GetParameters())
                result.Add(Resolve(parameter.ParameterType));
            return result;
        }
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Platystomum hysterioides Earle

### Remarks
null


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="horizontal">

        <com.bigscreen.binarygame.common.component.GameButton
            android:id="@+id/button_keyboard_7"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_margin="@dimen/line_padding"
            android:layout_weight="1"
            android:background="@drawable/bg_btn_primary_flat"
            android:text="7"
            android:textColor="@color/white"
            android:textSize="12sp"
            app:textFont="pressStart" />

        <com.bigscreen.binarygame.common.component.GameButton
            android:id="@+id/button_keyboard_8"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_margin="@dimen/line_padding"
            android:layout_weight="1"
            android:background="@drawable/bg_btn_primary_flat"
            android:text="8"
            android:textColor="@color/white"
            android:textSize="12sp"
            app:textFont="pressStart" />

        <com.bigscreen.binarygame.common.component.GameButton
            android:id="@+id/button_keyboard_9"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_margin="@dimen/line_padding"
            android:layout_weight="1"
            android:background="@drawable/bg_btn_primary_flat"
            android:text="9"
            android:textColor="@color/white"
            android:textSize="12sp"
            app:textFont="pressStart" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="horizontal">

        <com.bigscreen.binarygame.common.component.GameButton
            android:id="@+id/button_keyboard_4"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_margin="@dimen/line_padding"
            android:layout_weight="1"
            android:background="@drawable/bg_btn_primary_flat"
            android:text="4"
            android:textColor="@color/white"
            android:textSize="12sp"
            app:textFont="pressStart" />

        <com.bigscreen.binarygame.common.component.GameButton
            android:id="@+id/button_keyboard_5"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_margin="@dimen/line_padding"
            android:layout_weight="1"
            android:background="@drawable/bg_btn_primary_flat"
            android:text="5"
            android:textColor="@color/white"
            android:textSize="12sp"
            app:textFont="pressStart" />

        <com.bigscreen.binarygame.common.component.GameButton
            android:id="@+id/button_keyboard_6"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_margin="@dimen/line_padding"
            android:layout_weight="1"
            android:background="@drawable/bg_btn_primary_flat"
            android:text="6"
            android:textColor="@color/white"
            android:textSize="12sp"
            app:textFont="pressStart" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="horizontal">

        <com.bigscreen.binarygame.common.component.GameButton
            android:id="@+id/button_keyboard_1"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_margin="@dimen/line_padding"
            android:layout_weight="1"
            android:background="@drawable/bg_btn_primary_flat"
            android:text="1"
            android:textColor="@color/white"
            android:textSize="12sp"
            app:textFont="pressStart" />

        <com.bigscreen.binarygame.common.component.GameButton
            android:id="@+id/button_keyboard_2"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_margin="@dimen/line_padding"
            android:layout_weight="1"
            android:background="@drawable/bg_btn_primary_flat"
            android:text="2"
            android:textColor="@color/white"
            android:textSize="12sp"
            app:textFont="pressStart" />

        <com.bigscreen.binarygame.common.component.GameButton
            android:id="@+id/button_keyboard_3"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_margin="@dimen/line_padding"
            android:layout_weight="1"
            android:background="@drawable/bg_btn_primary_flat"
            android:text="3"
            android:textColor="@color/white"
            android:textSize="12sp"
            app:textFont="pressStart" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="horizontal">

        <com.bigscreen.binarygame.common.component.GameButton
            android:id="@+id/button_keyboard_del"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_margin="@dimen/line_padding"
            android:layout_weight="1"
            android:background="@drawable/bg_btn_accent_flat"
            android:text="DEL"
            android:textColor="@color/white"
            android:textSize="10sp"
            app:textFont="pressStart"
            tools:ignore="SmallSp" />

        <com.bigscreen.binarygame.common.component.GameButton
            android:id="@+id/button_keyboard_0"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_margin="@dimen/line_padding"
            android:layout_weight="1"
            android:background="@drawable/bg_btn_primary_flat"
            android:text="0"
            android:textColor="@color/white"
            android:textSize="12sp"
            app:textFont="pressStart" />

        <com.bigscreen.binarygame.common.component.GameButton
            android:id="@+id/button_keyboard_ok"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_margin="@dimen/line_padding"
            android:layout_weight="1"
            android:background="@drawable/bg_btn_accent_flat"
            android:text="OK"
            android:textColor="@color/white"
            android:textSize="10sp"
            app:textFont="pressStart"
            tools:ignore="SmallSp" />

    </LinearLayout>

</LinearLayout>


text:
using namespace lldb_private;
using namespace lldb;

// Include RegisterInfos_s390x to declare our g_register_infos_s390x structure.
#define DECLARE_REGISTER_INFOS_S390X_STRUCT
#include "RegisterInfos_s390x.h"
#undef DECLARE_REGISTER_INFOS_S390X_STRUCT

static const RegisterInfo *GetRegisterInfoPtr(const ArchSpec &target_arch) {
  switch (target_arch.GetMachine()) {
  case llvm::Triple::systemz:
    return g_register_infos_s390x;
  default:
    assert(false && "Unhandled target architecture.");
    return nullptr;
  }
}

static uint32_t GetRegisterInfoCount(const ArchSpec &target_arch) {
  switch (target_arch.GetMachine()) {
  case llvm::Triple::systemz:
    return k_num_registers_s390x;
  default:
    assert(false && "Unhandled target architecture.");
    return 0;
  }
}

static uint32_t GetUserRegisterInfoCount(const ArchSpec &target_arch) {
  switch (target_arch.GetMachine()) {
  case llvm::Triple::systemz:
    return k_num_user_registers_s390x + k_num_linux_registers_s390x;
  default:
    assert(false && "Unhandled target architecture.");
    return 0;
  }
}

RegisterContextLinux_s390x::RegisterContextLinux_s390x(
    const ArchSpec &target_arch)
    : lldb_private::RegisterInfoInterface(target_arch),
      m_register_info_p(GetRegisterInfoPtr(target_arch)),
      m_register_info_count(GetRegisterInfoCount(target_arch)),
      m_user_register_count(GetUserRegisterInfoCount(target_arch)) {}

const std::vector<lldb_private::RegisterInfo> *
RegisterContextLinux_s390x::GetDynamicRegisterInfoP() const {
  return &d_register_infos;
}

const RegisterInfo *RegisterContextLinux_s390x::GetRegisterInfo() const {
  return m_register_info_p;
}

uint32_t RegisterContextLinux_s390x::GetRegisterCount() const {
  return m_register_info_count;
}

uint32_t RegisterContextLinux_s390x::GetUserRegisterCount() const {
  return m_user_register_count;
}

size_t RegisterContextLinux_s390x::GetGPRSize() const { return 0; }


text:
A smooth, nice looking and IBDesignable flat design switch for iOS. Can be used instead of UISwitch.

Inspired by Creativedash's Dribbble post [here](http://dribbble.com/shots/1631598-On-Off)

## Requirements
- iOS 8.0+, tvOS 12.0+
- Xcode 11.0+
- Swift 5

## Usage

### Creating the flat switch

- Either programmatically

```swift
var flatSwitch = AIFlatSwitch(frame: CGRectMake(0, 0, 50, 50))
```

- Or in Interface Builder

### Methods

> To change its selected state:

```swift
flatSwitch.isSelected = true
```
- [x] IBInspectable

> or:

```swift
flatSwitch.setSelected(true, animated: true)
```

> To listen to its state changes:

```swift
@IBAction func handleSwitchValueChange(sender: AnyObject) {
		if let flatSwitch = sender as? AIFlatSwitch {
			print(flatSwitch.isSelected)
		}
	}
```

> Animation observer callbacks:

```swift
flatSwitch.selectionAnimationDidStart = { isSelected in
    print("New state: \(isSelected)")
}

flatSwitch.selectionAnimationDidStop = { isSelected in
    print("State when animation stopped: \(isSelected)")
}
```

> Styling the switch:

```swift
flatSwitch.lineWidth = 2.0
flatSwitch.strokeColor = UIColor.blue
flatSwitch.trailStrokeColor = UIColor.red
flatSwitch.backgroundLayerColor = UIColor.red
flatSwitch.animatesOnTouch = false
```
- [x] IBInspectable

## Contribution guidelines

- Make your changes in your branch
- Bump the pod version in AIFlatSwitch.podspec file (e.g. 1.0.1 to 1.0.2)
- Make sure the Example project compiles and works fine in the Simulator
- Find references to your source code changes in README.md and update them (e.g. method names, changed features)
- Create a pull request

## License

AIFlatSwitch is released under the MIT license. See LICENSE for details.

animated check button, checkmark


text:
Summary
=======
This project demonstrates spt ios sdk issue #409 -- https://github.com/spotify/ios-sdk/issues/409

In summary: switching from wifi to cellular-data (aka wwan) results in unacceptable delay when next track is played.

Using this project to demonstrate issue
=======================================
1.  change `DefaultSpotifyProxyImpl.swift` to add your app and client-id.
1.  follow the steps in the app gui.


text:
#pragma once

#include "../interactionbase_api.h"

#include "ExpressionContext.h"

namespace Interaction {

class Operator;
class ExpressionVisitor;

class INTERACTIONBASE_API Expression {
	public:
		Expression(const int type, Operator* parent = nullptr);
		virtual ~Expression();

		virtual QString renderText() = 0;
		virtual void accept(ExpressionVisitor* visitor) = 0;

		int length() {return renderText().size();}
		virtual ExpressionContext findContext(int cursor_pos) = 0;

		Operator* parent() {return parent_;}
		void setParent(Operator* new_parent);

		int type() {return type_;}

		// Returns this by default
		virtual Expression* smallestRightmostSubExpr();
		// Returns this by default
		virtual Expression* smallestLeftmostSubExpr();

		// Return nullptr by default, meaning can not cut this expression. This method is used when growing an operator.
		virtual Expression* findCutExpression(bool leftside, QString cut_string);

		void removeFromParent();
	private:
		const int type_;
		Operator* parent_;
};

} /* namespace InteractionBase */


text:
describe("Horizontal/Veritcal Layout tests", {

	horizontalTopBottomUndefinedHeight: asyncTest(function() {
		var win = Ti.UI.createWindow({ backgroundColor: 'white'});
		var parent = Ti.UI.createView({backgroundColor:'red',layout:'horizontal', horizontalWrap: true, width:200, height:300});

		var child1 =Ti.UI.createView({backgroundColor:'green', width: 40, top: 10,bottom:10, height: 50});
		var child2 =Ti.UI.createView({backgroundColor:'blue', left: 5, right:20, top: 20, bottom: 10,width:55});
		var child3 =Ti.UI.createView({backgroundColor:'#eee',height:120,width:50});

		parent.add(child1);
		parent.add(child2);
		parent.add(child3);

		win.addEventListener("open", this.async(function(e) {
			valueOf(child1.rect.height).shouldBe(50);
			valueOf(child1.rect.width).shouldBe(40);
			valueOf(child1.rect.y).shouldBe(10);
			valueOf(child1.rect.x).shouldBe(0);

			valueOf(child2.rect.height).shouldBe(270);
			valueOf(child2.rect.width).shouldBe(55);
			valueOf(child2.rect.y).shouldBe(20);
			valueOf(child2.rect.x).shouldBe(45);

			valueOf(child3.rect.height).shouldBe(120);
			valueOf(child3.rect.width).shouldBe(50);
			valueOf(child3.rect.y).shouldBe(90);
			valueOf(child3.rect.x).shouldBe(120);
		}));

		win.add(parent);
		win.open();
	}),
	horizontalLeftRightUndefinedWidth: asyncTest(function() {
		var win = Ti.UI.createWindow({ backgroundColor: 'white'});
		var parent = Ti.UI.createView({backgroundColor:'red',layout:'horizontal', horizontalWrap: true, width:200, height:300});

		var child1 =Ti.UI.createView({backgroundColor:'green', left: 10, right:10, height: 50});
		var child2 =Ti.UI.createView({backgroundColor:'blue', left: 5, right:20, height: 90,width:55});
		var child3 =Ti.UI.createView({backgroundColor:'#eee',left: 5,height:120,width:50});

		parent.add(child1);
		parent.add(child2);
		parent.add(child3);

		win.addEventListener("open", this.async(function(e) {
			valueOf(child1.rect.height).shouldBe(50);
			valueOf(child1.rect.width).shouldBe(180);
			valueOf(child1.rect.y).shouldBe(0);
			valueOf(child1.rect.x).shouldBe(10);

			valueOf(child2.rect.height).shouldBe(90);
			valueOf(child2.rect.width).shouldBe(55);
			// ((120 - 90) / 2) + 50
			// child3 determines the maximum height of that row, so we have to calculate accordingly.
			// We have to add 50 since the previous row just fills and this is in the second row
			valueOf(child2.rect.y).shouldBe(65);
			valueOf(child2.rect.x).shouldBe(5);

			valueOf(child3.rect.height).shouldBe(120);
			valueOf(child3.rect.width).shouldBe(50);
			valueOf(child3.rect.y).shouldBe(50);
			valueOf(child3.rect.x).shouldBe(85);
		}));

		win.add(parent);
		win.open();
	}),
	horizontalLeftRightUndefinedWidthNoWrap: asyncTest(function() {
		var win = Ti.UI.createWindow({ backgroundColor: 'white'});
		var parent = Ti.UI.createView({backgroundColor:'red',layout:'horizontal', horizontalWrap: false, width:200, height:300});

		var child1 =Ti.UI.createView({backgroundColor:'green', left: 10, right:10, height: 50});
		var child2 =Ti.UI.createView({backgroundColor:'blue', left: 5, right:20, height: 90,width:55});
		var child3 =Ti.UI.createView({backgroundColor:'#eee',left: 5,height:120,width:50});

		parent.add(child1);
		parent.add(child2);
		parent.add(child3);

		win.addEventListener("open", this.async(function(e) {
			valueOf(child1.rect.height).shouldBe(50);
			valueOf(child1.rect.width).shouldBe(180);
			// (300-50)/2
			valueOf(child1.rect.y).shouldBe(125);
			valueOf(child1.rect.x).shouldBe(10);

			valueOf(child2.rect.height).shouldBe(90);
			valueOf(child2.rect.width).shouldBe(55);
			valueOf(child2.rect.y).shouldBe(105);
			valueOf(child2.rect.x).shouldBe(205);

			valueOf(child3.rect.height).shouldBe(120);
			valueOf(child3.rect.width).shouldBe(50);
			valueOf(child3.rect.y).shouldBe(90);
			valueOf(child3.rect.x).shouldBe(285);
		}));
		win.add(parent);
		win.open();
	}),

	horizontalTopBottomUndefinedHeightNoWrap: asyncTest(function() {
		var win = Ti.UI.createWindow({ backgroundColor: 'white'});
		var parent = Ti.UI.createView({backgroundColor:'red',layout:'horizontal', horizontalWrap: false, width:200, height:300});

		var child1 =Ti.UI.createView({backgroundColor:'green', width: 40, top: 10,bottom:10, height: 50});
		var child2 =Ti.UI.createView({backgroundColor:'blue', left: 5, right:20, top: 20, bottom: 10,width:55});
		var child3 =Ti.UI.createView({backgroundColor:'#eee',height:120,width:50});

		parent.add(child1);
		parent.add(child2);
		parent.add(child3);

		win.addEventListener("open", this.async(function(e) {
			valueOf(child1.rect.height).shouldBe(50);
			valueOf(child1.rect.width).shouldBe(40);
			valueOf(child1.rect.y).shouldBe(10);
			valueOf(child1.rect.x).shouldBe(0);

			valueOf(child2.rect.height).shouldBe(270);
			valueOf(child2.rect.width).shouldBe(55);
			valueOf(child2.rect.y).shouldBe(20);
			valueOf(child2.rect.x).shouldBe(45);

			valueOf(child3.rect.height).shouldBe(120);
			valueOf(child3.rect.width).shouldBe(50);
			valueOf(child3.rect.y).shouldBe(90);
			valueOf(child3.rect.x).shouldBe(120);
		}));

		win.add(parent);
		win.open();
	})

})


text:
Wow I made another page

<input type=button value="index.html" style="font-size:30px" onclick="location='index.html'">


text:
#pragma once

struct FileSection;

/* SectionListener listens to unhandled Song FileSections
 * e.g. ISynth can then access the file to load/save its own settings
 */

class SectionListener
{
public:
	enum Flags {
		Load = 1,
		Save = 2
	};

	/* Return false if failed
	 */
	virtual bool onFileSectionLoad(const FileSection& section, int& offset);
	virtual void onFileSectionSave(FileSection& section);

	// Triggered on Song::clear() if the Load event is listened to
	virtual void onSongClear();
};


text:
#ifndef __C_PARTICLE_SPHERE_EMITTER_H_INCLUDED__
#define __C_PARTICLE_SPHERE_EMITTER_H_INCLUDED__

#include "IParticleSphereEmitter.h"
#include "irrArray.h"
#include "aabbox3d.h"

namespace irr
{
namespace scene
{

//! A default box emitter
class CParticleSphereEmitter : public IParticleSphereEmitter
{
public:

	//! constructor
	CParticleSphereEmitter(
		const core::vector3df& center, f32 radius,
		const core::vector3df& direction = core::vector3df(0.0f,0.03f,0.0f),
		u32 minParticlesPerSecond = 20,
		u32 maxParticlesPerSecond = 40,
		const video::SColor& minStartColor = video::SColor(255,0,0,0),
		const video::SColor& maxStartColor = video::SColor(255,255,255,255),
		u32 lifeTimeMin=2000,
		u32 lifeTimeMax=4000,
		s32 maxAngleDegrees=0,
		const core::dimension2df& minStartSize = core::dimension2df(5.0f,5.0f),
		const core::dimension2df& maxStartSize = core::dimension2df(5.0f,5.0f) );

	//! Prepares an array with new particles to emitt into the system
	//! and returns how much new particles there are.
	virtual s32 emitt(u32 now, u32 timeSinceLastCall, SParticle*& outArray) _IRR_OVERRIDE_;

	//! Set direction the emitter emits particles
	virtual void setDirection( const core::vector3df& newDirection ) _IRR_OVERRIDE_ { Direction = newDirection; }

	//! Set minimum number of particles per second.
	virtual void setMinParticlesPerSecond( u32 minPPS ) _IRR_OVERRIDE_ { MinParticlesPerSecond = minPPS; }

	//! Set maximum number of particles per second.
	virtual void setMaxParticlesPerSecond( u32 maxPPS ) _IRR_OVERRIDE_ { MaxParticlesPerSecond = maxPPS; }

	//! Set minimum start color
	virtual void setMinStartColor( const video::SColor& color ) _IRR_OVERRIDE_ { MinStartColor = color; }

	//! Set maximum start color
	virtual void setMaxStartColor( const video::SColor& color ) _IRR_OVERRIDE_ { MaxStartColor = color; }

	//! Set the maximum starting size for particles
	virtual void setMaxStartSize( const core::dimension2df& size ) _IRR_OVERRIDE_ { MaxStartSize = size; }

	//! Set the minimum starting size for particles
	virtual void setMinStartSize( const core::dimension2df& size ) _IRR_OVERRIDE_ { MinStartSize = size; }

	//! Set the minimum particle life-time in milliseconds
	virtual void setMinLifeTime( u32 lifeTimeMin ) _IRR_OVERRIDE_ { MinLifeTime = lifeTimeMin; }

	//! Set the maximum particle life-time in milliseconds
	virtual void setMaxLifeTime( u32 lifeTimeMax ) _IRR_OVERRIDE_ { MaxLifeTime = lifeTimeMax; }

	//!	Set maximal random derivation from the direction
	virtual void setMaxAngleDegrees( s32 maxAngleDegrees ) _IRR_OVERRIDE_ { MaxAngleDegrees = maxAngleDegrees; }

	//! Set the center of the sphere for particle emissions
	virtual void setCenter( const core::vector3df& center ) _IRR_OVERRIDE_ { Center = center; }

	//! Set the radius of the sphere for particle emissions
	virtual void setRadius( f32 radius ) _IRR_OVERRIDE_ { Radius = radius; }

	//! Gets direction the emitter emits particles
	virtual const core::vector3df& getDirection() const _IRR_OVERRIDE_ { return Direction; }

	//! Get minimum number of particles per second.
	virtual u32 getMinParticlesPerSecond() const _IRR_OVERRIDE_ { return MinParticlesPerSecond; }

	//! Get maximum number of particles per second.
	virtual u32 getMaxParticlesPerSecond() const _IRR_OVERRIDE_ { return MaxParticlesPerSecond; }

	//! Get minimum start color
	virtual const video::SColor& getMinStartColor() const _IRR_OVERRIDE_ { return MinStartColor; }

	//! Get maximum start color
	virtual const video::SColor& getMaxStartColor() const _IRR_OVERRIDE_ { return MaxStartColor; }

	//! Gets the maximum starting size for particles
	virtual const core::dimension2df& getMaxStartSize() const _IRR_OVERRIDE_ { return MaxStartSize; }

	//! Gets the minimum starting size for particles
	virtual const core::dimension2df& getMinStartSize() const _IRR_OVERRIDE_ { return MinStartSize; }

	//! Get the minimum particle life-time in milliseconds
	virtual u32 getMinLifeTime() const _IRR_OVERRIDE_ { return MinLifeTime; }

	//! Get the maximum particle life-time in milliseconds
	virtual u32 getMaxLifeTime() const _IRR_OVERRIDE_ { return MaxLifeTime; }

	//!	Get maximal random derivation from the direction
	virtual s32 getMaxAngleDegrees() const _IRR_OVERRIDE_ { return MaxAngleDegrees; }

	//! Get the center of the sphere for particle emissions
	virtual const core::vector3df& getCenter() const _IRR_OVERRIDE_ { return Center; }

	//! Get the radius of the sphere for particle emissions
	virtual f32 getRadius() const _IRR_OVERRIDE_ { return Radius; }

	//! Writes attributes of the object.
	virtual void serializeAttributes(io::IAttributes* out, io::SAttributeReadWriteOptions* options) const _IRR_OVERRIDE_;

	//! Reads attributes of the object.
	virtual void deserializeAttributes(io::IAttributes* in, io::SAttributeReadWriteOptions* options) _IRR_OVERRIDE_;

private:

	core::array<SParticle> Particles;

	core::vector3df	Center;
	f32 Radius;
	core::vector3df Direction;

	core::dimension2df MinStartSize, MaxStartSize;
	u32 MinParticlesPerSecond, MaxParticlesPerSecond;
	video::SColor MinStartColor, MaxStartColor;
	u32 MinLifeTime, MaxLifeTime;

	u32 Time;
	s32 MaxAngleDegrees;
};

} // end namespace scene
} // end namespace irr

#endif


text:
A replacement for cron, with sophisticated status-reporting and error-handling.

** NOTE ** Due to lack of time, this project is not actively maintained. Please get in touch if you're interested in taking it over.

## Intro

Jobber is a lightweight utility for Unix-like systems that can run arbitrary commands, or "jobs", according to a schedule.  It is meant to be a replacement for the classic Unix utility [cron](http://en.wikipedia.org/wiki/Cron).

Along with the functionality of cron, Jobber also provides:
* **Job execution history**: you can see what jobs have recently run, and whether they succeeded or failed.
* **Sophisticated error handling**: you can control whether and when a job is run again after it fails.  For example, after an initial failure of a job, Jobber can schedule future runs using an exponential backoff algorithm.
* **Sophisticated error reporting**: you can control whether Jobber notifies you about each failed run, or only about jobs that have been disabled due to repeated failures.

## Contributing

**Contributions/suggestions/requests are welcome!**  Feel free to [open an issue](https://github.com/dshearer/jobber/issues), or ask a question on [the mailing list](https://groups.google.com/d/forum/jobber-proj).

## More Info

More info can be found on [Jobber's website](http://dshearer.github.io/jobber/).


text:
A wrapper to do some easy logging and writing stuff to Google Spreadsheets

## Setup

First you must create a doc to write to.
Open your [Google Drive](https://drive.google.com/drive/#my-drive) and sign in.

Next we need to configure the `config.json`. The config expects the following values to be present:

```json
"auth": {
	"username": "example@gmail.com",
	"password": "password"
},
"sheet": {
	"name": "name of sheet",
	"id": "optional id",
	"worksheet": {
		"name": "worksheet name",
		"id": "optional id"
	}
}
```

The `sheet.id` and `sheet.worksheet.id` are optional.
These will appear in the console when not given, after that you could add them to make the connection faster.

## Mapping the sheet

Because Google sheets provides us with a json we can't really work with the data gets remapped.
You can ajust the names of the columns in the `config.json`. A mapping would look like this:

```json
"mapping": {
	"columns":[
		["1", "brand"],
		["2", "model"],
		["3", "customer"],
		["4", "status"],
		["5", "due_date"]
	]
}
```

##### How we receive the data
```json
{
	"1": {
	    "1": "motorola",
	    "2": "moto g",
	    "3": "t-mobile-usa",
	    "4": "IN",
	    "5": "31-10-2015"
	}
}
```
##### After mapping
```json
{
    "brand": "motorola",
    "model": "moto g",
    "customer": "t-mobile-usa",
    "status": "IN",
    "due_date": "31-10-2015",
    "id": 1
}

```

## Actions

The action have a very simple syntax:

```javascript
GQL.name_of_action( [id], data, function(){
	//Gets executed when done.
});

```

Although some action may require an id like:

- GET
- UPDATE
- DESTROY

Because else we wouldn't not know which record to update.

#### GET

The `GET` action requires an id or an query to find a array of records to match the query.

```javascript
// With an ID
GQL.get( id, data, function(){
	//Gets executed when done.
});
// => {} returns an Object

// With an query
// NOTE: Only `===` is supported at this point
GQL.get( 'brand === motorola', data, function(){
	//Gets executed when done.
});
// => [{}, {}, {}] returns an Array of Objects

```

#### CREATE

Adds a new record field to the db and updates it with the data that is given.

```javascript
GQL.create( data, function(){
	//Gets executed when done.
});

```
#### UPDATE

Update a record.

```javascript
GQL.update( id, data, function(){
	//Gets executed when done.
});

```
#### DESTROY

Removal is not possible. The record field will be made empty so count as inactive.

```javascript
GQL.destroy( id, function(){
	//Gets executed when done.
});

```

#### DB

If you want to provide al the info to a client side application you can just dump the entire db.

```javascript
GQL.db() // return entire db
```


text:
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (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.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is JavaScript Engine testing utilities.
 *
 * The Initial Developer of the Original Code is Mozilla Foundation.
 * Portions created by the Initial Developer are Copyright (C) 2007
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s): Norris Boyd
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

var gTestfile = 'evens.js';
//-----------------------------------------------------------------------------
var BUGNUMBER     = "(none)";
var summary = "Array comprehensions evens example from http://developer.mozilla.org/en/docs/New_in_JavaScript_1.7"
var actual, expect;

printBugNumber(BUGNUMBER);
printStatus(summary);

/**************
 * BEGIN TEST *
 **************/

function range(begin, end) {
  for (let i = begin; i < end; ++i) {
    yield i;
  }
}
var evens = [i for (i in range(0, 21)) if (i % 2 == 0)];

reportCompare("object", typeof evens, summary);
reportCompare("0,2,4,6,8,10,12,14,16,18,20", "" + evens, summary);


text:
import {Component, Input, Output, EventEmitter, OnChanges} from '@angular/core';

@Component({
    selector: 'trigger-filter',
    styleUrls: ['./trigger-filter.component.less'],
    templateUrl: './trigger-filter.component.html'
})
export class TriggerFilterComponent implements OnChanges {
    @Input() message: string;
    @Input() filterBy: string;

    @Output() filter: EventEmitter<any> = new EventEmitter();

    ngOnChanges(): void {

    }

    handleClick(): void {
        this.filter.emit({
            filterBy: this.filterBy
        });
    }
}


text:
import re
import json
from argparse import ArgumentTypeError, FileType

from . import PY3

RE_ASCII = re.compile(r'^[a-zA-Z0-9:_.-]+$')
RE_UUID = re.compile(r'^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$')

if PY3:
    long_int = int
else:
    long_int = long

def t_int(value):
    """Integer validator"""
    try:
        return str(long_int(value))
    except (TypeError, ValueError):
        raise ArgumentTypeError('Invalid number: "%s"' % value)

def t_ascii(value):
    """Ascii validator"""
    if RE_ASCII.match(value):
        return value

    raise ArgumentTypeError('Invalid parameter: "%s"' % value)

def t_uuid(value):
    """UUID validator"""
    if RE_UUID.match(value):
        return value

    raise ArgumentTypeError('Invalid uuid: "%s"' % value)

def t_file(value):
    fp = filter(None, value.split('/'))

    try:
        map(t_ascii, fp)
    except ArgumentTypeError:
        pass

    return value

def t_dataset(value):
    """Dataset validator"""
    ds = value.split('/')

    if len(ds) > 1:
        try:
            map(t_ascii, ds)
        except ArgumentTypeError:
            pass
        else:
            return value

    raise ArgumentTypeError('Invalid dataset: "%s"' % value)

def t_python_fun(string):
    """Return imported python function"""
    try:
        string = string.strip()
        x = string.split(':')
        mod_name, fun_name = x[0], x[1]
        fun_args = tuple(x[2:])
    except (IndexError, ValueError):
        raise ArgumentTypeError('Invalid value: "%s"' % string)

    try:
        mod = __import__(mod_name, fromlist=(fun_name,))
        fun = getattr(mod, fun_name)
    except (AttributeError, ImportError) as exc:
        raise ArgumentTypeError('Cannot import "%s": %s' % (string, exc))

    fun.orig_name = string
    fun.args = fun_args

    return fun

class JSONFileType(FileType):
    """Return loaded json from file"""
    def __call__(self, filename):
        fp = super(JSONFileType, self).__call__(filename)

        # noinspection PyBroadException
        try:
            return json.loads(fp.read())
        except (IOError, OSError):
            msg = 'Could not read file'
        except Exception:
            msg = 'Invalid json'

        raise ArgumentTypeError(msg)