text:
"""Keras implementation of StableDiffusion.

Credits:

- Original implementation: https://github.com/CompVis/stable-diffusion
- Initial TF/Keras port: https://github.com/divamgupta/stable-diffusion-tensorflow

The current implementation is a rewrite of the initial TF/Keras port by Divam Gupta.
"""

import math

import numpy as np
import tensorflow as tf
from tensorflow import keras

from keras_cv.models.stable_diffusion.clip_tokenizer import SimpleTokenizer
from keras_cv.models.stable_diffusion.constants import _ALPHAS_CUMPROD
from keras_cv.models.stable_diffusion.constants import _UNCONDITIONAL_TOKENS
from keras_cv.models.stable_diffusion.decoder import Decoder
from keras_cv.models.stable_diffusion.diffusion_model import DiffusionModel
from keras_cv.models.stable_diffusion.image_encoder import ImageEncoder
from keras_cv.models.stable_diffusion.text_encoder import TextEncoder

MAX_PROMPT_LENGTH = 77

class StableDiffusion:
    """Keras implementation of Stable Diffusion.

    Note that the StableDiffusion API, as well as the APIs of the sub-components
    of StableDiffusion (e.g. ImageEncoder, DiffusionModel) should be considered
    unstable at this point. We do not guarantee backwards compatability for
    future changes to these APIs.

    Stable Diffusion is a powerful image generation model that can be used,
    among other things, to generate pictures according to a short text description
    (called a "prompt").

    Arguments:
        img_height: Height of the images to generate, in pixel. Note that only
            multiples of 128 are supported; the value provided will be rounded
            to the nearest valid value. Default: 512.
        img_width: Width of the images to generate, in pixel. Note that only
            multiples of 128 are supported; the value provided will be rounded
            to the nearest valid value. Default: 512.
        jit_compile: Whether to compile the underlying models to XLA.
            This can lead to a significant speedup on some systems. Default: False.

    Example:

    ```python
    from keras_cv.models import StableDiffusion
    from PIL import Image

    model = StableDiffusion(img_height=512, img_width=512, jit_compile=True)
    img = model.text_to_image(
        prompt="A beautiful horse running through a field",
        batch_size=1,  # How many images to generate at once
        num_steps=25,  # Number of iterations (controls image quality)
        seed=123,  # Set this to always get the same image from the same prompt
    )
    Image.fromarray(img[0]).save("horse.png")
    print("saved at horse.png")
    ```

    References:

    - [About Stable Diffusion](https://stability.ai/blog/stable-diffusion-announcement)
    - [Original implementation](https://github.com/CompVis/stable-diffusion)
    """

    def __init__(
        self,
        img_height=512,
        img_width=512,
        jit_compile=False,
    ):
        # UNet requires multiples of 2**7 = 128
        img_height = round(img_height / 128) * 128
        img_width = round(img_width / 128) * 128
        self.img_height = img_height
        self.img_width = img_width

        # lazy initialize the component models and the tokenizer
        self._image_encoder = None
        self._text_encoder = None
        self._diffusion_model = None
        self._decoder = None
        self._tokenizer = None

        self.jit_compile = jit_compile

        print(
            "By using this model checkpoint, you acknowledge that its usage is "
            "subject to the terms of the CreativeML Open RAIL-M license at "
            "https://raw.githubusercontent.com/CompVis/stable-diffusion/main/LICENSE"
        )

    def text_to_image(
        self,
        prompt,
        batch_size=1,
        num_steps=25,
        unconditional_guidance_scale=7.5,
        seed=None,
    ):
        encoded_text = self.encode_text(prompt)

        return self.generate_image(
            encoded_text,
            batch_size=batch_size,
            num_steps=num_steps,
            unconditional_guidance_scale=unconditional_guidance_scale,
            seed=seed,
        )

    def encode_text(self, prompt):
        """Encodes a prompt into a latent text encoding.

        The encoding produced by this method should be used as the
        `encoded_text` parameter of `StableDiffusion.generate_image`. Encoding
        text separately from generating an image can be used to arbitrarily
        modify the text encoding priot to image generation, e.g. for walking
        between two prompts.

        Args:
            prompt: a string to encode, must be 77 tokens or shorter.

        Example:

        ```python
        from keras_cv.models import StableDiffusion

        model = StableDiffusion(img_height=512, img_width=512, jit_compile=True)
        encoded_text  = model.encode_text("Tacos at dawn")
        img = model.generate_image(encoded_text)
        ```
        """
        # Tokenize prompt (i.e. starting context)
        inputs = self.tokenizer.encode(prompt)
        if len(inputs) > MAX_PROMPT_LENGTH:
            raise ValueError(
                f"Prompt is too long (should be <= {MAX_PROMPT_LENGTH} tokens)"
            )
        phrase = inputs + [49407] * (MAX_PROMPT_LENGTH - len(inputs))
        phrase = tf.convert_to_tensor([phrase], dtype=tf.int32)

        context = self.text_encoder.predict_on_batch([phrase, self._get_pos_ids()])

        return context

    def generate_image(
        self,
        encoded_text,
        batch_size=1,
        num_steps=25,
        unconditional_guidance_scale=7.5,
        diffusion_noise=None,
        seed=None,
    ):
        """Generates an image based on encoded text.

        The encoding passed to this method should be derived from
        `StableDiffusion.encode_text`.

        Args:
            encoded_text: Tensor of shape (`batch_size`, 77, 768), or a Tensor
            of shape (77, 768). When the batch axis is omitted, the same encoded
            text will be used to produce every generated image.
            batch_size: number of images to generate. Default: 1.
            num_steps: number of diffusion steps (controls image quality).
                Default: 25.
            unconditional_guidance_scale: float controling how closely the image
                should adhere to the prompt. Larger values result in more
                closely adhering to the prompt, but will make the image noisier.
                Default: 7.5.
            diffusion_noise: Tensor of shape (`batch_size`, img_height // 8,
                img_width // 8, 4), or a Tensor of shape (img_height // 8,
                img_width // 8, 4). Optional custom noise to seed the diffusion
                process. When the batch axis is omitted, the same noise will be
                used to seed diffusion for every generated image.
            seed: integer which is used to seed the random generation of
                diffusion noise, only to be specified if `diffusion_noise` is
                None.

        Example:

        ```python
        from keras_cv.models import StableDiffusion

        batch_size = 8
        model = StableDiffusion(img_height=512, img_width=512, jit_compile=True)
        e_tacos = model.encode_text("Tacos at dawn")
        e_watermelons = model.encode_text("Watermelons at dusk")

        e_interpolated = tf.linspace(e_tacos, e_watermelons, batch_size)
        images = model.generate_image(e_interpolated, batch_size=batch_size)
        ```
        """
        if diffusion_noise is not None and seed is not None:
            raise ValueError(
                "`diffusion_noise` and `seed` should not both be passed to "
                "`generate_image`. `seed` is only used to generate diffusion "
                "noise when it's not already user-specified."
            )

        encoded_text = tf.squeeze(encoded_text)
        if encoded_text.shape.rank == 2:
            encoded_text = tf.repeat(
                tf.expand_dims(encoded_text, axis=0), batch_size, axis=0
            )

        context = encoded_text
        unconditional_context = tf.repeat(
            self._get_unconditional_context(), batch_size, axis=0
        )

        if diffusion_noise is not None:
            diffusion_noise = tf.squeeze(diffusion_noise)
            if diffusion_noise.shape.rank == 3:
                diffusion_noise = tf.repeat(
                    tf.expand_dims(diffusion_noise, axis=0), batch_size, axis=0
                )
            latent = diffusion_noise
        else:
            latent = self._get_initial_diffusion_noise(batch_size, seed)

        # Iterative reverse diffusion stage
        timesteps = tf.range(1, 1000, 1000 // num_steps)
        alphas, alphas_prev = self._get_initial_alphas(timesteps)
        progbar = keras.utils.Progbar(len(timesteps))
        iteration = 0
        for index, timestep in list(enumerate(timesteps))[::-1]:
            latent_prev = latent  # Set aside the previous latent vector
            t_emb = self._get_timestep_embedding(timestep, batch_size)
            unconditional_latent = self.diffusion_model.predict_on_batch(
                [latent, t_emb, unconditional_context]
            )
            latent = self.diffusion_model.predict_on_batch([latent, t_emb, context])
            latent = unconditional_latent + unconditional_guidance_scale * (
                latent - unconditional_latent
            )
            a_t, a_prev = alphas[index], alphas_prev[index]
            pred_x0 = (latent_prev - math.sqrt(1 - a_t) * latent) / math.sqrt(a_t)
            latent = latent * math.sqrt(1.0 - a_prev) + math.sqrt(a_prev) * pred_x0
            iteration += 1
            progbar.update(iteration)

        # Decoding stage
        decoded = self.decoder.predict_on_batch(latent)
        decoded = ((decoded + 1) / 2) * 255
        return np.clip(decoded, 0, 255).astype("uint8")

    def inpaint(
        self,
        prompt,
        image,
        mask,
        num_resamples=1,
        batch_size=1,
        num_steps=25,
        unconditional_guidance_scale=7.5,
        diffusion_noise=None,
        seed=None,
        verbose=True,
    ):
        """Inpaints a masked section of the provided image based on the provided prompt.

        Args:
            prompt: A string representing the prompt for generation.
            image: Tensor of shape (`batch_size`, `image_height`, `image_width`,
                3) with RGB values in [0, 255]. When the batch is omitted, the same
                image will be used as the starting image.
            mask: Tensor of shape (`batch_size`, `image_height`, `image_width`)
                with binary values 0 or 1. When the batch is omitted, the same mask
                will be used on all images.
            num_resamples: number of times to resample the generated mask region.
                Increasing the number of resamples improves the semantic fit of the
                generated mask region w.r.t the rest of the image. Default: 1.
            batch_size: number of images to generate. Default: 1.
            num_steps: number of diffusion steps (controls image quality).
                Default: 25.
            unconditional_guidance_scale: float controlling how closely the image
                should adhere to the prompt. Larger values result in more
                closely adhering to the prompt, but will make the image noisier.
                Default: 7.5.
            diffusion_noise: (Optional) Tensor of shape (`batch_size`,
                img_height // 8, img_width // 8, 4), or a Tensor of shape
                (img_height // 8, img_width // 8, 4). Optional custom noise to
                seed the diffusion process. When the batch axis is omitted, the
                same noise will be used to seed diffusion for every generated image.
            seed: (Optional) integer which is used to seed the random generation of
                diffusion noise, only to be specified if `diffusion_noise` is None.
            verbose: whether to print progress bar. Default: True.
        """
        if diffusion_noise is not None and seed is not None:
            raise ValueError(
                "Please pass either diffusion_noise or seed to inpaint(), seed "
                "is only used to generate diffusion noise when it is not provided. "
                "Received both diffusion_noise and seed."
            )

        encoded_text = self.encode_text(prompt)
        encoded_text = tf.squeeze(encoded_text)
        if encoded_text.shape.rank == 2:
            encoded_text = tf.repeat(
                tf.expand_dims(encoded_text, axis=0), batch_size, axis=0
            )

        image = tf.squeeze(image)
        image = tf.cast(image, dtype=tf.float32) / 255.0 * 2.0 - 1.0
        image = tf.expand_dims(image, axis=0)
        known_x0 = self.image_encoder(image)
        if image.shape.rank == 3:
            known_x0 = tf.repeat(known_x0, batch_size, axis=0)

        mask = tf.expand_dims(mask, axis=-1)
        mask = tf.cast(
            tf.nn.max_pool2d(mask, ksize=8, strides=8, padding="SAME"),
            dtype=tf.float32,
        )
        mask = tf.squeeze(mask)
        if mask.shape.rank == 2:
            mask = tf.repeat(tf.expand_dims(mask, axis=0), batch_size, axis=0)
        mask = tf.expand_dims(mask, axis=-1)

        context = encoded_text
        unconditional_context = tf.repeat(
            self._get_unconditional_context(), batch_size, axis=0
        )

        if diffusion_noise is not None:
            diffusion_noise = tf.squeeze(diffusion_noise)
            if diffusion_noise.shape.rank == 3:
                diffusion_noise = tf.repeat(
                    tf.expand_dims(diffusion_noise, axis=0), batch_size, axis=0
                )
            latent = diffusion_noise
        else:
            latent = self._get_initial_diffusion_noise(batch_size, seed)

        # Iterative reverse diffusion stage
        timesteps = tf.range(1, 1000, 1000 // num_steps)
        alphas, alphas_prev = self._get_initial_alphas(timesteps)
        if verbose:
            progbar = keras.utils.Progbar(len(timesteps))
            iteration = 0

        for index, timestep in list(enumerate(timesteps))[::-1]:
            a_t, a_prev = alphas[index], alphas_prev[index]
            latent_prev = latent  # Set aside the previous latent vector
            t_emb = self._get_timestep_embedding(timestep, batch_size)

            for resample_index in range(num_resamples):
                unconditional_latent = self.diffusion_model.predict_on_batch(
                    [latent, t_emb, unconditional_context]
                )
                latent = self.diffusion_model.predict_on_batch([latent, t_emb, context])
                latent = unconditional_latent + unconditional_guidance_scale * (
                    latent - unconditional_latent
                )
                pred_x0 = (latent_prev - math.sqrt(1 - a_t) * latent) / math.sqrt(a_t)
                latent = latent * math.sqrt(1.0 - a_prev) + math.sqrt(a_prev) * pred_x0

                # Use known image (x0) to compute latent
                if timestep > 1:
                    noise = tf.random.normal(tf.shape(known_x0), seed=seed)
                else:
                    noise = 0.0
                known_latent = (
                    math.sqrt(a_prev) * known_x0 + math.sqrt(1 - a_prev) * noise
                )
                # Use known latent in unmasked regions
                latent = mask * known_latent + (1 - mask) * latent
                # Resample latent
                if resample_index < num_resamples - 1 and timestep > 1:
                    beta_prev = 1 - (a_t / a_prev)
                    latent_prev = tf.random.normal(
                        tf.shape(latent),
                        mean=latent * math.sqrt(1 - beta_prev),
                        stddev=math.sqrt(beta_prev),
                        seed=seed,
                    )

            if verbose:
                iteration += 1
                progbar.update(iteration)

        # Decoding stage
        decoded = self.decoder.predict_on_batch(latent)
        decoded = ((decoded + 1) / 2) * 255
        return np.clip(decoded, 0, 255).astype("uint8")

    def _get_unconditional_context(self):
        unconditional_tokens = tf.convert_to_tensor(
            [_UNCONDITIONAL_TOKENS], dtype=tf.int32
        )
        unconditional_context = self.text_encoder.predict_on_batch(
            [unconditional_tokens, self._get_pos_ids()]
        )

        return unconditional_context

    @property
    def image_encoder(self):
        """image_encoder returns the VAE Encoder with pretrained weights.

        Usage:
        ```python
        sd = keras_cv.models.StableDiffusion()
        my_image = np.ones((512, 512, 3))
        latent_representation = sd.image_encoder.predict(my_image)
        ```
        """
        if self._image_encoder is None:
            self._image_encoder = ImageEncoder(self.img_height, self.img_width)
            if self.jit_compile:
                self._image_encoder.compile(jit_compile=True)
        return self._image_encoder

    @property
    def text_encoder(self):
        """text_encoder returns the text encoder with pretrained weights.
        Can be overriden for tasks like textual inversion where the text encoder
        needs to be modified.
        """
        if self._text_encoder is None:
            self._text_encoder = TextEncoder(MAX_PROMPT_LENGTH)
            if self.jit_compile:
                self._text_encoder.compile(jit_compile=True)
        return self._text_encoder

    @property
    def diffusion_model(self):
        """diffusion_model returns the diffusion model with pretrained weights.
        Can be overriden for tasks where the diffusion model needs to be modified.
        """
        if self._diffusion_model is None:
            self._diffusion_model = DiffusionModel(
                self.img_height, self.img_width, MAX_PROMPT_LENGTH
            )
            if self.jit_compile:
                self._diffusion_model.compile(jit_compile=True)
        return self._diffusion_model

    @property
    def decoder(self):
        """decoder returns the diffusion image decoder model with pretrained weights.
        Can be overriden for tasks where the decoder needs to be modified.
        """
        if self._decoder is None:
            self._decoder = Decoder(self.img_height, self.img_width)
            if self.jit_compile:
                self._decoder.compile(jit_compile=True)
        return self._decoder

    @property
    def tokenizer(self):
        """tokenizer returns the tokenizer used for text inputs.
        Can be overriden for tasks like textual inversion where the tokenizer needs to be modified.
        """
        if self._tokenizer is None:
            self._tokenizer = SimpleTokenizer()
        return self._tokenizer

    def _get_timestep_embedding(self, timestep, batch_size, dim=320, max_period=10000):
        half = dim // 2
        freqs = tf.math.exp(
            -math.log(max_period) * tf.range(0, half, dtype=tf.float32) / half
        )
        args = tf.convert_to_tensor([timestep], dtype=tf.float32) * freqs
        embedding = tf.concat([tf.math.cos(args), tf.math.sin(args)], 0)
        embedding = tf.reshape(embedding, [1, -1])
        return tf.repeat(embedding, batch_size, axis=0)

    def _get_initial_alphas(self, timesteps):
        alphas = [_ALPHAS_CUMPROD[t] for t in timesteps]
        alphas_prev = [1.0] + alphas[:-1]

        return alphas, alphas_prev

    def _get_initial_diffusion_noise(self, batch_size, seed):
        if seed is not None:
            return tf.random.stateless_normal(
                (batch_size, self.img_height // 8, self.img_width // 8, 4),
                seed=[seed, seed],
            )
        else:
            return tf.random.normal(
                (batch_size, self.img_height // 8, self.img_width // 8, 4)
            )

    @staticmethod
    def _get_pos_ids():
        return tf.convert_to_tensor([list(range(MAX_PROMPT_LENGTH))], dtype=tf.int32)


text:
import { BaseDataSourceOptions } from "../data-source/BaseDataSourceOptions"

/**
 * BaseConnectionOptions is set of connection options shared by all database types.
 *
 * @deprecated
 */
export type BaseConnectionOptions = BaseDataSourceOptions

redpajama_set_name: RedPajamaGithub


text:
<?php
namespace App\DTO\DownloadDTO;
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of RecipeItemRestoreDto
 *
 * @author niteen
 */
class RecipeItemRestoreDto {

    public $itemId;
    public $menuQty;
    public $itemQty;
    public $factor;

    public function __construct($itemId = null, $mQty = null, $iQty = null, $factor = null) {
        $this->itemId = $itemId;
        $this->menuQty = $mQty;
        $this->itemQty = $iQty;
        $this->factor = $factor;
    }
}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Windows.Devices.Enumeration;
using Windows.Foundation;
using Windows.Graphics.Display;
using Windows.Graphics.Imaging;
using Windows.Media.Capture;
using Windows.Media.Devices;
using Windows.Media.MediaProperties;
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media.Imaging;
using Panel = Windows.Devices.Enumeration.Panel;

namespace Shield.Services //CUT this down
{
    public class Camera
    {
        public enum CameraResolutionFormat
        {
            Unknown = -1,

            FourByThree = 0,

            SixteenByNine = 1
        }

        public enum DisplayAspectRatio
        {
            Unknown = -1,

            FifteenByNine = 0,

            SixteenByNine = 1
        }

        public MediaCapture captureManager;
        public bool isAutoFocus = false;
        public bool isPreviewing;

        public async Task InitializePreview(CaptureElement captureElement)
        {
            captureManager = new MediaCapture();

            var cameraID = await GetCameraID(Panel.Back);

            if (cameraID == null)
            {
                return;
            }

            await captureManager.InitializeAsync(new MediaCaptureInitializationSettings
            {
                StreamingCaptureMode = StreamingCaptureMode.Video,
                PhotoCaptureSource = PhotoCaptureSource.Photo,
                AudioDeviceId = string.Empty,
                VideoDeviceId = cameraID.Id
            });

            await
                captureManager.VideoDeviceController.SetMediaStreamPropertiesAsync(MediaStreamType.Photo,
                    maxResolution());

            captureManager.SetPreviewRotation(VideoRotation.Clockwise90Degrees);

            StartPreview(captureElement);
        }

        private async void StartPreview(CaptureElement captureElement)
        {
            captureElement.Visibility = Visibility.Visible;
            captureElement.Source = captureManager;

            await captureManager.StartPreviewAsync();

            isPreviewing = true;

            if (GetDisplayAspectRatio() == DisplayAspectRatio.FifteenByNine)
            {
                GetFifteenByNineBounds();
            }
        }

        private DisplayAspectRatio GetDisplayAspectRatio()
        {
            var result = DisplayAspectRatio.Unknown;

            //WP8.1 uses logical pixel dimensions, we need to convert this to raw pixel dimensions
            var logicalPixelWidth = Window.Current.Bounds.Width;
            var logicalPixelHeight = Window.Current.Bounds.Height;

            var rawPerViewPixels = DisplayInformation.GetForCurrentView().RawPixelsPerViewPixel;
            var rawPixelHeight = logicalPixelHeight*rawPerViewPixels;
            var rawPixelWidth = logicalPixelWidth*rawPerViewPixels;

            //calculate and return screen format
            var relation = Math.Max(rawPixelWidth, rawPixelHeight)/Math.Min(rawPixelWidth, rawPixelHeight);
            if (Math.Abs(relation - (15.0/9.0)) < 0.01)
            {
                result = DisplayAspectRatio.FifteenByNine;
            }
            else if (Math.Abs(relation - (16.0/9.0)) < 0.01)
            {
                result = DisplayAspectRatio.SixteenByNine;
            }

            return result;
        }

        /// <summary>
        ///     Helper to get the correct Bounds for 15:9 screens and to set finalPhotoAreaBorder values
        /// </summary>
        /// <returns></returns>
        private BitmapBounds GetFifteenByNineBounds()
        {
            var bounds = new BitmapBounds();

            //image size is raw pixels, so we need also here raw pixels
            var logicalPixelWidth = Window.Current.Bounds.Width;
            var logicalPixelHeight = Window.Current.Bounds.Height;

            var rawPerViewPixels = DisplayInformation.GetForCurrentView().RawPixelsPerViewPixel;
            var rawPixelHeight = logicalPixelHeight*rawPerViewPixels;
            var rawPixelWidth = logicalPixelWidth*rawPerViewPixels;

            //calculate scale factor of UniformToFill Height (remember, we rotated the preview)
            var scaleFactorVisualHeight = maxResolution().Width/rawPixelHeight;

            //calculate the visual Width
            //(because UniFormToFill scaled the previewElement Width down to match the previewElement Height)
            var visualWidth = maxResolution().Height/scaleFactorVisualHeight;

            //calculate cropping area for 15:9
            var scaledBoundsWidth = maxResolution().Height;
            var scaledBoundsHeight = (scaledBoundsWidth/9)*15;

            //we are starting at the top of the image
            bounds.Y = 0;
            //cropping the image width
            bounds.X = 0;
            bounds.Height = scaledBoundsHeight;
            bounds.Width = scaledBoundsWidth;

            //set finalPhotoAreaBorder values that shows the user the area that is captured
            //finalPhotoAreaBorder.Width = (scaledBoundsWidth / scaleFactorVisualHeight) / rawPerViewPixels;
            //finalPhotoAreaBorder.Height = (scaledBoundsHeight / scaleFactorVisualHeight) / rawPerViewPixels;
            //finalPhotoAreaBorder.Margin = new Thickness(
            //                                Math.Floor(((rawPixelWidth - visualWidth) / 2) / rawPerViewPixels),
            //                                0,
            //                                Math.Floor(((rawPixelWidth - visualWidth) / 2) / rawPerViewPixels),
            //                                0);
            //finalPhotoAreaBorder.Visibility = Visibility.Visible;

            return bounds;
        }

        private static async Task<DeviceInformation> GetCameraID(Panel camera)
        {
            var deviceID = (await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture))
                .FirstOrDefault(x => x.EnclosureLocation != null && x.EnclosureLocation.Panel == camera);

            return deviceID;
        }

        private CameraResolutionFormat MatchScreenFormat(Size resolution)
        {
            var result = CameraResolutionFormat.Unknown;

            var relation = Math.Max(resolution.Width, resolution.Height)/Math.Min(resolution.Width, resolution.Height);
            if (Math.Abs(relation - (4.0/3.0)) < 0.01)
            {
                result = CameraResolutionFormat.FourByThree;
            }
            else if (Math.Abs(relation - (16.0/9.0)) < 0.01)
            {
                result = CameraResolutionFormat.SixteenByNine;
            }

            return result;
        }

        private VideoEncodingProperties maxResolution()
        {
            VideoEncodingProperties resolutionMax = null;

            //get all photo properties
            var resolutions =
                captureManager.VideoDeviceController.GetAvailableMediaStreamProperties(MediaStreamType.Photo);

            //generate new list to work with
            var vidProps = new List<VideoEncodingProperties>();

            //add only those properties that are 16:9 to our own list
            for (var i = 0; i < resolutions.Count; i++)
            {
                var res = (VideoEncodingProperties) resolutions[i];

                if (MatchScreenFormat(new Size(res.Width, res.Height)) != CameraResolutionFormat.FourByThree)
                {
                    vidProps.Add(res);
                }
            }

            //order the list, and select the highest resolution that fits our limit
            if (vidProps.Count != 0)
            {
                vidProps = vidProps.OrderByDescending(r => r.Width).ToList();

                resolutionMax = vidProps.Where(r => r.Width < 2600).First();
            }

            return resolutionMax;
        }

        public async Task<StorageFile> Capture(string imageName)
        {
            return await CapturePreviewWithoutModifications(imageName);
        }

        private async Task<StorageFile> CapturePreviewWithoutModifications(string imageName)
        {
            //declare image format
            var format = ImageEncodingProperties.CreateJpeg();

            //generate file in local folder:
            //StorageFile capturefile = await ApplicationData.Current.LocalFolder.CreateFileAsync("photo_" + DateTime.Now.Ticks.ToString(), CreationCollisionOption.ReplaceExisting);
            var capturefile =
                await KnownFolders.CameraRoll.CreateFileAsync(imageName, CreationCollisionOption.ReplaceExisting);

            //take & save photo
            await captureManager.CapturePhotoToStorageFileAsync(format, capturefile);

            //show captured photo
            var img = new BitmapImage(new Uri(capturefile.Path));

            //canvasBackground.Source = img;
            //takenImage.Visibility = Visibility.Visible;

            //return img;
            return capturefile;
        }

        private async void CaptureSixteenByNineImage()
        {
            //declare string for filename
            var captureFileName = string.Empty;
            //declare image format
            var format = ImageEncodingProperties.CreateJpeg();

            //rotate and save the image
            using (var imageStream = new InMemoryRandomAccessStream())
            {
                //generate stream from MediaCapture
                await captureManager.CapturePhotoToStreamAsync(format, imageStream);

                //create decoder and encoder
                var dec = await BitmapDecoder.CreateAsync(imageStream);
                var enc = await BitmapEncoder.CreateForTranscodingAsync(imageStream, dec);

                //roate the image
                enc.BitmapTransform.Rotation = BitmapRotation.Clockwise90Degrees;

                //write changes to the image stream
                await enc.FlushAsync();

                //save the image
                var folder = KnownFolders.SavedPictures;
                var capturefile =
                    await
                        folder.CreateFileAsync("photo_" + DateTime.Now.Ticks + ".jpg",
                            CreationCollisionOption.ReplaceExisting);
                captureFileName = capturefile.Name;

                //store stream in file
                using (var fileStream = await capturefile.OpenStreamForWriteAsync())
                {
                    try
                    {
                        //because of using statement stream will be closed automatically after copying finished
                        await RandomAccessStream.CopyAsync(imageStream, fileStream.AsOutputStream());
                    }
                    catch
                    {
                    }
                }
            }
            CleanCapture();

            //load saved image
            //LoadCapturedphoto(captureFileName);
        }

        private async void CleanCapture()
        {
            if (captureManager != null)
            {
                if (isPreviewing)
                {
                    await captureManager.StopPreviewAsync();
                    isPreviewing = false;
                }
                captureManager.Dispose();

                //previewElement.Source = null;
                //previewElement.Visibility = Visibility.Collapsed;
                //takenImage.Source = null;
                //takenImage.Visibility = Visibility.Collapsed;
                //captureButton.Content = "capture";
            }
        }
    }
}


text:
package com.intellij.formatting;

import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;

public class AlignmentImpl extends Alignment {
  private static final List<LeafBlockWrapper> EMPTY = Collections.emptyList();
  private final boolean myAllowBackwardShift;
  private final Anchor myAnchor;
  private List<LeafBlockWrapper> myOffsetRespBlocks = EMPTY;
  private AlignmentImpl myParentAlignment;
  private ProbablyIncreasingLowerboundAlgorithm<LeafBlockWrapper> myOffsetRespBlocksCalculator;

  AlignmentImpl() {
    this(false, Anchor.LEFT);
  }

  AlignmentImpl(boolean allowBackwardShift, @NotNull Anchor anchor) {
    myAllowBackwardShift = allowBackwardShift;
    myAnchor = anchor;
    myOffsetRespBlocksCalculator = new ProbablyIncreasingLowerboundAlgorithm<>(myOffsetRespBlocks);
  }

  public boolean isAllowBackwardShift() {
    return myAllowBackwardShift;
  }

  @NotNull
  public Anchor getAnchor() {
    return myAnchor;
  }

  public String getId() {
    return String.valueOf(System.identityHashCode(this));
  }

  public void reset() {
    if (myOffsetRespBlocks != EMPTY) {
      myOffsetRespBlocks.clear();
    }
    myOffsetRespBlocksCalculator.reset();
  }

  public void setParent(final Alignment base) {
    myParentAlignment = (AlignmentImpl)base;
  }

  /**
   * Selects target wrapped block by the following algorithm:
   *

   *

   *      Filter blocks registered via {@link #setOffsetRespBlock(LeafBlockWrapper)} in order to process only those that start
   *      before the given block (blocks which start offset is lower than start offset of the given block).
   *

   *

   *      Try to find out result from those filtered blocks using the following algorithm:
   *

   *

   *            Use the last block (block which has the greatest start offset) after the block which
   *            {@link AbstractBlockWrapper#getWhiteSpace() white space} contains line feeds;
   *

   *

   *            Use the first block (block with the smallest start offset) if no block can be selected using the rule above;
   *

   *

   *            Use the last block (block with the greatest start offset) if no block can be selected using the rules above;
   *

   *

   *

   *

   *      Delegate the task to the {@link #setParent(Alignment) parent alignment} (if it's registered) if no blocks
   *      are configured for the current one;
   *

   *

   *
   * @param block     target block to use during blocks filtering
   * @return          block {@link #setOffsetRespBlock(LeafBlockWrapper) registered} for the current alignment object or
   *                  {@link #setParent(Alignment) its parent} using the algorithm above if any; {@code null} otherwise
   */
  @Nullable
  public LeafBlockWrapper getOffsetRespBlockBefore(@Nullable final AbstractBlockWrapper block) {
    if (!continueOffsetResponsibleBlockRetrieval(block)) {
      return null;
    }

    LeafBlockWrapper result = null;
    final List<LeafBlockWrapper> leftBlocks = myOffsetRespBlocksCalculator.getLeftSubList(block);
    if (!leftBlocks.isEmpty()) {
      result = leftBlocks.get(0);
    }

    if (result == null && myParentAlignment != null) {
      return myParentAlignment.getOffsetRespBlockBefore(block);
    }
    else {
      return result;
    }
  }

  /**
   * Registers wrapped block within the current alignment in order to use it for further
   * {@link #getOffsetRespBlockBefore(AbstractBlockWrapper)} calls processing.
   *
   * @param block   wrapped block to register within the current alignment object
   */
  public void setOffsetRespBlock(final LeafBlockWrapper block) {
    if (block == null) {
      return;
    }
    if (myOffsetRespBlocks == EMPTY) {
      myOffsetRespBlocks = new ArrayList<>(1);
      myOffsetRespBlocksCalculator.setBlocksList(myOffsetRespBlocks);
    }
    myOffsetRespBlocks.add(block);
  }

  public Set<LeafBlockWrapper> getOffsetResponsibleBlocks() {
    return ContainerUtil.newHashSet(myOffsetRespBlocks);
  }

  @NotNull
  private static AbstractBlockWrapper extendBlockFromStart(@NotNull AbstractBlockWrapper block) {
    while (true) {
      AbstractBlockWrapper parent = block.getParent();
      if (parent != null && parent.getStartOffset() == block.getStartOffset()) {
        block = parent;
      }
      else {
        return block;
      }
    }
  }

  @NotNull
  private static AbstractBlockWrapper extendBlockFromEnd(@NotNull AbstractBlockWrapper block) {
    while (true) {
      AbstractBlockWrapper parent = block.getParent();
      if (parent != null && parent.getEndOffset() == block.getEndOffset()) {
        block = parent;
      }
      else {
        return block;
      }
    }
  }

  private boolean continueOffsetResponsibleBlockRetrieval(@Nullable AbstractBlockWrapper block) {
    // We don't want to align block that doesn't start new line if it's not configured for 'by columns' alignment.
    if (!myAllowBackwardShift && block != null && !block.getWhiteSpace().containsLineFeeds()) {
      return false;
    }

    if (block != null) {
      AbstractBlockWrapper prevAlignBlock = myOffsetRespBlocksCalculator.getLeftRespNeighbor(block);
      if (!onDifferentLines(prevAlignBlock, block)) {
        return false;
      }

      //blocks are on different lines
      if (myAllowBackwardShift
          && myAnchor == Anchor.RIGHT
          && prevAlignBlock != null
          && prevAlignBlock.getWhiteSpace().containsLineFeeds() // {prevAlignBlock} starts new indent => can be moved
      ) {
        // extend block on position for right align
        prevAlignBlock = extendBlockFromStart(prevAlignBlock);

        AbstractBlockWrapper current = block;
        do {
          if (current.getStartOffset() < prevAlignBlock.getEndOffset()) {
            return false; //{prevAlignBlock{current}} | {current}{prevAlignBlock}, no new lines
          }
          if (current.getWhiteSpace().containsLineFeeds()) {
            break; // correct new line was found
          }
          else {
            AbstractBlockWrapper prev = current.getPreviousBlock();
            if (prev != null) {
                prev = extendBlockFromEnd(prev);
            }
            current = prev;
          }
        } while (current != null);
        if (current == null) {
          return false; //root block is the top
        }
      }
    }
    return myParentAlignment == null || myParentAlignment.continueOffsetResponsibleBlockRetrieval(block);
  }

  private static boolean onDifferentLines(AbstractBlockWrapper block1, AbstractBlockWrapper block2) {
    if (block1 == null || block2 == null) {
      return true;
    }

    AbstractBlockWrapper leftBlock = block1.getStartOffset() <= block2.getStartOffset() ? block1 : block2;
    AbstractBlockWrapper rightBlock = block1.getStartOffset() > block2.getStartOffset() ? block1 : block2;
    for (; rightBlock != null && rightBlock.getStartOffset() > leftBlock.getStartOffset(); rightBlock = rightBlock.getPreviousBlock()) {
      if (rightBlock.getWhiteSpace().containsLineFeeds()) {
        return true;
      }
    }
    return false;
  }

  @Override
  public String toString() {
    return "Align: " + System.identityHashCode(this) + "," +  getAnchor() +  (isAllowBackwardShift() ? "<" : "");
  }
}


text:
using FrannHammer.Domain.Contracts;
using FrannHammer.Utility;
using FrannHammer.WebScraping.Contracts.Moves;
using FrannHammer.WebScraping.Domain.Contracts;
using HtmlAgilityPack;
using System;
using System.Collections.Generic;

namespace FrannHammer.WebScraping.Moves
{
    public abstract class BaseMoveScraper : IMoveScraper
    {
        protected IMoveScrapingServices ScrapingServices { get; }

        public abstract Func<WebCharacter, IEnumerable<IMove>> Scrape { get; protected set; }

        protected BaseMoveScraper(IMoveScrapingServices scrapingServices)
        {
            Guard.VerifyObjectNotNull(scrapingServices, nameof(scrapingServices));
            ScrapingServices = scrapingServices;
        }

        protected abstract IMove GetMove(HtmlNodeCollection cells, WebCharacter character);

        protected static HtmlNodeCollection GetTableCells(HtmlNode row) => row.SelectNodes(ScrapingConstants.XPathTableCells);

        protected virtual IEnumerable<HtmlNode> GetTableRows(string sourceUrl, string xpath)
        {
            var htmlParser = ScrapingServices.CreateParserFromSourceUrl(sourceUrl);

            //get moves table html
            var movesTableHtml = htmlParser.GetSingle(xpath);

            var moveTableRows = HtmlNode.CreateNode(movesTableHtml)?.SelectNodes(ScrapingConstants.XPathTableRows);

            if (moveTableRows == null)
            { throw new Exception($"Error getting move table data after attempting to scrape full table using xpath: '{ScrapingConstants.XPathTableRows};"); }

            return moveTableRows;
        }

        protected static string GetStatName(HtmlNode cell)
        {
            var retVal = string.Empty;

            if (!string.IsNullOrEmpty(cell.InnerText))
            {
                retVal = cell.InnerText.Trim();
            }

            return retVal;
        }
    }
}


text:
/**
 * Bean Validation TCK
 *
 * License: Apache License, Version 2.0
 * See the license.txt file in the root directory or <http://www.apache.org/licenses/LICENSE-2.0>.
 */
package org.hibernate.beanvalidation.tck.tests.validation.graphnavigation.containerelement.model;

import javax.validation.constraints.NotNull;

public class VisitorWithGroups {

	@NotNull
	private final String name;

	@NotNull(groups = ExtendedChecks1.class)
	private final String extended1 = null;

	@NotNull(groups = ExtendedChecks2.class)
	private final String extended2 = null;

	public VisitorWithGroups(String name) {
		this.name = name;
	}
}


text:
        <form name="formArea">

                Nombre
                <input type="text" class="form-control" id="Nombre" required="required" ng-model="nombre">

                DNI
                <input type="text" class="form-control" id="id" required="required" ng-model="id">

                <input type="submit" class="btn btn-primary" ng-disabled="formArea.$invalid" value="Cargar" ng-show="!edit" ng-click="cargar()" />
                <input type="submit" class="btn btn-primary" ng-disabled="formArea.$invalid" value="Actualizar" ng-show="edit" ng-click="actualizar()" />

        </form>

Usuarios

                {{usuario.nombre}} BorrarEditar


text:
package org.jmock.test.unit.lib.legacy;

import org.jmock.imposters.ByteBuddyClassImposteriser;
import org.jmock.lib.JavaReflectionImposteriser;
import org.jmock.lib.legacy.ClassImposteriser;
import org.jmock.test.acceptance.AbstractImposteriserParameterResolver;

/**
 * Provide known instances of ClassImposteriser for tests
 *
 * @author oliverbye
 *
 */
public class ImposteriserParameterResolver extends AbstractImposteriserParameterResolver {

    public ImposteriserParameterResolver() {
        super(ByteBuddyClassImposteriser.INSTANCE,
                ClassImposteriser.INSTANCE,
                JavaReflectionImposteriser.INSTANCE);
    }

}


text:
1. [](#bugfix)
    * Fixed issue with modular Shortcode meta was not getting processed properly (Assets, Sections, etc.)

# v2.5.3
## 02/21/2017

1. [](#improved)
    * Added a reference to current Page in `ShortcodeManager`

# v2.5.2
## 01/26/2017

1. [](#bugfix)
    * Fixed Mozilla column css prefix

# v2.5.1
## 01/25/2017

1. [](#improved)
    * Added `moz-` prefix in column shortcode

# v2.5.0
## 01/25/2017

1. [](#new)
    * Added **new** `columns` shortcode for CSS columns support

# v2.4.0
## 01/17/2017

1. [](#improved)
    * Switched to `Regex` parser by default (previous was Regex)
    * Update to latest Shortcode library v0.6.5
1. [](#bugfix)
    * Removed `getParameterAt(0)` hack in favor of `getBbbCode()` that works with Regex parser

# v2.3.2
## 12/15/2016

1. [](#improved)
    * Update to latest Shortcode library v0.6.4 to address a parser bug [#25](https://github.com/getgrav/grav-plugin-shortcode-core/issues/25)

# v2.3.1
## 07/14/2016

1. [](#improved)
    * renamed internal `contentMeta` variables to `shortcodeMeta` and `shortcodeAssets`
    * Update to latest Shortcode library

# v2.3.0
## 05/20/2016

1. [](#improved)
    * Use new conentmeta approach from Grav 1.1

# v2.2.1
## 05/09/2016

1. [](#bugfix)
    * Always initialize current page even if collection exists [#3](https://github.com/getgrav/grav-plugin-shortcode-ui/issues/3)

# v2.2.0
## 04/23/2016

1. [](#new)
    * Added **new** `fa` FontAwesome shortcode

# v2.1.0
## 04/21/2016

1. [](#new)
    * Added **new** `notice` shortcode
1. [](#improved)
    * Updated to latest Shortcode library version

# v2.0.2
## 02/17/2016

1. [](#bugfix)
    * Initialized states in constructor

# v2.0.1
## 02/16/2016

1. [](#improved)
    * Support **modular** pages by populating Twig variables in `onTwigPageVariables()` event #8
1. [](#bugfix)
    * Better more flexible regex in the Markdown **block** definition for more reliable markdown in shortcodes. #3

# v2.0.0
## 02/11/2016

1. [](#new)
    * Added **new** `section` shortcode
    * Use new `contentMeta` mechanism for storing/caching objects and assets per page
    * Added new `ShortcodeManager::reset()` methods
1. [](#improved)
    * Completely refactored the plugin to use a new extensible mechanism that makes it easier to manage multiple shortcodes

# v1.4.0
## 02/03/2016

1. [](#improved)
    * Updated Shortcode to latest `dev-master` that includes Events
1. [](#bugfix)
    * Fixed `raw` shortcode to use new `FilterRawEventHandler` so it doesn't process shortcodes at all

# v1.3.0
## 01/29/2016

1. [](#improved)
    * Added markdown-shortcode-block support to the plugin
1. [](#bugfix)
    * Updated Core Thunderer Shortcode library with some important fixes

# v1.2.0
## 01/25/2016

1. [](#improved)
    * Customizable Parser.  Choose from `WordPress`, `Regex`, and `Regular`

# v1.1.0
## 01/24/2016

1. [](#improved)
    * Updated to latest Shortcode `dev-master` version that contains some important fixes
    * Switched to `WordPressParser` for 2x speed improvements

# v1.0.1
## 01/18/2016

1. [](#bugfix)
    * Fixed blueprint
    * Fixed a default yaml state

# v1.0.0
## 01/18/2016

1. [](#new)
    * ChangeLog started...


text:
package gamesoftitalia.bizbong.adapters;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import gamesoftitalia.bizbong.R;

/**
 * Created by Raffaella on 08/01/2017.
 */

public class ClassificaAdapter extends ArrayAdapter<String> {
    private final Context context;
    private final int[] punteggioClassificato;
    private final String[] nicknameClassificato, iconaProfiloClassificato;

    public ClassificaAdapter(Context context, String[] iconaProfiloClassificato, String[] nicknameClassificato, int[] punteggioClassificato) {
        super(context, R.layout.layout_classifica_list, nicknameClassificato);
        this.context = context;
        this.iconaProfiloClassificato = iconaProfiloClassificato;
        this.punteggioClassificato = punteggioClassificato;
        this.nicknameClassificato = nicknameClassificato;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View rowView = inflater.inflate(R.layout.layout_classifica_list, parent, false);
        TextView posizioneView = (TextView) rowView.findViewById(R.id.classifica_posizione);
        posizioneView.setText(String.valueOf(position+1));
        ImageView iconaProfiloImageView = (ImageView) rowView.findViewById(R.id.classifica_icona_profilo);
        TextView nicknameView = (TextView) rowView.findViewById(R.id.classifica_nickname);
        nicknameView.setText(nicknameClassificato[position]);
        TextView punteggioView = (TextView) rowView.findViewById(R.id.classifica_punteggio);
        punteggioView.setText(String.valueOf(punteggioClassificato[position]));

        // Change icon based on name
        iconaProfiloImageView.getResources().getIdentifier(iconaProfiloClassificato[position], null, context.getPackageName());

        return rowView;
    }
}


text: Documentation for OTBProject


text:
#include <aws/quicksight/model/TransformOperation.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace QuickSight
{
namespace Model
{

TransformOperation::TransformOperation() :
    m_projectOperationHasBeenSet(false),
    m_filterOperationHasBeenSet(false),
    m_createColumnsOperationHasBeenSet(false),
    m_renameColumnOperationHasBeenSet(false),
    m_castColumnTypeOperationHasBeenSet(false),
    m_tagColumnOperationHasBeenSet(false)
{
}

TransformOperation::TransformOperation(JsonView jsonValue) :
    m_projectOperationHasBeenSet(false),
    m_filterOperationHasBeenSet(false),
    m_createColumnsOperationHasBeenSet(false),
    m_renameColumnOperationHasBeenSet(false),
    m_castColumnTypeOperationHasBeenSet(false),
    m_tagColumnOperationHasBeenSet(false)
{
  *this = jsonValue;
}

TransformOperation& TransformOperation::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("ProjectOperation"))
  {
    m_projectOperation = jsonValue.GetObject("ProjectOperation");

    m_projectOperationHasBeenSet = true;
  }

  if(jsonValue.ValueExists("FilterOperation"))
  {
    m_filterOperation = jsonValue.GetObject("FilterOperation");

    m_filterOperationHasBeenSet = true;
  }

  if(jsonValue.ValueExists("CreateColumnsOperation"))
  {
    m_createColumnsOperation = jsonValue.GetObject("CreateColumnsOperation");

    m_createColumnsOperationHasBeenSet = true;
  }

  if(jsonValue.ValueExists("RenameColumnOperation"))
  {
    m_renameColumnOperation = jsonValue.GetObject("RenameColumnOperation");

    m_renameColumnOperationHasBeenSet = true;
  }

  if(jsonValue.ValueExists("CastColumnTypeOperation"))
  {
    m_castColumnTypeOperation = jsonValue.GetObject("CastColumnTypeOperation");

    m_castColumnTypeOperationHasBeenSet = true;
  }

  if(jsonValue.ValueExists("TagColumnOperation"))
  {
    m_tagColumnOperation = jsonValue.GetObject("TagColumnOperation");

    m_tagColumnOperationHasBeenSet = true;
  }

  return *this;
}

JsonValue TransformOperation::Jsonize() const
{
  JsonValue payload;

  if(m_projectOperationHasBeenSet)
  {
   payload.WithObject("ProjectOperation", m_projectOperation.Jsonize());

  }

  if(m_filterOperationHasBeenSet)
  {
   payload.WithObject("FilterOperation", m_filterOperation.Jsonize());

  }

  if(m_createColumnsOperationHasBeenSet)
  {
   payload.WithObject("CreateColumnsOperation", m_createColumnsOperation.Jsonize());

  }

  if(m_renameColumnOperationHasBeenSet)
  {
   payload.WithObject("RenameColumnOperation", m_renameColumnOperation.Jsonize());

  }

  if(m_castColumnTypeOperationHasBeenSet)
  {
   payload.WithObject("CastColumnTypeOperation", m_castColumnTypeOperation.Jsonize());

  }

  if(m_tagColumnOperationHasBeenSet)
  {
   payload.WithObject("TagColumnOperation", m_tagColumnOperation.Jsonize());

  }

  return payload;
}

} // namespace Model
} // namespace QuickSight
} // namespace Aws


text:
import { describe, it } from 'mocha';
import {
  expectPassesRule,
  expectFailsRule,
  expectFailsRuleWithSchema,
  expectPassesRuleWithSchema
} from './harness';
import {
  OverlappingFieldsCanBeMerged,
  fieldsConflictMessage,
} from '../rules/OverlappingFieldsCanBeMerged';
import {
  GraphQLSchema,
  GraphQLObjectType,
  GraphQLUnionType,
  GraphQLList,
  GraphQLNonNull,
  GraphQLInt,
  GraphQLString,
  GraphQLID,
} from '../../type';

describe('Validate: Overlapping fields can be merged', () => {

  it('unique fields', () => {
    expectPassesRule(OverlappingFieldsCanBeMerged, `
      fragment uniqueFields on Dog {
        name
        nickname
      }
    `);
  });

  it('identical fields', () => {
    expectPassesRule(OverlappingFieldsCanBeMerged, `
      fragment mergeIdenticalFields on Dog {
        name
        name
      }
    `);
  });

  it('identical fields with identical args', () => {
    expectPassesRule(OverlappingFieldsCanBeMerged, `
      fragment mergeIdenticalFieldsWithIdenticalArgs on Dog {
        doesKnowCommand(dogCommand: SIT)
        doesKnowCommand(dogCommand: SIT)
      }
    `);
  });

  it('identical fields with identical directives', () => {
    expectPassesRule(OverlappingFieldsCanBeMerged, `
      fragment mergeSameFieldsWithSameDirectives on Dog {
        name @include(if: true)
        name @include(if: true)
      }
    `);
  });

  it('different args with different aliases', () => {
    expectPassesRule(OverlappingFieldsCanBeMerged, `
      fragment differentArgsWithDifferentAliases on Dog {
        knowsSit: doesKnowCommand(dogCommand: SIT)
        knowsDown: doesKnowCommand(dogCommand: DOWN)
      }
    `);
  });

  it('different directives with different aliases', () => {
    expectPassesRule(OverlappingFieldsCanBeMerged, `
      fragment differentDirectivesWithDifferentAliases on Dog {
        nameIfTrue: name @include(if: true)
        nameIfFalse: name @include(if: false)
      }
    `);
  });

  it('Same aliases with different field targets', () => {
    expectFailsRule(OverlappingFieldsCanBeMerged, `
      fragment sameAliasesWithDifferentFieldTargets on Dog {
        fido: name
        fido: nickname
      }
    `, [
      { message: fieldsConflictMessage(
          'fido',
          'name and nickname are different fields'
        ),
        locations: [ { line: 3, column: 9 }, { line: 4, column: 9 } ] },
    ]);
  });

  it('Alias masking direct field access', () => {
    expectFailsRule(OverlappingFieldsCanBeMerged, `
      fragment aliasMaskingDirectFieldAccess on Dog {
        name: nickname
        name
      }
    `, [
      { message: fieldsConflictMessage(
          'name',
          'nickname and name are different fields'
        ),
        locations: [ { line: 3, column: 9 }, { line: 4, column: 9 } ] },
    ]);
  });

  it('conflicting args', () => {
    expectFailsRule(OverlappingFieldsCanBeMerged, `
      fragment conflictingArgs on Dog {
        doesKnowCommand(dogCommand: SIT)
        doesKnowCommand(dogCommand: HEEL)
      }
    `, [
      { message: fieldsConflictMessage(
          'doesKnowCommand',
          'they have differing arguments'
        ),
        locations: [ { line: 3, column: 9 }, { line: 4, column: 9 } ] }
    ]);
  });

  it('conflicting directives', () => {
    expectFailsRule(OverlappingFieldsCanBeMerged, `
      fragment conflictingDirectiveArgs on Dog {
        name @include(if: true)
        name @skip(if: false)
      }
    `, [
      { message: fieldsConflictMessage(
          'name',
          'they have differing directives'
        ),
        locations: [ { line: 3, column: 9 }, { line: 4, column: 9 } ] }
    ]);
  });

  it('conflicting directive args', () => {
    expectFailsRule(OverlappingFieldsCanBeMerged, `
      fragment conflictingDirectiveArgs on Dog {
        name @include(if: true)
        name @include(if: false)
      }
    `, [
      { message: fieldsConflictMessage(
          'name',
          'they have differing directives'
        ),
        locations: [ { line: 3, column: 9 }, { line: 4, column: 9 } ] }
    ]);
  });

  it('conflicting args with matching directives', () => {
    expectFailsRule(OverlappingFieldsCanBeMerged, `
      fragment conflictingArgsWithMatchingDirectiveArgs on Dog {
        doesKnowCommand(dogCommand: SIT) @include(if: true)
        doesKnowCommand(dogCommand: HEEL) @include(if: true)
      }
    `, [
      { message: fieldsConflictMessage(
          'doesKnowCommand',
          'they have differing arguments'
        ),
        locations: [ { line: 3, column: 9 }, { line: 4, column: 9 } ] }
    ]);
  });

  it('conflicting directives with matching args', () => {
    expectFailsRule(OverlappingFieldsCanBeMerged, `
      fragment conflictingDirectiveArgsWithMatchingArgs on Dog {
        doesKnowCommand(dogCommand: SIT) @include(if: true)
        doesKnowCommand(dogCommand: SIT) @skip(if: false)
      }
    `, [
      { message: fieldsConflictMessage(
          'doesKnowCommand',
          'they have differing directives'
        ),
        locations: [ { line: 3, column: 9 }, { line: 4, column: 9 } ] }
    ]);
  });

  it('encounters conflict in fragments', () => {
    expectFailsRule(OverlappingFieldsCanBeMerged, `
      {
        ...A
        ...B
      }
      fragment A on Type {
        x: a
      }
      fragment B on Type {
        x: b
      }
    `, [
      { message: fieldsConflictMessage('x', 'a and b are different fields'),
        locations: [ { line: 7, column: 9 }, { line: 10, column: 9 } ] }
    ]);
  });

  it('reports each conflict once', () => {
    expectFailsRule(OverlappingFieldsCanBeMerged, `
      {
        f1 {
          ...A
          ...B
        }
        f2 {
          ...B
          ...A
        }
        f3 {
          ...A
          ...B
          x: c
        }
      }
      fragment A on Type {
        x: a
      }
      fragment B on Type {
        x: b
      }
    `, [
      { message: fieldsConflictMessage('x', 'a and b are different fields'),
        locations: [ { line: 18, column: 9 }, { line: 21, column: 9 } ] },
      { message: fieldsConflictMessage('x', 'a and c are different fields'),
        locations: [ { line: 18, column: 9 }, { line: 14, column: 11 } ] },
      { message: fieldsConflictMessage('x', 'b and c are different fields'),
        locations: [ { line: 21, column: 9 }, { line: 14, column: 11 } ] }
    ]);
  });

  it('deep conflict', () => {
    expectFailsRule(OverlappingFieldsCanBeMerged, `
      {
        field {
          x: a
        },
        field {
          x: b
        }
      }
    `, [
      { message: fieldsConflictMessage(
          'field', [ [ 'x', 'a and b are different fields' ] ]
        ),
        locations: [
          { line: 3, column: 9 },
          { line: 6, column: 9 },
          { line: 4, column: 11 },
          { line: 7, column: 11 } ] },
    ]);
  });

  it('deep conflict with multiple issues', () => {
    expectFailsRule(OverlappingFieldsCanBeMerged, `
      {
        field {
          x: a
          y: c
        },
        field {
          x: b
          y: d
        }
      }
    `, [
      { message: fieldsConflictMessage(
          'field', [
            [ 'x', 'a and b are different fields' ],
            [ 'y', 'c and d are different fields' ]
          ]
        ),
        locations: [
          { line: 3, column: 9 },
          { line: 7, column: 9 },
          { line: 4, column: 11 },
          { line: 8, column: 11 },
          { line: 5, column: 11 },
          { line: 9, column: 11 } ] },
    ]);
  });

  it('very deep conflict', () => {
    expectFailsRule(OverlappingFieldsCanBeMerged, `
      {
        field {
          deepField {
            x: a
          }
        },
        field {
          deepField {
            x: b
          }
        }
      }
    `, [
      { message: fieldsConflictMessage(
          'field',
          [ [ 'deepField', [ [ 'x', 'a and b are different fields' ] ] ] ]
        ),
        locations: [
          { line: 3, column: 9 },
          { line: 8, column: 9 },
          { line: 4, column: 11 },
          { line: 9, column: 11 },
          { line: 5, column: 13 },
          { line: 10, column: 13 } ] },
    ]);
  });

  it('reports deep conflict to nearest common ancestor', () => {
    expectFailsRule(OverlappingFieldsCanBeMerged, `
      {
        field {
          deepField {
            x: a
          }
          deepField {
            x: b
          }
        },
        field {
          deepField {
            y
          }
        }
      }
    `, [
      { message: fieldsConflictMessage(
          'deepField', [ [ 'x', 'a and b are different fields' ] ]
        ),
        locations: [
          { line: 4, column: 11 },
          { line: 7, column: 11 },
          { line: 5, column: 13 },
          { line: 8, column: 13 } ] },
    ]);
  });

  describe('return types must be unambiguous', () => {

    var StringBox = new GraphQLObjectType({
      name: 'StringBox',
      fields: {
        scalar: { type: GraphQLString }
      }
    });

    var IntBox = new GraphQLObjectType({
      name: 'IntBox',
      fields: {
        scalar: { type: GraphQLInt }
      }
    });

    var NonNullStringBox1 = new GraphQLObjectType({
      name: 'NonNullStringBox1',
      fields: {
        scalar: { type: new GraphQLNonNull(GraphQLString) }
      }
    });

    var NonNullStringBox2 = new GraphQLObjectType({
      name: 'NonNullStringBox2',
      fields: {
        scalar: { type: new GraphQLNonNull(GraphQLString) }
      }
    });

    var BoxUnion = new GraphQLUnionType({
      name: 'BoxUnion',
      resolveType: () => StringBox,
      types: [ StringBox, IntBox, NonNullStringBox1, NonNullStringBox2 ]
    });

    var Connection = new GraphQLObjectType({
      name: 'Connection',
      fields: {
        edges: {
          type: new GraphQLList(new GraphQLObjectType({
            name: 'Edge',
            fields: {
              node: {
                type: new GraphQLObjectType({
                  name: 'Node',
                  fields: {
                    id: { type: GraphQLID },
                    name: { type: GraphQLString }
                  }
                })
              }
            }
          }))
        }
      }
    });

    var schema = new GraphQLSchema({
      query: new GraphQLObjectType({
        name: 'QueryRoot',
        fields: () => ({
          boxUnion: { type: BoxUnion },
          connection: { type: Connection }
        })
      })
    });

    it('conflicting scalar return types', () => {
      expectFailsRuleWithSchema(schema, OverlappingFieldsCanBeMerged, `
        {
          boxUnion {
            ...on IntBox {
              scalar
            }
            ...on StringBox {
              scalar
            }
          }
        }
      `, [
        { message: fieldsConflictMessage(
            'scalar',
            'they return differing types Int and String'
          ),
          locations: [ { line: 5, column: 15 }, { line: 8, column: 15 } ] }
      ]);
    });

    it('same wrapped scalar return types', () => {
      expectPassesRuleWithSchema(schema, OverlappingFieldsCanBeMerged, `
        {
          boxUnion {
            ...on NonNullStringBox1 {
              scalar
            }
            ...on NonNullStringBox2 {
              scalar
            }
          }
        }
      `);
    });

    it('allows inline typeless fragments', () => {
      expectPassesRuleWithSchema(schema, OverlappingFieldsCanBeMerged, `
        {
          a
          ... {
            a
          }
        }
      `);
    });

    it('compares deep types including list', () => {
      expectFailsRuleWithSchema(schema, OverlappingFieldsCanBeMerged, `
        {
          connection {
            ...edgeID
            edges {
              node {
                id: name
              }
            }
          }
        }

        fragment edgeID on Connection {
          edges {
            node {
              id
            }
          }
        }
      `, [
        { message: fieldsConflictMessage(
            'edges',
            [ [ 'node', [ [ 'id', 'id and name are different fields' ] ] ] ]
          ),
          locations: [
            { line: 14, column: 11 }, { line: 5, column: 13 },
            { line: 15, column: 13 }, { line: 6, column: 15 },
            { line: 16, column: 15 }, { line: 7, column: 17 },
          ] }
      ]);
    });

    it('ignores unknown types', () => {
      expectPassesRuleWithSchema(schema, OverlappingFieldsCanBeMerged, `
        {
          boxUnion {
            ...on UnknownType {
              scalar
            }
            ...on NonNullStringBox2 {
              scalar
            }
          }
        }
      `);
    });

  });

});


text:
<?php

class RemoteAddress
{
    /**
     * Whether to use proxy addresses or not.
     *
     * As default this setting is disabled - IP address is mostly needed to increase
     * security. HTTP_* are not reliable since can easily be spoofed. It can be enabled
     * just for more flexibility, but if user uses proxy to connect to trusted services
     * it's his/her own risk, only reliable field for IP address is $_SERVER['REMOTE_ADDR'].
     *
     * @var bool
     */
    protected $useProxy = false;

    /**
     * List of trusted proxy IP addresses
     *
     * @var array
     */
    protected $trustedProxies = array();

    /**
     * HTTP header to introspect for proxies
     *
     * @var string
     */
    protected $proxyHeader = 'HTTP_X_FORWARDED_FOR';

    // [...]

    /**
     * Returns client IP address.
     *
     * @return string IP address.
     */
    public function getIpAddress()
    {
        $ip = $this->getIpAddressFromProxy();
        if ($ip) {
            return $ip;
        }

        // direct IP address
        if (isset($_SERVER['REMOTE_ADDR'])) {
            return $_SERVER['REMOTE_ADDR'];
        }

        return '';
    }

    /**
     * Attempt to get the IP address for a proxied client
     *
     * @see http://tools.ietf.org/html/draft-ietf-appsawg-http-forwarded-10#section-5.2
     * @return false|string
     */
    protected function getIpAddressFromProxy()
    {
        if (!$this->useProxy
            || (isset($_SERVER['REMOTE_ADDR']) && !in_array($_SERVER['REMOTE_ADDR'], $this->trustedProxies))
        ) {
            return false;
        }

        $header = $this->proxyHeader;
        if (!isset($_SERVER[$header]) || empty($_SERVER[$header])) {
            return false;
        }

        // Extract IPs
        $ips = explode(',', $_SERVER[$header]);
        // trim, so we can compare against trusted proxies properly
        $ips = array_map('trim', $ips);
        // remove trusted proxy IPs
        $ips = array_diff($ips, $this->trustedProxies);

        // Any left?
        if (empty($ips)) {
            return false;
        }

        // Since we've removed any known, trusted proxy servers, the right-most
        // address represents the first IP we do not know about -- i.e., we do
        // not know if it is a proxy server, or a client. As such, we treat it
        // as the originating IP.
        // @see http://en.wikipedia.org/wiki/X-Forwarded-For
        $ip = array_pop($ips);
        return $ip;
    }

    // [...]
}


text:
const chai_as_promised = require('chai-as-promised');
// const fetch_mock = require('fetch-mock');

const events_actions = require('../../src/client/actions/events');

const expect = chai.expect;
chai.use(chai_as_promised);

describe('Events actions', function () {
    describe('#add_events', function () {
        it('returns an `ADD_EVENTS` action', function () {
            const events = [
                {
                    id: 'kin-1234:abcd:alpha',
                },
            ];
            expect(events_actions.add_events(events))
                .to.deep.equal({
                    type: 'ADD_EVENTS',
                    creating: false,
                    events: [
                        {
                            id: 'kin-1234:abcd:alpha',
                        },
                    ],
                });
        });
    });

    describe('#delete_events', function () {
        it('returns a `DELETE_EVENTS` action', function () {
            const event_id = 'kin-1234:abcd:alpha';
            expect(events_actions.delete_events([event_id]))
                .to.deep.equal({
                    type: 'DELETE_EVENTS',
                    ids: ['kin-1234:abcd:alpha'],
                });
        });
    });

    describe('#deselect_event', function () {
        beforeEach(function () {
            this.dispatch_spy = sinon.spy();
            this.get_state_stub = sinon.stub();
            this.foundation_spy = sinon.spy();
            $.fn.foundation = this.foundation_spy;
        });

        it('dispatches a `DESELECT_EVENT` when an event was selected', function () {
            this.get_state_stub.returns({
                selected_event: {
                    id: 'kin-1234:abcd:alpha',
                    dirty: false,
                },
                ui: {
                    color_picker_tooltip: {
                        show: false,
                    },
                },
            });
            events_actions.deselect_event()(this.dispatch_spy, this.get_state_stub);
            expect(this.dispatch_spy)
                .to.have.been.calledWith({
                    type: 'DESELECT_EVENT',
                });
            expect(this.dispatch_spy)
                .to.have.been.calledOnce;
        });

        it('dispatches a `TOGGLE_COLOR_PICKER_TOOLTIP` when an event was selected and the color picker was shown', function () {
            this.get_state_stub.returns({
                selected_event: {
                    id: 'kin-1234:abcd:alpha',
                    dirty: false,
                },
                ui: {
                    color_picker_tooltip: {
                        show: true,
                    },
                },
            });
            events_actions.deselect_event()(this.dispatch_spy, this.get_state_stub);
            expect(this.dispatch_spy)
                .to.have.been.calledWith({
                    type: 'DESELECT_EVENT',
                });
            expect(this.dispatch_spy)
                .to.have.been.calledWith({
                    type: 'TOGGLE_COLOR_PICKER_TOOLTIP',
                    toggle: false,
                });
        });

        it('shows the leave edit mode modal if the selected event is dirty', function () {
            this.get_state_stub.returns({
                selected_event: {
                    id: 'kin-1234:abcd:alpha',
                    dirty: true,
                },
            });
            events_actions.deselect_event()(this.dispatch_spy, this.get_state_stub);
            expect(this.foundation_spy)
                .to.have.been.calledWith('open');
        });

        it('does nothing when no event was selected', function () {
            this.get_state_stub.returns({
                selected_event: {
                    id: null,
                },
            });
            events_actions.deselect_event()(this.dispatch_spy, this.get_state_stub);
            expect(this.dispatch_spy)
                .to.not.have.been.called;
        });

        afterEach(function () {
            delete $.fn.foundation;
        });
    });

    describe('#select_event', function () {
        beforeEach(function () {
            this.get_state_stub = sinon.stub();
            this.dispatch_spy = sinon.spy(
                (action) => {
                    // Freely inspired by redux-thunk
                    if (typeof action === 'function') {
                        return action(this.dispatch_spy, this.get_state_stub);
                    }
                    return action;
                } // eslint-disable-line comma-dangle
            );
        });

        it('dispatches a `SELECT_EVENT` if no event was selected', function () {
            const event_id = 'kin-1234:abcd:alpha';
            $('<div/>').attr('id', event_id).appendTo($('body'));
            this.get_state_stub.returns({
                selected_event: {
                    id: null,
                },
                events: {
                    [event_id]: {
                        color: '#FFFFFF',
                    },
                },
            });
            events_actions.select_event(event_id)(this.dispatch_spy, this.get_state_stub);
            expect(this.dispatch_spy)
                .to.have.been.calledWith({
                    type: 'SELECT_EVENT',
                    force: false,
                    id: 'kin-1234:abcd:alpha',
                    creating: false,
                });
        });

        it('dispatches a `SELECT_EVENT` after a `DESELECT_EVENT` if an event was previously selected');

        it('does nothing if selecting an already selected event', function () {
            const event_id = 'kin-1234:abcd:alpha';
            this.get_state_stub.returns({
                selected_event: {
                    id: event_id,
                },
            });
            events_actions.select_event(event_id)(this.dispatch_spy, this.get_state_stub);
            expect(this.dispatch_spy)
                .to.not.have.been.called;
        });

        it('dispatches a `SELECT_EVENT` even if selecting an already selected event when setting `force`');
    });

    describe('#create_event', function () {
        it('dispatches an `ADD_EVENTS` and selects it `SELECT_EVENT`');
    });

    describe('#toggle_edit_selected_event', function () {
        it('returns a `TOGGLE_EDIT_SELECTED_EVENT` action', function () {
            expect(events_actions.toggle_edit_selected_event())
                .to.be.deep.equal({
                    type: 'TOGGLE_EDIT_SELECTED_EVENT',
                });
        });
    });

    describe('#set_dirty_selected_event', function () {
        it('returns a `SET_DIRTY_SELECTED_EVENT` action (dirty)', function () {
            expect(events_actions.set_dirty_selected_event(true))
                .to.be.deep.equal({
                    type: 'SET_DIRTY_SELECTED_EVENT',
                    dirty: true,
                });
        });

        it('returns a `SET_DIRTY_SELECTED_EVENT` action (not dirty)', function () {
            expect(events_actions.set_dirty_selected_event(false))
                .to.be.deep.equal({
                    type: 'SET_DIRTY_SELECTED_EVENT',
                    dirty: false,
                });
        });
    });

    describe('#async_load_events', function () {
        // TODO: test both incremental and full syncs?
        it('eventually dispatches an `ADD_EVENTS` and a `PATCH_LAYER`');
    });

    describe('#async_create_event', function () {
        // TODO: test notify attendees?
        it('eventually dispatches a `DELETE_EVENT` and a `DESELECT_EVENT` on placeholder event and an `ADD_EVENTS`');
    });

    describe('#async_save_event', function () {
        it('eventually dispatches a `DESELECT_EVENT` and a `ADD_EVENTS`');
    });

    describe('#async_delete_event', function () {
        it('eventually dispatches a `DESELECT_EVENT` and a `DELETE_EVENT`');
    });
});


text:
'use strict';

/* eslint-disable no-empty-function, no-unused-vars */

/**
 * @constructor
 * @struct
 * @param {!PluginContext} context
 */
function EmptyPlugin(context) {
    this.onStart = () => {};

    /**
     * @param {!WebSocketConnection} connection
     */
    this.onNewConnection = connection => {};

    /**
     * @param {!WebSocketMessage} message
     * @param {!WebSocketConnection} connection
     */
    this.onMessage = (message, connection) => {};

    /**
     * @param {!WebSocketConnection} connection
     */
    this.onConnectionClosed = connection => {};

    this.onStop = () => {};
}

module.exports = {
    name: 'empty2',
    description: 'This plugin does nothing.',
    createWorker: context => new EmptyPlugin(context)
};


text:
Step . Edit Learning Information

Learner Level

Resource Overview/Type

Subject Key Words

Teaching/Learning Strategy

Time Frame/Context

Language

Standards

Learning Information

Learner Level

ToL Learner Level

Choose a ToL Learner Level. You may select all
				levels that apply to your page.

                    <input jwcid="@Checkbox" value="ognl:treehouse.isBeginnerLevel"/>
                    Beginner

					<input jwcid="@Checkbox" value="ognl:treehouse.isIntermediateLevel"/>
					Intermediate

       <input jwcid="@Checkbox" value="ognl:treehouse.isAdvancedLevel"/>
					Advanced

Target Grade and Age Level

            Select one option:
                <select jwcid="@PropertySelection" model="ognl:gradeLevelModel" value="ognl:treehouse.gradeLevel"/>

		      <input jwcid="@Checkbox" value="ognl:treehouse.gradeModifiable"/> 	        Can be modified for many grade/age levels

 Resource Overview

Description

					<textarea jwcid="@TextArea" value="ognl:treehouse.description" cols="60" rows="5"></textarea>

Comments

 Use this section to add any
					additional information that you would like visitors to know about your
					treehouse.

<textarea jwcid="@TextArea" value="ognl:treehouse.comments" cols="50" rows="3"></textarea>

Resource Type

Additional Treehouse Type

 This treehouse is a .
  Select additional treehouse types that apply to your resource and that will help others find the resources that they need.

      <input jwcid="@Checkbox" value="ognl:treehouse.isGame"/>
      Game

    <input jwcid="@Checkbox" value="ognl:treehouse.isBiography"/>
    Biography

<input jwcid="@Checkbox" value="ognl:treehouse.isInvestigation"/>
Investigation

    <input jwcid="@Checkbox" value="ognl:treehouse.isStory"/>
    Story

    <input jwcid="@Checkbox" value="ognl:treehouse.isArtAndCulture"/>
   Art and Culture

    <input jwcid="@Checkbox" value="ognl:treehouse.isTeacherResource"/>
   Teacher Resource

Additional Resource Type

Select additional resource types that  describe your work. Assigning these categories to your resource will help visitors find your page when they do a treehouse search. Check all that apply:

              <input jwcid="@Checkbox" value="ognl:treehouse.isWebBased"/>
            Web-based resource

              <input jwcid="@Checkbox" value="ognl:treehouse.isHomeBased"/>
            Home-based resource

              <input jwcid="@Checkbox" value="ognl:treehouse.isInformal"/>
            Informal learning resource

              <input jwcid="@Checkbox" value="ognl:treehouse.isMuseumBased"/>
            Museum-based resource

              <input jwcid="@Checkbox" value="ognl:treehouse.isClassroom"/>
              Classroom resource

              <input jwcid="@Checkbox" value="ognl:treehouse.isLab"/>
            Lab resource

              <input jwcid="@Checkbox" value="ognl:treehouse.isField"/>             Field resource

              <input jwcid="@Checkbox" value="ognl:treehouse.isFieldTrip"/>             Field Trip resource

Subject/Keywords

Select  keywords that match the content area learning of your teacher resource. Please be sure to limit
                    your selection to topics for which your teacher resource has special
                    relevance. Additional subjects that are not covered in this
                    list can be entered in the Key Words field
                    below.

Science Subject/Keywords

Additional Curricular Area Key Words

		  <input jwcid="@Checkbox" value="ognl:treehouse.isLanguageArts"/>
		  Language Arts

		  <input jwcid="@Checkbox" value="ognl:treehouse.isTechnology"/>
		    Technology

		  <input jwcid="@Checkbox" value="ognl:treehouse.isMathematics"/>
		    Mathematics
  		  <input jwcid="@Checkbox" value="ognl:treehouse.isHealth"/>
	          Health

		  <input jwcid="@Checkbox" value="ognl:treehouse.isSocialStudies"/>
	            Social Studies

		  <input jwcid="@Checkbox" value="ognl:treehouse.isArts"/>
            Arts

Teaching and Learning Strategy

Select the learning and grouping strategies that best describe your resource.
            You may select more than one strategy but be sure and select only the most relevant categories.

 Strategy

              <input jwcid="@Checkbox" value="ognl:treehouse.isLearningModules"/> Learning Modules/Centers

              <input jwcid="@Checkbox" value="ognl:treehouse.isDiscussion"/> Discussion

              <input jwcid="@Checkbox" value="ognl:treehouse.isDemonstration"/> Demonstration

              <input jwcid="@Checkbox" value="ognl:treehouse.isLecture"/> Lecture

              <input jwcid="@Checkbox" value="ognl:treehouse.isPresentation"/> Presentation

              <input type="checkbox">               Other
             <input jwcid="@TextField" value="ognl:treehouse.otherLearningStrategy"/>

              <input jwcid="@Checkbox" value="ognl:treehouse.isInquiryLearning"/>
             Inquiry Learning

              <input jwcid="@Checkbox" value="ognl:treehouse.isHandsOnLearning"/>
           Hands-on Learning

              <input jwcid="@Checkbox" value="ognl:treehouse.isVisualInstruction"/>
           Visual Instruction

              <input jwcid="@Checkbox" value="ognl:treehouse.isRolePlaying"/>
           Role-Playing

 <input jwcid="@Checkbox" value="ognl:treehouse.isMovement"/>
           Movement, Play, Games

              <input jwcid="@Checkbox" value="ognl:treehouse.isTechnologyIntegration"/> Technology Integration/

              Computer Assisted Instruction

Grouping

Select Grouping Organization (select all that apply)

              <input jwcid="@Checkbox" value="ognl:treehouse.isHeterogeneous"/>
Heterogeneous grouping

              <input jwcid="@Checkbox" value="ognl:treehouse.isHomogeneous"/>
Homogeneous grouping

              <input jwcid="@Checkbox" value="ognl:treehouse.isCrossAge"/>                Cross age or multi-age teaching

 <input jwcid="@Checkbox" value="ognl:treehouse.isIndividualized"/>
           Individualized instruction

              <input jwcid="@Checkbox" value="ognl:treehouse.isLargeGroup"/>
Large Group instruction

              <input jwcid="@Checkbox" value="ognl:treehouse.isSmallGroup"/>               Small Group instruction

Time Frame

Please indicate the time needed for the activity and the time frame, for example: This activity will take about 45 minutes per session over the course of 3 to 4 sessions.

Suggested time frame:
         <input jwcid="@TextArea" value="ognl:treehouse.timeFrame" cols="60" rows="5"/>

 Sequence and Context

Describe in what context you present this resource. For example, indicate if this treehouse is an introductory lesson, a stand-alone lesson, an anticipatory set, a culminating activity, or part of a unit or extended project (indicate what part). Note that you may add this resource to a teacher resource portfolio that presents to others a group of resources in an integrated context.

<textarea jwcid="@TextArea" value="ognl:treehouse.sequenceContext" cols="60" rows="5"/>

Language

Languages that apply to this resource:

                <input jwcid="@Checkbox" value="ognl:treehouse.languages.english"/>
              English

                <input jwcid="@Checkbox" value="ognl:treehouse.languages.spanish"/>
              Spanish

                <input jwcid="@Checkbox" value="ognl:treehouse.languages.german"/>
              German

                <input jwcid="@Checkbox" value="ognl:treehouse.languages.french"/>
              French

Other language
			  <inpuw jwcid="@TextField" value="ognl:treehouse.languages.otherLanguage"/>

Standards

 State Education Standards

 State:
			<input jwcid="@TextField" type="text" size="10" value="ognl:treehouse.stateStandards"/>

Subject Areas
			<input jwcid="@TextArea" cols="50" rows="2" value="ognl:treehouse.stateStandardsSubjects"/>

		Add State Education Standards by writing them in the space below.

Standards Text

				<textarea jwcid="@PreparedTextArea" cols="50" rows="20" valuePath="stateStandardsValue" textAreaId="statestandards"
                	useDefaultText="ognl:false" useEditor="prop:useHTMLEditor"/>

National Education Standards

 Subject Areas
		<input jwcid="@TextArea" cols="50" rows="2" value="ognl:treehouse.nationalStandardsSubjects"/>

		Add National Education Standards by writing them in the space below.

Standards Text

   			<textarea jwcid="@PreparedTextArea" cols="50" rows="20" valuePath="nationalStandardsValue" textAreaId="nationalstandards"
               useDefaultText="ognl:false" useEditor="prop:useHTMLEditor"/>